# **Worldwide**{: .color-primary} Education Statistics

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Literacy Rate**{: .color-primary}
<|{'{:.2f}%'.format(np.average(data_world_education['Literacy Rate']))}|text|class_name=h2|>
|>

<|card|
**School Enrollment**{: .color-primary}
<|{'{:.2f}%'.format(np.average(data_world_education['School Enrollment']))}|text|class_name=h2|>
|>

<|part|class_name=card|
**Education Spending**{: .color-primary}
<|{'{:.2f}%'.format(np.average(data_world_education['Education Spending']))}|text|class_name=h2|>
|>
|>

<|{selected_education_metric}|toggle|lov={education_metric_selector}|>

<|part|render={selected_education_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_world_education_pie_absolute}|chart|type=pie|labels=Country|values=Literacy Rate|title=Global Literacy Rate Distribution|>

<|{data_world_education_evolution_absolute}|chart|properties={data_world_education_evolution_properties}|title=Education Trends Worldwide|>
|>
|>

<|part|render={selected_education_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_world_education_pie_relative}|chart|type=pie|labels=Country|values=School Enrollment|>

<|{data_world_education_evolution_relative}|chart|properties={data_world_education_evolution_relative_properties}|>
|>
|>


<|layout|columns=2 9|gap=50px|
<sidebar|sidebar|
**Transportation Efficiency** Setup

<|{selected_transport_scenario}|transport_scenario_selector|>
|sidebar>

<transport_scenario|part|render={selected_transport_scenario}|
# **Public Transport Analysis**{: .color-primary} page

<|1 1|layout|
<date|
#### Analysis **Date**{: .color-primary}

<|{analysis_date}|date|on_change=on_change_transport_params|>
|date>

<route|
#### **Route**{: .color-primary} for Analysis

<|{selected_route}|selector|lov={selector_route}|dropdown|on_change=on_change_transport_params|label=Route|>
|route>
|>

<|{selected_transport_scenario}|transport_scenario|on_submission_change=on_transport_scenario_submission_change|not expanded|>

---------------------------------------

## **Transport Efficiency Metrics**{: .color-primary} and Trends

<|{selected_transport_scenario.result.read() if selected_transport_scenario and selected_transport_scenario.result.read() is not None else default_transport_result}|chart|x=Time|y[1]=Passenger Count|y[2]=Average Delay|type[1]=bar|title=Route Efficiency Analysis|>

<|Data Nodes|expandable|
<|1 5|layout|
<|{selected_data_node}|data_node_selector|>

<|{selected_data_node}|data_node|>
|>
|>

|transport_scenario>
|>


from taipy.gui import Gui
import pandas as pd

audio_data = None
audio_path = ""

def audio_upload(state):
    if state.audio_path:
        audio_data = state.audio_path  # Directly use the path for audio elements

audio_page = """
<|{audio_path}|file_selector|accept=audio/*|on_action=audio_upload|>
<|{audio_data}|audio|controls=True|>
"""

Gui(audio_page).run()


from taipy.gui import Gui
import pandas as pd
import matplotlib.pyplot as plt
import io

csv_data = None
csv_path = ""

def csv_upload_analyze(state):
    if state.csv_path:
        state.csv_data = pd.read_csv(state.csv_path)
        plt.figure()
        state.csv_data.hist()
        plt.xlabel("Values")
        plt.ylabel("Frequency")
        plt.title("Data Distribution")
        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        state.plot_image = buf.read()

csv_analyze_page = """
<|{csv_path}|file_selector|accept=.csv|on_action=csv_upload_analyze|>
<|{csv_data}|table|>
<|{plot_image}|image|>
"""

Gui(csv_analyze_page).run()


from taipy.gui import Gui
import pandas as pd

# Load project task data
task_data = pd.read_csv("project_task_data.csv")

# Initialize variables
projects = list(task_data["Project"].unique())
priorities = list(task_data["Priority"].unique())
project = projects
priority = priorities

# Markdown for the entire page
page = """<|toggle|theme|>

<|layout|columns=20 80|gap=30px|
<sidebar|
## **Filter**{: .orange} Project Tasks:

<|{project}|selector|lov={projects}|multiple|label=Select Project|dropdown|on_change=on_filter|width=100%|>

<|{priority}|selector|lov={priorities}|multiple|label=Select Priority|dropdown|on_change=on_filter|width=100%|>
|sidebar>

<main_page|
# Project Task Management System

<|layout|columns=1 1 1|
<total_tasks|
## Total Tasks:
### <|{len(df_selection)}|>
|total_tasks>

<average_completion|
## Average Completion Time:
### <|{round(df_selection["Completion Time"].mean(), 2)}|> days
|average_completion>

<task_management_table|
Display df_selection in an expandable
<|Task Management Table|expandable|expanded=False|
<|{df_selection}|table|width=100%|page_size=10|rebuild|class_name=table|>
|task_management_table>
|main_page>
|>

Code adapted from [Project Task Management](https://github.com/task_management_app)

Get the Taipy Code [here](https://github.com/Avaiga/project-task-management-app)


from taipy.gui import Gui
import taipy as tp

# Import pages for the homecare sector
from pages.homecare.home import home_md
from pages.homecare.services import services_md
from pages.homecare.appointments import appointments_md
from pages.homecare.contacts import contacts_md

# Define your pages dictionary
pages = {
    '/home': home_md,
    '/services': services_md,
    '/appointments': appointments_md,
    '/contacts': contacts_md
}

# Create a Gui with your pages
gui_homecare = Gui(pages=pages)

if __name__ == '__main__':
    tp.Core().run()

    # Run the multi-page app
    gui_homecare.run(title="Homecare Dashboard")


# **Global**{: .color-primary} Technology Adoption

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Internet Users**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_tech['Internet Users']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|card|
**Smartphone Penetration**{: .color-primary}
<|{'{:.2f}%'.format(np.average(data_world_tech['Smartphone Penetration']))}|text|class_name=h2|>
|>

<|part|class_name=card|
**AI Adoption**{: .color-primary}
<|{'{:.2f}%'.format(np.average(data_world_tech['AI Adoption']))}|text|class_name=h2|>
|>
|>

<|{selected_tech_metric}|toggle|lov={tech_metric_selector}|>

<|part|render={selected_tech_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_world_tech_pie_absolute}|chart|type=pie|labels=Country|values=Internet Users|title=Global Internet Usage|>

<|{data_world_tech_evolution_absolute}|chart|properties={data_world_tech_evolution_properties}|title=Technology Evolution Worldwide|>
|>
|>

<|part|render={selected_tech_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_world_tech_pie_relative}|chart|type=pie|labels=Country|values=Smartphone Penetration|>

<|{data_world_tech_evolution_relative}|chart|properties={data_world_tech_evolution_relative_properties}|>
|>
|>


<|layout|columns=2 9|gap=50px|
<sidebar|sidebar|
**Supply Chain Analysis** Configuration

<|{selected_supply_chain_scenario}|supply_chain_scenario_selector|>
|sidebar>

<supply_chain_scenario|part|render={selected_supply_chain_scenario}|
# **Supply Chain Optimization**{: .color-primary} page

<|1 1|layout|
<date|
#### Analysis **Start Date**{: .color-primary}

<|{analysis_start_date}|date|on_change=on_change_supply_chain_params|>
|date>

<product|
#### **Product**{: .color-primary} for Analysis

<|{selected_product}|selector|lov={selector_product}|dropdown|on_change=on_change_supply_chain_params|label=Product|>
|product>
|>

<|{selected_supply_chain_scenario}|supply_chain_scenario|on_submission_change=on_supply_chain_scenario_submission_change|not expanded|>

---------------------------------------

## **Supply Chain Dynamics**{: .color-primary} and Forecast

<|{selected_supply_chain_scenario.result.read() if selected_supply_chain_scenario and selected_supply_chain_scenario.result.read() is not None else default_supply_chain_result}|chart|x=Date|y[1]=Demand|y[2]=Supply|type[1]=line|title=Supply vs. Demand Forecast|>

<|Data Nodes|expandable|
<|1 5|layout|
<|{selected_data_node}|data_node_selector|>

<|{selected_data_node}|data_node|>
|>
|>

|supply_chain_scenario>
|>


# **Global**{: .color-primary} Tourism Statistics

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**International Tourist Arrivals**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_tourism['Tourist Arrivals']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|card|
**Tourism Revenue**{: .color-primary}
<|{'${:,.2f}'.format(np.sum(data_world_tourism['Revenue']))}|text|class_name=h2|>
|>

<|part|class_name=card|
**Hotel Occupancy Rates**{: .color-primary}
<|{'{:.2f}%'.format(np.average(data_world_tourism['Occupancy']))}|text|class_name=h2|>
|>
|>

<|{selected_tourism_metric}|toggle|lov={tourism_metric_selector}|>

<|part|render={selected_tourism_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_world_tourism_pie_absolute}|chart|type=pie|labels=Country|values=Tourist Arrivals|title=Global Tourist Arrivals|>

<|{data_world_tourism_evolution_absolute}|chart|properties={data_world_tourism_evolution_properties}|title=Tourism Trends Worldwide|>
|>
|>

<|part|render={selected_tourism_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_world_tourism_pie_relative}|chart|type=pie|labels=Country|values=Occupancy|>

<|{data_world_tourism_evolution_relative}|chart|properties={data_world_tourism_evolution_relative_properties}|>
|>
|>


# **Global**{: .color-primary} E-Commerce Trends

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Online Sales Volume**{: .color-primary}
<|{'${:,.2f}'.format(np.sum(data_world_ecommerce['Sales Volume']))}|text|class_name=h2|>
|>

<|card|
**Active Online Users**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_ecommerce['Active Users']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|part|class_name=card|
**Average Purchase Value**{: .color-primary}
<|{'${:,.2f}'.format(np.average(data_world_ecommerce['Purchase Value']))}|text|class_name=h2|>
|>
|>

<|{selected_ecommerce_metric}|toggle|lov={ecommerce_metric_selector}|>

<|part|render={selected_ecommerce_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_world_ecommerce_pie_absolute}|chart|type=pie|labels=Country|values=Sales Volume|title=Global Online Sales Volume|>

<|{data_world_ecommerce_evolution_absolute}|chart|properties={data_world_ecommerce_evolution_properties}|title=E-Commerce Trends Worldwide|>
|>
|>

<|part|render={selected_ecommerce_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_world_ecommerce_pie_relative}|chart|type=pie|labels=Country|values=Active Users|>

<|{data_world_ecommerce_evolution_relative}|chart|properties={data_world_ecommerce_evolution_relative_properties}|>
|>
|>


# **Global**{: .color-primary} Automotive Industry

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Total Vehicle Production**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_automotive['Vehicle Production']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|card|
**Electric Vehicle Sales**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_automotive['EV Sales']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|part|class_name=card|
**Market Share**{: .color-primary}
<|{'{:.2f}%'.format(np.average(data_world_automotive['Market Share']))}|text|class_name=h2|>
|>
|>

<|{selected_automotive_metric}|toggle|lov={automotive_metric_selector}|>

<|part|render={selected_automotive_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_world_automotive_pie_absolute}|chart|type=pie|labels=Country|values=Vehicle Production|title=Global Vehicle Production|>

<|{data_world_automotive_evolution_absolute}|chart|properties={data_world_automotive_evolution_properties}|title=Automotive Industry Trends|>
|>
|>

<|part|render={selected_automotive_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_world_automotive_pie_relative}|chart|type=pie|labels=Country|values=EV Sales|>

<|{data_world_automotive_evolution_relative}|chart|properties={data_world_automotive_evolution_relative_properties}|>
|>
|>


from taipy import Gui

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

WINDOW_SIZE = 500

cm = plt.cm.get_cmap("viridis")

def generate_mandelbrot(
    center: int = WINDOW_SIZE / 2,
    dx_range: int = 1000,
    dx_start: float = -0.12,
    dy_range: float = 1000,
    dy_start: float = -0.82,
    iterations: int = 50,
    max_value: int = 200,
    i: int = 0,
) -> str:
    mat = np.zeros((WINDOW_SIZE, WINDOW_SIZE))
    for y in range(WINDOW_SIZE):
        for x in range(WINDOW_SIZE):
            dx = (x - center) / dx_range + dx_start
            dy = (y - center) / dy_range + dy_start
            a = dx
            b = dy
            for t in range(iterations):
                d = (a * a) - (b * b) + dx
                b = 2 * (a * b) + dy
                a = d
                h = d > max_value
                if h is True:
                    mat[x, y] = t

    colored_mat = cm(mat / mat.max())
    im = Image.fromarray((colored_mat * 255).astype(np.uint8))
    path = f"mandelbrot_{i}.png"
    im.save(path)

    return path

def generate(state):
    state.i = state.i + 1
    state.path = generate_mandelbrot(
        dx_start=-state.dx_start / 100,
        dy_start=(state.dy_start - 100) / 100,
        iterations=state.iterations,
        i=state.i,
    )

i = 0
dx_start = 11
dy_start = 17
iterations = 50

path = generate_mandelbrot(
    dx_start=-dx_start / 100,
    dy_start=(dy_start - 100) / 100,
)

page = """
# Mandelbrot Generator

