Instruction:
rview.md": "Client Storage Overview",
    "docs/state_structure/overview.md": "State Structure Overview",
    "docs/state/overview.md": "State Overview",
    "docs/styling/overview.md": "Styling Overview",
    "docs/ui/overview.md": "UI Overview",
    "docs/wrapping-react/overview.md": "Wrapping React Overview",
    "docs/library/html/html.md": "HTML Elements",
    "docs/recipes-overview.md": "Recipes Overview",
    "docs/events/special_events.md": "Special Events Docs",
    "docs/library/graphing/general/tooltip.md": "Graphing Tooltip",
    "docs/recipes/content/grid.md": "Grid Recipe",
}

def get_component(doc: str, title: str):
    if doc.endswith("-style.md"):
        return

    if doc.endswith("-ll.md"):
        return

    # Get the docpage component.
    doc = doc.replace("\\", "/")
    route = rx.utils.format.to_kebab_case(f"/{doc.replace('.md', '/')}")
    # Handle index files: /folder/index/ -> /folder/
    if route.endswith("/index/"):
        route = route[:-7] + "/"

Input:
    category = os.path.basename(os.path.dirname(doc)).title()

    if not _check_whitelisted_path(route):
        return

    d = Document.from_file(doc)

    if doc.startswith("docs/library/graphing"):
        if should_skip_compile(doc):
            outblocks.append((d, route))
            return
        clist = [title, *get_components_from_metadata(d)]
        graphing_components[category].append(clist)
        return multi_docs(path=route, comp=d, component_list=clist, title=title2)
    if doc.startswith("docs/library"):
        clist = [title, *get_components_from_metadata(d)]
        component_list[category].append(clist)
        if should_skip_compile(doc):
            outblocks.append((d, route))
            return
        return multi_docs(path=route, comp=d, component_list=clist, title=title2)

    if should_skip_compile(doc):
        outblocks.append((d, route))
        return

    def comp():
        return (get_toc(d, doc), xd.render(d, doc))

    doc_path = Path(doc)

Output: title2 = manual_titles[doc] if doc in manual_titles else to_title_case(title)


Instruction: """Plugins API reference page."""

Input:
from pcweb.templates.docpage import docpage

@docpage("/docs/api-reference/plugins/")
def plugins():
    """Plugins API reference page."""
    with open("docs/api-reference/plugins.md", encoding="utf-8") as f:
        content = f.read()
    return rx.markdown(content)

Output: import reflex as rx


Instruction: """Utils API reference page."""

Input:
from pcweb.templates.docpage import docpage

@docpage("/docs/api-reference/utils/")
def utils():
    """Utils API reference page."""
    with open("docs/api-reference/utils.md", encoding="utf-8") as f:
        content = f.read()
    return rx.markdown(content)

Output: import reflex as rx


Instruction:
           # Tag filtering
            if self.checked_tags and not (set(app_tags) & self.checked_tags):
                continue

            filtered.append(app_title)

        return filtered

    @rx.event
    def clear_filters(self):
        self.checked_tags = set()
        self.page = 1

    @rx.var
    def filtered_templates(self) -> list[str]:
        all_filtered = self._get_all_filtered_templates()
        self.total_pages = (
            (len(all_filtered) + ITEMS_PER_PAGE - 1) // ITEMS_PER_PAGE
            if all_filtered
            else 1
        )
        start = (self.page - 1) * ITEMS_PER_PAGE
        end = start + ITEMS_PER_PAGE
        return all_filtered[start:end]

    @rx.event
    def set_query(self, value: str):
        self.query = value
        self.page = 1

    @rx.event
    def toggle_template(self, value: str):
        if value in self.checked_tags:
            self.checked_tags.remove(value)
        else:
            self.checked_tags.add(value)

Input:
    @rx.event
    def prev_page(self):
        if self.page > 1:
            self.page -= 1

    @rx.event
    def next_page(self):
        if self.page < self.total_pages:
            self.page += 1