<|layout|columns=35 65|
Display image from path
<|{path}|image|width=500px|height=500px|class_name=img|>

Iterations:

Create a slider to select iterations
<|{iterations}|slider|min=10|max=50|continuous=False|on_change=generate|>

X Position:

<|{dy_start}|slider|min=0|max=100|continuous=False|on_change=generate|>

Y Position:

Slider dx_start
<|{dx_start}|slider|min=0|max=100|continuous=False|on_change=generate|>

|>
"""

Gui(page).run(title="Mandelbrot Generator")


<|{all_appointments}|table|columns={appointment_columns}|width='100%'|on_action={on_appointment_select}|style=appointment_style|>
<|Book Appointment|button|on_action={open_book_appointment_dialog}|>
<|Refresh Appointments|button|on_action={refresh_appointment_list}|>

<|{show_book_appointment_dialog}|dialog|title=Book New Appointment|
<|{patient_name}|input|placeholder='Patient Name'|
<|{appointment_date}|datetime_picker|>
<|{doctor_selector}|selector|lov={get_all_doctors()}|>
<|Book|button|on_action={book_appointment}|>
<|Cancel|button|on_action={close_book_appointment_dialog}|>
|>

<|{show_appointment_details}|pane|

# Appointment Details <|Edit|button|on_action=edit_selected_appointment|> <|Cancel|button|on_action=cancel_selected_appointment|>

<|layout|columns=1|
<|part|class_name=card|
## Patient Name
<|{selected_appointment.patient_name}|>
|>

<|part|class_name=card|
## Date and Time
<|{selected_appointment.date.strftime("%b %d, %Y at %H:%M")}|>
|>

<|part|class_name=card|
## Doctor
<|{selected_appointment.doctor}|>
|>

<|part|class_name=card|
## Status
<|{get_appointment_status(selected_appointment)}|>
|>

----
|>


# **Global**{: .color-primary} Food Security and Agriculture

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Cereal Production**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_agri['Cereal Production']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|card|
**Agricultural Land**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_agri['Agricultural Land']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|part|class_name=card|
**Undernourishment Rate**{: .color-primary}
<|{'{:.2f}%'.format(np.average(data_world_agri['Undernourishment Rate']))}|text|class_name=h2|>
|>
|>

<|{selected_agri_metric}|toggle|lov={agri_metric_selector}|>

<|part|render={selected_agri_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_world_agri_pie_absolute}|chart|type=pie|labels=Country|values=Cereal Production|title=Global Cereal Production|>

<|{data_world_agri_evolution_absolute}|chart|properties={data_world_agri_evolution_properties}|title=Agricultural Trends Worldwide|>
|>
|>

<|part|render={selected_agri_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_world_agri_pie_relative}|chart|type=pie|labels=Country|values=Undernourishment Rate|>

<|{data_world_agri_evolution_relative}|chart|properties={data_world_agri_evolution_relative_properties}|>
|>
|>


if __name__ == "__main__":
    # Initialize with custom sector-related values
    topic = "E-commerce"
    mood = "shopping"
    style = "ecommerceexpert"

    # Create a GUI page with custom settings
    page = """
    <|container|
    # **Generate**{: .color-primary} E-commerce Tweets

    This mini-app generates Tweets related to E-commerce using OpenAI's GPT-3 based [Davinci model](https://beta.openai.com/docs/models/overview) for texts and [DALL·E](https://beta.openai.com/docs/guides/images) for images. You can find the code on [GitHub](https://github.com/Avaiga/demo-tweet-generation) and the original author on [Twitter](https://twitter.com/kinosal).

    <|layout|columns=1 1 1|gap=30px|class_name=card|
    <topic|
    ## **Topic**{: .color-primary} (or hashtag)

    <|{topic}|input|label=E-commerce Topic (or hashtag)|>
    |topic>

    <mood|
    ## **Mood**{: .color-primary}

    <|{mood}|input|label=Mood (e.g. shopping, deals, online retail) (optional)|>
    |mood>


from taipy.gui import Gui
import taipy as tp

# Import pages related to education and healthcare (replace with actual imports)
from pages.education.education import education_md
from pages.healthcare.healthcare import healthcare_md

# Define the pages
pages = {
    '/': root,  # Replace with the root page if you have one
    "Education": education_md,
    "Healthcare": healthcare_md,
}

# Create a Gui instance with the pages
gui_multi_pages = Gui(pages=pages)

if __name__ == '__main__':
    tp.Core().run()

    # Run the multi-page app
    gui_multi_pages.run(title="Education & Healthcare Dashboard")


<|{all_properties}|table|columns={property_columns}|width='100%'|on_action={on_property_select}|style=property_style|>
<|Add Property|button|on_action={open_add_property_dialog}|>
<|Refresh Properties|button|on_action={refresh_property_list}|>

<|{show_add_property_dialog}|dialog|title=Add New Property|
<|{property_address}|input|placeholder='Address'|
<|{property_price}|number_input|placeholder='Price'|
<|Add Property|button|on_action={add_property}|>
<|Cancel|button|on_action={close_add_property_dialog}|>
|>

<|{show_property_details}|pane|

# Property Details <|Edit|button|on_action=edit_selected_property|> <|Remove|button|on_action=remove_selected_property|>

<|layout|columns=2|
<|part|class_name=card|
## Address
<|{selected_property.address}|>
|>

<|part|class_name=card|
## Price
<|{selected_property.price}|>
|>

<|part|class_name=card|
## Listed Date
<|{selected_property.listed_date.strftime("%b %d, %Y")}|>
|>

----
|>


from taipy.gui import Gui
import taipy as tp

# Import pages for the education sector
from pages.education.home import home_md
from pages.education.courses import courses_md
from pages.education.students import students_md
from pages.education.teachers import teachers_md

# Define your pages dictionary
pages = {
    '/home': home_md,
    '/courses': courses_md,
    '/students': students_md,
    '/teachers': teachers_md
}

# Create a Gui with your pages
gui_education = Gui(pages=pages)

if __name__ == '__main__':
    tp.Core().run()

    # Run the multi-page app
    gui_education.run(title="Education Dashboard")


# **Country**{: .color-primary} Education Statistics

<|layout|columns=1 1 1|
<|{selected_country_education}|selector|lov={selector_country_education}|on_change=on_change_country_education|dropdown|label=Country|>

<|{selected_education_level}|toggle|lov={education_level_selector}|on_change=update_education_level_display|>
|>

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Literacy Rate**{: .color-primary}
<|{'{:.2f}%'.format(education_data.iloc[-1]['Literacy Rate'])}|text|class_name=h2|>
|>

<|card|
**School Enrollment**{: .color-primary}
<|{'{:.2f}%'.format(education_data.iloc[-1]['School Enrollment'])}|text|class_name=h2|>
|>

<|card|
**Average Education Years**{: .color-primary}
<|{'{:.1f}'.format(education_data.iloc[-1]['Average Education Years'])}|text|class_name=h2|>
|>
|>

<|layout|columns=2 1|
<|{education_data}|chart|type=bar|x=Year|y[3]=Literacy Rate|y[2]=School Enrollment|y[1]=Average Education Years|layout={layout}|options={options}|title=Education Progress|>

<|{education_level_chart}|chart|type=pie|values=education_level_values|labels=education_level_labels|title=Education Level Distribution|>
|>


# **Worldwide**{: .color-primary} Renewable Energy Usage

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Solar Energy Production**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_energy['Solar Energy']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|card|
**Wind Energy Production**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_energy['Wind Energy']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|part|class_name=card|
**Hydropower Energy Production**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_energy['Hydropower']))).replace(',', ' ')}|text|class_name=h2|>
|>
|>

<|{selected_energy_metric}|toggle|lov={energy_metric_selector}|>

<|part|render={selected_energy_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_world_energy_pie_absolute}|chart|type=pie|labels=Country|values=Solar Energy|title=Global Solar Energy Production|>

<|{data_world_energy_evolution_absolute}|chart|properties={data_world_energy_evolution_properties}|title=Renewable Energy Trends Worldwide|>
|>
|>

<|part|render={selected_energy_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_world_energy_pie_relative}|chart|type=pie|labels=Country|values=Wind Energy|>

<|{data_world_energy_evolution_relative}|chart|properties={data_world_energy_evolution_relative_properties}|>
|>
|>


from taipy.gui import Gui
import pandas as pd

excel_data = []
excel_path = ""

def excel_upload(state):
    state.excel_data = pd.read_excel(state.excel_path)

excel_page = """
<|{excel_path}|file_selector|accept=.xlsx|on_action=excel_upload|>
<|{excel_data}|table|>
"""

Gui(excel_page).run()


from taipy.gui import Gui
import taipy as tp

# Import pages for the retail sector
from pages.retail.home import home_md
from pages.retail.products import products_md
from pages.retail.customers import customers_md
from pages.retail.sales import sales_md

# Define your pages dictionary
pages = {
    '/home': home_md,
    '/products': products_md,
    '/customers': customers_md,
    '/sales': sales_md
}

# Create a Gui with your pages
gui_retail = Gui(pages=pages)

if __name__ == '__main__':
    tp.Core().run()

    # Run the multi-page app
    gui_retail.run(title="Retail Dashboard")


from taipy.gui import Gui
import pandas as pd

# Load customer feedback data
feedback_data = pd.read_csv("customer_feedback_data.csv")

# Initialize variables
products = list(feedback_data["Product"].unique())
sentiments = list(feedback_data["Sentiment"].unique())
product = products
sentiment = sentiments