def pagination() -> rx.Component:
    return rx.box(
        rx.box(
            button(
                icon=rx.icon(tag="chevron-left", size=16, class_name="!text-slate-10"),
                disabled=TemplatesState.page == 1,
                variant="secondary",
                size="icon-sm",
                on_click=TemplatesState.prev_page,
            ),
            button(
                icon=rx.icon(tag="chevron-right", size=16, class_name="!text-slate-10"),
                disabled=TemplatesState.page == TemplatesState.total_pages,
                variant="secondary",
                size="icon-sm",
                on_click=TemplatesState.next_page,
            ),
            class_name="flex flex-row items-center gap-2",
        ),
        rx.text(
            f"{TemplatesSt

Output: self.page = 1


Instruction:
import reflex as rx

from pcweb.components.hosting_banner import HostingBannerState
from pcweb.components.new_button import button

Input:
def hero() -> rx.Component:
    """Render the hero section of the landing page."""
    return rx.el.section(
        # Headings
        rx.el.h1(
            "Deploy with a single command",
            class_name="max-w-full inline-block bg-clip-text bg-gradient-to-r from-slate-12 to-slate-11 w-full text-4xl lg:text-5xl text-center text-transparent text-balance mx-auto break-words font-semibold",
        ),
        # TODO: Change this wording
        rx.el.h2(
            """A unified platform to build and manage your Reflex apps""",
            class_name="max-w-full w-full font-large text-center text-slate-11 -mt-2 font-normal text-[1.25rem] mx-auto text-balance word-wrap break-words md:whitespace-pre",
        ),
        # Buttons
        rx.box(
            rx.link(
                button(
                    "Start deploying",
                    size="xl",
                    class_name="w-full lg:w-fit",
                ),
                underline="none",
                hre

Output: from pcweb.pages.docs import hosting


Instruction:
import reflex as rx
import reflex_ui as ui
from reflex.experimental import ClientStateVar

from .integration_list import get_integration_path

Input:
selected_filter = ClientStateVar.create("selected_filter", "All")

FilterOptions = [
    {"name": "AI", "icon": "BotIcon"},
    {"name": "DevTools", "icon": "WorkflowSquare10Icon"},
    {"name": "Data Infrastructure", "icon": "DatabaseAddIcon"},
    {"name": "Authentication", "icon": "LockPasswordIcon"},
    {"name": "Communication", "icon": "SentIcon"},
    {"name": "All", "icon": "CellsIcon"},
]

def integration_filter_button(data: dict):
    active_pill = "border border-violet-8 bg-violet-3 hover:bg-violet-3 !text-violet-10"

    return ui.button(
        ui.icon(icon=data["icon"]),
        rx.el.p(data["name"], class_name="text-sm"),
        variant="outline",
        class_name="flex flex-row items-center "
        + rx.cond(selected_filter.value == data["name"], active_pill, "").to(str),
        on_click=selected_filter.set_value(data["name"]),
    )

def integration_filters():
    return rx.el.div(
        rx.el.div(
            *[integration_filter_button(data) for data in

Output: from .integration_request import request_integration_dialog


Instruction:
import reflex as rx
import reflex_ui as ui
from reflex.experimental import ClientStateVar

from pcweb.components.icons.icons import get_icon

Input:
company_cs = ClientStateVar.create("company", "")
area_x_pos = ClientStateVar.create(var_name="area_x_pos", default=0)
area_y_pos = ClientStateVar.create(var_name="area_y_pos", default=0)
area_opacity = ClientStateVar.create(var_name="area_opacity", default=0)

companies_list = [
    "apple",
    "microsoft",
    "amazon",
    "fastly",
    "accenture",
    "ibm",
    "unicef",
    "autodesk",
    "STATS",
    "sellerx",
    "ford",
    "paloalto",
    "bosch",
    "dell",
    "twilio",
    "rappi",
    "nike",
]

companies_case_studies = {
    "dell": {
        "company_name": "Dell",
        "quote": """Reflex has been a game changer.
        In just a week, I had a demo up and running with excellent performance.
        It made the project feasible for my support team, helping us build a smooth, efficient interface.""",
        "person": "JL",
        "picture": "/favicon.ico",
        "role": "Principal Engineer",
    },
    "autodesk": {
        "company_name": "Autodesk",

Output: from pcweb.pages.framework.views.companies import companies as index_companies


Instruction:
import base64
import uuid
from typing import TypedDict

import httpx
import reflex as rx
import reflex_ui as ui
from reflex.experimental import ClientStateVar

from pcweb.components.numbers_pattern import numbers_pattern
from pcweb.constants import (
    MAX_FILE_SIZE_BYTES,
    MAX_FILE_SIZE_MB,
    MAX_IMAGES_COUNT,
    PROMPT_MAP,
    REFLEX_BUILD_URL,
    RX_BUILD_BACKEND,
)

def is_content_type_valid(content_type: str) -> bool:
    """Check if the content type is valid."""
    return content_type.startswith("image/")

Input:
textarea_y_pos = ClientStateVar.create(var_name="textarea_y_pos", default=0)
textarea_opacity = ClientStateVar.create(var_name="textarea_opacity", default=0)
show_default_prompt = ClientStateVar.create(
    var_name="show_default_prompt", default=True
)

class ImageData(TypedDict):
    data: bytes
    mime_type: str

class SubmitPromptState(rx.State):
    _images: list[ImageData] | None = None
    is_uploading: rx.Field[bool] = rx.field(False)
    is_processing: rx.Field[bool] = rx.field(False)

    @rx.event(background=True, temporal=True)
    async def redirect_to_ai_builder(self, form_data: dict):
        if prompt := form_data.get("prompt"):
            if len(prompt) < 5:
                return rx.toast.warning(
                    "Your prompt needs at least 5 characters. Please add more details.",
                )
            random_uuid = uuid.uuid4()
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    RX_B

Output: textarea_x_pos = ClientStateVar.create(var_name="textarea_x_pos", default=0)


Instruction:
tics",
                "Get alerts and metrics",
                "Get alerts and metrics for your Reflex app to help you monitor and optimize your app.",
            ),
            class_name="flex flex-col max-w-full lg:max-w-[21.4375rem] divide-y divide-slate-3",
        ),
        rx.box(
            rx.image(
                src="/landing/hosting_features/light/card.webp",
                class_name="absolute top-0 left-0 w-full h-full object-cover pointer-events-none dark:hidden",
            ),
            rx.image(
                src="/landing/hosting_features/dark/card.webp",
                class_name="absolute top-0 left-0 w-full h-full object-cover pointer-events-none dark:block hidden",
            ),
            class_name="justify-center items-center relative overflow-hidden w-full lg:flex hidden",
        ),
        class_name="flex flex-col lg:flex-row max-w-[64.19rem] mx-auto w-full border-x-0 lg:border-x border-slate-3 divide-x-0 lg:divide-x divide-slate-3",
    )

Input:
def hosting_section() -> rx.Component:
    return rx.el.section(
        header(),
        # graph(),
        content(),
        class_name="flex flex-col mx-auto w-full max-w-[84.19rem] relative",
    )

Output:
def graph() -> rx.Component:
    return rx.box(
        rx.image(
            src="/hosting_graphing.svg",
            class_name="w-full h-[10rem]",
        ),
        class_name="flex flex-col lg:flex-row max-w-[64.19rem] mx-auto w-full border-x-0 lg:border-x border-slate-3 divide-x-0 lg:divide-x divide-slate-3 p-10",
    )


Instruction:
         line_svg(class_name="right-[12rem] top-1/2 -translate-y-1/2 scale-x-[-1]"),
            class_name="relative overflow-hidden",
        ),
        class_name="grid grid-cols-2 absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 lg:w-[43.5rem] w-[36rem] z-[0] overflow-hidden h-[20rem]",
    )

def integrations_row() -> rx.Component:
    return rx.el.div(
        lines(),
        rx.el.div(
            intregation_card("supabase", "langchain"),
            intregation_card("openai", "databricks"),
            intregation_card("stripe", "anthropic"),
            class_name="flex flex-col gap-10",
        ),
        r_logo_card(),
        rx.el.div(
            intregation_card("aws", "gcp"),
            intregation_card("azure", "oracle"),
            intregation_card("databricks", "reflex"),
            class_name="flex flex-col gap-10",
        ),
        class_name="flex flex-row items-center lg:gap-[7.5rem] gap-14 mt-10 relative max-lg:w-full justify-center",
    )

Output:
def integrations() -> rx.Component:
    return rx.el.section(
        numbers_pattern(side="left", class_name="left-0 top-0"),
        numbers_pattern(side="right", class_name="right-0 top-0"),
        header(),
        integrations_row(),
        class_name="flex flex-col items-center mx-auto w-full max-w-[64.19rem] lg:border-x border-slate-3 relative overflow-hidden lg:border-t lg:pb-26 pb-20 pt-20",
    )


Instruction:
from typing import List

import reflex as rx

Input:
from pcweb.components.new_button import button

# Outcomes features data
OUTCOMES_FEATURES = [
    {
        "title": "Dedicated Engineer",
        "description": "An expert engineer is assigned to your team to build your first app.",
        "icon": "backend_auth",
    },
    {
        "title": "Fast Time to Launch",
        "description": "Get your first app up and running quickly with expert guidance.",
        "icon": "zap",
    },
    {
        "title": "Guaranteed Success",
        "description": "We ensure your app reaches a successful state before handoff.",
        "icon": "star",
    },
    {
        "title": "Training and Enablement",
        "description": "Hands-on training so your team can maintain and extend your app.",
        "icon": "document_code",
    },
]

def header() -> rx.Component:
    return rx.box(
        rx.el.h3(
            "Deliver Outcomes",
            class_name="lg:text-3xl text-xl font-semibold text-slate-12 text-balance",
        ),
        rx.el

Output: from pcweb.components.icons import get_icon


Instruction:
import reflex as rx
import reflex_ui as ui
from reflex.experimental.client_state import ClientStateVar

Input:
collapsed_calculator_cs = ClientStateVar.create("collapsed_calculator", default=True)

CREDITS_PER_HOUR_CPU = 0.2
CREDITS_PER_HOUR_GB = 0.5

COMPUTE_TABLE = {
    "c1m.5": {"vcpu": 1, "ram": 0.5},
    "c1m1": {"vcpu": 1, "ram": 1},
    "c1m2": {"vcpu": 1, "ram": 2},
    "c2m2": {"vcpu": 2, "ram": 2},
    "c2m4": {"vcpu": 2, "ram": 4},
    "c4m4": {"vcpu": 4, "ram": 4},
    "c4m8": {"vcpu": 4, "ram": 8},
}

def table_header(cost_text: str) -> rx.Component:
    return rx.box(
        rx.text("Machine", class_name="text-sm font-semibold text-slate-12"),
        rx.text("vCPU", class_name="text-sm font-semibold text-slate-12"),
        rx.text("GB RAM", class_name="text-sm font-semibold text-slate-12"),
        rx.el.div(
            ui.icon("TokenCircleIcon", class_name="text-slate-9 size-4"),
            rx.text(
                cost_text, class_name="text-sm font-semibold text-slate-12 text-end"
            ),
            class_name="flex flex-row gap-1 items-center justify-end",

Output: from pcweb.components.tabs import tabs


Instruction:
# FONT STYLES

font_family = "Instrument Sans"

small = {
    "font-family": font_family,
    "font-style": "normal",
    "font-weight": "500",
    "font-size": "14px",
    "line-height": "20px",
    "letter-spacing": "-0.0125em",
}

small_semibold = {
    "font-family": font_family,
    "font-size": "14px",
    "font-style": "normal",
    "font-weight": "600",
    "line-height": "20px",
    "letter-spacing": "-0.0125em",
}

Input:
base_semibold = {
    "font-family": font_family,
    "font-style": "normal",
    "font-weight": "600",
    "font-size": "16px",
    "line-height": "24px",
    "letter-spacing": "-0.015em",
}

medium = {
    "font-family": font_family,
    "font-style": "normal",
    "font-weight": "500",
    "font-size": "18px",
    "line-height": "26px",
    "letter-spacing": "-0.015em",
}

medium_leading_5 = {
    "font-family": font_family,
    "font-style": "normal",
    "font-weight": "500",
    "font-size": "18px",
    "line-height": "20px",
    "letter-spacing": "-0.015em",
}

large = {
    "font-family": font_family,
    "font-style": "normal",
    "font-weight": "600",
    "font-size": "24px",
    "line-height": "32px",
    "letter-spacing": "-0.015em",
}

x_large = {
    "font-family": font_family,
    "font-style": "normal",
    "font-weight": "600",
    "font-size": ["24px", "32px"],
    "line-height": ["32px", "40px"],
    "letter-spacing": ["-0.02em", "-0.03em"],
}

xx_large = {
    "

Output:
base = {
    "font-family": font_family,
    "font-style": "normal",
    "font-weight": "500",
    "font-size": ["14px", "16px"],
    "line-height": ["20px", "24px"],
    "letter-spacing": "-0.015em",
}


Instruction:
import functools
from typing import Callable

import reflex as rx

Input:
from pcweb.route import Route

def gallery_app_page(
    path: str,
    title: str,
    description: str,
    image: str,
    demo: str,
    meta: list[dict[str, str]] | None = None,
    props=None,
    add_as_page=True,
) -> Callable:
    """A template that most pages on the reflex.dev site should use.

    This template wraps the webpage with the navbar and footer.

    Args:
        path: The path of the page.
        title: The title of the page.
        description: The description of the page.
        image: The image of the page.
        demo: The demo link of the app.
        meta: The meta tags of the page.
        props: Props to apply to the template.
        add_as_page: whether to add the route to the app pages.

    Returns:
        A wrapper function that returns the full webpage.
    """
    props = props or {}

    def webpage(contents: Callable[[], Route]) -> Route:
        """Wrapper to create a templated route.

        Args:
            contents: The function to

Output: from pcweb.pages.framework.index_colors import index_colors


Instruction:
from typing import Callable

import reflex as rx

Input:
from pcweb.route import Route

DEFAULT_TITLE = "Web Apps in Pure Python"

def mainpage(
    path: str,
    title: str = DEFAULT_TITLE,
    description: str | None = None,
    image: str | None = None,
    meta: list[dict[str, str]] = meta_tags,
    props=None,
    add_as_page=True,
) -> Callable:
    """A template that most pages on the reflex.dev site should use.

    This template wraps the webpage with the navbar and footer.

    Args:
        path: The path of the page.
        title: The title of the page.
        description: The description of the page.
        image: The image of the page.
        meta: The meta tags of the page.
        props: Props to apply to the template.
        add_as_page: whether to add the route to the app pages.

    Returns:
        A wrapper function that returns the full webpage.
    """
    props = props or {}

    def mainpage(contents: Callable[[], Route]) -> Route:
        """Wrapper to create a templated route.

        Args:
            con

Output: from pcweb.meta.meta import meta_tags


Instruction:
"""Template for documentation pages."""

import functools
from datetime import datetime
from typing import Callable

import flexdown
import mistletoe
import reflex as rx
from reflex.components.radix.themes.base import LiteralAccentColor
from reflex.utils.format import to_snake_case, to_title_case

from pcweb.components.button import button

Input:
from pcweb.route import Route, get_path
from pcweb.styles.colors import c_color

from .blocks import *
from .state import FeedbackState

def right_sidebar_item_highlight():
    return r"""
   function setupTableOfContentsHighlight() {
    // Delay to ensure DOM is fully loaded
    setTimeout(() => {
        const tocLinks = document.querySelectorAll('#toc-navigation a');
        const activeClass = 'text-violet-9';
        const defaultClass = 'text-slate-9';

        function normalizeId(id) {
            return id.toLowerCase().replace(/\s+/g, '-');
        }

        function highlightTocLink() {
            // Get the current hash from the URL
            const currentHash = window.location.hash.substring(1);

            // Reset all links
            tocLinks.forEach(link => {
                link.classList.remove(activeClass);
                link.classList.add(defaultClass);
            });

            // If there's a hash, find and highlight the corresponding link

Output: from pcweb.components.icons.icons import get_icon


Instruction:
 parts
    formatted_parts = []

    # Iterate over dictionary items
    for key, value in input_dict.items():
        # Format each key-value pair
        if isinstance(value, str):
            formatted_part = f'{key}="{value}"'  # Enclose string values in quotes
        else:
            formatted_part = f"{key}={value}"  # Non-string values as is

        # Append the formatted part to the list
        formatted_parts.append(formatted_part)

    # Join all parts with a comma and a space
    return ", ".join(formatted_parts)

def used_component(
    component_used: rx.Component,
    components_passed: rx.Component | str | None,
    color_scheme: str,
    variant: str,
    high_contrast: bool,
    disabled: bool = False,
    **kwargs,
) -> rx.Component:
    if components_passed is None and disabled is False:
        return component_used(
            color_scheme=color_scheme,
            variant=variant,
            high_contrast=high_contrast,
            **kwargs,
        )

Input:
def style_grid(
    component_used: rx.Component,
    component_used_str: str,
    variants: list,
    components_passed: rx.Component | str | None = None,
    disabled: bool = False,
    **kwargs,
) -> rx.Component:
    text_cn = "text-nowrap font-md flex items-center"
    return rx.box(
        rx.grid(
            rx.text("", size="5"),
            *[
                rx.text(variant, class_name=text_cn + " text-slate-11")
                for variant in variants
            ],
            rx.text(
                "Accent",
                color=f"var(--{RadixDocState.color}-10)",
                class_name=text_cn,
            ),
            *[
                hover_item(
                    component=used_component(
                        component_used=component_used,
                        components_passed=components_passed,
                        color_scheme=RadixDocState.color,
                        variant=variant,
                        high_contrast=False,

Output:
elif components_passed is not None and disabled is False:
        return component_used(
            components_passed,
            color_scheme=color_scheme,
            variant=variant,
            high_contrast=high_contrast,
            **kwargs,
        )

    elif components_passed is None and disabled is True:
        return component_used(
            color_scheme=color_scheme,
            variant=variant,
            high_contrast=high_contrast,
            disabled=True,
            **kwargs,
        )

    else:
        return component_used(
            components_passed,
            color_scheme=color_scheme,
            variant=variant,
            high_contrast=high_contrast,
            disabled=True,
            **kwargs,
        )


Instruction:
ode = textwrap.dedent(
            "\n".join(code.strip().splitlines()[lines[0] : lines[1]])
        ).strip()

    # Create the code snippet.
    cb = code_block_dark if theme == "dark" else code_block
    return cb(
        code=code,
        language=language,
    )

def docdemo(
    code: str,
    state: str | None = None,
    comp: rx.Component | None = None,
    context: bool = False,
    demobox_props: dict[str, Any] | None = None,
    theme: str | None = None,
    **props,
) -> rx.Component:
    """Create a documentation demo with code and output.

    Args:
        code: The code to render the component.
        state: Code for any state needed for the component.
        comp: The pre-rendered component.
        context: Whether to wrap the render code in a function.
        demobox_props: Props to apply to the demo box.
        theme: The theme for the code snippet.
        props: Additional props to apply to the component.

    Returns:
        The styled demo.
    """

Input:
    # Render the component if necessary.
    if comp is None:
        comp = eval(code)

    # Wrap the render code in a function if needed.
    if context:
        code = f"""def index():
        return {code}
        """

    # Add the state code
    if state is not None:
        code = state + code

    if demobox_props.pop("toggle", False):
        return rx.tabs.root(
            rx.tabs.list(
                rx.tabs.trigger(
                    rx.box(
                        "UI",
                    ),
                    value="tab1",
                    class_name="tab-style",
                ),
                rx.tabs.trigger(
                    rx.box(
                        "Code",
                    ),
                    value="tab2",
                    class_name="tab-style",
                ),
                class_name="justify-end",
            ),
            rx.tabs.content(
                rx.box(docdemobox(comp, **(demobox_props or {})), class_name="my-4"),

Output: demobox_props = demobox_props or {}


Instruction:
from datetime import datetime

import reflex as rx

from pcweb.components.icons.icons import get_icon

Input:
from pcweb.pages.blog import blogs
from pcweb.pages.docs import getting_started, hosting
from pcweb.pages.docs.library import library
from pcweb.pages.errors import errors
from pcweb.pages.faq import faq
from pcweb.pages.gallery import gallery
from pcweb.pages.use_cases.use_cases import use_cases_page
from pcweb.signup import IndexState

def footer_link(text: str, href: str) -> rx.Component:
    return rx.link(
        text,
        href=href,
        class_name="font-small text-slate-9 hover:!text-slate-11 no-underline transition-color",
    )

def footer_link_flex(heading: str, links: list[rx.Component]) -> rx.Component:
    return rx.box(
        rx.el.h4(
            heading,
            class_name="font-smbold text-slate-12",
        ),
        *links,
        class_name="flex flex-col gap-4",
    )

def social_menu_item(icon: str, url: str = "/", class_name: str = "") -> rx.Component:
    return rx.link(
        get_icon(icon=icon),
        class_name="flex justify-center ite

Output:
from pcweb.constants import (
    DISCORD_URL,
    FORUM_URL,
    GITHUB_URL,
    LINKEDIN_URL,
    ROADMAP_URL,
    TWITTER_URL,
)


Instruction:
#!/usr/bin/env python3
"""Dead link checker for the Reflex website.
Crawls the deployed site and checks for broken links.
"""

import argparse
import sys

Input:
import xml.etree.ElementTree as ET
from collections import deque
from urllib.parse import urljoin, urlparse

import requests
from bs4 import BeautifulSoup

class DeadLinkChecker:
    def __init__(self, base_url, max_pages=None, timeout=10, delay=0.5):
        self.base_url = base_url.rstrip("/")
        self.domain = urlparse(base_url).netloc
        self.max_pages = max_pages
        self.timeout = timeout
        self.delay = delay

        self.visited_pages = set()
        self.checked_links = set()
        self.dead_links = []
        self.pages_to_visit = deque([base_url])

        self.session = requests.Session()
        self.session.headers.update(
            {"User-Agent": "Mozilla/5.0 (compatible; DeadLinkChecker/1.0)"}
        )

    def is_internal_url(self, url):
        """Check if URL is internal to our domain."""
        parsed = urlparse(url)
        return parsed.netloc == self.domain or parsed.netloc == ""

    def normalize_url(self, url):
        """Normalize U

Output: import time


Instruction:
elf.delay = delay

        self.visited_pages = set()
        self.checked_links = set()
        self.dead_links = []
        self.pages_to_visit = deque([base_url])

        self.session = requests.Session()
        self.session.headers.update(
            {"User-Agent": "Mozilla/5.0 (compatible; DeadLinkChecker/1.0)"}
        )

    def is_internal_url(self, url):
        """Check if URL is internal to our domain."""
        parsed = urlparse(url)
        return parsed.netloc == self.domain or parsed.netloc == ""

    def normalize_url(self, url):
        """Normalize URL for comparison."""
        parsed = urlparse(url)
        normalized = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
        if parsed.query:
            normalized += f"?{parsed.query}"
        return normalized

    def check_link(self, url, source_page):
        """Check if a single link is working."""
        if url in self.checked_links:
            return True

        self.checked_links.add(url)

Input:
        if parsed.netloc in ["fonts.googleapis.com", "fonts.gstatic.com"]:
            return True

        try:
            response = self.session.head(
                url, timeout=self.timeout, allow_redirects=True
            )

            if response.status_code == 405:
                response = self.session.get(
                    url, timeout=self.timeout, allow_redirects=True
                )

            if response.status_code == 403 and parsed.netloc in [
                "twitter.com",
                "www.twitter.com",
                "x.com",
                "www.x.com",
            ]:
                print(f"Warning: Twitter/X link may be blocked by bot detection: {url}")
                return True

            if response.status_code >= 400:
                self.dead_links.append(
                    {
                        "url": url,
                        "status_code": response.status_code,
                        "source_page": source_page,

Output: parsed = urlparse(url)


Instruction:
)
        text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
        text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
        text = re.sub(r"\n\s*\n+", "\n\n", text)
        return text.strip()

    def extract_headings(self, content: str) -> List[str]:
        """Extract headings from markdown content."""
        headings = []
        lines = content.split("\n")

        for line in lines:
            line = line.strip()
            if line.startswith("#"):
                heading_text = re.sub(r"^#+\s*", "", line)
                heading_text = re.sub(r"\{[^}]*\}", "", heading_text)
                if heading_text:
                    headings.append(heading_text.strip())

        return headings

    def summarize_markdown(self, md_path: str, max_lines: int = 100) -> str:
        """Your existing summarize function - simplified."""
        with open(md_path, "r", encoding="utf-8") as f:
            content = f.read()

        cleaned = self.clean_markdown(content)

Input:
        truncated_lines = lines[:max_lines]
        truncated_text = "\n".join(truncated_lines).strip()

        if len(truncated_lines) < max_lines:
            return truncated_text

        return truncated_text

    def name_from_url(self, url: str) -> str:
        parts = url.strip("/").split("/")
        if parts[0] == "docs":
            parts = parts[1:]
        if parts and parts[-1] == "low":
            parts[-1] = "low-level"
        readable = " ".join(part.replace("-", " ") for part in parts)
        return self.smart_title_case(readable)

    def extract_components(self, file_path: str) -> List[str]:
        """Extract components from raw markdown file content."""
        with open(file_path, "r", encoding="utf-8") as f:
            content = f.read()

        patterns = [
            r"(?:rx|reflex)\.([A-Z][a-zA-Z0-9_]*)",
            r"\b([A-Z][a-z]+(?:[A-Z][a-z]*)*Component?)\b",
        ]
        components = set()
        for pattern in patterns:
            matche

Output: lines = cleaned.splitlines()


Instruction:
ng_text)
                if heading_text:
                    headings.append(heading_text.strip())

        return headings

    def summarize_markdown(self, md_path: str, max_lines: int = 100) -> str:
        """Your existing summarize function - simplified."""
        with open(md_path, "r", encoding="utf-8") as f:
            content = f.read()

        cleaned = self.clean_markdown(content)
        lines = cleaned.splitlines()
        truncated_lines = lines[:max_lines]
        truncated_text = "\n".join(truncated_lines).strip()

        if len(truncated_lines) < max_lines:
            return truncated_text

        return truncated_text

    def name_from_url(self, url: str) -> str:
        parts = url.strip("/").split("/")
        if parts[0] == "docs":
            parts = parts[1:]
        if parts and parts[-1] == "low":
            parts[-1] = "low-level"
        readable = " ".join(part.replace("-", " ") for part in parts)
        return self.smart_title_case(readable)

Input:
    def process_doc_file(self, docs_path: str, file: str, root: str) -> Optional[dict]:
        """Your existing process_file function adapted for Typesense."""
        file_path = os.path.join(root, file)
        rel_path = os.path.relpath(file_path, docs_path)
        parts = pathlib.Path(rel_path).parts

        filename_no_ext = file.rsplit(".", 1)[0]

        parts_clean = []
        for i, p in enumerate(parts):
            is_last = i == len(parts) - 1
            if is_last:
                if filename_no_ext.lower().endswith("-ll"):
                    parts_clean.append("Low Level")
                else:
                    parts_clean.append(self.clean_name(filename_no_ext))
            else:
                parts_clean.append(self.clean_name(p))

        url_parts = [p.replace("_", "-").rsplit(".", 1)[0] for p in parts]
        if url_parts and url_parts[-1].endswith("-ll"):
            url_parts[-1] = url_parts[-1].replace("-ll", "/low")

        url = "/" + "/".join(url

Output:
def extract_components(self, file_path: str) -> List[str]:
        """Extract components from raw markdown file content."""
        with open(file_path, "r", encoding="utf-8") as f:
            content = f.read()

        patterns = [
            r"(?:rx|reflex)\.([A-Z][a-zA-Z0-9_]*)",
            r"\b([A-Z][a-z]+(?:[A-Z][a-z]*)*Component?)\b",
        ]
        components = set()
        for pattern in patterns:
            matches = re.findall(pattern, content)
            components.update(matches)
        return list(components)


Instruction:
ttern, content)
            components.update(matches)
        return list(components)

    def process_doc_file(self, docs_path: str, file: str, root: str) -> Optional[dict]:
        """Your existing process_file function adapted for Typesense."""
        file_path = os.path.join(root, file)
        rel_path = os.path.relpath(file_path, docs_path)
        parts = pathlib.Path(rel_path).parts

        filename_no_ext = file.rsplit(".", 1)[0]

        parts_clean = []
        for i, p in enumerate(parts):
            is_last = i == len(parts) - 1
            if is_last:
                if filename_no_ext.lower().endswith("-ll"):
                    parts_clean.append("Low Level")
                else:
                    parts_clean.append(self.clean_name(filename_no_ext))
            else:
                parts_clean.append(self.clean_name(p))

        url_parts = [p.replace("_", "-").rsplit(".", 1)[0] for p in parts]
        if url_parts and url_parts[-1].endswith("-ll"):

Input:
        url = "/" + "/".join(url_parts)
        name = " ".join(parts_clean)

        full_content = self.summarize_markdown(file_path, max_lines=100)
        components = self.extract_components(file_path)
        headings = self.extract_headings(open(file_path, "r", encoding="utf-8").read())

        parent = parts[0] if parts else ""
        cluster = "Uncategorized"
        for cluster_name, folder_list in CLUSTERS.items():
            if parent in folder_list:
                cluster = cluster_name
                break

        return {
            "id": str(rel_path),
            "title": name,
            "content": full_content,
            "components": components,
            "headings": headings,
            "path": str(rel_path),
            "url": f"docs{url}",
            "section": parent,
            "subsection": parts[1] if len(parts) > 1 else None,
            "cluster": cluster,
            "is_blog": False,
            "parts": parts_clean,
        }

    def _i

Output: url_parts[-1] = url_parts[-1].replace("-ll", "/low")


Instruction:
"""Integration tests for all titles in Reflex."""

import sys
from collections import Counter
from pathlib import Path

Input:
sys.path.append(str(Path(__file__).resolve().parent.parent))

@pytest.fixture
def routes_fixture():
    from pcweb.pages import routes

    yield routes

def test_unique_titles(routes_fixture):
    assert routes_fixture is not None

    titles = [route for route in routes_fixture if hasattr(route, "title")]

    # Count occurrences of each title
    title_counts = Counter(titles)
    # Find duplicate titles
    duplicates = [title for title, count in title_counts.items() if count > 1]

    # Assert that there are no duplicates
    assert len(duplicates) == 0, f"Duplicate titles found: {duplicates}"

    print(f"Test passed. All {len(titles)} titles are unique.")

Output: import pytest


Instruction:
_raw_date.strftime("%b %Y")
            else:
                filtered_data[-1]["date"] = last_raw_date.strftime("%b %d")
            if filtered_data[-1]["value"] != self._raw_net_worth_data[-1]["value"]:
                filtered_data.append(
                    {
                        "date": filtered_data[-1]["date"],
                        "value": self._raw_net_worth_data[-1]["value"],
                    }
                )
        return filtered_data

    @rx.var
    def total_assets(self) -> float:
        """Calculate total assets."""
        return round(
            sum((item["value"] for item in self.assets_summary)),
            2,
        )

    @rx.var
    def total_liabilities(self) -> float:
        """Calculate total liabilities."""
        cc_balance = next(
            (
                cat["total_balance"]
                for cat in self.account_categories
                if cat["category_name"] == "Credit Cards"
            ),
            0,
        )

Input:
        return round(other_liabilities + abs(cc_balance), 2)

    @rx.var
    def asset_percentages(
        self,
    ) -> List[AssetLiabilitySummaryItem]:
        """Calculate asset percentages."""
        total = self.total_assets
        if total == 0:
            return [
                {
                    "name": item["name"],
                    "value": 0.0,
                    "color": item["color"],
                }
                for item in self.assets_summary
            ]
        return [
            {
                "name": item["name"],
                "value": round(item["value"] / total * 100, 1),
                "color": item["color"],
            }
            for item in self.assets_summary
        ]

    @rx.var
    def liability_percentages(
        self,
    ) -> List[AssetLiabilitySummaryItem]:
        """Calculate liability percentages."""
        total = self.total_liabilities
        if total == 0:
            return [
                {

Output:
other_liabilities = sum(
            (
                item["value"]
                for item in self.liabilities_summary
                if item["name"] != "Credit Cards"
            )
        )


Instruction:
icon_base_class} text-gray-700"
    inactive_icon_class = f"{icon_base_class} text-gray-400 group-hover:text-gray-600"
    is_active_column = DashboardState.sort_column == column_key
    return rx.cond(
        is_active_column,
        rx.cond(
            DashboardState.sort_order == "asc",
            rx.icon(
                "arrow-up",
                size=12,
                class_name=active_icon_class,
            ),
            rx.icon(
                "arrow-down",
                size=12,
                class_name=active_icon_class,
            ),
        ),
        rx.icon(
            "chevrons-up-down",
            size=12,
            class_name=inactive_icon_class,
        ),
    )

def sortable_table_header(col_name: str, column_key: SortColumn) -> rx.Component:
    """Renders a sortable table header cell."""
    base_class = "px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider group"
    sortable_class = f"{base_class} cursor-pointer"

Input:
    justify_content_val = rx.match(
        col_name,
        ("Revenue", "flex-end"),
        ("Licenses", "center"),
        ("Active licenses", "center"),
        "flex-start",
    )
    combined_class = f"{sortable_class} {text_align_class}"
    header_content_inner = rx.el.div(
        col_name,
        sort_icon(column_key),
        class_name="flex items-center group-hover:text-gray-700 transition-colors duration-150 ease-in-out",
        style={"justify_content": justify_content_val},
    )
    return rx.el.th(
        header_content_inner,
        scope="col",
        class_name=combined_class,
        on_click=lambda: DashboardState.sort_by(column_key),
    )

def non_sortable_table_header(
    col_name: str,
) -> rx.Component:
    """Renders a non-sortable table header cell."""
    base_class = (
        "px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
    )
    text_align_class = rx.match(
        col_name,
        ("Revenue", "text-right")

Output:
text_align_class = rx.match(
        col_name,
        ("Revenue", "text-right"),
        ("Licenses", "text-center"),
        ("Active licenses", "text-center"),
        "text-left",
    )


Instruction:
from datetime import datetime
from typing import (
    List,
    Literal,
    Optional,
    Tuple,
)

import reflex as rx

from admin_dashboard.models.models import CustomerData
from admin_dashboard.states.data import initial_customer_data_raw
from admin_dashboard.states.utils import parse_date

SortColumn = Literal[
    "id",
    "next_renewal",
    "revenue",
    "licenses",
    "active_licenses",
]

Input:
processed_customers: List[CustomerData] = [
    {
        **customer,
        "next_renewal_date": parse_date(customer["next_renewal"]),
    }
    for customer in initial_customer_data_raw
]

COLUMN_MAPPING: List[Tuple[str, Optional[SortColumn]]] = [
    ("ID", "id"),
    ("Customer name", None),
    ("Next renewal", "next_renewal"),
    ("Revenue", "revenue"),
    ("Licenses", "licenses"),
    ("Active licenses", "active_licenses"),
    ("Active license growth", None),
    ("Industry", None),
    ("Platform", None),
]

class DashboardState(rx.State):
    """State class managing the customer dashboard data and UI interactions."""

    customers: List[CustomerData] = processed_customers
    selected_customer_id: Optional[int] = None
    search_term: str = ""
    sort_column: Optional[SortColumn] = "id"
    sort_order: SortOrder = "asc"

    @rx.var
    def column_data(
        self,
    ) -> List[Tuple[str, Optional[SortColumn]]]:
        """Returns the master list of column configur

Output: SortOrder = Literal["asc", "desc"]


Instruction:
ist[str] = [
        "Collaboration",
        "Leadership",
        "Innovation",
        "Creativity",
        "Feedback",
        "Coaching",
        "Mentoring",
        "Delegation",
    ]
    sort_column: str = "name"
    sort_order: str = "asc"
    current_page: int = 1
    items_per_page: int = 10
    total_db_customers: int = 0
    _target_customer_email_for_tags: str | None = None
    _target_customer_tag_str: str | None = None
    _target_customer_role: str | None = None
    _next_customer_id: int = 1
    search_query: str = ""

    @rx.var
    def total_users(self) -> int:
        return len(self._processed_customers)

    @rx.var
    def total_pages(self) -> int:
        num_items = len(self._processed_customers)
        if (
            self.items_per_page <= 0
        ):  # Guard against division by zero or invalid items_per_page
            return 0
        if num_items == 0:
            return 0
        return math.ceil(num_items / self.items_per_page)

    @rx.var

Input:
    @rx.var
    def customers(self) -> List[CustomerData]:
        data_for_page = self._processed_customers
        start_index = (self.current_page - 1) * self.items_per_page
        end_index = start_index + self.items_per_page
        return data_for_page[start_index:end_index]

    def _parse_tags_string(self, tags_str: str | None) -> List[str]:
        if not tags_str:
            return []
        tag_names_from_input = [
            name.strip() for name in tags_str.split(",") if name.strip()
        ]
        unique_tags: List[str] = []
        seen_tags: Set[str] = set()
        for tag in tag_names_from_input:
            if tag not in seen_tags:
                unique_tags.append(tag)
                seen_tags.add(tag)
        return unique_tags

    def _format_tags_list_to_string(self, tags_list: List[str]) -> str:
        return ", ".join(tags_list)

    @rx.event
    def sort_by_column(self, column_name: str):
        if self.sort_column == column_name:
            se

Output:
def _processed_customers(self) -> List[CustomerData]:
        data_to_process = list(
            self._all_customers_data
        )  # Make a copy to avoid modifying the original list if needed elsewhere

        # Apply search filter
        if self.search_query and self.search_query.strip():
            query_lower = self.search_query.lower().strip()
            data_to_process = [
                c
                for c in data_to_process
                if query_lower
                in f"{c.get('first_name', '')} {c.get('last_name', '')}".lower()
            ]

        # Apply sorting
        def get_sort_value(customer_data_item: CustomerData):
            if self.sort_column == "name":
                first = customer_data_item.get("first_name", "")
                last = customer_data_item.get("last_name", "")
                return (first.lower(), last.lower())

            sort_val = customer_data_item.get(self.sort_column)
            if isinstance(sort_val, str):
                return sort_val.lower()
            return sort_val

        sorted_data = sorted(
            data_to_process,
            key=get_sort_value,
            reverse=self.sort_order == "desc",
        )
        return sorted_data


Instruction:
= (self.current_page - 1) * self.items_per_page
        end_index = start_index + self.items_per_page
        return data_for_page[start_index:end_index]

    def _parse_tags_string(self, tags_str: str | None) -> List[str]:
        if not tags_str:
            return []
        tag_names_from_input = [
            name.strip() for name in tags_str.split(",") if name.strip()
        ]
        unique_tags: List[str] = []
        seen_tags: Set[str] = set()
        for tag in tag_names_from_input:
            if tag not in seen_tags:
                unique_tags.append(tag)
                seen_tags.add(tag)
        return unique_tags

    def _format_tags_list_to_string(self, tags_list: List[str]) -> str:
        return ", ".join(tags_list)

    @rx.event
    def sort_by_column(self, column_name: str):
        if self.sort_column == column_name:
            self.sort_order = "desc" if self.sort_order == "asc" else "asc"
        else:
            self.sort_column = column_name

Input:
        self.current_page = 1

    @rx.event
    async def fetch_customers(self):
        self.loading = True
        self.error_message = ""
        self.all_selected = False
        target_email = self._target_customer_email_for_tags
        target_tag_str = self._target_customer_tag_str
        target_role = self._target_customer_role
        self._target_customer_email_for_tags = None
        self._target_customer_tag_str = None
        self._target_customer_role = None

        if not self._all_customers_data:
            fake_customers_temp: List[CustomerData] = []
            first_names = [
                "John",
                "Jane",
                "Alice",
                "Bob",
                "Charlie",
                "David",
                "Eve",
                "Fiona",
                "George",
                "Hannah",
            ]
            last_names = [
                "Doe",
                "Smith",
                "Johnson",
                "Brown",

Output: self.sort_order = "asc"


Instruction:
s = email_from_form
        self._target_customer_tag_str = tags_str_from_form
        self._target_customer_role = role_from_form

        self.show_edit_dialog = False
        self._reset_form_fields()
        self.total_db_customers = len(self._all_customers_data)

        yield CustomerState.fetch_customers
        yield rx.toast(toast_message, duration=3000)

    @rx.event
    def set_form_status(self, status: str):
        self.form_status = status

    @rx.event
    def set_form_tags(self, tags: str):
        self.form_tags = tags

    @rx.event
    def set_form_role(self, role: str):
        self.form_role = role

    @rx.event
    def toggle_select_all(self):
        self.all_selected = not self.all_selected
        for i in range(len(self._all_customers_data)):
            self._all_customers_data[i]["selected"] = self.all_selected

    @rx.event
    def toggle_select_customer(self, customer_id: int):
        all_are_selected_after_toggle = True
        found = False

Input:
        if found:
            self.all_selected = all_are_selected_after_toggle

    @rx.event(background=True)
    async def download_csv(self):
        async with self:
            if not self._all_customers_data:
                self.error_message = "No customer data available to download. Please fetch customers first."
                yield rx.toast(
                    "No customer data to download.",
                    duration=3000,
                )
                return
            self.loading = True
            self.error_message = ""
        try:
            df_export_data = []
            for cust_data_item in self._all_customers_data:
                tags_str_repr = ", ".join(cust_data_item["tags"])
                df_export_data.append(
                    {
                        "ID": cust_data_item["customer_id"],
                        "First Name": cust_data_item["first_name"],
                        "Last Name": cust_data_item["last_name"],

Output:
for i in range(len(self._all_customers_data)):
            if self._all_customers_data[i]["customer_id"] == customer_id:
                self._all_customers_data[i]["selected"] = not self._all_customers_data[
                    i
                ]["selected"]
                found = True
            if not self._all_customers_data[i]["selected"]:
                all_are_selected_after_toggle = False


Instruction: import reflex as rx

Input:
border = f"1.5px solid {rx.color('gray', 5, True)}"
content_max_width = "1280px"
sidebar_bg = rx.color("gray", 2)
content_bg_color = rx.color("gray", 1)

image_style = {
    "decoding": "auto",
    "loading": "eager",
    "vertical_align": "middle",
    "object_fit": "contain",
    "width": "auto",
}

image_height = ["400px", "500px", "650px", "850px"]

image_props = {
    "style": image_style,
    "width": "100%",
    "height": image_height,
}

button_props = {
    "size": "2",
    "cursor": "pointer",
    "variant": "outline",
}

box_shadow = "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)"

base_stylesheets = [
    "https://fonts.googleapis.com/css2?family=Roboto+Flex:wght@400;500;600;700;800&display=swap",
    "react-zoom.css",
]

base_style = {
    "font_family": "Roboto Flex",
    rx.icon: {
        "stroke_width": "1.75px",
    },
}

Output: sidebar_width = ["100%", "100%", "100%", "375px", "450px"]


Instruction:
import reflex as rx

sidebar_width = ["100%", "100%", "100%", "375px", "450px"]

Input:
content_max_width = "1280px"
sidebar_bg = rx.color("gray", 2)
content_bg_color = rx.color("gray", 1)

image_style = {
    "decoding": "auto",
    "loading": "eager",
    "vertical_align": "middle",
    "object_fit": "contain",
    "width": "auto",
}

image_height = ["400px", "500px", "650px", "850px"]

image_props = {
    "style": image_style,
    "width": "100%",
    "height": image_height,
}

button_props = {
    "size": "2",
    "cursor": "pointer",
    "variant": "outline",
}

box_shadow = "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)"

base_stylesheets = [
    "https://fonts.googleapis.com/css2?family=Roboto+Flex:wght@400;500;600;700;800&display=swap",
    "react-zoom.css",
]

base_style = {
    "font_family": "Roboto Flex",
    rx.icon: {
        "stroke_width": "1.75px",
    },
}

Output: border = f"1.5px solid {rx.color('gray', 5, True)}"


Instruction:
import asyncio
import datetime
import os
from enum import Enum

import reflex as rx
import replicate

Input:
from .options import OptionsState

DEFAULT_IMAGE = "/default.webp"
API_TOKEN_ENV_VAR = "REPLICATE_API_TOKEN"

CopyLocalState = rx._x.client_state(default=False, var_name="copying")

class ResponseStatus(Enum):
    STARTING = "starting"
    PROCESSING = "processing"
    SUCCEEDED = "succeeded"
    FAILED = "failed"
    CANCELED = "canceled"

class GeneratorState(rx.State):
    is_generating: bool = False
    is_upscaling: bool = False
    _request_id: str = None
    output_image: str = DEFAULT_IMAGE
    output_list: list[str] = []
    upscaled_image: str = ""
    is_downloading: bool = False

    @rx.event
    def set_output_image(self, value: str):
        self.output_image = value

    @rx.event(background=True)
    async def generate_image(self):
        try:
            # Check if the env variable is set
            if not self._check_api_token():
                return
            if self.is_upscaling:
                yield rx.toast.warning("Wait for the image to upscale first"

Output: import requests


Instruction:
= ""
                self.output_image = response.output[0]
                self.output_list = [] if len(response.output) == 1 else response.output
                self._reset_state()

        except Exception as e:
            async with self:
                self._reset_state()
            yield rx.toast.error(f"Error, please try again: {e}")

    @rx.event(background=True)
    async def upscale_image(self):
        try:
            # Check if the env variable is set
            if not self._check_api_token():
                return
            if self.is_generating:
                yield rx.toast.warning("Wait for the image to generate first")
                return
            if self.output_image == DEFAULT_IMAGE:
                yield rx.toast.warning("Please generate an image first")
                return
            if self.upscaled_image != "":
                yield rx.toast.warning("Image already upscaled")
                return
            async with self:

Input:
            input = {
                "prompt": "masterpiece, best quality, highres, <lora:more_details:0.5> <lora:SDXLrender_v2.0:1>",
                "negative_prompt": "(worst quality, low quality, normal quality:2) JuggernautNegative-neg",
                "num_inference_steps": 18,
                "scheduler": "DPM++ 3M SDE Karras",
                "image": self.output_image,
                "dynamic": 6,
                "handfix": "disabled",
                "sharpen": 0,
                "sd_model": "juggernaut_reborn.safetensors [338b85bc4f]",
                "creativity": 0.35,
                "lora_links": "",
                "downscaling": False,
                "resemblance": 0.6,
                "scale_factor": 2,
                "tiling_width": 112,
                "output_format": "png",
                "tiling_height": 144,
                "custom_sd_model": "",
                "downscaling_resolution": 768,
            }
            # Add "seed" to the input if it is no

Output: Options = await self.get_state(OptionsState)


Instruction:
TARTING.value or not response:
                async with self:
                    self._request_id, self.is_upscaling = None, False
                yield rx.toast.error("Error starting upscaling")
                return

            async with self:
                self.is_upscaling = True
                self._request_id = response.id
                yield

            while True:
                response = await replicate.predictions.async_get(response.id)
                async with self:
                    if response.status in (
                        ResponseStatus.CANCELED.value,
                        ResponseStatus.FAILED.value,
                    ):
                        self._reset_state()
                        if response.status == ResponseStatus.FAILED.value:
                            yield rx.toast.warning(
                                f"Error upscaling image: {response.error}"
                            )
                        return

Input:
                await asyncio.sleep(0.15)
            async with self:
                self.upscaled_image = response.output[0]
                self.output_list = []
                self._request_id, self.is_upscaling = None, False

        except Exception as e:
            async with self:
                self._reset_state()
            yield rx.toast.error(f"Error, please try again: {e}")

    def cancel_generation(self):
        if self._request_id is None:
            return
        try:
            response = replicate.predictions.cancel(self._request_id)
            if response.status != ResponseStatus.CANCELED.value:
                raise Exception("Error cancelling generation")
        except Exception as e:
            yield rx.toast.error(f"Error cancelling generation: {e}")
        finally:
            self._reset_state()

    def _reset_state(self):
        self._request_id = None
        self.is_generating = False
        self.is_upscaling = False

    def _check_api_tok

Output:
elif response.status == ResponseStatus.SUCCEEDED.value:
                        break


Instruction:
import random

import reflex as rx

Input:
from ..components.styles_preset import styles_preset

class OptionsState(rx.State):
    dimensions: list[tuple[int, int]] = [
        (1728, 576),
        (1664, 576),
        (1600, 640),
        (1536, 640),
        (1472, 704),
        (1408, 704),
        (1344, 704),
        (1344, 768),
        (1280, 768),
        (1216, 832),
        (1152, 832),
        (1152, 896),
        (1088, 896),
        (1088, 960),
        (1024, 960),
        (1024, 1024),
        (960, 1024),
        (960, 1088),
        (896, 1088),
        (896, 1152),
        (832, 1152),
        (832, 1216),
        (768, 1280),
        (768, 1344),
        (704, 1344),
        (704, 1408),
        (704, 1472),
        (640, 1536),
        (640, 1600),
        (576, 1664),
        (576, 1728),
    ]
    slider_tick: int = len(dimensions) // 2
    selected_dimensions: tuple[int, int] = dimensions[slider_tick]
    hover: bool = False
    styles_preset: dict[str, dict[str, str]] = styles_preset
    selected_style

Output: from ..components.prompt_list import prompt_list


Instruction:
ist[dict[str, str]]
    get_table_headers: list[str]
    paginated_data: list[dict[str, str]]

    # vars for pagination ...
    number_of_rows: int
    limits: list[str] = ["10", "20", "50"]
    current_limit: int = 10
    offset: int = 0
    current_page: int = 1
    total_pages: int = 1
    formatted_headers: dict

    @rx.event
    def set_req_url(self, url: str):
        self.req_url = url

    @rx.event
    def get_request(self, method: str):
        self.current_req = method

    @rx.event
    def add_header(self):
        self.headers.append(
            {"id": str(uuid.uuid4()), "identifier": "headers", "key": "", "value": ""}
        )

    @rx.event
    def add_body(self):
        self.body.append(
            {"id": str(uuid.uuid4()), "identifier": "body", "key": "", "value": ""}
        )

    @rx.event
    def add_cookies(self):
        self.cookies.append(
            {"id": str(uuid.uuid4()), "identifier": "cookies", "key": "", "value": ""}
        )

    @rx.event

Input:
    @rx.event
    async def update_attribute(self, data: dict[str, str], attribute: str, value: str):
        data[attribute] = value

        if data["identifier"] == "headers":
            self.headers = [
                data if item["id"] == data["id"] else item for item in self.headers
            ]

        if data["identifier"] == "body":
            self.body = [
                data if item["id"] == data["id"] else item for item in self.body
            ]

        if data["identifier"] == "cookies":
            self.cookies = [
                data if item["id"] == data["id"] else item for item in self.cookies
            ]

    @rx.event
    async def update_keyy(self, key: str, data: dict[str, str]):
        await self.update_attribute(data, "key", key)

    @rx.event
    async def update_value(self, value: str, data: dict[str, str]):
        await self.update_attribute(data, "value", value)

class QueryAPI(QueryState):
    # vars to update row entries ...
    is_open: bo

Output:
def remove_entry(self, data: dict[str, str]):
        if data["identifier"] == "headers":
            self.headers = [item for item in self.headers if item["id"] != data["id"]]

        if data["identifier"] == "body":
            self.body = [item for item in self.body if item["id"] != data["id"]]

        if data["identifier"] == "cookies":
            self.cookies = [item for item in self.cookies if item["id"] != data["id"]]


Instruction:
ns import Counter, defaultdict
from typing import Dict, List, TypedDict

import reflex as rx
from faker import Faker

from business_analytics_dashboard.models.employee import Employee

fake = Faker()

class DepartmentData(TypedDict):
    name: str
    value: int

class AverageSalaryData(TypedDict):
    department: str
    average_salary: float

class DashboardState(rx.State):
    """State for the dashboard."""

    employees: List[Employee] = []
    search_query: str = ""
    selected_department: str = "All"
    loading: bool = False
    _base_department_colors: list[str] = [
        "#FF6347",
        "#4CAF50",
        "#FFEB3B",
        "#2196F3",
        "#9C27B0",
        "#FFC107",
        "#8BC34A",
        "#FF9800",
        "#F44336",
        "#00BCD4",
    ]
    current_page: int = 1
    items_per_page: int = 10

    @rx.event(background=True)
    async def fetch_dashboard_data(self):
        """Generate fake data for the dashboard."""
        async with self:

Input:
            self.current_page = 1
        await asyncio.sleep(0.5)
        await self._generate_fake_data()
        async with self:
            self.loading = False

    async def _generate_fake_data(self):
        """Helper method to generate fake employee data."""
        departments = [
            "Sales",
            "Marketing",
            "Engineering",
            "Support",
            "HR",
            "Finance",
            "Product",
            "Design",
            "Operations",
            "Legal",
        ]
        employees_data = []
        for i in range(1, 101):
            first_name = fake.first_name()
            last_name = fake.last_name()
            department = random.choice(departments)
            employees_data.append(
                Employee(
                    employee_id=1000 + i,
                    first_name=first_name,
                    last_name=last_name,
                    email=fake.email(),
                    department=department,

Output: self.loading = True


Instruction:
ict):
    department: str
    average_salary: float

class DashboardState(rx.State):
    """State for the dashboard."""

    employees: List[Employee] = []
    search_query: str = ""
    selected_department: str = "All"
    loading: bool = False
    _base_department_colors: list[str] = [
        "#FF6347",
        "#4CAF50",
        "#FFEB3B",
        "#2196F3",
        "#9C27B0",
        "#FFC107",
        "#8BC34A",
        "#FF9800",
        "#F44336",
        "#00BCD4",
    ]
    current_page: int = 1
    items_per_page: int = 10

    @rx.event(background=True)
    async def fetch_dashboard_data(self):
        """Generate fake data for the dashboard."""
        async with self:
            self.loading = True
            self.current_page = 1
        await asyncio.sleep(0.5)
        await self._generate_fake_data()
        async with self:
            self.loading = False

    async def _generate_fake_data(self):
        """Helper method to generate fake employee data."""

Input:
        employees_data = []
        for i in range(1, 101):
            first_name = fake.first_name()
            last_name = fake.last_name()
            department = random.choice(departments)
            employees_data.append(
                Employee(
                    employee_id=1000 + i,
                    first_name=first_name,
                    last_name=last_name,
                    email=fake.email(),
                    department=department,
                    salary=random.randint(50000, 150000),
                    projects_closed=random.randint(0, 20),
                    pending_projects=random.randint(0, 5),
                )
            )
        async with self:
            self.employees = employees_data

    @rx.var
    def available_departments(self) -> list[str]:
        """Get a sorted list of unique departments including 'All'."""
        if not self.employees:
            return ["All"]
        departments = sorted({emp["department"] for emp in self.

Output:
departments = [
            "Sales",
            "Marketing",
            "Engineering",
            "Support",
            "HR",
            "Finance",
            "Product",
            "Design",
            "Operations",
            "Legal",
        ]


Instruction:
    "#9C27B0",
        "#FFC107",
        "#8BC34A",
        "#FF9800",
        "#F44336",
        "#00BCD4",
    ]
    current_page: int = 1
    items_per_page: int = 10

    @rx.event(background=True)
    async def fetch_dashboard_data(self):
        """Generate fake data for the dashboard."""
        async with self:
            self.loading = True
            self.current_page = 1
        await asyncio.sleep(0.5)
        await self._generate_fake_data()
        async with self:
            self.loading = False

    async def _generate_fake_data(self):
        """Helper method to generate fake employee data."""
        departments = [
            "Sales",
            "Marketing",
            "Engineering",
            "Support",
            "HR",
            "Finance",
            "Product",
            "Design",
            "Operations",
            "Legal",
        ]
        employees_data = []
        for i in range(1, 101):
            first_name = fake.first_name()

Input:
            department = random.choice(departments)
            employees_data.append(
                Employee(
                    employee_id=1000 + i,
                    first_name=first_name,
                    last_name=last_name,
                    email=fake.email(),
                    department=department,
                    salary=random.randint(50000, 150000),
                    projects_closed=random.randint(0, 20),
                    pending_projects=random.randint(0, 5),
                )
            )
        async with self:
            self.employees = employees_data

    @rx.var
    def available_departments(self) -> list[str]:
        """Get a sorted list of unique departments including 'All'."""
        if not self.employees:
            return ["All"]
        departments = sorted({emp["department"] for emp in self.employees})
        return ["All", *departments]

    @rx.var
    def departments_for_filter(self) -> list[str]:
        """Get a sorted list of

Output: last_name = fake.last_name()


Instruction:
import asyncio
import os
from typing import List, TypedDict

import reflex as rx

class Message(TypedDict):
    text: str
    is_ai: bool

class ChatState(rx.State):
    messages: List[Message] = []
    typing: bool = False
    has_openai_key: bool = "OPENAI_API_KEY" in os.environ

    @rx.event
    def clear_messages(self):
        """Clears all chat messages and resets typing status."""
        self.typing = False

Input:
    @rx.event
    def send_message(self, form_data: dict):
        """Adds a user message and triggers AI response generation."""
        if self.typing:
            return
        message = form_data["message"].strip()
        if message:
            self.messages.append({"text": message, "is_ai": False})
            self.messages.append({"text": "", "is_ai": True})
            self.typing = True
            yield ChatState.generate_response

    @rx.event(background=True)
    async def generate_response(self):
        """Generates a response (mock or OpenAI)."""
        if not self.has_openai_key:
            await asyncio.sleep(1)
            response = "This is a mock response as the OPENAI_API_KEY is not set. Please set the environment variable to use the actual LLM."
            current_text = ""
            async with self:
                if not self.messages:
                    self.typing = False
                    return
            for char in response:

Output: self.messages = []


Instruction:
           "pipeline",
                        "status",
                        "workflow",
                        "timestamp",
                        "duration",
                    ]
                )
            ]

        return items

    @rx.var(cache=True)
    def page_number(self) -> int:
        return (self.offset // self.limit) + 1

    @rx.var(cache=True)
    def total_pages(self) -> int:
        return (self.total_items // self.limit) + (
            1 if self.total_items % self.limit else 0
        )

    @rx.var(cache=True, initial_value=[])
    def get_current_page(self) -> list[Item]:
        start_index = self.offset
        end_index = start_index + self.limit
        return self.filtered_sorted_items[start_index:end_index]

    def prev_page(self):
        if self.page_number > 1:
            self.offset -= self.limit

    def next_page(self):
        if self.page_number < self.total_pages:
            self.offset += self.limit

    def first_page(self):

Input:
    def last_page(self):
        self.offset = (self.total_pages - 1) * self.limit

    def load_entries(self):
        with Path("data.csv").open(encoding="utf-8") as file:
            reader = csv.DictReader(file)
            self.items = [Item(**row) for row in reader]
            self.total_items = len(self.items)

    def toggle_sort(self):
        self.sort_reverse = not self.sort_reverse
        self.load_entries()

Output: self.offset = 0


Instruction:
"""The about page of the app."""

from pathlib import Path

import reflex as rx

Input:
from ..templates import template

@template(route="/about", title="About")
def about() -> rx.Component:
    """The about page.

    Returns:
        The UI for the about page.

    """
    with Path("README.md").open(encoding="utf-8") as readme:
        content = readme.read()
    return rx.markdown(content, component_map=styles.markdown_style)

Output: from .. import styles


Input:
from reflex.components.radix.themes.base import LiteralAccentColor, LiteralGrayColor

from .. import styles
from ..templates.template import ThemeState

primary_color_dict: dict[str, str] = {
    color.capitalize(): f"linear-gradient(45deg, {rx.color(color, 10)}, {rx.color(color, 8)})"
    for color in LiteralAccentColor.__args__
}

secondary_color_dict: dict[str, str] = {
    color.capitalize(): f"linear-gradient(45deg, {rx.color(color, 10)}, {rx.color(color, 8)})"
    for color in LiteralGrayColor.__args__
    if color != "auto"  # Remove auto from the list
}

class ColorPickerState(rx.State):
    primary_color_options: dict[str, str] = primary_color_dict
    secondary_color_options: dict[str, str] = secondary_color_dict

def _display_primary_color(color: list) -> rx.Component:
    return rx.tooltip(
        rx.box(
            rx.cond(
                color[0].lower() == ThemeState.accent_color.lower(),
                rx.box(
                    rx.icon("check", color=rx.color("

Output: import reflex as rx


Instruction:
er": "Executive summary",
                "section_type": "Narrative",
                "status": "Done",
                "target": 10,
                "limit": 13,
                "reviewer": "Eddie Lake",
            }
        )
        self.document_data[3].update(
            {
                "header": "Technical approach",
                "section_type": "Narrative",
                "status": "Done",
                "target": 27,
                "limit": 23,
                "reviewer": "Jamik Tashpulatov",
            }
        )

    @rx.event
    def load_initial_data(self):
        """Load initial fake data if not already loaded."""
        if (
            not self.key_metrics
            and (not self.visitor_data)
            and (not self.document_data)
        ):
            self._generate_fake_data()

    @rx.event
    def set_visitor_timeframe(self, timeframe: str):
        self.selected_visitor_timeframe = timeframe

        if timeframe == "Last 3 months":

Input:
        if timeframe == "Last 30 days":
            self.displayed_visitor_data = self.visitor_data[-30:]

        if timeframe == "Last 7 days":
            self.displayed_visitor_data = self.visitor_data[-7:]

    @rx.event
    def set_document_tab(self, tab: str):
        self.selected_document_tab = tab

TOOLTIP_PROPS = {
    "separator": ": ",
    "cursor": False,
    "is_animation_active": False,
    "label_style": {"fontWeight": "500"},
    "item_style": {
        "color": "currentColor",
        "display": "flex",
        "paddingBottom": "0px",
        "justifyContent": "space-between",
        "textTransform": "capitalize",
    },
    "content_style": {
        "borderRadius": "5px",
        "boxShadow": "0px 2px 6px 0px rgba(0, 0, 0, 0.1)",
        "fontSize": "0.75rem",
        "lineHeight": "1rem",
        "fontWeight": "500",
        "minWidth": "8rem",
        "width": "auto",
        "padding": "0.375rem 0.625rem",
        "backgroundColor": "white",
        "border"

Output: self.displayed_visitor_data = self.visitor_data


Instruction: import os

Input:
database_url = os.getenv("DATABASE_URL", "sqlite:///reflex.db")

config = rx.Config(
    app_name="customer_data",
    db_url=database_url,
    plugins=[rx.plugins.SitemapPlugin()],
)

Output: import reflex as rx


Instruction:
"""Welcome to Reflex! This file outlines the steps to create a basic app."""

import os

import openai
import reflex as rx

_client = None

def get_openai_client():
    global _client
    if _client is None:
        _client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

    return _client

class State(rx.State):
    """The app state."""

Input:
    image_processing = False
    image_made = False

    def get_dalle_result(self, form_data: dict[str, str]):
        prompt_text: str = form_data["prompt_text"]
        self.image_made = False
        self.image_processing = True
        # Yield here so the image_processing take effects and the circular progress is shown.
        yield
        try:
            response = get_openai_client().images.generate(
                prompt=prompt_text, n=1, size="1024x1024"
            )
            self.image_url = response.data[0].url
            self.image_processing = False
            self.image_made = True
            yield
        except Exception as ex:
            self.image_processing = False
            yield rx.window_alert(f"Error with OpenAI Execution. {ex}")

def index():
    return rx.center(
        rx.vstack(
            rx.heading("DALL-E", font_size="1.5em"),
            rx.form(
                rx.vstack(
                    rx.input(
                        id="prompt_

Output: image_url = ""


Input:
from pathlib import Path
from typing import List

import reflex as rx

class Item(rx.Base):
    """The item class."""

    name: str
    payment: float
    date: str
    status: str

class TableState(rx.State):
    """The state class."""

    items: List[Item] = []

    search_value: str = ""
    sort_value: str = ""
    sort_reverse: bool = False

    total_items: int = 0
    offset: int = 0
    limit: int = 12  # Number of rows per page

    @rx.event
    def set_search_value(self, value: str):
        self.search_value = value

    @rx.event
    def set_sort_value(self, value: str):
        self.sort_value = value

    @rx.var(cache=True)
    def filtered_sorted_items(self) -> List[Item]:
        items = self.items

        # Filter items based on selected item
        if self.sort_value:
            if self.sort_value in ["payment"]:
                items = sorted(
                    items,
                    key=lambda item: float(getattr(item, self.sort_value)),

Output: import csv


Instruction:
         item
                for item in items
                if any(
                    search_value in str(getattr(item, attr)).lower()
                    for attr in [
                        "name",
                        "payment",
                        "date",
                        "status",
                    ]
                )
            ]

        return items

    @rx.var(cache=True)
    def page_number(self) -> int:
        return (self.offset // self.limit) + 1

    @rx.var(cache=True)
    def total_pages(self) -> int:
        return (self.total_items // self.limit) + (
            1 if self.total_items % self.limit else 1
        )

    @rx.var(cache=True, initial_value=[])
    def get_current_page(self) -> list[Item]:
        start_index = self.offset
        end_index = start_index + self.limit
        return self.filtered_sorted_items[start_index:end_index]

    def prev_page(self):
        if self.page_number > 1:
            self.offset -= self.limit

Input:
    def first_page(self):
        self.offset = 0

    def last_page(self):
        self.offset = (self.total_pages - 1) * self.limit

    def load_entries(self):
        with Path("items.csv").open(mode="r", encoding="utf-8") as file:
            reader = csv.DictReader(file)
            self.items = [Item(**row) for row in reader]
            self.total_items = len(self.items)

    def toggle_sort(self):
        self.sort_reverse = not self.sort_reverse
        self.load_entries()

Output:
def next_page(self):
        if self.page_number < self.total_pages:
            self.offset += self.limit


Instruction:
"""Common templates used between pages in the app."""

from __future__ import annotations

from typing import Callable

import reflex as rx

from .. import styles
from ..components.navbar import navbar
from ..components.sidebar import sidebar

# Meta tags for the app.
default_meta = [
    {
        "name": "viewport",
        "content": "width=device-width, shrink-to-fit=no, initial-scale=1",
    },
]

Input:
class ThemeState(rx.State):
    """The state for the theme of the app."""

    accent_color: str = "crimson"

    gray_color: str = "gray"

    radius: str = "large"

    scaling: str = "100%"

    @rx.event
    def set_scaling(self, value: str):
        self.scaling = value

    @rx.event
    def set_radius(self, value: str):
        self.radius = value

    @rx.event
    def set_accent_color(self, value: str):
        self.accent_color = value

    @rx.event
    def set_gray_color(self, value: str):
        self.gray_color = value

ALL_PAGES = []

def template(
    route: str | None = None,
    title: str | None = None,
    description: str | None = None,
    meta: str | None = None,
    script_tags: list[rx.Component] | None = None,
    on_load: rx.event.EventType[()] | None = None,
) -> Callable[[Callable[[], rx.Component]], rx.Component]:
    """The template for each page of the app.

    Args:
        route: The route to reach the page.
        title: The title of the page.

Output:
def menu_item_link(text, href):
    return rx.menu.item(
        rx.link(
            text,
            href=href,
            width="100%",
            color="inherit",
        ),
        _hover={
            "color": styles.accent_color,
            "background_color": styles.accent_text_color,
        },
    )


Input:
from ..templates.template import ThemeState

def radius_picker() -> rx.Component:
    return (
        rx.vstack(
            rx.hstack(
                rx.icon("radius"),
                rx.heading("Radius", size="6"),
                align="center",
            ),
            rx.select(
                [
                    "none",
                    "small",
                    "medium",
                    "large",
                    "full",
                ],
                size="3",
                value=ThemeState.radius,
                on_change=ThemeState.set_radius,
            ),
            width="100%",
        ),
    )

Output: import reflex as rx


Instruction:
import reflex as rx

from manufacturing_dashboard.states.dashboard_state import DashboardState

def time_completion_circle() -> rx.Component:
    """Renders the circular progress indicator for time to completion."""

Input:
    return rx.el.svg(
        rx.el.circle(
            cx="50",
            cy="50",
            r=str(radius),
            stroke="#334155",
            stroke_width="8",
            fill="none",
            class_name="text-slate-700",
        ),
        rx.el.circle(
            cx="50",
            cy="50",
            r=str(radius),
            stroke="#06b6d4",
            stroke_width="8",
            fill="none",
            stroke_dasharray=DashboardState.get_time_stroke_dasharray,
            stroke_linecap="round",
            transform="rotate(-90 50 50)",
            class_name="transition-all duration-300 ease-linear",
        ),
        rx.el.text(
            DashboardState.time_to_completion.to(int).to_string() + "%",
            x="50",
            y="50",
            text_anchor="middle",
            dominant_baseline="middle",
            font_size="18",
            font_weight="bold",
            fill="#cbd5e1",
        ),
        view_box="0 0 100 100",

Output: radius = 40


Instruction:
         "value": metric["ooc_percent"],
                    "fill": fill_color,
                }
            )
    if not pie_data:
        default_low_ooc = [
            ("Diameter", 0.5),
            ("Etch1", 0.3),
        ]
        for name, value in default_low_ooc:
            pie_data.append(
                {
                    "name": name,
                    "value": value,
                    "fill": colors_pass[color_index_pass % len(colors_pass)],
                }
            )
            color_index_pass += 1
    return pie_data

def _generate_distribution_data(
    spc_data: List[SpcDataPoint], num_bins=8
) -> List[DistributionPoint]:
    """Generates histogram-like data from SPC points."""
    if not spc_data:
        return []
    values = [p["value"] for p in spc_data]
    min_val, max_val = (min(values), max(values))
    if min_val == max_val:
        return [{"name": f"{min_val:.3f}", "value": len(values)}]
    bin_width = (max_val - min_val) / num_bins

Input:
    for val in values:
        bin_index = min(int((val - min_val) / bin_width), num_bins - 1)
        if val == max_val:
            bin_index = num_bins - 1
        bins[bin_index] += 1
    dist_data = []
    for i in range(num_bins):
        bin_start = min_val + i * bin_width
        bin_name = f"{bin_start:.3f}"
        dist_data.append({"name": bin_name, "value": bins[i]})
    return dist_data

initial_process_metrics = _generate_process_metrics()
initial_spc_data = _generate_spc_data(base_min=0.415, base_max=0.424)
initial_pie_data = _generate_pie_data(initial_process_metrics)
initial_distribution_data = _generate_distribution_data(initial_spc_data)

class DashboardState(rx.State):
    """Handles the state and logic for the dashboard application."""

    operator_id: str = fake.bothify(text="OP-####")
    time_to_completion: float = 0.0
    is_running: bool = False
    ucl: float = 0.432
    lcl: float = 0.407
    target_mean: float = 0.42
    usl: float = 0.424
    lsl: floa

Output: bins = [0] * num_bins


Instruction:
 = False
    ucl: float = 0.432
    lcl: float = 0.407
    target_mean: float = 0.42
    usl: float = 0.424
    lsl: float = 0.415
    process_metrics: List[MetricData] = initial_process_metrics
    spc_chart_data: List[SpcDataPoint] = initial_spc_data
    pie_data: List[PieChartData] = initial_pie_data
    distribution_data: List[DistributionPoint] = initial_distribution_data

    def _reset_to_initial(self):
        """Resets data to a new initial state."""
        self.process_metrics = _generate_process_metrics()
        self.spc_chart_data = _generate_spc_data(base_min=self.lsl, base_max=self.usl)
        self.pie_data = _generate_pie_data(self.process_metrics)
        self.distribution_data = _generate_distribution_data(self.spc_chart_data)

    @rx.event(background=True)
    async def start_process(self):
        """Simulates starting a process and updating data over time using Faker."""
        async with self:
            if self.is_running:
                return

Input:
            self.time_to_completion = 0.0
        update_interval = 0.1
        data_gen_interval = 10
        metrics_update_interval = 30
        for i in range(101):
            async with self:
                self.time_to_completion = float(i)
                if i > 0 and i % data_gen_interval == 0:
                    last_name = (
                        self.spc_chart_data[-1]["name"] if self.spc_chart_data else -1
                    )
                    new_name = last_name + 1
                    new_value_base = fake.pyfloat(
                        left_digits=0,
                        right_digits=4,
                        positive=True,
                        min_value=self.lsl - 0.002,
                        max_value=self.usl + 0.002,
                    )
                    if self.spc_chart_data:
                        drift = random.uniform(-0.001, 0.001)
                        new_value_base = self.spc_chart_data[-1]["value"] + drift
                    if

Output: self.is_running = True


Instruction:
 = _generate_process_metrics()
        self.spc_chart_data = _generate_spc_data(base_min=self.lsl, base_max=self.usl)
        self.pie_data = _generate_pie_data(self.process_metrics)
        self.distribution_data = _generate_distribution_data(self.spc_chart_data)

    @rx.event(background=True)
    async def start_process(self):
        """Simulates starting a process and updating data over time using Faker."""
        async with self:
            if self.is_running:
                return
            self.is_running = True
            self.time_to_completion = 0.0
        update_interval = 0.1
        data_gen_interval = 10
        metrics_update_interval = 30
        for i in range(101):
            async with self:
                self.time_to_completion = float(i)
                if i > 0 and i % data_gen_interval == 0:
                    last_name = (
                        self.spc_chart_data[-1]["name"] if self.spc_chart_data else -1
                    )

Input:
                    new_value_base = fake.pyfloat(
                        left_digits=0,
                        right_digits=4,
                        positive=True,
                        min_value=self.lsl - 0.002,
                        max_value=self.usl + 0.002,
                    )
                    if self.spc_chart_data:
                        drift = random.uniform(-0.001, 0.001)
                        new_value_base = self.spc_chart_data[-1]["value"] + drift
                    if random.random() < 0.08:
                        new_value_base += random.uniform(0.003, 0.008)
                    elif random.random() < 0.08:
                        new_value_base -= random.uniform(0.003, 0.008)
                    new_value = round(
                        max(
                            self.lcl - 0.01,
                            min(
                                self.ucl + 0.01,
                                new_value_base,
                            ),

Output: new_name = last_name + 1


Instruction:
       4,
                    )
                    new_point: SpcDataPoint = {
                        "name": new_name,
                        "value": new_value,
                    }
                    self.spc_chart_data = ([*self.spc_chart_data, new_point])[-50:]
                    self.distribution_data = _generate_distribution_data(
                        self.spc_chart_data
                    )
                if i > 0 and i % metrics_update_interval == 0:
                    self.process_metrics = _generate_process_metrics()
                    self.pie_data = _generate_pie_data(self.process_metrics)
            await asyncio.sleep(update_interval)
            yield
        async with self:
            self.is_running = False
            self._reset_to_initial()

    @rx.var
    def get_time_stroke_dasharray(self) -> str:
        """Calculates the stroke-dasharray for the time completion circle."""
        percentage = self.time_to_completion
        radius = 40

Input:
        clamped_percentage = max(0, min(percentage, 100))
        dash_length = clamped_percentage / 100 * circumference
        dash_length = max(0, dash_length)
        gap_length = max(0, circumference - dash_length)
        return f"{dash_length:.2f} {gap_length:.2f}"

    @rx.var
    def ooc_points(self) -> List[SpcDataPoint]:
        """Filters SPC data to find points outside control limits (OOC)."""
        ooc = []
        if not self.spc_chart_data:
            return []
        ooc = [
            point
            for point in self.spc_chart_data
            if isinstance(point.get("value"), (int, float))
            and (point["value"] < self.lcl or point["value"] > self.ucl)
        ]

        return ooc

Output: circumference = 2 * 3.14159 * radius


Instruction:
from typing import Dict, List

import numpy as np
import pandas as pd
import reflex as rx

from .data_items import all_items

Input:
nba_csv = "nbastats.csv"

class State(rx.State):
    """The app state."""

    players: list[Player] = []

    search_value: str = ""
    sort_value: str = ""
    sort_reverse: bool = False

    total_items: int = 0
    offset: int = 0
    limit: int = 12  # Number of rows per page

    selected_items: Dict[str, List] = (
        all_items  # We add all items to the selected items by default
    )
    age: tuple[int, int] = (19, 40)
    salary: tuple[int, int] = (0, 25000000)

    @rx.event
    def set_age(self, value: list[int | float]):
        self.age = (int(value[0]), int(value[1]))

    @rx.event
    def set_salary(self, value: list[int | float]):
        self.salary = (int(value[0]), int(value[1]))

    @rx.event
    def set_sort_value(self, value: str):
        self.sort_value = value

    @rx.event
    def set_search_value(self, value: str):
        self.search_value = value

    @rx.var(cache=True)
    def filtered_sorted_players(self) -> list[Player]:
        players = se

Output: from .player import Player


Instruction:
lleges"]
                and player.position in self.selected_items["positions"]
                and self.age[0] <= player.age <= self.age[1]
                and self.salary[0] <= float(player.salary) <= self.salary[1]
            ):
                age = player.age
                if age not in age_salary_data:
                    age_salary_data[age] = 0
                    age_count[age] = 0

                age_salary_data[age] += float(player.salary)
                age_count[age] += 1

        return [
            {
                "age": age,
                "average salary": round(
                    age_salary_data.get(age, 0) / age_count.get(age, 1), 2
                ),
            }
            for age in range(self.age[0], self.age[1] + 1)  # Ensure we include all ages
        ]

    @rx.var(cache=True)
    def get_position_salary_chart_data(self) -> list[dict]:
        position_salary_data = {}
        position_count = {}

        for player in self.players:

Input:
        return [
            {
                "position": position,
                "average salary": round(
                    position_salary_data[position] / position_count[position], 2
                ),
            }
            for position in position_salary_data
        ]

    @rx.var(cache=True)
    def get_team_salary_chart_data(self) -> list[dict]:
        team_salary_data = {}
        team_count = {}

        for player in self.players:
            if (
                not pd.isna(player.team)
                and not pd.isna(player.salary)
                and player.team in self.selected_items["teams"]
                and player.college in self.selected_items["colleges"]
                and player.position in self.selected_items["positions"]
                and self.age[0] <= player.age <= self.age[1]
                and self.salary[0] <= float(player.salary) <= self.salary[1]
            ):
                team = player.team
                if team not in team_salary_d

Output:
if (
                not pd.isna(player.position)
                and not pd.isna(player.salary)
                and player.team in self.selected_items["teams"]
                and player.college in self.selected_items["colleges"]
                and player.position in self.selected_items["positions"]
                and self.age[0] <= player.age <= self.age[1]
                and self.salary[0] <= float(player.salary) <= self.salary[1]
            ):
                position = player.position
                if position not in position_salary_data:
                    position_salary_data[position] = 0
                    position_count[position] = 0

                position_salary_data[position] += float(player.salary)
                position_count[position] += 1


Instruction:
lleges"]
                and player.position in self.selected_items["positions"]
                and self.age[0] <= player.age <= self.age[1]
                and self.salary[0] <= float(player.salary) <= self.salary[1]
            ):
                position = player.position
                if position not in position_age_data:
                    position_age_data[position] = []
                    position_count[position] = 0

                position_age_data[position].append(player.age)
                position_count[position] += 1

        return [
            {
                "position": position,
                "average age": round(sum(ages) / position_count[position], 2),
            }
            for position, ages in position_age_data.items()
        ]

    def add_selected(self, list_name: str, item: str):
        self.selected_items[list_name].append(item)

    def remove_selected(self, list_name: str, item: str):
        self.selected_items[list_name].remove(item)

Input:
    def clear_selected(self, list_name: str):
        self.selected_items[list_name].clear()

    def random_selected(self, list_name: str):
        self.selected_items[list_name] = np.random.choice(
            all_items[list_name],
            size=np.random.randint(1, len(all_items[list_name]) + 1),
            replace=False,
        ).tolist()

Output:
def add_all_selected(self, list_name: str):
        self.selected_items[list_name] = list(all_items[list_name])


Instruction:
alue": "$200",
            "value_num": 200.0,
            "percentage": 68.1,
            "color": "bg-indigo-600",
        },
        {
            "label": "On-demand charges",
            "value": "$61.1",
            "value_num": 61.1,
            "percentage": 20.8,
            "color": "bg-purple-600",
        },
        {
            "label": "Caching",
            "value": "$31.9",
            "value_num": 31.9,
            "percentage": 11.1,
            "color": "bg-gray-400",
        },
    ]
    overview_metrics: List[OverviewMetric] = overview_metrics_data
    chart_visibility: Dict[str, bool] = {
        metric["id"]: True for metric in overview_metrics_data
    }
    temp_chart_visibility: Dict[str, bool] = {}
    show_customize_dialog: bool = False

    @rx.var
    def current_total_cost(self) -> float:
        """Calculates the current total cost from the breakdown items."""
        return sum((item["value_num"] for item in self.billing_costs_items))

    @rx.var

Input:
    @rx.var
    def remaining_budget_percentage(self) -> float:
        """Calculates the remaining budget percentage."""
        if self.total_budget == 0:
            return 0.0
        percentage = self.remaining_budget_value / self.total_budget * 100
        return round(percentage * 10) / 10

    @rx.var
    def total_cost_percentage(self) -> float:
        """Calculates the total percentage used based on cost items."""
        return sum((item["percentage"] for item in self.billing_costs_items))

    @rx.var
    def visible_overview_metrics(
        self,
    ) -> List[OverviewMetric]:
        """Returns the list of overview metrics that are marked as visible."""
        return [
            metric
            for metric in self.overview_metrics
            if self.chart_visibility.get(metric["id"], False)
        ]

    @rx.event
    def set_active_nav(self, item_name: str):
        new_nav_items = []
        for item in self.nav_items:
            new_item = item.copy()

Output:
def remaining_budget_value(self) -> float:
        """Calculates the remaining budget value."""
        return self.total_budget - self.current_total_cost