# Markdown for the entire page
page = """<|toggle|theme|>

<|layout|columns=20 80|gap=30px|
<sidebar|
## **Filter**{: .orange} Customer Feedback Analysis:

<|{product}|selector|lov={products}|multiple|label=Select Product|dropdown|on_change=on_filter|width=100%|>

<|{sentiment}|selector|lov={sentiments}|multiple|label=Select Sentiment|dropdown|on_change=on_filter|width=100%|>
|sidebar>

<main_page|
# Customer Feedback Analysis

<|layout|columns=1 1 1|
<total_feedback|
## Total Feedback:
### <|{len(df_selection)}|>
|total_feedback>

<average_rating|
## Average Rating:
### <|{round(df_selection["Rating"].mean(), 2)}|> out of 5
|average_rating>

<feedback_table|
Display df_selection in an expandable
<|Feedback Table|expandable|expanded=False|
<|{df_selection}|table|width=100%|page_size=10|rebuild|class_name=table|>
|feedback_table>
|main_page>
|>

Code adapted from [Customer Feedback Analysis](https://github.com/feedback_analysis_app)

Get the Taipy Code [here](https://github.com/Avaiga/customer-feedback-analysis-app)


<|layout|columns=2 9|gap=50px|
<sidebar|sidebar|
**Forecast** Creation

<|{selected_forecast}|forecast_selector|>
|sidebar>

<forecast|part|render={selected_forecast}|
# **Financial Forecast**{: .color-primary} page

<|1 1|layout|
<date|
#### Start **Date**{: .color-primary} of Forecast

<|{forecast_start_date}|date|on_change=on_change_forecast_params|>
|date>

<market|
#### **Market**{: .color-primary} for Forecast

<|{selected_market}|selector|lov={selector_market}|dropdown|on_change=on_change_forecast_params|label=Market|>
|market>
|>

<|{selected_forecast}|forecast|on_submission_change=on_submission_change_forecast|not expanded|>

---------------------------------------

## **Market Predictions**{: .color-primary} and Data Explorer

<|{selected_forecast.result.read() if selected_forecast and selected_forecast.result.read() is not None else default_market_result}|chart|x=Date|y[1]=Market Value|y[2]=Trend Prediction|type[1]=line|title=Market Forecast|>

<|Data Nodes|expandable|
<|1 5|layout|
<|{selected_data_node}|data_node_selector|>

<|{selected_data_node}|data_node|>
|>
|>

|forecast>
|>


<|{all_classes}|table|columns={class_columns}|width='100%'|on_action={on_class_select}|style=class_style|>
<|Schedule Class|button|on_action={open_schedule_class_dialog}|>
<|Refresh Classes|button|on_action={refresh_class_list}|>

<|{show_schedule_class_dialog}|dialog|title=Schedule New Class|
<|{class_subject}|input|placeholder='Class Subject'|
<|{class_date}|date_picker|>
<|Schedule|button|on_action={schedule_class}|>
<|Cancel|button|on_action={close_schedule_class_dialog}|>
|>

<|{show_class_details}|pane|

# Class Details <|Edit|button|on_action=edit_selected_class|> <|Cancel|button|on_action=cancel_selected_class|>

<|layout|columns=1|
<|part|class_name=card|
## Subject
<|{selected_class.subject}|>
|>

<|part|class_name=card|
## Date
<|{selected_class.date.strftime("%b %d, %Y at %H:%M")}|>
|>

<|part|class_name=card|
## Instructor
<|{selected_class.instructor}|>
|>

<|part|class_name=card|
## Enrollment
<|{selected_class.enrollment}|number_input|disabled=True|>
|>

----
|>


if __name__ == "__main__":
    # Initialize with custom sector-related values
    topic = "Healthcare"
    mood = "medical"
    style = "healthexpert"

    # Create a GUI page with custom settings
    page = """
    <|container|
    # **Generate**{: .color-primary} Healthcare Tweets

    This mini-app generates Tweets related to Healthcare using OpenAI's GPT-3 based [Davinci model](https://beta.openai.com/docs/models/overview) for texts and [DALL·E](https://beta.openai.com/docs/guides/images) for images. You can find the code on [GitHub](https://github.com/Avaiga/demo-tweet-generation) and the original author on [Twitter](https://twitter.com/kinosal).

    <|layout|columns=1 1 1|gap=30px|class_name=card|
    <topic|
    ## **Topic**{: .color-primary} (or hashtag)

    <|{topic}|input|label=Healthcare Topic (or hashtag)|>
    |topic>

    <mood|
    ## **Mood**{: .color-primary}

    <|{mood}|input|label=Mood (e.g. medical, informative, healthcare) (optional)|>
    |mood>


from taipy.gui import Gui
import pandas as pd

video_data = None
video_path = ""

def video_upload(state):
    if state.video_path:
        video_data = state.video_path  # Directly use the path for video elements

video_page = """
<|{video_path}|file_selector|accept=video/*|on_action=video_upload|>
<|{video_data}|video|controls=True|>
"""

Gui(video_page).run()


<|layout|columns=2 9|gap=50px|
<sidebar|sidebar|
**Impact Monitoring** Configuration

<|{selected_environmental_scenario}|environmental_scenario_selector|>
|sidebar>

<environmental_scenario|part|render={selected_environmental_scenario}|
# **Environmental Impact Assessment**{: .color-primary} page

<|1 1|layout|
<date|
#### Monitoring **Date**{: .color-primary}

<|{monitoring_date}|date|on_change=on_change_environmental_params|>
|date>

<region|
#### **Region**{: .color-primary} for Monitoring

<|{selected_region}|selector|lov={selector_region}|dropdown|on_change=on_change_environmental_params|label=Region|>
|region>
|>

<|{selected_environmental_scenario}|environmental_scenario|on_submission_change=on_environmental_scenario_submission_change|not expanded|>

---------------------------------------

## **Environmental Metrics**{: .color-primary} and Trends

<|{selected_environmental_scenario.result.read() if selected_environmental_scenario and selected_environmental_scenario.result.read() is not None else default_environmental_result}|chart|x=Date|y[1]=Air Quality Index|y[2]=Water Purity Level|type[1]=line|title=Environmental Conditions|>

<|Data Nodes|expandable|
<|1 5|layout|
<|{selected_data_node}|data_node_selector|>

<|{selected_data_node}|data_node|>
|>
|>

|environmental_scenario>
|>


if __name__ == "__main__":
    # Initialize with custom sector-related values
    topic = "Healthcare"
    mood = "healthtech"
    style = "healthcarepro"

    # Create a GUI page with custom settings
    page = """
    <|container|
    # **Generate**{: .color-primary} Healthcare Tweets

    This mini-app generates Tweets related to Healthcare using OpenAI's GPT-3 based [Davinci model](https://beta.openai.com/docs/models/overview) for texts and [DALL·E](https://beta.openai.com/docs/guides/images) for images. You can find the code on [GitHub](https://github.com/Avaiga/demo-tweet-generation) and the original author on [Twitter](https://twitter.com/kinosal).

    <|layout|columns=1 1 1|gap=30px|class_name=card|
    <topic|
    ## **Topic**{: .color-primary} (or hashtag)

    <|{topic}|input|label=Healthcare Topic (or hashtag)|>
    |topic>

    <mood|
    ## **Mood**{: .color-primary}

    <|{mood}|input|label=Mood (e.g. healthtech, medicalresearch, healthcareinnovation) (optional)|>
    |mood>


from taipy.gui import Gui
import pandas as pd
import matplotlib.pyplot as plt
import io

csv_data = pd.DataFrame()
csv_path = ""

def csv_upload_plot(state):
    if state.csv_path:
        state.csv_data = pd.read_csv(state.csv_path)
        plt.figure()
        state.csv_data.plot(kind='line')
        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        state.plot_image = buf.read()

csv_plot_page = """
<|{csv_path}|file_selector|accept=.csv|on_action=csv_upload_plot|>
<|{plot_image}|image|>
"""

Gui(csv_plot_page).run()


<|layout|columns=2 9|gap=50px|
<sidebar|sidebar|
**Weather Forecast** Setup

<|{selected_weather_forecast}|weather_forecast_selector|>
|sidebar>

<weather_forecast|part|render={selected_weather_forecast}|
# **Weather Prediction**{: .color-primary} page

<|1 1|layout|
<date|
#### Forecast **Date**{: .color-primary}

<|{forecast_date}|date|on_change=on_change_weather_params|>
|date>

<location|
#### **Location**{: .color-primary} for Forecast

<|{selected_location}|selector|lov={selector_location}|dropdown|on_change=on_change_weather_params|label=Location|>
|location>
|>

<|{selected_weather_forecast}|weather_forecast|on_submission_change=on_submission_change_weather|not expanded|>

---------------------------------------

## **Weather Predictions**{: .color-primary} and Data Analysis

<|{selected_weather_forecast.result.read() if selected_weather_forecast and selected_weather_forecast.result.read() is not None else default_weather_result}|chart|x=Date|y[1]=Temperature|y[2]=Humidity|y[3]=Precipitation|type[1]=line|title=Weather Forecast|>

<|Data Nodes|expandable|
<|1 5|layout|
<|{selected_data_node}|data_node_selector|>

<|{selected_data_node}|data_node|>
|>
|>

|weather_forecast>
|>


<|{all_books}|table|columns={book_columns}|width='100%'|on_action={on_book_select}|style=book_style|>
<|Add Book|button|on_action={open_add_book_dialog}|>
<|Refresh Books|button|on_action={refresh_book_list}|>

<|{show_add_book_dialog}|dialog|title=Add New Book|
<|{book_title}|input|placeholder='Title'|
<|{book_author}|input|placeholder='Author'|
<|{book_genre}|selector|lov={get_all_genres()}|>
<|Add Book|button|on_action={add_book}|>
<|Cancel|button|on_action={close_add_book_dialog}|>
|>

<|{show_book_details}|pane|

# Book Details <|Edit|button|on_action=edit_selected_book|> <|Remove|button|on_action=remove_selected_book|>

<|layout|columns=1|
<|part|class_name=card|
## Title
<|{selected_book.title}|>
|>

<|part|class_name=card|
## Author
<|{selected_book.author}|>
|>

<|part|class_name=card|
## Genre
<|{selected_book.genre}|>
|>

<|part|class_name=card|
## ISBN
<|{selected_book.isbn}|>
|>

----
|>


if __name__ == "__main__":
    # Initialize with custom sector-related values
    topic = "Transportation"
    mood = "travel"
    style = "transitexpert"

    # Create a GUI page with custom settings
    page = """
    <|container|
    # **Generate**{: .color-primary} Transportation Tweets

    This mini-app generates Tweets related to Transportation using OpenAI's GPT-3 based [Davinci model](https://beta.openai.com/docs/models/overview) for texts and [DALL·E](https://beta.openai.com/docs/guides/images) for images. You can find the code on [GitHub](https://github.com/Avaiga/demo-tweet-generation) and the original author on [Twitter](https://twitter.com/kinosal).

    <|layout|columns=1 1 1|gap=30px|class_name=card|
    <topic|
    ## **Topic**{: .color-primary} (or hashtag)

    <|{topic}|input|label=Transportation Topic (or hashtag)|>
    |topic>

    <mood|
    ## **Mood**{: .color-primary}

    <|{mood}|input|label=Mood (e.g. travel, transit, journeys) (optional)|>
    |mood>


# **Worldwide**{: .color-primary} Energy Consumption

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Total Energy Consumption**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_energy_consumption['Total Energy']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|card|
**Renewable Energy Consumption**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_energy_consumption['Renewable Energy']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|part|class_name=card|
**Fossil Fuel Consumption**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_energy_consumption['Fossil Fuels']))).replace(',', ' ')}|text|class_name=h2|>
|>
|>

<|{selected_energy_consumption_metric}|toggle|lov={energy_consumption_metric_selector}|>

<|part|render={selected_energy_consumption_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_world_energy_consumption_pie_absolute}|chart|type=pie|labels=Country|values=Total Energy|title=Global Energy Consumption|>

<|{data_world_energy_consumption_evolution_absolute}|chart|properties={data_world_energy_consumption_evolution_properties}|title=Energy Consumption Trends Worldwide|>
|>
|>

<|part|render={selected_energy_consumption_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_world_energy_consumption_pie_relative}|chart|type=pie|labels=Country|values=Renewable Energy|>

<|{data_world_energy_consumption_evolution_relative}|chart|properties={data_world_energy_consumption_evolution_relative_properties}|>
|>
|>


from taipy import Gui
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

WINDOW_SIZE = 500

cm = plt.cm.get_cmap("viridis")

def generate_mandelbrot(
    center: int = WINDOW_SIZE / 2,
    dx_range: int = 1000,
    dx_start: float = -0.12,
    dy_range: float = 1000,
    dy_start: float = -0.82,
    iterations: int = 50,
    max_value: int = 200,
    i: int = 0,
) -> str:
    mat = np.zeros((WINDOW_SIZE, WINDOW_SIZE))
    for y in range(WINDOW_SIZE):
        for x in range(WINDOW_SIZE):
            dx = (x - center) / dx_range + dx_start
            dy = (y - center) / dy_range + dy_start
            a = dx
            b = dy
            for t in range(iterations):
                d = (a * a) - (b * b) + dx
                b = 2 * (a * b) + dy
                a = d
                h = d > max_value
                if h is True:
                    mat[x, y] = t

    colored_mat = cm(mat / mat.max())
    im = Image.fromarray((colored_mat * 255).astype(np.uint8))
    path = f"mandelbrot_{i}.png"
    im.save(path)

    return path

def generate(state):
    state.i = state.i + 1
    state.path = generate_mandelbrot(
        dx_start=-state.dx_start / 100,
        dy_start=(state.dy_start - 100) / 100,
        iterations=state.iterations,
        i=state.i,
    )

i =


from taipy import Gui
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

WINDOW_SIZE = 500

cm = plt.cm.get_cmap("viridis")

def generate_mandelbrot(
    center: int = WINDOW_SIZE / 2,
    dx_range: int = 1000,
    dx_start: float = -0.12,
    dy_range: float = 1000,
    dy_start: float = -0.82,
    iterations: int = 50,
    max_value: int = 200,
    i: int = 0,
) -> str:
    mat = np.zeros((WINDOW_SIZE, WINDOW_SIZE))
    for y in range(WINDOW_SIZE):
        for x in range(WINDOW_SIZE):
            dx = (x - center) / dx_range + dx_start
            dy = (y - center) / dy_range + dy_start
            a = dx
            b = dy
            for t in range(iterations):
                d = (a * a) - (b * b) + dx
                b = 2 * (a * b) + dy
                a = d
                h = d > max_value
                if h is True:
                    mat[x, y] = t

    colored_mat = cm(mat / mat.max())
    im = Image.fromarray((colored_mat * 255).astype(np.uint8))
    path = f"mandelbrot_{i}.png"
    im.save(path)

    return path

def generate(state):
    state.i = state.i + 1
    state.path = generate_mandelbrot(
        dx_start=-state.dx_start / 100,
        dy_start=(state.dy_start - 100) / 100,
        iterations=state.iterations,
        i=state.i,
    )

i = 0
dx_start = 11
dy_start = 17
iterations = 50

path = generate_mandelbrot(
    dx_start=-dx_start / 100,
    dy_start=(dy_start - 100) / 100,
)

page = """
# Mandelbrot Fractal for Automotive Visualization

<|layout|columns=35 65|
Visualize Complex Patterns with Mandelbrot Fractals
<|{path}|image|width=500px|height=500px|class_name=img|>

Iterations:

Select the number of iterations to explore fractal patterns
<|{iterations}|slider|min=10|max=50|continuous=False|on_change=generate|>

X Position:

<|{dy_start}|slider|min=0|max=100|continuous=False|on_change=generate|>

Y Position:

Slider dx_start
<|{dx_start}|slider|min=0|max=100|continuous=False|on_change=generate|>

|>
"""

Gui(page).run(title="Mandelbrot Fractal for Automotive Visualization")


<|{all_fitness_classes}|table|columns={fitness_class_columns}|width='100%'|on_action={on_fitness_class_select}|style=fitness_class_style|>
<|Schedule Fitness Class|button|on_action={open_schedule_fitness_class_dialog}|>
<|Refresh Classes|button|on_action={refresh_fitness_classes}|>

<|{show_schedule_fitness_class_dialog}|dialog|title=Schedule Fitness Class|
<|{class_type}|selector|lov={get_all_class_types()}|>
<|{class_instructor}|input|placeholder='Instructor Name'|
<|{class_time}|time_picker|>
<|Schedule Class|button|on_action={schedule_fitness_class}|>
<|Cancel|button|on_action={close_schedule_fitness_class_dialog}|>
|>

<|{show_fitness_class_details}|pane|

# Class Details <|Edit|button|on_action=edit_selected_class|> <|Cancel|button|on_action=cancel_selected_class|>

<|layout|columns=1|
<|part|class_name=card|
## Class Type
<|{selected_fitness_class.type}|>
|>

<|part|class_name=card|
## Instructor
<|{selected_fitness_class.instructor}|>
|>

<|part|class_name=card|
## Time
<|{selected_fitness_class.time.strftime("%H:%M")}|>
|>

----
|>


# **Global**{: .color-primary} Digital Connectivity

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Internet Connectivity Rate**{: .color-primary}
<|{'{:.2f}%'.format(np.average(data_world_digital['Connectivity Rate']))}|text|class_name=h2|>
|>

<|card|
**Smart Device Usage**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_digital['Smart Devices']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|part|class_name=card|
**Broadband Subscriptions**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_digital['Broadband Subscriptions']))).replace(',', ' ')}|text|class_name=h2|>
|>
|>

<|{selected_digital_metric}|toggle|lov={digital_metric_selector}|>

<|part|render={selected_digital_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_world_digital_pie_absolute}|chart|type=pie|labels=Country|values=Connectivity Rate|title=Global Internet Connectivity|>

<|{data_world_digital_evolution_absolute}|chart|properties={data_world_digital_evolution_properties}|title=Digital Connectivity Trends|>
|>
|>

<|part|render={selected_digital_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_world_digital_pie_relative}|chart|type=pie|labels=Country|values=Smart Devices|>

<|{data_world_digital_evolution_relative}|chart|properties={data_world_digital_evolution_relative_properties}|>
|>
|>


if __name__ == "__main__":
    # Initialize with custom sector-related values
    topic = "Automotive"
    mood = "automotivenews"
    style = "automotivepro"

    # Create a GUI page with custom settings
    page = """
    <|container|
    # **Generate**{: .color-primary} Automotive Tweets

    This mini-app generates Tweets related to Automotive using OpenAI's GPT-3 based [Davinci model](https://beta.openai.com/docs/models/overview) for texts and [DALL·E](https://beta.openai.com/docs/guides/images) for images. You can find the code on [GitHub](https://github.com/Avaiga/demo-tweet-generation) and the original author on [Twitter](https://twitter.com/kinosal).

    <|layout|columns=1 1 1|gap=30px|class_name=card|
    <topic|
    ## **Topic**{: .color-primary} (or hashtag)

    <|{topic}|input|label=Automotive Topic (or hashtag)|>
    |topic>

    <mood|
    ## **Mood**{: .color-primary}

    <|{mood}|input|label=Mood (e.g. automotivenews, carreviews, automotiveinnovation) (optional)|>
    |mood>


from taipy import Gui
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

WINDOW_SIZE = 500

cm = plt.cm.get_cmap("viridis")

def generate_mandelbrot(
    center: int = WINDOW_SIZE / 2,
    dx_range: int = 1000,
    dx_start: float = -0.12,
    dy_range: float = 1000,
    dy_start: float = -0.82,
    iterations: int = 50,
    max_value: int = 200,
    i: int = 0,
) -> str:
    mat = np.zeros((WINDOW_SIZE, WINDOW_SIZE))
    for y in range(WINDOW_SIZE):
        for x in range(WINDOW_SIZE):
            dx = (x - center) / dx_range + dx_start
            dy = (y - center) / dy_range + dy_start
            a = dx
            b = dy
            for t in range(iterations):
                d = (a * a) - (b * b) + dx
                b = 2 * (a * b) + dy
                a = d
                h = d > max_value
                if h is True:
                    mat[x, y] = t

    colored_mat = cm(mat / mat.max())
    im = Image.fromarray((colored_mat * 255).astype(np.uint8))
    path = f"mandelbrot_{i}.png"
    im.save(path)

    return path

def generate(state):
    state.i = state.i + 1
    state.path = generate_mandelbrot(
        dx_start=-state.dx_start / 100,
        dy_start=(state.dy_start - 100) / 100,
        iterations=state.iterations,
        i=state.i,
    )

i = 0
dx_start = 11
dy_start = 17
iterations = 50

path = generate_mandelbrot(
    dx_start=-dx_start / 100,
    dy_start=(dy_start - 100) / 100,
)

page = """
# Mandelbrot Fractal for Logistics Visualization

<|layout|columns=35 65|
Visualize Complex Patterns with Mandelbrot Fractals
<|{path}|image|width=500px|height=500px|class_name=img|>

Iterations:

Select the number of iterations to explore fractal patterns
<|{iterations}|slider|min=10|max=50|continuous=False|on_change=generate|>

X Position:

<|{dy_start}|slider|min=0|max=100|continuous=False|on_change=generate|>

Y Position:

Slider dx_start
<|{dx_start}|slider|min=0|max=100|continuous=False|on_change=generate|>

|>
"""

Gui(page).run(title="Mandelbrot Fractal for Logistics Visualization")


# **Country**{: .color-primary} Population Growth

<|layout|columns=1 1 1|
<|{selected_country_population}|selector|lov={selector_country_population}|on_change=on_change_country_population|dropdown|label=Country|>

<|{selected_population_metric}|toggle|lov={population_metric_selector}|on_change=update_population_metric|>
|>

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Total Population**{: .color-primary}
<|{'{:,}'.format(int(population_data.iloc[-1]['Total Population']))}|text|class_name=h2|>
|>

<|card|
**Urban Population**{: .color-primary}
<|{'{:,}'.format(int(population_data.iloc[-1]['Urban Population']))}|text|class_name=h2|>
|>

<|card|
**Rural Population**{: .color-primary}
<|{'{:,}'.format(int(population_data.iloc[-1]['Rural Population']))}|text|class_name=h2|>
|>
|>

<|layout|columns=2 1|
<|{population_data}|chart|type=bar|x=Year|y[3]=Total Population|y[2]=Urban Population|y[1]=Rural Population|layout={layout}|options={options}|title=Population Trends|>

<|{population_distribution_chart}|chart|type=pie|values=distribution_values|labels=distribution_labels|title=Urban vs Rural Population|>
|>


# **Stock**{: .color-primary} Market Overview

<|layout|columns=1 1 1|
<|{selected_stock}|selector|lov={selector_stock}|on_change=on_change_stock|dropdown|label=Stock|>

<|{selected_indicator}|toggle|lov={indicator_selector}|on_change=update_indicator_display|>
|>

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Market Value**{: .color-primary}
<|{'${:,.2f}'.format(stock_data.iloc[-1]['Market Value'])}|text|class_name=h2|>
|>

<|card|
**Volume**{: .color-primary}
<|{'{:,}'.format(stock_data.iloc[-1]['Volume'])}|text|class_name=h2|>
|>

<|card|
**Change (%)**{: .color-primary}
<|{'{:+.2f}%'.format(stock_data.iloc[-1]['Change'])}|text|class_name=h2|>
|>
|>

<|layout|columns=2 1|
<|{stock_data}|chart|type=line|x=Date|y[3]=Market Value|y[2]=Volume|y[1]=Change|layout={layout}|options={options}|title=Stock Performance|>

<|{sector_distribution_chart}|chart|type=pie|values=sector_values|labels=sector_labels|title=Market Sector Distribution|>
|>


from taipy.gui import Gui
import pandas as pd

# Load the sales data
df = pd.read_excel(
    io="data/supermarkt_sales.xlsx",
    engine="openpyxl",
    sheet_name="Sales",
    skiprows=3,
    usecols="B:R",
    nrows=1000,
)

# Add 'hour' column to the dataframe
df["hour"] = pd.to_datetime(df["Time"], format="%H:%M:%S").dt.hour

# Initialize variables
cities = list(df["City"].unique())
types = list(df["Customer_type"].unique())
genders = list(df["Gender"].unique())
city = cities
customer_type = types
gender = genders

layout = {"margin": {"l": 220}}

# Markdown for the entire page
page = """<|toggle|theme|>

<|layout|columns=20 80|gap=30px|
<sidebar|
## Please **filter**{: .orange} here:

<|{city}|selector|lov={cities}|multiple|label=Select the City|dropdown|on_change=on_filter|width=100%|>

<|{customer_type}|selector|lov={types}|multiple|label=Select the Customer Type|dropdown|on_change=on_filter|width=100%|>

<|{gender}|selector|lov={genders}|multiple|label=Select the Gender|dropdown|on_change=on_filter|width=100%|>
|sidebar>

<main_page|
# 📊 **Sales**{: .orange} Dashboard

<|layout|columns=1 1 1|
<total_sales|
## **Total**{: .orange} sales:
### US $ <|{int(df_selection["Total"].sum())}|>
|total_sales>

<average_rating|
## **Average**{: .orange} Rating:
### <|{round(df_selection["Rating"].mean(), 1)}|> <|{"⭐" * int(round(round(df_selection["Rating"].mean(), 1), 0))}|>
|average_rating>

<average_sale|
## Average Sales Per **Transaction**{: .orange}:
### US $ <|{round(df_selection["Total"].mean(), 2)}|>
|average_sale>
|>

<br/>

Display df_selection in an expandable
<|Sales Table|expandable|expanded=False|
<|{df_selection}|table|width=100%|page_size=5|rebuild|class_name=table|>
|>

<charts|
<|{sales_by_hour}|chart|x=Hour|y=Total|type=bar|title=Sales by Hour|color=#ff462b|>

<|{sales_by_product_line}|chart|x=Total|y=Product|type=bar|orientation=h|title=Sales by Product|layout={layout}|color=#ff462b|>
|charts>
|main_page>
|>

Code from [Coding is Fun](https://github.com/Sven-Bo)

Get the Taipy Code [here](https://github.com/Avaiga/demo-sales-dashboard) and the original code [here](https://github.com/Sven-Bo/streamlit-sales-dashboard)
"""

def filter(city, customer_type, gender):
    df_selection = df[
        df["City"].isin(city)
        & df["Customer_type"].isin(customer_type)
        & df["Gender"].isin(gender)
    ]

    # SALES BY PRODUCT LINE [BAR CHART]
    sales_by_product_line = (
        df_selection[["Product line", "Total"]]
        .groupby(by=["Product line"])
        .sum()[["Total"]]
        .sort_values(by="Total")
    )
    sales_by_product_line["Product"] = sales_by_product_line.index

    # SALES BY HOUR [BAR CHART]
    sales_by_hour = (
        df_selection[["hour", "Total"]].groupby(by=["hour"]).sum()[["Total"]]
    )
    sales_by_hour["Hour"] = sales_by_hour.index
    return df_selection, sales_by_product_line, sales_by_hour

def on_filter(state):
    state.df_selection, state.sales_by_product_line, state.sales_by_hour = filter(
        state.city, state.customer_type, state.gender
    )

if __name__ == "__main__":
    # Initialize dataframes
    df_selection, sales_by_product_line, sales_by_hour = filter(
        city, customer_type, gender
    )

    # Run the app
    Gui(page).run()


# **Country**{: .color-primary} Health Indicators

<|layout|columns=1 1 1|
<|{selected_country_health}|selector|lov={selector_country_health}|on_change=on_change_country_health|dropdown|label=Country|>

<|{selected_health_metric}|toggle|lov={health_metric_selector}|on_change=update_health_metric_display|>
|>

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Life Expectancy**{: .color-primary}
<|{'{:.2f}'.format(health_data.iloc[-1]['Life Expectancy'])}|text|class_name=h2|>
|>

<|card|
**Infant Mortality Rate**{: .color-primary}
<|{'{:.2f}'.format(health_data.iloc[-1]['Infant Mortality'])}|text|class_name=h2|>
|>

<|card|
**Healthcare Expenditure**{: .color-primary}
<|{'${:,.2f}'.format(health_data.iloc[-1]['Expenditure'])}|text|class_name=h2|>
|>
|>

<|layout|columns=2 1|
<|{health_data}|chart|type=line|x=Year|y[3]=Life Expectancy|y[2]=Infant Mortality|y[1]=Expenditure|layout={layout}|options={options}|title=Healthcare Trends|>

<|{healthcare_distribution_chart}|chart|type=pie|values=healthcare_values|labels=healthcare_labels|title=Healthcare Distribution|>
|>


# **Worldwide**{: .color-primary} Space Exploration

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Space Missions**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_space['Missions']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|card|
**Satellites Launched**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_world_space['Satellites']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|part|class_name=card|
**Budget for Space Programs**{: .color-primary}
<|{'${:,.2f}'.format(np.sum(data_world_space['Budget']))}|text|class_name=h2|>
|>
|>

<|{selected_space_metric}|toggle|lov={space_metric_selector}|>

<|part|render={selected_space_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_world_space_pie_absolute}|chart|type=pie|labels=Country|values=Missions|title=Global Space Missions|>

<|{data_world_space_evolution_absolute}|chart|properties={data_world_space_evolution_properties}|title=Space Exploration Trends|>
|>
|>

<|part|render={selected_space_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_world_space_pie_relative}|chart|type=pie|labels=Country|values=Satellites|>

<|{data_world_space_evolution_relative}|chart|properties={data_world_space_evolution_relative_properties}|>
|>
|>


if __name__ == "__main__":
    # Initialize with custom sector-related values
    topic = "Education"
    mood = "educational"
    style = "educationexpert"

    # Create a GUI page with custom settings
    page = """
    <|container|
    # **Generate**{: .color-primary} Education Tweets

    This mini-app generates Tweets related to Education using OpenAI's GPT-3 based [Davinci model](https://beta.openai.com/docs/models/overview) for texts and [DALL·E](https://beta.openai.com/docs/guides/images) for images. You can find the code on [GitHub](https://github.com/Avaiga/demo-tweet-generation) and the original author on [Twitter](https://twitter.com/kinosal).

    <|layout|columns=1 1 1|gap=30px|class_name=card|
    <topic|
    ## **Topic**{: .color-primary} (or hashtag)

    <|{topic}|input|label=Education Topic (or hashtag)|>
    |topic>

    <mood|
    ## **Mood**{: .color-primary}

    <|{mood}|input|label=Mood (e.g. educational, informative, learning) (optional)|>
    |mood>


from taipy.gui import Gui
import taipy as tp

# Import pages for the energy sector
from pages.energy.dashboard import dashboard_md
from pages.energy.consumption import consumption_md
from pages.energy.production import production_md
from pages.energy.renewables import renewables_md

# Define your pages dictionary
pages = {
    '/dashboard': dashboard_md,
    '/consumption': consumption_md,
    '/production': production_md,
    '/renewables': renewables_md
}

# Create a Gui with your pages
gui_energy = Gui(pages=pages)

if __name__ == '__main__':
    tp.Core().run()

    # Run the multi-page app
    gui_energy.run(title="Energy Dashboard")


<|layout|columns=2 9|gap=50px|
<sidebar|sidebar|
**Traffic Analysis** Setup

<|{selected_traffic_scenario}|traffic_scenario_selector|>
|sidebar>

<traffic_scenario|part|render={selected_traffic_scenario}|
# **Traffic Flow Prediction**{: .color-primary} page

<|1 1|layout|
<date|
#### Prediction **Date**{: .color-primary}

<|{prediction_date}|date|on_change=on_change_traffic_params|>
|date>

<area|
#### **Area**{: .color-primary} of Prediction

<|{selected_area}|selector|lov={selector_area}|dropdown|on_change=on_change_traffic_params|label=Area|>
|area>
|>

<|{selected_traffic_scenario}|traffic_scenario|on_submission_change=on_traffic_scenario_submission_change|not expanded|>

---------------------------------------

## **Traffic Predictions**{: .color-primary} and Data Visualization

<|{selected_traffic_scenario.result.read() if selected_traffic_scenario and selected_traffic_scenario.result.read() is not None else default_traffic_result}|chart|x=Time|y[1]=Vehicle Count|y[2]=Congestion Level|type[1]=line|title=Traffic Forecast|>

<|Data Nodes|expandable|
<|1 5|layout|
<|{selected_data_node}|data_node_selector|>

<|{selected_data_node}|data_node|>
|>
|>

|traffic_scenario>
|>


# **City**{: .color-primary} Urban Development Index

<|layout|columns=1 1 1|
<|{selected_city_development}|selector|lov={selector_city_development}|on_change=on_change_city_development|dropdown|label=City|>

<|{selected_development_aspect}|toggle|lov={development_aspect_selector}|on_change=update_development_aspect_display|>
|>

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Population Growth**{: .color-primary}
<|{'{:.2f}%'.format(development_data.iloc[-1]['Population Growth'])}|text|class_name=h2|>
|>

<|card|
**Infrastructure Rating**{: .color-primary}
<|{'{:.2f}'.format(development_data.iloc[-1]['Infrastructure'])}|text|class_name=h2|>
|>

<|card|
**Economic Activity**{: .color-primary}
<|{'{:.2f}'.format(development_data.iloc[-1]['Economic Activity'])}|text|class_name=h2|>
|>
|>

<|layout|columns=2 1|
<|{development_data}|chart|type=bar|x=Year|y[3]=Population Growth|y[2]=Infrastructure|y[1]=Economic Activity|layout={layout}|options={options}|title=Urban Development Trends|>

<|{development_aspect_chart}|chart|type=pie|values=development_aspect_values|labels=development_aspect_labels|title=Aspect Distribution|>
|>


<|layout|columns=2 9|gap=50px|
<sidebar|sidebar|
**Performance Analysis** Setup

<|{selected_educational_scenario}|educational_scenario_selector|>
|sidebar>

<educational_scenario|part|render={selected_educational_scenario}|
# **Student Performance Prediction**{: .color-primary} page

<|1 1|layout|
<date|
#### Analysis **Date**{: .color-primary}

<|{analysis_date}|date|on_change=on_change_educational_params|>
|date>

<school|
#### **School**{: .color-primary} for Analysis

<|{selected_school}|selector|lov={selector_school}|dropdown|on_change=on_change_educational_params|label=School|>
|school>
|>

<|{selected_educational_scenario}|educational_scenario|on_submission_change=on_educational_scenario_submission_change|not expanded|>

---------------------------------------

## **Student Performance Trends**{: .color-primary} and Insights

<|{selected_educational_scenario.result.read() if selected_educational_scenario and selected_educational_scenario.result.read() is not None else default_educational_result}|chart|x=Subject|y[1]=Average Score|y[2]=Grade Level|type[1]=bar|title=Academic Performance|>

<|Data Nodes|expandable|
<|1 5|layout|
<|{selected_data_node}|data_node_selector|>

<|{selected_data_node}|data_node|>
|>
|>

|educational_scenario>
|>


<|layout|columns=1 1|
<|part|class_name=card|
### Select Patient Group

<|{patient_group_selected}|selector|lov=group_diabetes;group_cardio;group_respiratory|dropdown|on_change=on_patient_group_change|>
|>

<|part|class_name=card|
### Select Comparison Group

<|{comparison_group_selected}|selector|lov=group_diabetes;group_cardio;group_respiratory|dropdown|on_change=on_comparison_group_change|>
|>

|>

<|Patient Data Overview|expandable|expanded=True|
Display patient_group_data and comparison_group_data
<|layout|columns=1 1|
<|{patient_group_data}|table|page_size=5|>

<|{comparison_group_data}|table|page_size=5|>
|>
|>

<|layout|columns=1 1|
<|part|class_name=card|
<|{age_distribution_chart}|chart|type=bar|x=Age Group|y=Patients|title=Age Distribution|>
|>

<|part|class_name=card|
<|{disease_prevalence_chart}|chart|type=pie|options={disease_options}|


if __name__ == "__main__":
    # Initialize with custom sector-related values
    topic = "Logistics"
    mood = "supplychain"
    style = "logisticsexpert"

    # Create a GUI page with custom settings
    page = """
    <|container|
    # **Generate**{: .color-primary} Logistics Tweets

    This mini-app generates Tweets related to Logistics using OpenAI's GPT-3 based [Davinci model](https://beta.openai.com/docs/models/overview) for texts and [DALL·E](https://beta.openai.com/docs/guides/images) for images. You can find the code on [GitHub](https://github.com/Avaiga/demo-tweet-generation) and the original author on [Twitter](https://twitter.com/kinosal).

    <|layout|columns=1 1 1|gap=30px|class_name=card|
    <topic|
    ## **Topic**{: .color-primary} (or hashtag)

    <|{topic}|input|label=Logistics Topic (or hashtag)|>
    |topic>

    <mood|
    ## **Mood**{: .color-primary}

    <|{mood}|input|label=Mood (e.g. supplychain, shipping, logistics) (optional)|>
    |mood>


<|layout|columns=1 1|
<|part|class_name=card|
### Select Team

<|{team_selected}|selector|lov=team_lakers;team_warriors;team_celtics|dropdown|on_change=on_team_change|>
|>

<|part|class_name=card|
### Select Season

<|{season_selected}|selector|lov=season_2020;season_2021;season_2022|dropdown|on_change=on_season_change|>
|>

|>

<|Team Performance Overview|expandable|expanded=True|
Display team_data and season_data
<|layout|columns=1 1|
<|{team_data}|table|page_size=5|>

<|{season_data}|table|page_size=5|>
|>
|>

<|layout|columns=1 1|
<|part|class_name=card|
<|{player_stats_chart}|chart|type=bar|x=Player|y=Points|title=Player Performance|>
|>

<|part|class_name=card|
<|{win_loss_chart}|chart|type=line|x=Game|y=Win/Loss|title=Win-Loss Record|>
|>
|>

### Analyze Team Dynamics:
<|{team_dynamics_analysis}|scenario|on_submission_change=on_team_dynamics_status_change|expandable=False|expanded=False|>

<|{team_dynamics_analysis}|scenario_dag|>

### View team dynamics results:
<|{team_dynamics_analysis.results if team_dynamics_analysis else None}|data_node|>


if __name__ == "__main__":
    # Initialize with custom sector-related values
    topic = "Technology"
    mood = "innovative"
    style = "techgiant"

    # Create a GUI page with custom settings
    page = """
    <|container|
    # **Generate**{: .color-primary} Technology Tweets

    This mini-app generates Tweets related to Technology using OpenAI's GPT-3 based [Davinci model](https://beta.openai.com/docs/models/overview) for texts and [DALL·E](https://beta.openai.com/docs/guides/images) for images. You can find the code on [GitHub](https://github.com/Avaiga/demo-tweet-generation) and the original author on [Twitter](https://twitter.com/kinosal).

    <|layout|columns=1 1 1|gap=30px|class_name=card|
    <topic|
    ## **Topic**{: .color-primary} (or hashtag)

    <|{topic}|input|label=Technology Topic (or hashtag)|>
    |topic>

    <mood|
    ## **Mood**{: .color-primary}

    <|{mood}|input|label=Mood (e.g. innovative, futuristic, informative) (optional)|>
    |mood>


# **Global**{: .color-primary} Environmental Statistics

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Carbon Emissions**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_global_environment['Emissions']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|card|
**Deforestation**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_global_environment['Deforestation']))).replace(',', ' ')}|text|class_name=h2|>
|>

<|part|class_name=card|
**Renewable Energy Usage**{: .color-primary}
<|{'{:,}'.format(int(np.sum(data_global_environment['Renewable Energy']))).replace(',', ' ')}|text|class_name=h2|>
|>
|>

<|{selected_metric}|toggle|lov={metric_selector}|>

<|part|render={selected_metric=='Absolute'}|
<|layout|columns=1 2|
<|{data_global_pie_absolute}|chart|type=pie|labels=Country|values=Emissions|title=Emissions Distribution Worldwide|>

<|{data_global_environment_evolution_absolute}|chart|properties={data_global_environment_evolution_properties}|title=Environmental Trends Worldwide|>
|>
|>

<|part|render={selected_metric=='Relative'}|
<|layout|columns=1 2|
<|{data_global_pie_relative}|chart|type=pie|labels=Country|values=Deforestation|>

<|{data_global_environment_evolution_relative}|chart|properties={data_global_environment_evolution_relative_properties}|>
|>
|>


from taipy.gui import Gui
import open3d as o3d
import numpy as np

model_data = None
model_path = ""

def model_upload_view(state):
    if state.model_path:
        model = o3d.io.read_triangle_mesh(state.model_path)
        state.model_data = np.asarray(model.vertices)

model_view_page = """
<|{model_path}|file_selector|accept=.ply,.stl|on_action=model_upload_view|>
<|{model_data}|viewer3d|>
"""

Gui(model_view_page).run()


from taipy import Gui
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

WINDOW_SIZE = 500

cm = plt.cm.get_cmap("viridis")

def generate_mandelbrot(
    center: int = WINDOW_SIZE / 2,
    dx_range: int = 1000,
    dx_start: float = -0.12,
    dy_range: float = 1000,
    dy_start: float = -0.82,
    iterations: int = 50,
    max_value: int = 200,
    i: int = 0,
) -> str:
    mat = np.zeros((WINDOW_SIZE, WINDOW_SIZE))
    for y in range(WINDOW_SIZE):
        for x in range(WINDOW_SIZE):
            dx = (x - center) / dx_range + dx_start
            dy = (y - center) / dy_range + dy_start
            a = dx
            b = dy
            for t in range(iterations):
                d = (a * a) - (b * b) + dx
                b = 2 * (a * b) + dy
                a = d
                h = d > max_value
                if h is True:
                    mat[x, y] = t

    colored_mat = cm(mat / mat.max())
    im = Image.fromarray((colored_mat * 255).astype(np.uint8))
    path = f"mandelbrot_{i}.png"
    im.save(path)

    return path

def generate(state):
    state.i = state.i + 1
    state.path = generate_mandelbrot(
        dx_start=-state.dx_start / 100,
        dy_start=(state.dy_start - 100) / 100,
        iterations=state.iterations,
        i=state.i,
    )

i = 0
dx_start = 11
dy_start = 17
iterations = 50

path = generate_mandelbrot(
    dx_start=-dx_start / 100,
    dy_start=(dy_start - 100) / 100,
)

page = """
# Mandelbrot Fractal for Financial Visualization

<|layout|columns=35 65|
Visualize Complex Patterns with Mandelbrot Fractals
<|{path}|image|width=500px|height=500px|class_name=img|>

Iterations:

Select the number of iterations to explore fractal patterns
<|{iterations}|slider|min=10|max=50|continuous=False|on_change=generate|>

X Position:

<|{dy_start}|slider|min=0|max=100|continuous=False|on_change=generate|>

Y Position:

Slider dx_start
<|{dx_start}|slider|min=0|max=100|continuous=False|on_change=generate|>

|>
"""

Gui(page).run(title="Mandelbrot Fractal for Financial Visualization")


<|{all_feedback}|table|columns={feedback_columns}|width='100%'|on_action={on_feedback_select}|style=feedback_style|>
<|Add Feedback|button|on_action={open_add_feedback_dialog}|>
<|Refresh Feedback|button|on_action={refresh_feedback_list}|>

<|{show_add_feedback_dialog}|dialog|title=Submit New Feedback|
<|{customer_name}|input|placeholder='Customer Name'|
<|{feedback_content}|textarea|placeholder='Enter feedback here...'|
<|Submit|button|on_action={submit_feedback}|>
<|Cancel|button|on_action={close_add_feedback_dialog}|>
|>

<|{show_feedback_details}|pane|

# Feedback Details <|Archive|button|on_action=archive_selected_feedback|>

<|layout|columns=1|
<|part|class_name=card|
## Customer Name
<|{selected_feedback.customer_name}|>
|>

<|part|class_name=card|
## Feedback
<|{selected_feedback.content}|textarea|disabled=True|>
|>

<|part|class_name=card|
## Submission Date
<|{selected_feedback.date.strftime("%b %d, %Y at %H:%M:%S")}|>
|>

----
|>


from taipy import Gui
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

WINDOW_SIZE = 500

cm = plt.cm.get_cmap("viridis")

def generate_mandelbrot(
    center: int = WINDOW_SIZE / 2,
    dx_range: int = 1000,
    dx_start: float = -0.12,
    dy_range: float = 1000,
    dy_start: float = -0.82,
    iterations: int = 50,
    max_value: int = 200,
    i: int = 0,
) -> str:
    mat = np.zeros((WINDOW_SIZE, WINDOW_SIZE))
    for y in range(WINDOW_SIZE):
        for x in range(WINDOW_SIZE):
            dx = (x - center) / dx_range + dx_start
            dy = (y - center) / dy_range + dy_start
            a = dx
            b = dy
            for t in range(iterations):
                d = (a * a) - (b * b) + dx
                b = 2 * (a * b) + dy
                a = d
                h = d > max_value
                if h is True:
                    mat[x, y] = t

    colored_mat = cm(mat / mat.max())
    im = Image.fromarray((colored_mat * 255).astype(np.uint8))
    path = f"mandelbrot_{i}.png"
    im.save(path)

    return path

def generate(state):
    state.i = state.i + 1
    state.path = generate_mandelbrot(
        dx_start=-state.dx_start / 100,
        dy_start=(state.dy_start - 100) / 100,
        iterations=state.iterations,
        i=state.i,
    )

i = 0
dx_start = 11
dy_start = 17
iterations = 50

path = generate_mandelbrot(
    dx_start=-dx_start / 100,
    dy_start=(dy_start - 100) / 100,
)

page = """
# Mandelbrot Fractal for Sports Visualization

<|layout|columns=35 65|
Visualize Complex Patterns with Mandelbrot Fractals
<|{path}|image|width=500px|height=500px|class_name=img|>

Iterations:

Select the number of iterations to explore fractal patterns
<|{iterations}|slider|min=10|max=50|continuous=False|on_change=generate|>

X Position:

<|{dy_start}|slider|min=0|max=100|continuous=False|on_change=generate|>

Y Position:

Slider dx_start
<|{dx_start}|slider|min=0|max=100|continuous=False|on_change=generate|>

|>
"""

Gui(page).run(title="Mandelbrot Fractal for Sports Visualization")


<|{all_vehicles}|table|columns={vehicle_columns}|width='100%'|on_action={on_vehicle_select}|style=vehicle_style|>
<|Log Maintenance|button|on_action={open_log_maintenance_dialog}|>
<|Refresh Vehicles|button|on_action={refresh_vehicle_list}|>

<|{show_log_maintenance_dialog}|dialog|title=Log Vehicle Maintenance|
<|{vehicle_id}|selector|lov={get_all_vehicle_ids()}|>
<|{maintenance_type}|input|placeholder='Maintenance Type'|
<|{maintenance_date}|date_picker|>
<|Log Maintenance|button|on_action={log_maintenance}|>
<|Cancel|button|on_action={close_log_maintenance_dialog}|>
|>

<|{show_vehicle_details}|pane|

# Vehicle Details <|Edit|button|on_action=edit_selected_vehicle|> <|Remove|button|on_action=remove_selected_vehicle|>

<|layout|columns=1|
<|part|class_name=card|
## Vehicle ID
<|{selected_vehicle.id}|>
|>

<|part|class_name=card|
## Maintenance Type
<|{selected_vehicle.maintenance_type}|>
|>

<|part|class_name=card|
## Maintenance Date
<|{selected_vehicle.maintenance_date.strftime("%b %d, %Y")}|>
|>

----
|>


<|layout|columns=2 9|gap=50px|
<sidebar|sidebar|
**Resource Allocation** Planner

<|{selected_healthcare_scenario}|healthcare_scenario_selector|>
|sidebar>

<healthcare_scenario|part|render={selected_healthcare_scenario}|
# **Resource Distribution**{: .color-primary} page

<|1 1|layout|
<date|
#### Effective **Date**{: .color-primary}

<|{effective_date}|date|on_change=on_change_healthcare_params|>
|date>

<hospital|
#### **Hospital**{: .color-primary} for Allocation

<|{selected_hospital}|selector|lov={selector_hospital}|dropdown|on_change=on_change_healthcare_params|label=Hospital|>
|hospital>
|>

<|{selected_healthcare_scenario}|healthcare_scenario|on_submission_change=on_healthcare_scenario_submission_change|not expanded|>

---------------------------------------

## **Resource Allocation**{: .color-primary} and Analysis

<|{selected_healthcare_scenario.result.read() if selected_healthcare_scenario and selected_healthcare_scenario.result.read() is not None else default_resource_allocation}|chart|x=Resource|y[1]=Allocated|y[2]=Required|type[1]=bar|title=Healthcare Resource Allocation|>

<|Data Nodes|expandable|
<|1 5|layout|
<|{selected_data_node}|data_node_selector|>

<|{selected_data_node}|data_node|>
|>
|>

|healthcare_scenario>
|>


from taipy.gui import Gui
import pandas as pd

# Load inventory data
inventory_data = pd.read_csv("inventory_data.csv")

# Initialize variables
categories = list(inventory_data["Category"].unique())
locations = list(inventory_data["Location"].unique())
category = categories
location = locations

# Markdown for the entire page
page = """<|toggle|theme|>

<|layout|columns=20 80|gap=30px|
<sidebar|
## **Filter**{: .orange} Inventory:

<|{category}|selector|lov={categories}|multiple|label=Select Category|dropdown|on_change=on_filter|width=100%|>

<|{location}|selector|lov={locations}|multiple|label=Select Location|dropdown|on_change=on_filter|width=100%|>
|sidebar>

<main_page|
# Inventory Management System

<|layout|columns=1 1 1|
<total_items|
## Total Items:
### <|{len(df_selection)}|>
|total_items>

<average_price|
## Average Price:
### US $ <|{round(df_selection["Price"].mean(), 2)}|>
|average_price>

<inventory_table|
Display df_selection in an expandable
<|Inventory Table|expandable|expanded=False|
<|{df_selection}|table|width=100%|page_size=10|rebuild|class_name=table|>
|inventory_table>
|main_page>
|>

Code adapted from [Inventory Management](https://github.com/inventory_management_app)

Get the Taipy Code [here](https://github.com/Avaiga/inventory-management-app)


from taipy.gui import Gui
import fitz  # PyMuPDF
import io

pdf_data = None
pdf_path = ""

def pdf_upload(state):
    if state.pdf_path:
        pdf_doc = fitz.open(state.pdf_path)
        page = pdf_doc.load_page(0)  # Display the first page
        state.pdf_data = io.BytesIO(page.get_pixmap().tobytes("png"))

pdf_page = """
<|{pdf_path}|file_selector|accept=.pdf|on_action=pdf_upload|>
<|{pdf_data}|image|>
"""

Gui(pdf_page).run()


# **City**{: .color-primary} Environmental Data

<|layout|columns=1 1 1|
<|{selected_city}|selector|lov={selector_city}|on_change=on_change_city|dropdown|label=City|>

<|{selected_pollutant}|toggle|lov={pollutant_selector}|on_change=update_pollutant_display|>
|>

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Air Quality Index**{: .color-primary}
<|{'{:,}'.format(int(city_data.iloc[-1]['AQI'])).replace(',', ' ')}|text|class_name=h2|>
|>

<|card|
**Pollution Level**{: .color-primary}
<|{city_data.iloc[-1]['Pollution Level']}|text|class_name=h2|>
|>

<|card|
**Temperature**{: .color-primary}
<|{'{:.1f}°C'.format(city_data.iloc[-1]['Temperature'])}|text|class_name=h2|>
|>
|>

<|layout|columns=2 1|
<|{city_data}|chart|type=line|x=Date|y[3]=AQI|y[2]=Pollution Level|y[1]=Temperature|layout={layout}|options={options}|title=Environmental Trends|>

<|{pollution_distribution_chart}|chart|type=pie|values=pollution_values|labels=pollution_labels|title=Pollution Source Distribution|>
|>


if __name__ == "__main__":
    # Initialize with custom sector-related values
    topic = "Finance"
    mood = "financial"
    style = "financialexpert"

    # Create a GUI page with custom settings
    page = """
    <|container|
    # **Generate**{: .color-primary} Finance Tweets

    This mini-app generates Tweets related to Finance using OpenAI's GPT-3 based [Davinci model](https://beta.openai.com/docs/models/overview) for texts and [DALL·E](https://beta.openai.com/docs/guides/images) for images. You can find the code on [GitHub](https://github.com/Avaiga/demo-tweet-generation) and the original author on [Twitter](https://twitter.com/kinosal).

    <|layout|columns=1 1 1|gap=30px|class_name=card|
    <topic|
    ## **Topic**{: .color-primary} (or hashtag)

    <|{topic}|input|label=Finance Topic (or hashtag)|>
    |topic>

    <mood|
    ## **Mood**{: .color-primary}

    <|{mood}|input|label=Mood (e.g. financial, investment, money) (optional)|>
    |mood>


# **City**{: .color-primary} Crime Statistics

<|layout|columns=1 1 1|
<|{selected_city_crime}|selector|lov={selector_city_crime}|on_change=on_change_city_crime|dropdown|label=City|>

<|{selected_crime_type}|toggle|lov={crime_type_selector}|on_change=update_crime_type_display|>
|>

<|layout|columns=1 1 1 1|gap=50px|
<|card|
**Total Crimes**{: .color-primary}
<|{'{:,}'.format(int(crime_data.iloc[-1]['Total']))}|text|class_name=h2|>
|>

<|card|
**Violent Crimes**{: .color-primary}
<|{'{:,}'.format(int(crime_data.iloc[-1]['Violent']))}|text|class_name=h2|>
|>

<|card|
**Property Crimes**{: .color-primary}
<|{'{:,}'.format(int(crime_data.iloc[-1]['Property']))}|text|class_name=h2|>
|>
|>

<|layout|columns=2 1|
<|{crime_data}|chart|type=bar|x=Year|y[3]=Total|y[2]=Violent|y[1]=Property|layout={layout}|options={options}|title=Crime Trends|>

<|{crime_type_distribution_chart}|chart|type=pie|values=crime_type_values|labels=crime_type_labels|title=Crime Type Distribution|>
|>


<|layout|columns=2 9|gap=50px|
<sidebar|sidebar|
**Yield Forecast** Configuration

<|{selected_yield_forecast}|yield_forecast_selector|>
|sidebar>

<yield_forecast|part|render={selected_yield_forecast}|
# **Crop Yield Prediction**{: .color-primary} page

<|1 1|layout|
<date|
#### Forecast **Start Date**{: .color-primary}

<|{forecast_start_date}|date|on_change=on_change_yield_params|>
|date>

<crop|
#### **Crop Type**{: .color-primary} for Forecast

<|{selected_crop_type}|selector|lov={selector_crop_type}|dropdown|on_change=on_change_yield_params|label=Crop Type|>
|crop>
|>

<|{selected_yield_forecast}|yield_forecast|on_submission_change=on_yield_forecast_submission_change|not expanded|>

---------------------------------------

## **Crop Yield Predictions**{: .color-primary} and Data Analysis

<|{selected_yield_forecast.result.read() if selected_yield_forecast and selected_yield_forecast.result.read() is not None else default_yield_result}|chart|x=Date|y[1]=Predicted Yield|y[2]=Historical Yield|type[1]=bar|title=Crop Yield Forecast|>

<|Data Nodes|expandable|
<|1 5|layout|
<|{selected_data_node}|data_node_selector|>

<|{selected_data_node}|data_node|>
|>
|>

|yield_forecast>
|>


<|layout|columns=1 1|
<|part|class_name=card|
### Select Sales Period

<|{sales_period_selected}|selector|lov=period_last_month;period_last_quarter;period_last_year|dropdown|on_change=on_sales_period_change|>
|>

<|part|class_name=card|
### Select Product Category

<|{product_category_selected}|selector|lov=category_electronics;category_clothing;category_home_goods|dropdown|on_change=on_product_category_change|>
|>

|>

<|Sales Data Overview|expandable|expanded=True|
Display sales_data and category_data
<|layout|columns=1 1|
<|{sales_data}|table|page_size=5|>

<|{category_data}|table|page_size=5|>
|>
|>

<|layout|columns=1 1|
<|part|class_name=card|
<|{sales_volume_chart}|chart|type=line|x=Month|y=Sales Volume|title=Monthly Sales Volume|>
|>

<|part|class_name=card|
<|{product_category_chart}|chart|type=pie|options={category_options}|layout={category_layout}|>
|>
|>

### Analyze Sales Performance:
<|{sales_performance}|scenario|on_submission_change=on_sales_performance_status_change|expandable=False|expanded=False|>

<|{sales_performance}|scenario_dag|>

### View the analysis results:
<|{sales_performance.results if sales_performance else None}|data_node|>


#!/usr/bin/env python    """The setup script."""  import json  import os    from setuptools import find_namespace_packages, find_packages, setup    with open("README.md") as readme_file:      readme = readme_file.read()    with open(f"src{os.sep}taipy{os.sep}core{os.sep}version.json") as version_file:      version = json.load(version_file)      version_string = f'{version.get("major", 0)}.{version.get("minor", 0)}.{version.get("patch", 0)}'      if vext := version.get("ext"):          version_string = f"{version_string}.{vext}"    requirements = [      "pyarrow>=10.0.1,<11.0",      "networkx>=2.6,<3.0",      "openpyxl>=3.1.2,<3.2",      "modin[dask]>=0.23.0,<1.0",      "pymongo[srv]>=4.2.0,<5.0",      "sqlalchemy>=2.0.16,<2.1",      "toml>=0.10,<0.11",      "taipy-config@git+https://git@github.com/Avaiga/taipy-config.git@develop",  ]    test_requirements = ["pytest>=3.8"]    extras_require = {      "fastparquet": ["fastparquet==2022.11.0"],      "mssql": ["pyodbc>=4,<4.1"],      "mysql": ["pymysql>1,<1.1"],      "postgresql": ["psycopg2>2.9,<2.10"],  }    setup(      author="Avaiga",      author_email="dev@taipy.io",      python_requires=">=3.8",      classifiers=[          "Intended Audience :: Developers",          "License :: OSI Approved :: Apache Software License",          "Natural Language :: English",          "Programming Language :: Python :: 3",          "Programming Language :: Python :: 3.8",          "Programming Language :: Python :: 3.9",          "Programming Language :: Python :: 3.10",          "Programming Language :: Python :: 3.11",      ],      description="A Python library to build powerful and customized data-driven back-end applications.",      install_requires=requirements,      long_description=readme,      long_description_content_type="text/markdown",      license="Apache License 2.0",      keywords="taipy-core",      name="taipy-core",      package_dir={"": "src"},      packages=find_namespace_packages(where="src") + find_packages(include=["taipy", "taipy.core", "taipy.core.*"]),      include_package_data=True,      test_suite="tests",      tests_require=test_requirements,      url="https://github.com/avaiga/taipy-core",      version=version_string,      zip_safe=False,      extras_require=extras_require,  )


"""Unit test package for taipy."""


import pytest    from src.taipy.core import Core  from src.taipy.core._orchestrator._dispatcher import _DevelopmentJobDispatcher, _StandaloneJobDispatcher  from src.taipy.core._orchestrator._orchestrator import _Orchestrator  from src.taipy.core._orchestrator._orchestrator_factory import _OrchestratorFactory  from src.taipy.core.config.job_config import JobConfig  from src.taipy.core.exceptions.exceptions import CoreServiceIsAlreadyRunning  from taipy.config import Config  from taipy.config.exceptions.exceptions import ConfigurationUpdateBlocked      class TestCore:      def test_run_core_trigger_config_check(self, caplog):          Config.configure_data_node(id="d0", storage_type="toto")          with pytest.raises(SystemExit):              core = Core()              core.run()          expected_error_message = (              "`storage_type` field of DataNodeConfig `d0` must be either csv, sql_table,"              " sql, mongo_collection, pickle, excel, generic, json, parquet, or in_memory."              ' Current value of property `storage_type` is "toto".'          )          assert expected_error_message in caplog.text          core.stop()        def test_run_core_as_a_service_development_mode(self):          _OrchestratorFactory._dispatcher = None            core = Core()          assert core._orchestrator is None          assert core._dispatcher is None          assert _OrchestratorFactory._dispatcher is None            core.run()          assert core._orchestrator is not None          assert core._orchestrator == _Orchestrator          assert _OrchestratorFactory._orchestrator is not None          assert _OrchestratorFactory._orchestrator == _Orchestrator          assert core._dispatcher is not None          assert isinstance(core._dispatcher, _DevelopmentJobDispatcher)          assert isinstance(_OrchestratorFactory._dispatcher, _DevelopmentJobDispatcher)          core.stop()        def test_run_core_as_a_service_standalone_mode(self):          _OrchestratorFactory._dispatcher = None            core = Core()          assert core._orchestrator is None            assert core._dispatcher is None          assert _OrchestratorFactory._dispatcher is None            Config.configure_job_executions(mode=JobConfig._STANDALONE_MODE, max_nb_of_workers=2)          core.run()          assert core._orchestrator is not None          assert core._orchestrator == _Orchestrator          assert _OrchestratorFactory._orchestrator is not None          assert _OrchestratorFactory._orchestrator == _Orchestrator          assert core._dispatcher is not None          assert isinstance(core._dispatcher, _StandaloneJobDispatcher)          assert isinstance(_OrchestratorFactory._dispatcher, _StandaloneJobDispatcher)          assert core._dispatcher.is_running()          assert _OrchestratorFactory._dispatcher.is_running()          core.stop()        def test_core_service_can_only_be_run_once(self):          core_instance_1 = Core()          core_instance_2 = Core()            core_instance_1.run()            with pytest.raises(CoreServiceIsAlreadyRunning):              core_instance_1.run()          with pytest.raises(CoreServiceIsAlreadyRunning):              core_instance_2.run()            # Stop the Core service and run it again should work          core_instance_1.stop()            core_instance_1.run()          core_instance_1.stop()          core_instance_2.run()          core_instance_2.stop()        def test_block_config_update_when_core_service_is_running_development_mode(self):          _OrchestratorFactory._dispatcher = None            core = Core()          core.run()          with pytest.raises(ConfigurationUpdateBlocked):              Config.configure_data_node(id="i1")          core.stop()        def test_block_config_update_when_core_service_is_running_standalone_mode(self):          _OrchestratorFactory._dispatcher = None            core = Core()          Config.configure_job_executions(mode=JobConfig._STANDALONE_MODE, max_nb_of_workers=2)          core.run()          with pytest.raises(ConfigurationUpdateBlocked):              Config.configure_data_node(id="i1")          core.stop()


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


import json  import os  from datetime import datetime, timedelta    import pytest    from src.taipy.core._repository._decoder import _Decoder  from src.taipy.core._repository._encoder import _Encoder      @pytest.fixture(scope="function", autouse=True)  def create_and_delete_json_file():      test_json_file = {          "name": "testing",          "date": datetime(1991, 1, 1),          "default_data": "data for testing encoder",          "validity_period": timedelta(days=1),      }      with open("data.json", "w") as f:          json.dump(test_json_file, f, ensure_ascii=False, indent=4, cls=_Encoder)      yield      os.unlink("data.json")      def test_json_encoder():      with open("data.json") as json_file:          data = json.load(json_file)          assert data["name"] == "testing"          assert data["default_data"] == "data for testing encoder"          assert data["date"] == {              "__type__": "Datetime",              "__value__": "1991-01-01T00:00:00",          }          assert data["date"].get("__type__") == "Datetime"          assert data["date"].get("__value__") == "1991-01-01T00:00:00"      def test_json_decoder():      with open("data.json") as json_file:          data = json.load(json_file, cls=_Decoder)          assert data["name"] == "testing"          assert data["default_data"] == "data for testing encoder"          assert data["date"] == datetime(1991, 1, 1)


import src.taipy.core.taipy as tp  from src.taipy.core.config import Config      def test_no_special_characters():      scenario_config = Config.configure_scenario("scenario_1")        scenario = tp.create_scenario(scenario_config, name="martin")      assert scenario.name == "martin"      scenarios = tp.get_scenarios()      assert len(scenarios) == 1      assert scenarios[0].name == "martin"      def test_many_special_characters():      scenario_config = Config.configure_scenario("scenario_1")        special_characters = (          "!#$%&'()*+,-./:;<=>?@[]^_`\\{"          "»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ"          "×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñò"          "óôõö÷øùúûüýþÿĀāĂăĄąĆćĈĉĊċČčĎ"          "ďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪ"          "īĬĭĮįİĲĳĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇ"          "ňŉŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţ"          "ŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſ"      )        scenario = tp.create_scenario(scenario_config, name=special_characters)      assert scenario.name == special_characters      scenarios = tp.get_scenarios()      assert len(scenarios) == 1      assert scenarios[0].name == special_characters


import json  import os  import pathlib  import shutil    import pytest    from src.taipy.core.exceptions.exceptions import InvalidExportPath  from taipy.config.config import Config    from .mocks import MockConverter, MockFSRepository, MockModel, MockObj, MockSQLRepository      class TestRepositoriesStorage:      @pytest.mark.parametrize(          "mock_repo,params",          [              (MockFSRepository, {"model_type": MockModel, "dir_name": "mock_model", "converter": MockConverter}),              (MockSQLRepository, {"model_type": MockModel, "converter": MockConverter}),          ],      )      def test_save_and_fetch_model(self, mock_repo, params, init_sql_repo):          r = mock_repo(**params)          m = MockObj("uuid", "foo")          r._save(m)            fetched_model = r._load(m.id)          assert m == fetched_model        @pytest.mark.parametrize(          "mock_repo,params",          [              (MockFSRepository, {"model_type": MockModel, "dir_name": "mock_model", "converter": MockConverter}),              (MockSQLRepository, {"model_type": MockModel, "converter": MockConverter}),          ],      )      def test_exists(self, mock_repo, params, init_sql_repo):          r = mock_repo(**params)          m = MockObj("uuid", "foo")          r._save(m)            assert r._exists(m.id)          assert not r._exists("not-existed-model")        @pytest.mark.parametrize(          "mock_repo,params",          [              (MockFSRepository, {"model_type": MockModel, "dir_name": "mock_model", "converter": MockConverter}),              (MockSQLRepository, {"model_type": MockModel, "converter": MockConverter}),          ],      )      def test_get_all(self, mock_repo, params, init_sql_repo):          objs = []          r = mock_repo(**params)          r._delete_all()            for i in range(5):              m = MockObj(f"uuid-{i}", f"Foo{i}")              objs.append(m)              r._save(m)          _objs = r._load_all()            assert len(_objs) == 5            for obj in _objs:              assert isinstance(obj, MockObj)          assert sorted(objs, key=lambda o: o.id) == sorted(_objs, key=lambda o: o.id)        @pytest.mark.parametrize(          "mock_repo,params",          [              (MockFSRepository, {"model_type": MockModel, "dir_name": "mock_model", "converter": MockConverter}),              (MockSQLRepository, {"model_type": MockModel, "converter": MockConverter}),          ],      )      def test_delete_all(self, mock_repo, params, init_sql_repo):          r = mock_repo(**params)          r._delete_all()            for i in range(5):              m = MockObj(f"uuid-{i}", f"Foo{i}")              r._save(m)            _models = r._load_all()          assert len(_models) == 5            r._delete_all()          _models = r._load_all()          assert len(_models) == 0        @pytest.mark.parametrize(          "mock_repo,params",          [              (MockFSRepository, {"model_type": MockModel, "dir_name": "mock_model", "converter": MockConverter}),              (MockSQLRepository, {"model_type": MockModel, "converter": MockConverter}),          ],      )      def test_delete_many(self, mock_repo, params, init_sql_repo):          r = mock_repo(**params)          r._delete_all()            for i in range(5):              m = MockObj(f"uuid-{i}", f"Foo{i}")              r._save(m)            _models = r._load_all()          assert len(_models) == 5          r._delete_many(["uuid-0", "uuid-1"])          _models = r._load_all()          assert len(_models) == 3        @pytest.mark.parametrize(          "mock_repo,params",          [              (MockFSRepository, {"model_type": MockModel, "dir_name": "mock_model", "converter": MockConverter}),              (MockSQLRepository, {"model_type": MockModel, "converter": MockConverter}),          ],      )      def test_search(self, mock_repo, params, init_sql_repo):          r = mock_repo(**params)          r._delete_all()            m = MockObj("uuid", "foo")          r._save(m)            m1 = r._search("name", "bar")          m2 = r._search("name", "foo")            assert m1 == []          assert m2 == [m]        @pytest.mark.parametrize(          "mock_repo,params",          [              (MockFSRepository, {"model_type": MockModel, "dir_name": "mock_model", "converter": MockConverter}),              (MockSQLRepository, {"model_type": MockModel, "converter": MockConverter}),          ],      )      @pytest.mark.parametrize("export_path", ["tmp"])      def test_export(self, mock_repo, params, export_path, init_sql_repo):          r = mock_repo(**params)            m = MockObj("uuid", "foo")          r._save(m)            r._export("uuid", export_path)          assert pathlib.Path(os.path.join(export_path, "mock_model/uuid.json")).exists()          with open(os.path.join(export_path, "mock_model/uuid.json"), "r") as exported_file:              exported_data = json.load(exported_file)              assert exported_data["id"] == "uuid"              assert exported_data["name"] == "foo"            # Export to same location again should work          r._export("uuid", export_path)          assert pathlib.Path(os.path.join(export_path, "mock_model/uuid.json")).exists()            if mock_repo == MockFSRepository:              with pytest.raises(InvalidExportPath):                  r._export("uuid", Config.core.storage_folder)            shutil.rmtree(export_path, ignore_errors=True)


import dataclasses  import pathlib  from dataclasses import dataclass  from typing import Any, Dict, Optional    from sqlalchemy import Column, String, Table  from sqlalchemy.dialects import sqlite  from sqlalchemy.orm import declarative_base, registry  from sqlalchemy.schema import CreateTable    from src.taipy.core._repository._abstract_converter import _AbstractConverter  from src.taipy.core._repository._filesystem_repository import _FileSystemRepository  from src.taipy.core._repository._sql_repository import _SQLRepository  from src.taipy.core._version._version_manager import _VersionManager  from taipy.config.config import Config      class Base:      __allow_unmapped__ = True      Base = declarative_base(cls=Base)  # type: ignore  mapper_registry = registry()      @dataclass  class MockObj:      def __init__(self, id: str, name: str, version: Optional[str] = None) -> None:          self.id = id          self.name = name          if version:              self._version = version          else:              self._version = _VersionManager._get_latest_version()      @dataclass  class MockModel(Base):  # type: ignore      __table__ = Table(          "mock_model",          mapper_registry.metadata,          Column("id", String(200), primary_key=True),          Column("name", String(200)),          Column("version", String(200)),      )      id: str      name: str      version: str        def to_dict(self):          return dataclasses.asdict(self)        @staticmethod      def from_dict(data: Dict[str, Any]):          return MockModel(id=data["id"], name=data["name"], version=data["version"])        def _to_entity(self):          return MockObj(id=self.id, name=self.name, version=self.version)        @classmethod      def _from_entity(cls, entity: MockObj):          return MockModel(id=entity.id, name=entity.name, version=entity._version)        def to_list(self):          return [self.id, self.name, self.version]      class MockConverter(_AbstractConverter):      @classmethod      def _entity_to_model(cls, entity):          return MockModel(id=entity.id, name=entity.name, version=entity._version)        @classmethod      def _model_to_entity(cls, model):          return MockObj(id=model.id, name=model.name, version=model.version)      class MockFSRepository(_FileSystemRepository):      def __init__(self, **kwargs):          super().__init__(**kwargs)        @property      def _storage_folder(self) -> pathlib.Path:          return pathlib.Path(Config.core.storage_folder)  # type: ignore      class MockSQLRepository(_SQLRepository):      def __init__(self, **kwargs):          super().__init__(**kwargs)          self.db.execute(str(CreateTable(MockModel.__table__, if_not_exists=True).compile(dialect=sqlite.dialect())))


import pytest    from taipy.config.config import Config      def test_job_config():      assert Config.job_config.mode == "development"        job_c = Config.configure_job_executions(mode="standalone", max_nb_of_workers=2)      assert job_c.mode == "standalone"      assert job_c.max_nb_of_workers == 2        assert Config.job_config.mode == "standalone"      assert Config.job_config.max_nb_of_workers == 2        Config.configure_job_executions(foo="bar")      assert Config.job_config.foo == "bar"      def test_clean_config():      job_config = Config.configure_job_executions(mode="standalone", max_nb_of_workers=2, prop="foo")        assert Config.job_config is job_config        job_config._clean()        # Check if the instance before and after _clean() is the same      assert Config.job_config is job_config        assert job_config.mode == "development"      assert job_config._config == {"max_nb_of_workers": 1}      assert job_config.properties == {}


from taipy.config.config import Config      def migrate_pickle_path(dn):      dn.path = "s1.pkl"      def migrate_skippable(task):      task.skippable = True      def test_migration_config():      assert Config.migration_functions.migration_fcts == {}        data_nodes1 = Config.configure_data_node("data_nodes1", "pickle")        migration_cfg = Config.add_migration_function(          target_version="1.0",          config=data_nodes1,          migration_fct=migrate_pickle_path,      )        assert migration_cfg.migration_fcts == {"1.0": {"data_nodes1": migrate_pickle_path}}      assert migration_cfg.properties == {}        data_nodes2 = Config.configure_data_node("data_nodes2", "pickle")        migration_cfg = Config.add_migration_function(          target_version="1.0",          config=data_nodes2,          migration_fct=migrate_pickle_path,      )      assert migration_cfg.migration_fcts == {          "1.0": {"data_nodes1": migrate_pickle_path, "data_nodes2": migrate_pickle_path}      }      def test_clean_config():      assert Config.migration_functions.migration_fcts == {}        data_nodes1 = Config.configure_data_node("data_nodes1", "pickle")      migration_cfg = Config.add_migration_function(          target_version="1.0",          config=data_nodes1,          migration_fct=migrate_pickle_path,      )        assert migration_cfg.migration_fcts == {"1.0": {"data_nodes1": migrate_pickle_path}}      assert migration_cfg.properties == {}        migration_cfg._clean()        assert migration_cfg.migration_fcts == {}      assert migration_cfg._properties == {}