text:
# https://dash-bootstrap-components.opensource.faculty.ai/docs/components/alert/

using Dash, DashHtmlComponents, DashCoreComponents, DashBootstrapComponents

"""

[Alert](https://dash-bootstrap-components.opensource.faculty.ai/docs/components/alert/)
"""
function hello_world()
    app = dash(external_stylesheets=[dbc_themes.BOOTSTRAP])

    app.layout = dbc_container(className = "p-5") do
        dbc_alert("Hello World!", color="success"),
        dbc_alert("Primary", color="primary"),
        # Link
        dbc_alert([
            "Link to ",
            html_a("Here", href="#", className="alert-link")
        ], color="primary"),
        dbc_alert([
            html_h4("Well done!"),
            html_p([
                "This is a success alert ",
                "and second message."
            ]),
            html_hr(),
            html_p(
                "Let's put some more text down here, but remove the bottom margin",
                className="mb-0"
            ),
        ])

    end

    return app
    # run_server(
    #     app, "0.0.0.0",
    #     8050,
    #     debug=true, # enables hot reload and more
    # )
end

"""
[Alert Dismissing](https://dash-bootstrap-components.opensource.faculty.ai/docs/components/alert/)
"""
function alert_dismissing()
    #<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    #app = dash(external_stylesheets=["https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"])
    #app = dash(external_stylesheets=[dbc_themes.MATERIA])
    #app = dash(external_stylesheets=[dbc_themes.MATERIA, "assets/my.css"])
    app = dash()

    #app = dash(external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"])
    app.layout = dbc_container() do
        # class btn is making all text uppercase
        # class mbtn is defined in assets/my.css
        dbc_button(
            "Toggle alert with fade",
            color="primary", className="mybtn"
        ),
        dbc_button(
            "Toggle alert without fade"
        ),
        html_hr(),
        dbc_alert(
            "Hello!  I am an alert",
            id="alert-fade",
            dismissable=true,
            is_open=true,
        ),
        dbc_alert(
            "Hello! I am an alert that does not fade",
            id="alert-no-fade",
            dismissable=true,
            fade=false,
            is_open=true,
        )
    end

    return app

end

function badge_example(; app=nothing)
    if isnothing(app)
        app = dash()
    end
    app.layout = dbc_container() do
        # Simple example
        dbc_container([
            html_h3("Simple example"),
            dbc_button([
                "Notifications",
                dbc_badge("4", color="light", className="ml-1")
            ],
            color="primary")
        ],
        className="p-3 my-2 border rounded"
        ),
        # Badge sizing
        dbc_container([
            html_h3("Badge sizing"),
            html_h1(["Example heading", dbc_badge("New", className="ml-1")]),
            html_h2(["Example heading", dbc_badge("New", className="ml-1")]),
            html_h3(["Example heading", dbc_badge("New", className="ml-1")]),
            html_h4(["Example heading", dbc_badge("New", className="ml-1")]),
            html_h5(["Example heading", dbc_badge("New", className="ml-1")]),
            html_h6(["Example heading", dbc_badge("New", className="ml-1")]),
        ],
        className="p-3 my-2 border rounded"
        ),
        # Contextual variations
        dbc_container([
            html_h3("Contextual variations"),
            dbc_badge("Primary", color="primary", className="mr-1"),
            dbc_badge("Secondary", color="secondary", className="mr-1"),
            dbc_badge("Success", color="success", className="mr-1"),
            dbc_badge("Warning", color="warning", className="mr-1"),
            dbc_badge("Danger", color="danger", className="mr-1"),
            dbc_badge("Info", color="info", className="mr-1"),
            dbc_badge("Light", color="light", className="mr-1"),
            dbc_badge("Dark", color="dark"),
        ],
        className="p-3 my-2 border rounded"
        ),
        # Pill badges
        dbc_container([
            html_h3("Pill badges"),
            dbc_badge("Primary", color="primary", className="mr-1", pill=true),
            dbc_badge("Secondary", color="secondary", className="mr-1", pill=true),
            dbc_badge("Success", color="success", className="mr-1", pill=true),
            dbc_badge("Warning", color="warning", className="mr-1", pill=true),
            dbc_badge("Danger", color="danger", className="mr-1", pill=true),
            dbc_badge("Info", color="info", className="mr-1", pill=true),
            dbc_badge("Light", color="light", className="mr-1", pill=true),
            dbc_badge("Dark", color="dark", pill=true),

        ],
        className="p-3 my-2 border rounded"
        ),
        # Links
        dbc_container([
            html_h3("Links"),
            dbc_badge("Primary", color="primary", className="mr-1", href="#"),
            dbc_badge("Secondary", color="secondary", className="mr-1", href="#"),
            dbc_badge("Success", color="success", className="mr-1", href="#"),
            dbc_badge("Warning", color="warning", className="mr-1", href="#"),
            dbc_badge("Danger", color="danger", className="mr-1", href="#"),
            dbc_badge("Info", color="info", className="mr-1", href="#"),
            dbc_badge("Light", color="light", className="mr-1", href="#"),
            dbc_badge("Dark", color="dark", href="#"),
            dcc_markdown("""
            ```julia
            # Test code block with Markdown
            # Not highlighted for Julia yet
            dbc_badge("Primary", color="primary", className="mr-1", href="#"),
            dbc_badge("Secondary", color="secondary", className="mr-1", href="#"),
            dbc_badge("Success", color="success", className="mr-1", href="#"),
            dbc_badge("Warning", color="warning", className="mr-1", href="#"),
            dbc_badge("Danger", color="danger", className="mr-1", href="#"),
            dbc_badge("Info", color="info", className="mr-1", href="#"),
            dbc_badge("Light", color="light", className="mr-1", href="#"),
            dbc_badge("Dark", color="dark", href="#")
            ```
            """,
            className="p-2 my-2 border",
            highlight_config=Dict("theme"=>"light"))
        ],
        className="p-3 my-2 border rounded"
        )
    end

    return app
end

function button_example(; app=nothing)
    if isnothing(app)
        app = dash()
    end

    app.layout = dbc_container() do
        dbc_container([
            html_h3("Buttons"),
            dbc_button("Primary", color="primary", className="mr-1"),
            dbc_button("Secondary", color="secondary", className="mr-1"),
            dbc_button("Success", color="success", className="mr-1"),
            dbc_button("Warning", color="warning", className="mr-1"),
            dbc_button("Danger", color="danger", className="mr-1"),
            dbc_button("Info", color="info", className="mr-1"),
            dbc_button("Light", color="light", className="mr-1"),
            dbc_button("Dark", color="dark", className="mr-1"),
            dbc_button("Link", color="link"),
        ],
        className="p-3 my-2 border rounded"
        ),
        dbc_container([
            html_h3("Using buttons"),
            dbc_button("Click me", id="click-me", className="mr-2"),
            html_span(id="click-me-output", style=Dict("vertical-align"=>"middle"))
        ], className="p-3 my-2 border rounded"),
        # Outline buttons
        dbc_container([
            html_h3("Outline buttons"),
            dbc_button("Primary", color="primary", className="mr-1", outline=true),
            dbc_button("Secondary", color="secondary", className="mr-1", outline=true),
            dbc_button("Success", color="success", className="mr-1", outline=true),
            dbc_button("Warning", color="warning", className="mr-1", outline=true),
            dbc_button("Danger", color="danger", className="mr-1", outline=true),
            dbc_button("Info", color="info", className="mr-1", outline=true),
            dbc_button("Light", color="light", className="mr-1", outline=true),
            dbc_button("Dark", color="dark", className="mr-1", outline=true),
            dbc_button("Link", color="link", outline=true),
        ], className="p-3 my-2 border rounded"),
        # Button size
        dbc_container([
            html_h3("Button size"),
            dbc_button("Large button", size="lg", className="mr-1"),
            dbc_button("Regular button", className="mr-1"),
            dbc_button("Small button", size="sm"),
            html_hr(),
            # Block button
            dbc_button("Block button", block=true)
        ], className="p-3 my-2 border rounded"),
        # Active and disabled states
        dbc_container([
            html_h3("Active and disabled states"),
            dbc_button("Regular", color="primary", className="mr-1"),
            dbc_button("Active", color="primary", active=true, className="mr-1"),
            dbc_button("Disabled", color="primary", disabled=true),
        ], className="p-3 my-2 border rounded")
    end

    callback!( # Click me button
        app,
        Output("click-me-output", "children"),
        Input("click-me", "n_clicks")
    ) do n
        #@show n

        if isnothing(n)
            return "Not clicked"
        else
            return "Clicked $n times"
        end
    end

    return app
end

function button_group_example(; app=nothing)
    if isnothing(app)
        app = dash()
    end

    app.layout = dbc_container() do
        dbc_container([
            html_h3("Simple example"),
            dbc_buttongroup([
                dbc_button("Left"), dbc_button("Middle"), dbc_button("Right"),
            ])
        ], className="p-3 my-2 border rounded"),
        dbc_container([
            html_h3("Size"),
            dbc_buttongroup([
                dbc_button("Left"), dbc_button("Middle"), dbc_button("Right"),
            ], size="lg", className="mr-1"),
            dbc_buttongroup([
                dbc_button("Left"), dbc_button("Middle"), dbc_button("Right"),
            ], size="md", className="mr-1"),
            dbc_buttongroup([
                dbc_button("Left"), dbc_button("Middle"), dbc_button("Right"),
            ], size="sm", className="mr-1"),
        ], className="p-3 my-2 border rounded"),
        dbc_container([
            html_h3("Dropdown"),
            dbc_dropdownmenu([
                dbc_dropdownmenuitem("Item 1"), dbc_dropdownmenuitem("Item 2"),
            ], label="Dropdown", group=false)
        ], className="p-3 my-2 border rounded"),
        dbc_container([
            html_h3("Simple example"),
            dbc_buttongroup([
                dbc_button("Top"), dbc_button("Middle"), dbc_button("Bottom"),
            ], vertical=true)
        ], className="p-3 my-2 border rounded")
    end

    return app
end

function card_example(; app=nothing)
    if isnothing(app)
        app = dash()
    end

    # Objects to be used later
    top_card = dbc_card([
        dbc_cardimg(src="assets/images/placeholder286x180.png", top=true),
        dbc_cardbody(
            html_p("This card has an image at the top", className="card-text")
        ),
    ])

    bottom_card = dbc_card([
        dbc_cardbody(
            html_p("This is the bottom image", className="card-text"),
        ),
        dbc_cardimg(src="assets/images/placeholder286x180.png", bottom=true)
    ])

    card_1 = dbc_card(
        dbc_cardbody([
            html_h5("Card title", className="card-title"),
            html_p("This card has some text content, but not much else"),
            dbc_button("Go", color="primary"),
        ])
    )
    card_2 = dbc_card(
        dbc_cardbody([
            html_h5("Card title", className="card-title"),
            html_p("""
            This card also has some text content and not much else, but
            it is twice as wide as the first card.
            """),
            dbc_button("Go", color="success")
        ])
    )

    card_content = [
        dbc_cardheader("Card header"),
        dbc_cardbody([
            html_h5("Card title", className="card-title"),
            html_p("""
            This is some card content that we will reuse."
            """,
            className="card-text")
        ])
    ]

    card_content_1 = card_content

    card_content_2 = [
        dbc_cardbody([
            dcc_markdown("""
            > A learning experience is one of those things that says,
            > 'you know that thing you just did?  Don't do that.'
            >
            > *Douglas Adams*
            """),
        ])
    ]

    card_content_3 = [
        dbc_cardimg(src="assets/images/placeholder286x180.png"),
        dbc_cardbody([
            dcc_markdown("""
            ##### Card with image
            This card has an image on top, and a button below."
            """, className="card-text"),
            dbc_button("Click", color="primary"),
        ]),
    ]

    app.layout = dbc_container() do
        dbc_container([ # Simple example
            html_h3("Simple example"),
            dbc_card([
                dbc_cardimg(src="/assets/images/placeholder286x180.png", top=true),
                dbc_cardbody([
                    html_h4("Card title", className="card-title"),
                    html_p([
                        "Some quick example text to build on the card title and ",
                        "make up the bulk of the card's content",
                    ], className="card-text"),
                    dbc_button("Go somewhere", color="primary"),
                ]),
            ], style=Dict("width"=>"18rem")),
        ], className="p-3 my-2 border rounded"),

        dbc_container([ # Content types
            html_h3("Content types"),
            html_p("Cards support a wide variety of content. Here are some of the building blocks you can use when creating your own cards."),

            html_h4("Body"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_card(
                dbc_cardbody("This is within a card body"),
                className="mb-3",
            ),
            dbc_card("Card body with card directly", body=true, className="mb-3"),

            html_h4("Titles, text and links"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_card(
                dbc_cardbody([
                    html_h4("Title", className="card-title"),
                    html_h5("Subtitle", className="card-subtitle"),
                    html_p([
                        "Some quick example text to build on the card title and make ",
                        "up the bulk of the card's content.",
                    ], className="card-text"),
                    dbc_cardlink("Card link", href="#"),
                    dbc_cardlink("Google", href="https://google.com"),
                ]), style=Dict("width"=>"18rem")
            ),

            html_h4("Images"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_row([
                dbc_col(top_card, width="auto"), dbc_col(bottom_card, width="auto")
            ]),

            html_h4("List groups"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_card(
                dbc_listgroup([
                    dbc_listgroupitem("Item 1"),
                    dbc_listgroupitem("Item 2"),
                    dbc_listgroupitem("Item 3"),
                    dbc_listgroupitem("Item 4"),
                ]),
                style=Dict("width"=>"18rem")
            ),

            html_h4("Header and footer"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_card([
                dbc_cardheader("Header"),
                dbc_cardbody([
                    html_h4("Card title", className="card-title"),
                    html_p("This is some card text.", className="card-text"),
                ]),
                dbc_cardfooter("Footer"),
            ], style=Dict("width"=>"20rem")),
        ], className="p-3 my-2 border rounded"),

        dbc_container([ # Sizing
            html_h3("Sizing"),
            html_p("As mentioned previously, cards assume no specific width, so they will expand to the width of the parent element unless otherwise specified. You can change this behaviour as needed in one of three different ways."),

            html_h4("Using grid components"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_row([
                dbc_col(card_1, width=4), dbc_col(card_2, width=8)
            ]),

            html_h4("Using Bootstrap utility classes"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_card(
                dbc_cardbody([
                    html_h5("75% width card", className="card-title"),
                    dcc_markdown("""
                    This card uses the `w-75` class to set the width to 75%.
                    """),
                    html_p([
                        "This card uses the ",
                        html_code("w-75"),
                        " class to set the width to 75%",
                    ])
                ]),
                className="w-75 mb-3"
            ),
            dbc_card(
                dbc_cardbody([
                    html_h5("50% width card", className="card-title"),
                    dcc_markdown("""
                    This card uses the `w-50` class to set the width to 50%.
                    """)
                ]),
                className="w-50 mb-3"
            ),

            html_h4("Using custom CSS"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_card(
                dbc_cardbody([
                    html_h5("Custom CSS", className="card-title"),
                    dcc_markdown("""
                    This card has inline styles applied controlling the width.
                    You could also apply the same styles with a custom CSS
                    class.
                    """)
                ]),
                style=Dict("width"=>"18rem"),
            )
        ], className="p-3 my-2 border rounded"),

        dbc_container([ # Card style
            html_h3("Card style"),
            html_h4("Background and color"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_row([
                dbc_col(dbc_card(card_content, color="primary", inverse=true)),
                dbc_col(dbc_card(card_content, color="secondary", inverse=true)),
                dbc_col(dbc_card(card_content, color="info", inverse=true)),
            ], className="mb-4"),
            dbc_row([
                dbc_col(dbc_card(card_content, color="success", inverse=true)),
                dbc_col(dbc_card(card_content, color="warning", inverse=true)),
                dbc_col(dbc_card(card_content, color="danger", inverse=true)),
            ], className="mb-4"),
            dbc_row([
                dbc_col(dbc_card(card_content, color="light", inverse=false)),
                dbc_col(dbc_card(card_content, color="dark", inverse=true)),
            ], className="mb-4"),

            html_h4("Outline style"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_row([
                dbc_col(dbc_card(card_content, color="primary", outline=true)),
                dbc_col(dbc_card(card_content, color="secondary", outline=true)),
                dbc_col(dbc_card(card_content, color="info", outline=true)),
            ], className="mb-4"),
            dbc_row([
                dbc_col(dbc_card(card_content, color="success", outline=true)),
                dbc_col(dbc_card(card_content, color="warning", outline=true)),
                dbc_col(dbc_card(card_content, color="danger", outline=true)),
            ], className="mb-4"),
            dbc_row([
                dbc_col(dbc_card(card_content, color="light", outline=true)),
                dbc_col(dbc_card(card_content, color="dark", outline=true)),
            ], className="mb-4"),

        ], className="p-3 my-2 border rounded"),

        dbc_container([ # Card layout
            html_h3("Card layout"),
            html_h4("Card group"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_cardgroup([
                dbc_card(dbc_cardbody([
                    html_h5("Card 1", className="card-title"),
                    dcc_markdown("""
                    This cas has some text content, which is a little
                    bit longer than the second card.
                    """, className="card-text"),
                    dbc_button("Go", color="success", className="mt-auto"),
                ])),
                dbc_card(dbc_cardbody([
                    html_h5("Card 2", className="card-title"),
                    dcc_markdown("""
                    This card has some text content.
                    """, className="card-text"),
                    dbc_button("Go", color="warning", className="mt-auto"),
                ])),
                dbc_card(dbc_cardbody([
                    html_h5("Card 3", className="card-title"),
                    dcc_markdown("""
                    This card has some text content, which is longer than
                    both of the other two cards, in order to demonstrate the
                    equal height property of cards in a card group.
                    """, className="card-text"),
                    dbc_button("Go", color="danger", className="mt-auto"),
                ])),
            ], className="mb-3"),

            html_h4("Card deck"),
            html_small("$(@__FILE__): $(@__LINE__)"),
            dbc_carddeck([
                dbc_card(dbc_cardbody([
                    html_h5("Card 1", className="card-title"),
                    dcc_markdown("""
                    This cas has some text content, which is a little
                    bit longer than the second card.
                    """, className="card-text"),
                    dbc_button("Go", color="success", className="mt-auto"),
                ])),
                dbc_card(dbc_cardbody([
                    html_h5("Card 2", className="card-title"),
                    dcc_markdown("""
                    This card has some text content.
                    """, className="card-text"),
                    dbc_button("Go", color="warning", className="mt-auto"),
                ])),
                dbc_card(dbc_cardbody([
                    html_h5("Card 3", className="card-title"),
                    dcc_markdown("""
                    This card has some text content, which is longer than
                    both of the other two cards, in order to demonstrate the
                    equal height property of cards in a card group.
                    """, className="card-text"),
                    dbc_button("Go", color="danger", className="mt-auto"),
                ])),
            ], className="mb-3"),

            html_h4("Card columns"),
            dbc_badge("Line: $(@__LINE__)", color="info", className="mb-1"),
            dbc_cardcolumns([
                dbc_card(card_content_1, color="primary", inverse=true),
                dbc_card(card_content_2),
                dbc_card(card_content_1, color="secondary", inverse=true),
                dbc_card(card_content_3, color="info", inverse=true),
                dbc_card(card_content_1, color="success", inverse=true),
                dbc_card(card_content_1, color="warning", inverse=true),
                dbc_card(card_content_1, color="danger", inverse=true),
                dbc_card(card_content_3, color="light", inverse=false),
                dbc_card(card_content_1, color="dark", inverse=true),

            ]),

        ], className="p-3 my-2 border rounded")

    end

    return app
end

function layout_row_with_columns_1(;app=nothing)
    if isnothing(app)
        app = dash()
    end

    app.layout = html_div() do
        dbc_row(dbc_col(html_div("A single column", style=Dict("backgroundColor"=>"#32a852")))),
        dbc_row([
            dbc_col("One of three columns"),
            dbc_col("One of three columns"),
            dbc_col("One of three columns"),
        ])
    end

    return app
end

function layout_row_with_columns_2(;app=nothing)
    if isnothing(app)
        app = dash()
    end

    bg_style = Dict("backgroundColor"=>"#a3ffdd")

    # 12 columns grid
    app.layout = html_div() do
        dbc_row(dbc_col("A single, half-width column", width=6, style=bg_style)),
        dbc_row(dbc_col("An automatically sized column", width="auto")),
        dbc_row([
            dbc_col("One of three columns", width=3),
            dbc_col("One of three columns"),
            dbc_col("One of three columns", width=3),
        ])
    end

    return app
end

function layout_specify_order_and_offset(;app=nothing)
    if isnothing(app)
        app = dash()
    end

    bg_style = Dict("backgroundColor"=>"#a3ffdd")

    app.layout = dbc_container(style=Dict("backgroundColor"=>"orange")) do
        dbc_row(
            dbc_col(
                "A single, half-width column",
                width = Dict("size"=>6, "offset"=>3),
                style = bg_style,
            )
        ),
        dbc_row([
            dbc_col(
                "The last of three columns",
                width = Dict("size"=>3, "order"=>"last", "offset"=>1),
                style = bg_style,
            ),
            dbc_col(
                "The first of three columns",
                width = Dict("size"=>3, "order"=>1, "offset"=>2),
                style = bg_style,
            ),
            dbc_col(
                "The second of three columns",
                width = Dict("size"=>3, "order"=>12),
                style = bg_style,
            ),
        ])
    end

    return app
end

function layout_specify_width_for_different_screen_sizes(;app=nothing)
    if isnothing(app)
        app = dash()
    end

    bg_style = Dict("backgroundColor"=>"#a3ffdd")

    app.layout = dbc_container(style=Dict("backgroundColor"=>"orange")) do
        dbc_row([
            dbc_col("One of three columns", md=4, style=bg_style),
            dbc_col("One of three columns", md=4, style=bg_style),
            dbc_col("One of three columns", md=4, style=bg_style),
        ]),
        dbc_row([
            dbc_col("One of four columns", width=6, lg=3, style=bg_style),
            dbc_col("One of four columns", width=6, lg=3, style=bg_style),
            dbc_col("One of four columns", width=6, lg=3, style=bg_style),
            dbc_col("One of four columns", width=6, lg=3, style=bg_style),
        ])
    end

    return app
end

function nav_example(; app=nothing)
    if isnothing(app)
        app = dash(external_stylesheets=[dbc_themes.SPACELAB])
    end

    content = [
        dbc_container([html_h3("Base nav"),
            dbc_badge("Line $(@__LINE__)"),
            dcc_markdown("""Use `dbc_navitem` with `dbc_navlink`. """),
            dbc_nav([
                dbc_navitem(dbc_navlink("Active", active=true, href="#")),
                dbc_navitem(dbc_navlink("Link 1", href="#")),
                dbc_navitem(dbc_navlink("Link 2", href="#")),
                dbc_navitem(dbc_navlink("Disabled", disabled=true, href="#")),
                dbc_dropdownmenu([
                    dbc_dropdownmenuitem("Item 1"),
                    dbc_dropdownmenuitem("Item 2"),
                ],
                label="Dropdown",
                nav=true, # button looking -> menu looking
                ),
            ]),
            dbc_badge("Line $(@__LINE__)"),
            dcc_markdown("""Use `dbc_navlink` directly."""),
            dbc_nav([
                dbc_navlink("Active", active=true, href="#"),
                dbc_navlink("Link 1", href="#"),
                dbc_navlink("Link 2", href="#"),
                dbc_navlink("Disabled", disabled=true, href="#"),
                dbc_dropdownmenu([
                    dbc_dropdownmenuitem("Item 1"),
                    dbc_dropdownmenuitem("Item 2"),
                ],
                label="Dropdown",
                nav=true, # button looking -> menu looking
                ),
            ])

        ], className="p-3 my-2 border rounded"),

        dbc_container([html_h3("Using NavLink"),
            dbc_badge("Source", href="https://dash-bootstrap-components.opensource.faculty.ai/docs/components/nav/"),
            dbc_badge("Line $(@__LINE__)", className="ml-1"),

        ], className="p-3 my-2 border rounded"),
    ]

    app.layout = dbc_container(content)

    return app
end

function navbar_example(; app=nothing)
    if isnothing(app)
        app = dash(external_stylesheets=[dbc_themes.SPACELAB])
    end

    content = [
        dbc_container([html_h3("NavbarSimple"),
            dbc_badge("Line $(@__LINE__)"),
            dbc_navbarsimple(children = [
                dbc_navitem(dbc_navlink("Page 1", href="#")),
                dbc_navitem(dbc_navlink("Page 2", href="#")),
                dbc_dropdownmenu([
                    dbc_dropdownmenuitem("More pages", header=true),
                    dbc_dropdownmenuitem("Page 3", href="#"),
                    dbc_dropdownmenuitem("Page 4", href="#"),
                ],
                nav = true,
                in_navbar=true,
                label="More",
                )

            ],
            brand = "NavbarSimple",
            brand_href="#",
            color = "primary",
            dark = true,
            ),

        ], className="p-3 my-2 border rounded"),
        dbc_container([html_h3("Navbar"),
            dbc_badge("Line $(@__LINE__)"),

        ], className="p-3 my-2 border rounded"),

    ]

    app.layout = dbc_container(content)

    return app
end


text:
export BrickServoPulseWidth
struct BrickServoPulseWidth
    min::Integer
    max::Integer
end

export BrickServoDegree
struct BrickServoDegree
    min::Integer
    max::Integer
end

export BrickServoSPITFPBaudrateConfig
struct BrickServoSPITFPBaudrateConfig
    enable_dynamic_baudrate::Bool
    minimum_dynamic_baudrate::Integer
end

export BrickServoSPITFPErrorCount
struct BrickServoSPITFPErrorCount
    error_count_ack_checksum::Integer
    error_count_message_checksum::Integer
    error_count_frame::Integer
    error_count_overflow::Integer
end

export BrickServoProtocol1BrickletName
struct BrickServoProtocol1BrickletName
    protocol_version::Integer
    firmware_version::Vector{Integer}
    name::String
end

export BrickServoIdentity
struct BrickServoIdentity
    uid::String
    connected_uid::String
    position::Char
    hardware_version::Vector{Integer}
    firmware_version::Vector{Integer}
    device_identifier::Integer
end

export BrickServo
"""
Drives up to 7 RC Servos with up to 3A
"""
mutable struct BrickServo <: TinkerforgeDevice
    ipcon::IPConnection
    deviceInternal::PyObject

    """
    Creates an object with the unique device ID *uid* and adds it to
    the IP Connection *ipcon*.
    """
    function BrickServo(uid::String, ipcon::IPConnection)
        package = pyimport("tinkerforge.brick_servo")
        deviceInternal = package.BrickServo(uid, ipcon.ipconInternal)

        return new(ipcon, deviceInternal)
    end
end

export enable
"""
    $(SIGNATURES)

Enables a servo (0 to 6). If a servo is enabled, the configured position,
velocity, acceleration, etc. are applied immediately.
"""
function enable(device::BrickServo, servo_num)
    device.deviceInternal.enable(servo_num)
end

export disable
"""
    $(SIGNATURES)

Disables a servo (0 to 6). Disabled servos are not driven at all, i.e. a
disabled servo will not hold its position if a load is applied.
"""
function disable(device::BrickServo, servo_num)
    device.deviceInternal.disable(servo_num)
end

export is_enabled
"""
    $(SIGNATURES)

Returns *true* if the specified servo is enabled, *false* otherwise.
"""
function is_enabled(device::BrickServo, servo_num)
    return device.deviceInternal.is_enabled(servo_num)
end

export set_position
"""
    $(SIGNATURES)

Sets the position for the specified servo.

The default range of the position is -9000 to 9000, but it can be specified
according to your servo with :func:`Set Degree`.

If you want to control a linear servo or RC brushless motor controller or
similar with the Servo Brick, you can also define lengths or speeds with
:func:`Set Degree`.
"""
function set_position(device::BrickServo, servo_num, position)
    device.deviceInternal.set_position(servo_num, position)
end

export get_position
"""
    $(SIGNATURES)

Returns the position of the specified servo as set by :func:`Set Position`.
"""
function get_position(device::BrickServo, servo_num)
    return device.deviceInternal.get_position(servo_num)
end

export get_current_position
"""
    $(SIGNATURES)

Returns the *current* position of the specified servo. This may not be the
value of :func:`Set Position` if the servo is currently approaching a
position goal.
"""
function get_current_position(device::BrickServo, servo_num)
    return device.deviceInternal.get_current_position(servo_num)
end

export set_velocity
"""
    $(SIGNATURES)

Sets the maximum velocity of the specified servo. The velocity
is accelerated according to the value set by :func:`Set Acceleration`.

The minimum velocity is 0 (no movement) and the maximum velocity is 65535.
With a value of 65535 the position will be set immediately (no velocity).
"""
function set_velocity(device::BrickServo, servo_num, velocity)
    device.deviceInternal.set_velocity(servo_num, velocity)
end

export get_velocity
"""
    $(SIGNATURES)

Returns the velocity of the specified servo as set by :func:`Set Velocity`.
"""
function get_velocity(device::BrickServo, servo_num)
    return device.deviceInternal.get_velocity(servo_num)
end

export get_current_velocity
"""
    $(SIGNATURES)

Returns the *current* velocity of the specified servo. This may not be the
value of :func:`Set Velocity` if the servo is currently approaching a
velocity goal.
"""
function get_current_velocity(device::BrickServo, servo_num)
    return device.deviceInternal.get_current_velocity(servo_num)
end

export set_acceleration
"""
    $(SIGNATURES)

Sets the acceleration of the specified servo.

The minimum acceleration is 1 and the maximum acceleration is 65535.
With a value of 65535 the velocity will be set immediately (no acceleration).
"""
function set_acceleration(device::BrickServo, servo_num, acceleration)
    device.deviceInternal.set_acceleration(servo_num, acceleration)
end

export get_acceleration
"""
    $(SIGNATURES)

Returns the acceleration for the specified servo as set by
:func:`Set Acceleration`.
"""
function get_acceleration(device::BrickServo, servo_num)
    return device.deviceInternal.get_acceleration(servo_num)
end

export set_output_voltage
"""
    $(SIGNATURES)

Sets the output voltages with which the servos are driven.

.. note::
 We recommend that you set this value to the maximum voltage that is
 specified for your servo, most servos achieve their maximum force only
 with high voltages.
"""
function set_output_voltage(device::BrickServo, voltage)
    device.deviceInternal.set_output_voltage(voltage)
end

export get_output_voltage
"""
    $(SIGNATURES)

Returns the output voltage as specified by :func:`Set Output Voltage`.
"""
function get_output_voltage(device::BrickServo)
    return device.deviceInternal.get_output_voltage()
end

export set_pulse_width
"""
    $(SIGNATURES)

Sets the minimum and maximum pulse width of the specified servo.

Usually, servos are controlled with a
`PWM <https://en.wikipedia.org/wiki/Pulse-width_modulation>`__, whereby the
length of the pulse controls the position of the servo. Every servo has
different minimum and maximum pulse widths, these can be specified with
this function.

If you have a datasheet for your servo that specifies the minimum and
maximum pulse width, you should set the values accordingly. If your servo
comes without any datasheet you have to find the values via trial and error.

The minimum must be smaller than the maximum.
"""
function set_pulse_width(device::BrickServo, servo_num, min, max)
    device.deviceInternal.set_pulse_width(servo_num, min, max)
end

export get_pulse_width
"""
    $(SIGNATURES)

Returns the minimum and maximum pulse width for the specified servo as set by
:func:`Set Pulse Width`.
"""
function get_pulse_width(device::BrickServo, servo_num)
    return device.deviceInternal.get_pulse_width(servo_num)
end

export set_degree
"""
    $(SIGNATURES)

Sets the minimum and maximum degree for the specified servo (by default
given as °/100).

This only specifies the abstract values between which the minimum and maximum
pulse width is scaled. For example: If you specify a pulse width of 1000µs
to 2000µs and a degree range of -90° to 90°, a call of :func:`Set Position`
with 0 will result in a pulse width of 1500µs
(-90° = 1000µs, 90° = 2000µs, etc.).

Possible usage:

* The datasheet of your servo specifies a range of 200° with the middle position
  at 110°. In this case you can set the minimum to -9000 and the maximum to 11000.
* You measure a range of 220° on your servo and you don't have or need a middle
  position. In this case you can set the minimum to 0 and the maximum to 22000.
* You have a linear servo with a drive length of 20cm, In this case you could
  set the minimum to 0 and the maximum to 20000. Now you can set the Position
  with :func:`Set Position` with a resolution of cm/100. Also the velocity will
  have a resolution of cm/100s and the acceleration will have a resolution of
  cm/100s².
* You don't care about units and just want the highest possible resolution. In
  this case you should set the minimum to -32767 and the maximum to 32767.
* You have a brushless motor with a maximum speed of 10000 rpm and want to
  control it with a RC brushless motor controller. In this case you can set the
  minimum to 0 and the maximum to 10000. :func:`Set Position` now controls the rpm.

The minimum must be smaller than the maximum.
"""
function set_degree(device::BrickServo, servo_num, min, max)
    device.deviceInternal.set_degree(servo_num, min, max)
end

export get_degree
"""
    $(SIGNATURES)

Returns the minimum and maximum degree for the specified servo as set by
:func:`Set Degree`.
"""
function get_degree(device::BrickServo, servo_num)
    return device.deviceInternal.get_degree(servo_num)
end

export set_period
"""
    $(SIGNATURES)

Sets the period of the specified servo.

Usually, servos are controlled with a
`PWM <https://en.wikipedia.org/wiki/Pulse-width_modulation>`__. Different
servos expect PWMs with different periods. Most servos run well with a
period of about 20ms.

If your servo comes with a datasheet that specifies a period, you should
set it accordingly. If you don't have a datasheet and you have no idea
what the correct period is, the default value will most likely
work fine.
"""
function set_period(device::BrickServo, servo_num, period)
    device.deviceInternal.set_period(servo_num, period)
end

export get_period
"""
    $(SIGNATURES)

Returns the period for the specified servo as set by :func:`Set Period`.
"""
function get_period(device::BrickServo, servo_num)
    return device.deviceInternal.get_period(servo_num)
end

export get_servo_current
"""
    $(SIGNATURES)

Returns the current consumption of the specified servo.
"""
function get_servo_current(device::BrickServo, servo_num)
    return device.deviceInternal.get_servo_current(servo_num)
end

export get_overall_current
"""
    $(SIGNATURES)

Returns the current consumption of all servos together.
"""
function get_overall_current(device::BrickServo)
    return device.deviceInternal.get_overall_current()
end

export get_stack_input_voltage
"""
    $(SIGNATURES)

Returns the stack input voltage. The stack input voltage is the
voltage that is supplied via the stack, i.e. it is given by a
Step-Down or Step-Up Power Supply.
"""
function get_stack_input_voltage(device::BrickServo)
    return device.deviceInternal.get_stack_input_voltage()
end

export get_external_input_voltage
"""
    $(SIGNATURES)

Returns the external input voltage. The external input voltage is
given via the black power input connector on the Servo Brick.

If there is an external input voltage and a stack input voltage, the motors
will be driven by the external input voltage. If there is only a stack
voltage present, the motors will be driven by this voltage.

.. warning::
 This means, if you have a high stack voltage and a low external voltage,
 the motors will be driven with the low external voltage. If you then remove
 the external connection, it will immediately be driven by the high
 stack voltage
"""
function get_external_input_voltage(device::BrickServo)
    return device.deviceInternal.get_external_input_voltage()
end

export set_minimum_voltage
"""
    $(SIGNATURES)

Sets the minimum voltage, below which the :cb:`Under Voltage` callback
is triggered. The minimum possible value that works with the Servo Brick is 5V.
You can use this function to detect the discharge of a battery that is used
to drive the stepper motor. If you have a fixed power supply, you likely do
not need this functionality.
"""
function set_minimum_voltage(device::BrickServo, voltage)
    device.deviceInternal.set_minimum_voltage(voltage)
end

export get_minimum_voltage
"""
    $(SIGNATURES)

Returns the minimum voltage as set by :func:`Set Minimum Voltage`
"""
function get_minimum_voltage(device::BrickServo)
    return device.deviceInternal.get_minimum_voltage()
end

export enable_position_reached_callback
"""
    $(SIGNATURES)

Enables the :cb:`Position Reached` callback.

Default is disabled.

.. versionadded:: 2.0.1\$nbsp;(Firmware)
"""
function enable_position_reached_callback(device::BrickServo)
    device.deviceInternal.enable_position_reached_callback()
end

export disable_position_reached_callback
"""
    $(SIGNATURES)

Disables the :cb:`Position Reached` callback.

.. versionadded:: 2.0.1\$nbsp;(Firmware)
"""
function disable_position_reached_callback(device::BrickServo)
    device.deviceInternal.disable_position_reached_callback()
end

export is_position_reached_callback_enabled
"""
    $(SIGNATURES)

Returns *true* if :cb:`Position Reached` callback is enabled, *false* otherwise.

.. versionadded:: 2.0.1\$nbsp;(Firmware)
"""
function is_position_reached_callback_enabled(device::BrickServo)
    return device.deviceInternal.is_position_reached_callback_enabled()
end

export enable_velocity_reached_callback
"""
    $(SIGNATURES)

Enables the :cb:`Velocity Reached` callback.

Default is disabled.

.. versionadded:: 2.0.1\$nbsp;(Firmware)
"""
function enable_velocity_reached_callback(device::BrickServo)
    device.deviceInternal.enable_velocity_reached_callback()
end

export disable_velocity_reached_callback
"""
    $(SIGNATURES)

Disables the :cb:`Velocity Reached` callback.

Default is disabled.

.. versionadded:: 2.0.1\$nbsp;(Firmware)
"""
function disable_velocity_reached_callback(device::BrickServo)
    device.deviceInternal.disable_velocity_reached_callback()
end

export is_velocity_reached_callback_enabled
"""
    $(SIGNATURES)

Returns *true* if :cb:`Velocity Reached` callback is enabled, *false* otherwise.

.. versionadded:: 2.0.1\$nbsp;(Firmware)
"""
function is_velocity_reached_callback_enabled(device::BrickServo)
    return device.deviceInternal.is_velocity_reached_callback_enabled()
end

export set_spitfp_baudrate_config
"""
    $(SIGNATURES)

The SPITF protocol can be used with a dynamic baudrate. If the dynamic baudrate is
enabled, the Brick will try to adapt the baudrate for the communication
between Bricks and Bricklets according to the amount of data that is transferred.

The baudrate will be increased exponentially if lots of data is sent/received and
decreased linearly if little data is sent/received.

This lowers the baudrate in applications where little data is transferred (e.g.
a weather station) and increases the robustness. If there is lots of data to transfer
(e.g. Thermal Imaging Bricklet) it automatically increases the baudrate as needed.

In cases where some data has to transferred as fast as possible every few seconds
(e.g. RS485 Bricklet with a high baudrate but small payload) you may want to turn
the dynamic baudrate off to get the highest possible performance.

The maximum value of the baudrate can be set per port with the function
:func:`Set SPITFP Baudrate`. If the dynamic baudrate is disabled, the baudrate
as set by :func:`Set SPITFP Baudrate` will be used statically.

.. versionadded:: 2.3.4\$nbsp;(Firmware)
"""
function set_spitfp_baudrate_config(device::BrickServo, enable_dynamic_baudrate, minimum_dynamic_baudrate)
    device.deviceInternal.set_spitfp_baudrate_config(enable_dynamic_baudrate, minimum_dynamic_baudrate)
end

export get_spitfp_baudrate_config
"""
    $(SIGNATURES)

Returns the baudrate config, see :func:`Set SPITFP Baudrate Config`.

.. versionadded:: 2.3.4\$nbsp;(Firmware)
"""
function get_spitfp_baudrate_config(device::BrickServo)
    return device.deviceInternal.get_spitfp_baudrate_config()
end

export get_send_timeout_count
"""
    $(SIGNATURES)

Returns the timeout count for the different communication methods.

The methods 0-2 are available for all Bricks, 3-7 only for Master Bricks.

This function is mostly used for debugging during development, in normal operation
the counters should nearly always stay at 0.

.. versionadded:: 2.3.2\$nbsp;(Firmware)
"""
function get_send_timeout_count(device::BrickServo, communication_method)
    return device.deviceInternal.get_send_timeout_count(communication_method)
end

export set_spitfp_baudrate
"""
    $(SIGNATURES)

Sets the baudrate for a specific Bricklet port.

If you want to increase the throughput of Bricklets you can increase
the baudrate. If you get a high error count because of high
interference (see :func:`Get SPITFP Error Count`) you can decrease the
baudrate.

If the dynamic baudrate feature is enabled, the baudrate set by this
function corresponds to the maximum baudrate (see :func:`Set SPITFP Baudrate Config`).

Regulatory testing is done with the default baudrate. If CE compatibility
or similar is necessary in your applications we recommend to not change
the baudrate.

.. versionadded:: 2.3.2\$nbsp;(Firmware)
"""
function set_spitfp_baudrate(device::BrickServo, bricklet_port, baudrate)
    device.deviceInternal.set_spitfp_baudrate(bricklet_port, baudrate)
end

export get_spitfp_baudrate
"""
    $(SIGNATURES)

Returns the baudrate for a given Bricklet port, see :func:`Set SPITFP Baudrate`.

.. versionadded:: 2.3.2\$nbsp;(Firmware)
"""
function get_spitfp_baudrate(device::BrickServo, bricklet_port)
    return device.deviceInternal.get_spitfp_baudrate(bricklet_port)
end

export get_spitfp_error_count
"""
    $(SIGNATURES)

Returns the error count for the communication between Brick and Bricklet.

The errors are divided into

* ACK checksum errors,
* message checksum errors,
* framing errors and
* overflow errors.

The errors counts are for errors that occur on the Brick side. All
Bricklets have a similar function that returns the errors on the Bricklet side.

.. versionadded:: 2.3.2\$nbsp;(Firmware)
"""
function get_spitfp_error_count(device::BrickServo, bricklet_port)
    return device.deviceInternal.get_spitfp_error_count(bricklet_port)
end

export enable_status_led
"""
    $(SIGNATURES)

Enables the status LED.

The status LED is the blue LED next to the USB connector. If enabled is is
on and it flickers if data is transfered. If disabled it is always off.

The default state is enabled.

.. versionadded:: 2.3.1\$nbsp;(Firmware)
"""
function enable_status_led(device::BrickServo)
    device.deviceInternal.enable_status_led()
end

export disable_status_led
"""
    $(SIGNATURES)

Disables the status LED.

The status LED is the blue LED next to the USB connector. If enabled is is
on and it flickers if data is transfered. If disabled it is always off.

The default state is enabled.

.. versionadded:: 2.3.1\$nbsp;(Firmware)
"""
function disable_status_led(device::BrickServo)
    device.deviceInternal.disable_status_led()
end

export is_status_led_enabled
"""
    $(SIGNATURES)

Returns *true* if the status LED is enabled, *false* otherwise.

.. versionadded:: 2.3.1\$nbsp;(Firmware)
"""
function is_status_led_enabled(device::BrickServo)
    return device.deviceInternal.is_status_led_enabled()
end

export get_protocol1_bricklet_name
"""
    $(SIGNATURES)

Returns the firmware and protocol version and the name of the Bricklet for a
given port.

This functions sole purpose is to allow automatic flashing of v1.x.y Bricklet
plugins.
"""
function get_protocol1_bricklet_name(device::BrickServo, port)
    return device.deviceInternal.get_protocol1_bricklet_name(port)
end

export get_chip_temperature
"""
    $(SIGNATURES)

Returns the temperature as measured inside the microcontroller. The
value returned is not the ambient temperature!

The temperature is only proportional to the real temperature and it has an
accuracy of ±15%. Practically it is only useful as an indicator for
temperature changes.
"""
function get_chip_temperature(device::BrickServo)
    return device.deviceInternal.get_chip_temperature()
end

export reset
"""
    $(SIGNATURES)

Calling this function will reset the Brick. Calling this function
on a Brick inside of a stack will reset the whole stack.

After a reset you have to create new device objects,
calling functions on the existing ones will result in
undefined behavior!
"""
function reset(device::BrickServo)
    device.deviceInternal.reset()
end

export write_bricklet_plugin
"""
    $(SIGNATURES)

Writes 32 bytes of firmware to the bricklet attached at the given port.
The bytes are written to the position offset * 32.

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function write_bricklet_plugin(device::BrickServo, port, offset, chunk)
    device.deviceInternal.write_bricklet_plugin(port, offset, chunk)
end

export read_bricklet_plugin
"""
    $(SIGNATURES)

Reads 32 bytes of firmware from the bricklet attached at the given port.
The bytes are read starting at the position offset * 32.

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function read_bricklet_plugin(device::BrickServo, port, offset)
    return device.deviceInternal.read_bricklet_plugin(port, offset)
end

export get_identity
"""
    $(SIGNATURES)

Returns the UID, the UID where the Brick is connected to,
the position, the hardware and firmware version as well as the
device identifier.

The position is the position in the stack from '0' (bottom) to '8' (top).

The device identifier numbers can be found :ref:`here <device_identifier>`.
|device_identifier_constant|
"""
function get_identity(device::BrickServo)
    return device.deviceInternal.get_identity()
end

export register_callback
"""
Registers the given *function* with the given *callback_id*.
"""
function register_callback(device::BrickServo, callback_id, function_)
    if isnothing(function_)
        device.registered_callbacks.pop(callback_id, None)
    else
        device.registered_callbacks[callback_id] = function_
    end
end

ext: jl


text:
using Test
using ManifoldsBase

using ManifoldsBase: AbstractTrait, TraitList, EmptyTrait, trait, merge_traits
using ManifoldsBase: expand_trait, next_trait
import ManifoldsBase: active_traits, parent_trait

struct IsCool <: AbstractTrait end
struct IsNice <: AbstractTrait end

abstract type AbstractA end
abstract type DecoA <: AbstractA end
# A few concrete types
struct A <: AbstractA end
struct A1 <: DecoA end
struct A2 <: DecoA end
struct A3 <: DecoA end
struct A4 <: DecoA end
struct A5 <: DecoA end

# just some function
f(::AbstractA, x) = x + 2
g(::DecoA, x, y) = x + y

struct IsGreat <: AbstractTrait end # a special case of IsNice
parent_trait(::IsGreat) = IsNice()

active_traits(f, ::A1, ::Any) = merge_traits(IsNice())
active_traits(f, ::A2, ::Any) = merge_traits(IsCool())
active_traits(f, ::A3, ::Any) = merge_traits(IsCool(), IsNice())
active_traits(f, ::A5, ::Any) = merge_traits(IsGreat())

f(a::DecoA, b) = f(trait(f, a, b), a, b)

f(::TraitList{IsNice}, a, b) = g(a, b, 3)
f(::TraitList{IsCool}, a, b) = g(a, b, 5)

# generic forward to the next trait to be looked at
f(t::TraitList, a, b) = f(next_trait(t), a, b)
# generic fallback when no traits are defined
f(::EmptyTrait, a, b) = invoke(f, Tuple{AbstractA,typeof(b)}, a, b)

@testset "Decorator trait tests" begin
    t = ManifoldsBase.EmptyTrait()
    t2 = ManifoldsBase.TraitList(t, t)
    @test merge_traits() == t
    @test merge_traits(t) == t
    @test merge_traits(t, t) == t
    @test merge_traits(t2) == t2
    @test merge_traits(
        merge_traits(IsGreat(), IsNice()),
        merge_traits(IsGreat(), IsNice()),
    ) === merge_traits(IsGreat(), IsNice(), IsGreat(), IsNice())
    @test expand_trait(merge_traits(IsGreat(), IsCool())) ===
          merge_traits(IsGreat(), IsNice(), IsCool())
    @test expand_trait(merge_traits(IsCool(), IsGreat())) ===
          merge_traits(IsCool(), IsGreat(), IsNice())

    @test string(merge_traits(IsGreat(), IsNice())) ==
          "TraitList(IsGreat(), TraitList(IsNice(), EmptyTrait()))"

    global f
    @test f(A(), 0) == 2
    @test f(A2(), 0) == 5
    @test f(A3(), 0) == 5
    @test f(A4(), 0) == 2
    @test f(A5(), 890) == 893
    f(::TraitList{IsGreat}, a, b) = g(a, b, 54)
    @test f(A5(), 890) == 944

    @test next_trait(EmptyTrait()) === EmptyTrait()
end

#
# A Manifold decorator test - check that EmptyTrait cases call Abstract and those fail with
# MethodError due to ambiguities (between Abstract and Decorator)
struct NonDecoratorManifold <: AbstractDecoratorManifold{ManifoldsBase.ℝ} end
ManifoldsBase.representation_size(::NonDecoratorManifold) = (2,)

@testset "Testing a NonDecoratorManifold - emptytrait fallbacks" begin
    M = NonDecoratorManifold()
    p = [2.0, 1.0]
    q = similar(p)
    X = [1.0, 0.0]
    Y = similar(X)
    @test ManifoldsBase.check_size(M, p) === nothing
    @test ManifoldsBase.check_size(M, p, X) === nothing
    # default to identity
    @test embed(M, p) == p
    @test embed!(M, q, p) == p
    @test embed(M, p, X) == X
    @test embed!(M, Y, p, X) == X
    # the following is implemented but passes to the second and hence fails
    @test_throws MethodError exp(M, p, X)
    @test_throws MethodError exp!(M, q, p, X)
    @test_throws MethodError retract(M, p, X)
    @test_throws MethodError retract!(M, q, p, X)
    @test_throws MethodError log(M, p, q)
    @test_throws MethodError log!(M, Y, p, q)
    @test_throws MethodError inverse_retract(M, p, q)
    @test_throws MethodError inverse_retract!(M, Y, p, q)
    @test_throws MethodError parallel_transport_along(M, p, X, :curve)
    @test_throws MethodError parallel_transport_along!(M, Y, p, X, :curve)
    @test_throws MethodError parallel_transport_direction(M, p, X, X)
    @test_throws MethodError parallel_transport_direction!(M, Y, p, X, X)
    @test_throws MethodError parallel_transport_to(M, p, X, q)
    @test_throws MethodError parallel_transport_to!(M, Y, p, X, q)
    @test_throws MethodError vector_transport_along(M, p, X, :curve)
    @test_throws MethodError vector_transport_along!(M, Y, p, X, :curve)
end

# With even less, check that representation size stack overflows
struct NonDecoratorNonManifold <: AbstractDecoratorManifold{ManifoldsBase.ℝ} end
@testset "Testing a NonDecoratorNonManifold - emptytrait fallback Errors" begin
    N = NonDecoratorNonManifold()
    @test_throws StackOverflowError representation_size(N)
end

h(::AbstractA, x::Float64, y; a = 1) = x + y - a
h(::DecoA, x, y) = x + y
ManifoldsBase.@invoke_maker 1 AbstractA h(A::DecoA, x::Float64, y)

@testset "@invoke_maker" begin
    @test h(A1(), 1.0, 2) == 2
    sig = ManifoldsBase._split_signature(:(fname(x::T; k::Float64 = 1) where {T}))
    @test sig.fname == :fname
    @test sig.where_exprs == Any[:T]
    @test sig.callargs == Any[:(x::T)]
    @test sig.kwargs_list == Any[:($(Expr(:kw, :(k::Float64), 1)))]
    @test sig.argnames == [:x]
    @test sig.argtypes == [:T]
    @test sig.kwargs_call == Expr[:(k = k)]
    @test_throws ErrorException ManifoldsBase._split_signature(:(a = b))

    sig2 = ManifoldsBase._split_signature(:(fname(x; kwargs...)))
    @test sig2.kwargs_call == Expr[:(kwargs...)]

    sig3 = ManifoldsBase._split_signature(:(fname(x::T, y::Int = 10; k1 = 1) where {T}))
    @test sig3.kwargs_call == Expr[:(k1 = k1)]
    @test sig3.callargs[2] == :($(Expr(:kw, :(y::Int), 10)))
    @test sig3.argnames == [:x, :y]
end


text:
using DrWatson
@quickactivate "StatReth"

# %%
using Plots
using StatsPlots
using DataFrames
using StatsBase
using Distributions

# %%
data = DataFrame(
    birth1 = [1,0,0,0,1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,0,1,0,0,0,1,0,
              0,0,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,0,1,0,0,1,1,0,1,0,0,0,0,0,0,0,
              1,1,0,1,0,0,1,0,0,0,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,0,0,1,0,1,1,0,
              1,0,1,1,1,0,1,1,1,1],
    birth2 = [0,1,0,1,0,1,1,1,0,0,1,1,1,1,1,0,0,1,1,1,0,0,1,1,1,0,
              1,1,1,0,1,1,1,0,1,0,0,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,
              1,1,1,0,1,1,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,0,0,1,1,
              0,0,0,1,1,1,0,0,0,0]
)

# %%
boys = sum(data.birth1) + sum(data.birth2)
all_births = length(data.birth1) + length(data.birth2)

p_grid = range(0, 1, length = 1000)
prior = ones(length(p_grid))
likelihood = @. pdf(Binomial(all_births, p_grid), boys)
posterior = likelihood .* prior
posterior ./= sum(posterior)
plot(p_grid, posterior)

p_grid[argmax(posterior)]

N = 10_000
samples = sample(p_grid, pweights(posterior), N)

# %%
plot(p_grid, posterior .* length(posterior))
density!(samples)

# %%
using Turing
chn = Chains(samples, ["boys"])
hpd(chn; alpha = 0.5)
hpd(chn; alpha = 1-0.89)
hpd(chn; alpha = 1-0.97)

# %%
mix = MixtureModel(Binomial.(200, samples))
predpos_samples = rand(mix, 10_000)
density(predpos_samples)

# %%
mix = MixtureModel(Binomial.(100, samples))
predpos_samples = rand(mix, 10_000)
density(predpos_samples)
vline!([sum(data.birth1), sum(data.birth2)])

# %%
firstborn_girls = count(data.birth1 .== 0)
born_after_girls = data.birth2[data.birth1 .== 0]
boy_after_girl = count(born_after_girls .== 1)

mix = MixtureModel(Binomial.(firstborn_girls, samples))
predpos_samples = rand(mix, 10_000)
density(predpos_samples)
vline!([boy_after_girl])


text:
@testset "Lattice Type" begin
end


text:
@testset "ParquetFile" begin

    @testset "ParquetFile" begin

        left = ParquetFile("left.parquet")

        @test eltype(left) == NamedTuple{(:Chrom, :Pos, :Val),Tuple{Union{Missing,String},Union{Missing,Int64},Union{Missing,String}}}

        val, state = iterate(left)
        @test val == (Chrom = "chr1", Pos = 1, Val = "l1")
    end

    @testset "Table interface" begin

        using Tables
        left = ParquetFile("left.parquet")

        @test Tables.istable(left)
        @test Tables.rowaccess(left)
        @test Tables.schema(left) == Tables.Schema{(:Chrom, :Pos, :Val),Tuple{Union{Missing,String},Union{Missing,Int64},Union{Missing,String}}}()

        ri = Tables.rows(left)
        val, state = iterate(ri)
        @test val == (Chrom = "chr1", Pos = 1, Val = "l1")

    end
end


text:
using VulkanCore
using VulkanCore.LibVulkan
using Test
using GLFW

const api = VulkanCore.vk

convert_vk_back(::Type{UInt32}, version::VersionNumber) = (version.major << 22) + (version.minor << 12) + version.patch
convert_vk(::Type{VersionNumber}, version::UInt32) = VersionNumber(UInt32(version) >> 22, (UInt32(version) >> 12) & 0x3ff, UInt32(version) & 0xfff)

count = Ref{Cuint}()
# Scan layers
@test vkEnumerateInstanceLayerProperties(count, C_NULL) == VK_SUCCESS
global_layer_properties = Vector{VkLayerProperties}(undef, count[])
@test vkEnumerateInstanceLayerProperties(count, global_layer_properties) == VK_SUCCESS

function Base.show(io::IO, lp::VkLayerProperties)
	println(io, "Layer Properties: ")
	println(io, "    Layer Name: ", String(filter(x->x!=0, UInt8[lp.layerName...])))
	println(io, "    Spec Version: ", convert_vk(VersionNumber, lp.specVersion))
	println(io, "    Implementation Version: ", convert_vk(VersionNumber, lp.implementationVersion))
	println(io, "    description: ", String(filter(x->x!=0, UInt8[lp.description...])))
end

println.(global_layer_properties)

appname = "vulkaninfo"

app_info = Ref(VkApplicationInfo(VK_STRUCTURE_TYPE_APPLICATION_INFO,
								 C_NULL,
								 pointer(appname),
								 1,
								 pointer(appname),
								 1,
								 convert_vk_back(UInt32, v"1.2")))

inst_info = Ref(VkInstanceCreateInfo(VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
								     C_NULL,
									 UInt32(0),
									 Base.unsafe_convert(Ptr{VkApplicationInfo}, app_info),
									 0,
									 C_NULL,
									 0,
									 C_NULL))

instance = Ref{VkInstance}()

@test vkCreateInstance(inst_info, C_NULL, instance) == VK_SUCCESS
println(instance)

gpu_count = Ref{Cuint}()
@test vkEnumeratePhysicalDevices(instance[], gpu_count, C_NULL) == VK_SUCCESS
devices = Array{VkPhysicalDevice}(undef, gpu_count[])

@test vkEnumeratePhysicalDevices(instance[], gpu_count, devices) == VK_SUCCESS

deviceprops = Ref{VkPhysicalDeviceProperties}()
device = first(devices)
vkGetPhysicalDeviceProperties(device, deviceprops)

function Base.show(io::IO, pdsp::VkPhysicalDeviceSparseProperties)
	println(io, "Physical device Sparse Properties: ")
	for name in fieldnames(typeof(pdsp))
		println(io, "    ", name, " ", getfield(pdsp, name) == 1)
	end
end
function Base.show(io::IO, pdp::VkPhysicalDeviceProperties)
	println(io, "Physical Device Properties: ")
	println(io, "    API Version: ", convert_vk(VersionNumber, pdp.apiVersion))
	println(io, "    Driver Version: ", convert_vk(VersionNumber, pdp.driverVersion))

	println(io, "    Vendor ID ", pdp.vendorID)
	println(io, "    Device ID: ", pdp.deviceID)
	println(io, "    Device Type: ", pdp.deviceType)
	println(io, "    Device Name: ", String(filter(x->x!=0, UInt8[pdp.deviceName...])))
	println(io, "    Pipeline Cache UUID: ", String(collect(pdp.pipelineCacheUUID)))
	println(io, "    Limits: ", pdp.limits)
	println(io, "    Sparse Properties: \n    ", pdp.sparseProperties)
end

limitshow(x::Cuint) = Int(x)
limitshow(x::NTuple) = "<"*join(map(limitshow, x), " ")*">"
limitshow(x) = x

function Base.show(io::IO, pdl::VkPhysicalDeviceLimits)
	println(io, "Physical Device Limits: ")
	for name in fieldnames(typeof(pdl))
		println(io, "    ", name, " ", limitshow(getfield(pdl, name)))
	end
end

println(deviceprops[])

queue_count = Ref{Cuint}()
vkGetPhysicalDeviceQueueFamilyProperties(device, queue_count, C_NULL)
queueprops = Array{VkQueueFamilyProperties}(undef, queue_count[])
println(queue_count[])
vkGetPhysicalDeviceQueueFamilyProperties(device, queue_count, queueprops)
println(queueprops)

memprops = Ref{VkPhysicalDeviceMemoryProperties}()
vkGetPhysicalDeviceMemoryProperties(device, memprops)

println(memprops[])
devicefeatures = Ref{VkPhysicalDeviceFeatures}()
vkGetPhysicalDeviceFeatures(device, devicefeatures)

function Base.show(io::IO, df::VkPhysicalDeviceFeatures)
	println(io, "Physical device features: ")
	for name in fieldnames(typeof(df))
		println(io, "    ", name, ": ", getfield(df, name) != 1 ? "un" : "", "supported")
	end
end
println(devicefeatures[])


text:
# ---
# title: 963. Minimum Area Rectangle II
# id: problem963
# author: Indigo
# date: 2021-01-25
# difficulty: Medium
# categories: Math, Geometry
# link: <https://leetcode.com/problems/minimum-area-rectangle-ii/description/>
# hidden: true
# ---
#
# Given a set of points in the xy-plane, determine the minimum area of **any**
# rectangle formed from these points, with sides **not necessarily parallel** to
# the x and y axes.
#
# If there isn't any rectangle, return 0.
#
#
#
# **Example 1:**
#
# ![](https://assets.leetcode.com/uploads/2018/12/21/1a.png)
#
#
#
#     Input: [[1,2],[2,1],[1,0],[0,1]]
#     Output: 2.00000
#     Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.
#
#
# **Example 2:**
#
# ![](https://assets.leetcode.com/uploads/2018/12/22/2.png)
#
#
#
#     Input: [[0,1],[2,1],[1,1],[1,0],[2,0]]
#     Output: 1.00000
#     Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.
#
#
# **Example 3:**
#
# ![](https://assets.leetcode.com/uploads/2018/12/22/3.png)
#
#
#
#     Input: [[0,3],[1,2],[3,1],[1,3],[2,1]]
#     Output: 0
#     Explanation: There is no possible rectangle to form from these points.
#
#
# **Example 4:**
#
# ![](https://assets.leetcode.com/uploads/2018/12/21/4c.png)
#
#
#
#     Input: [[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]]
#     Output: 2.00000
#     Explanation: The minimum area rectangle occurs at [2,1],[2,3],[3,3],[3,1], with an area of 2.
#
#
#
#
# **Note:**
#
#   1. `1 <= points.length <= 50`
#   2. `0 <= points[i][0] <= 40000`
#   3. `0 <= points[i][1] <= 40000`
#   4. All points are distinct.
#   5. Answers within `10^-5` of the actual value will be accepted as correct.
#
#
## @lc code=start
using LeetCode

function min_area_free_rect(points::Vector{Vector{Int}})
    function is_right_angle(p1, p2, p3)
        return (p1[1] - p2[1]) * (p1[1] - p3[1]) + (p1[2] - p2[2]) * (p1[2] - p3[2]) == 0
    end
    point_set = Set(points)
    res, len = Inf, length(points)
    for i in 1 : len
        for j in 1 + i : len
            for k in 1 + j : len
                flg = false
                if is_right_angle(points[i], points[j], points[k])
                    flg = true
                elseif is_right_angle(points[j], points[k], points[i])
                    flg = true
                    i, j = j, i
                elseif is_right_angle(points[k], points[i], points[j])
                    i, k = k, i
                    flg = true
                end
                if flg && (points[j] + points[k] - points[i]) in point_set
                    area = sqrt(sum((points[i] - points[j]) .^ 2) * sum((points[i] - points[k]) .^ 2))
                    (area > 0) && (res = min(res, area))
                end
            end
        end
    end
    (res == Inf) ? 0.0 : res
end
## @lc code=end


text:
#=
# convention:
# a variable representing PyPtr can be
#             nothing => Py_None
#             DIO_Err => Py_NULL = PyPtr(0)
#             RC(a)   => PyPtr(a)
# unintialized variables are DIO_Err
=#
export DIO_ExceptCode, DIO_Undef
export @DIO_Obj, @DIO_SetLineno
export @DIO_MakePtrCFunc
export DIO_HasCast, DIO_Cast, DIO_CastExc

struct DIO_UndefType end
const DIO_Undef = DIO_UndefType()

const PyConstants = Set{Addr}()
function DIO_Obj(addr::Addr)::PyPtr
    o = reinterpret(PyPtr, addr)
    addr in PyConstants || begin
        push!(PyConstants, addr)
        Py_INCREF(o)
    end
    return o
end

macro DIO_Obj(addr::Addr)
    DIO_Obj(addr)
end

@exportapi PyCFunction_NewEx
@autoapi PyCFunction_NewEx(Ptr{Nothing}, PyPtr, PyPtr)::PyPtr

@exportapi PyCFunction_New
function PyCFunction_New(apis, cfuncptr::Ptr{Nothing}, UNUSED::PyPtr)
    @ccall $(apis.PyCFunction_NewEx)(cfuncptr::Ptr{Nothing}, UNUSED::PyPtr, Py_NULL::PyPtr)::PyPtr
end

macro DIO_SetLineno(line::Int, filename::String)
    LineNumberNode(line, Symbol(filename))
end

DIO_ExceptCode(f) = error("no error handling for $(f).")
DIO_HasCast(f) = false
# f -> bool
function DIO_CastExc end
# (f, val) -> PyPtr
function DIO_Cast end

macro DIO_MakePtrCFunc(narg::Int, jl_func::Symbol, funcname::Symbol)
    if narg == 0
        DIO_MakePtrCFunc0(jl_func, funcname, __module__)
    elseif narg == 1
        DIO_MakePtrCFunc1(jl_func, funcname, __module__)
    else
        DIO_MakePtrCFuncN(narg, jl_func, funcname, __module__)
    end
end

function DIO_MakePtrCFunc0(jl_func::Symbol, funcname::Symbol, __module__::Any)
    CFunc = Symbol(:CFunc_, jl_func)
    CFuncPtr = Symbol(:CFuncPtr_, jl_func)
    PyMeth = Symbol(:PyMeth_, jl_func)
    Doc = Symbol(:DOC_, jl_func)
    PyFunc = Symbol(:PyFunc_, jl_func)
    ex = @q begin
        @inline DIO.DIO_ExceptCode(::typeof($jl_func)) = Py_NULL
        function $CFunc(_ :: PyPtr, _::PyPtr)::PyPtr
            return $jl_func()
        end
        const $CFuncPtr = @cfunction($CFunc, PyPtr, (PyPtr, PyPtr))
        const $PyMeth = PyMethodDef(
            Base.unsafe_convert(Cstring, $(QuoteNode(funcname))),
            $CFuncPtr,
            METH_NOARGS,
            Base.unsafe_convert(Cstring, $Doc)
        )
        const $PyFunc = PyCFunction_NewEx(pointer_from_objref($PyMeth), Py_NULL, Py_NULL)
    end
    if DEBUG
        @info ex
    end
    foreach(__module__.eval, ex.args)
end

function DIO_MakePtrCFunc1(jl_func::Symbol, funcname::Symbol, __module__::Any)
    CFunc = Symbol(:CFunc_, jl_func)
    CFuncPtr = Symbol(:CFuncPtr_, jl_func)
    PyMeth = Symbol(:PyMeth_, jl_func)
    Doc = Symbol(:DOC_, jl_func)
    PyFunc = Symbol(:PyFunc_, jl_func)
    ex = @q begin
        @inline DIO.DIO_ExceptCode(::typeof($jl_func)) = Py_NULL
        function $CFunc(_ :: PyPtr, arg::PyPtr)::PyPtr
            return $jl_func(arg)
        end
        const $CFuncPtr = @cfunction($CFunc, PyPtr, (PyPtr, PyPtr))
        const $PyMeth = PyMethodDef(
            Base.unsafe_convert(Cstring, $(QuoteNode(funcname))),
            $CFuncPtr,
            METH_O,
            Base.unsafe_convert(Cstring, $Doc)
        )
        const $PyFunc = PyCFunction_NewEx(pointer_from_objref($PyMeth), Py_NULL, Py_NULL)
    end
    if DEBUG
        @info ex
    end
    foreach(__module__.eval, ex.args)
end

function DIO_MakePtrCFuncN(narg::Int, jl_func::Symbol, funcname::Symbol, __module__::Any)
    CFunc = Symbol(:CFunc_, jl_func)
    CFuncPtr = Symbol(:CFuncPtr_, jl_func)
    PyMeth = Symbol(:PyMeth_, jl_func)
    Doc = Symbol(:DOC_, jl_func)
    PyFunc = Symbol(:PyFunc_, jl_func)

    error_string = "expect $(narg) arguments, while got "
    error_string = :("$($error_string)$(n).")

    vectorargs = gensym("vectorargs")
    call_jl_func = Expr(:call, jl_func)
    for i = 1:narg
        push!(call_jl_func.args, :(unsafe_load($vectorargs, $i)))
    end

    PyAPI_Struct = __module__.PyAPI_Struct
    ex = @q begin
        @inline DIO.DIO_ExceptCode(::typeof($jl_func)) = Py_NULL
        function $CFunc(self :: PyPtr, $vectorargs::Ptr{PyPtr}, argc::Py_ssize_t)::PyPtr
            if argc != $narg
                msg = $error_string
                cmsg = Base.unsafe_convert(Cstring, msg)
                GC.@preserve msg begin
                    ccall(
                        $(PyAPI_Struct.PyErr_SetString),
                        Cvoid,
                        (PyPtr, Cstring),
                        $(PyAPI_Struct.PyExc_TypeError), cmsg)
                end
                return Py_NULL
            end
            return $call_jl_func
        end
        const $CFuncPtr = @cfunction($CFunc, PyPtr, (PyPtr, Ptr{PyPtr}, Py_ssize_t))
        const $PyMeth = PyMethodDef(
            Base.unsafe_convert(Cstring, $(QuoteNode(funcname))),
            $CFuncPtr,
            METH_FASTCALL,
            Base.unsafe_convert(Cstring, $Doc)
        )
        const $PyFunc = PyCFunction_NewEx(pointer_from_objref($PyMeth), Py_NULL, Py_NULL)
    end
    if DEBUG
        @info ex
    end
    foreach(__module__.eval, ex.args)
end

@exportapi DIO_WrapIntValue
@inline DIO_WrapIntValue(apis, i::Union{Cint, Clong})::PyPtr = begin
    i = Clong(i)
    ccall(apis.PyLong_FromLong, PyPtr, (Clong, ), i)
end

@inline DIO_WrapIntValue(apis, i::Csize_t)::PyPtr = begin
    ccall(apis.PyLong_FromSize_t, PyPtr, (Csize_t, ), i)
end

@inline DIO_WrapIntValue(apis, i)::PyPtr = begin
    msg = "Cannot wrap $i :: $(typeof(i))!"
    cmsg = Base.unsafe_convert(Cstring, msg)
    GC.@preserve msg begin
        ccall(
            apis.PyErr_SetString,
            Cvoid,
            (PyPtr, Cstring),
            apis.PyExc_TypeError, cmsg)
    end
    Py_NULL
end

@exportapi DIO_NewNone
@inline DIO_NewNone(apis) = begin
    none = apis.PyO.None
    Py_INCREF(none)
    none
end


text:
@testset "JointAccelerationTask" begin
    Random.seed!(1)
    mechanism = RBD.rand_tree_mechanism(Float64, [Revolute{Float64} for _ = 1 : 10]...)
    state = MechanismState(mechanism)
    rand!(state)
    nv = num_velocities(mechanism)
    v̇ = [Parametron.Variable(i) for i = 1 : nv]
    v̇vals = rand!(similar(velocity(state)))
    qpmodel = mock_model()
    tasks = Dict{Joint{Float64, Revolute{Float64}}, JointAccelerationTask{Revolute{Float64}}}()
    for joint in tree_joints(mechanism)
        task = JointAccelerationTask(joint)
        @test QPC.dimension(task) == num_velocities(joint)
        tasks[joint] = task
        setdesired!(task, rand())
    end
    for (joint, task) in tasks
        err = QPC.task_error(task, qpmodel, state, v̇)
        @test map(f -> f(Dict(zip(v̇, v̇vals))), err()) == v̇vals[joint] .- task.desired
        allocs = @allocated err()
        @test allocs == 0
    end
end

@testset "AngularAccelerationTask" begin
    Random.seed!(2)
    mechanism = RBD.rand_tree_mechanism(Float64, [Revolute{Float64} for _ = 1 : 10]...)
    state = MechanismState(mechanism)
    rand_configuration!(state)
    nv = num_velocities(mechanism)
    v̇ = [Parametron.Variable(i) for i = 1 : nv]
    qpmodel = mock_model()
    for testnum = 1 : 10
        base = rand(bodies(mechanism))
        body = rand(setdiff(bodies(mechanism), [base]))
        p = RBD.path(mechanism, base, body)
        task = AngularAccelerationTask(mechanism, p)
        @test QPC.dimension(task) == 3
        err = QPC.task_error(task, qpmodel, state, v̇)

        bodyframe = default_frame(body)
        baseframe = default_frame(base)
        desired = FreeVector3D(bodyframe, SVector(1., 2, 3))
        QPC.setdesired!(task, desired)

        zero_velocity!(state)
        v̇0 = zeros(length(v̇))
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == -desired.v

        QPC.setdesired!(task, zero(desired))
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == zeros(3)
        rand_velocity!(state)
        biasaccel = transform(state, -RBD.bias_acceleration(state, base) + RBD.bias_acceleration(state, body), bodyframe)
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == angular(biasaccel)

        zero_velocity!(state)
        setdirty!(qpmodel)
        v̇rand = rand(nv)
        expected = angular(transform(state, SpatialAcceleration(geometric_jacobian(state, p), v̇rand), bodyframe))
        @test map(f -> f(Dict(zip(v̇, v̇rand))), err()) ≈ expected atol = 1e-12

        allocs = @allocated err()
        @test allocs == 0
    end
end

@testset "PointAccelerationTask" begin
    Random.seed!(3)
    mechanism = RBD.rand_tree_mechanism(Float64, [Revolute{Float64} for _ = 1 : 10]...)
    state = MechanismState(mechanism)
    rand_configuration!(state)
    nv = num_velocities(mechanism)
    v̇ = [Parametron.Variable(i) for i = 1 : nv]
    qpmodel = mock_model()
    for testnum = 1 : 10
        base = rand(bodies(mechanism))
        body = rand(setdiff(bodies(mechanism), [base]))
        path_to_body = RBD.path(mechanism, base, body)
        point = Point3D(default_frame(body), randn(SVector{3, Float64}))
        task = PointAccelerationTask(mechanism, path_to_body, point)
        @test QPC.dimension(task) == 3
        err = QPC.task_error(task, qpmodel, state, v̇)

        bodyframe = default_frame(body)
        baseframe = default_frame(base)
        desired = FreeVector3D(baseframe, SVector(1., 2, 3))
        QPC.setdesired!(task, desired)

        zero_velocity!(state)
        v̇0 = zeros(length(v̇))
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == -desired.v

        QPC.setdesired!(task, zero(desired))
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == zeros(3)

        rand_velocity!(state)
        T = transform(state, relative_twist(state, body, base), baseframe)
        ω = angular(T)
        ṗ = point_velocity(T, transform(state, point, baseframe))
        bias = transform(state,
            -RBD.bias_acceleration(state, base) + RBD.bias_acceleration(state, body),
            baseframe)
        expected = ω × ṗ.v + (angular(bias) × transform(state, point, baseframe).v + linear(bias))
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == expected

        zero_velocity!(state)
        setdirty!(qpmodel)
        v̇rand = rand(nv)
        J_point = point_jacobian(state, path_to_body, transform(state, point, baseframe))
        expected = point_velocity(J_point, v̇rand).v
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇rand))), err()) ≈ expected atol=1e-12

        allocs = @allocated err()
        @test allocs == 0
    end
end

@testset "LinearAccelerationTask" begin
    Random.seed!(4)
    mechanism = RBD.rand_tree_mechanism(Float64, [Revolute{Float64} for _ = 1 : 10]...)
    state = MechanismState(mechanism)
    rand_configuration!(state)
    nv = num_velocities(mechanism)
    v̇ = [Parametron.Variable(i) for i = 1 : nv]
    qpmodel = mock_model()
    for testnum = 1 : 10
        base = rand(bodies(mechanism))
        body = rand(setdiff(bodies(mechanism), [base]))
        p = RBD.path(mechanism, base, body)
        task = LinearAccelerationTask(mechanism, p)
        @test QPC.dimension(task) == 3
        err = QPC.task_error(task, qpmodel, state, v̇)

        bodyframe = default_frame(body)
        baseframe = default_frame(base)
        desired = FreeVector3D(bodyframe, SVector(1., 2, 3))
        QPC.setdesired!(task, desired)

        zero_velocity!(state)
        v̇0 = zeros(length(v̇))
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == -desired.v

        QPC.setdesired!(task, zero(desired))
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == zeros(3)
        rand_velocity!(state)
        biasaccel = transform(state, -RBD.bias_acceleration(state, base) + RBD.bias_acceleration(state, body), bodyframe)
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == linear(biasaccel)

        zero_velocity!(state)
        setdirty!(qpmodel)
        v̇rand = rand(nv)
        expected = linear(transform(state, SpatialAcceleration(geometric_jacobian(state, p), v̇rand), bodyframe))
        @test map(f -> f(Dict(zip(v̇, v̇rand))), err()) ≈ expected atol = 1e-12

        allocs = @allocated err()
        @test allocs == 0
    end
end

@testset "SpatialAccelerationTask" begin
    Random.seed!(5)
    mechanism = RBD.rand_tree_mechanism(Float64, [Revolute{Float64} for _ = 1 : 10]...)
    state = MechanismState(mechanism)
    rand_configuration!(state)
    nv = num_velocities(mechanism)
    v̇ = [Parametron.Variable(i) for i = 1 : nv]
    qpmodel = mock_model()
    for testnum = 1 : 10
        base = rand(bodies(mechanism))
        body = rand(setdiff(bodies(mechanism), [base]))
        p = RBD.path(mechanism, base, body)
        task = SpatialAccelerationTask(mechanism, p)
        @test QPC.dimension(task) == 6
        err = QPC.task_error(task, qpmodel, state, v̇)

        bodyframe = default_frame(body)
        baseframe = default_frame(base)
        desired = SpatialAcceleration(bodyframe, baseframe, bodyframe, SVector(1., 2., 3.), SVector(4., 5., 6.))
        QPC.setdesired!(task, desired)

        zero_velocity!(state)
        v̇0 = zeros(length(v̇))
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == -SVector(desired)

        QPC.setdesired!(task, zero(desired))
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == zeros(6)
        rand_velocity!(state)
        biasaccel = transform(state, -RBD.bias_acceleration(state, base) + RBD.bias_acceleration(state, body), bodyframe)
        setdirty!(qpmodel)
        @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == SVector(biasaccel)

        zero_velocity!(state)
        setdirty!(qpmodel)
        v̇rand = rand(nv)
        expected = SVector(transform(state, SpatialAcceleration(geometric_jacobian(state, p), v̇rand), bodyframe))
        @test map(f -> f(Dict(zip(v̇, v̇rand))), err()) ≈ expected atol = 1e-12

        allocs = @allocated err()
        @test allocs == 0
    end
end

@testset "MomentumRateTask" begin
    Random.seed!(6)
    mechanism = RBD.rand_tree_mechanism(Float64, [Revolute{Float64} for _ = 1 : 10]...)
    state = MechanismState(mechanism)
    rand_configuration!(state)
    nv = num_velocities(mechanism)
    v̇ = [Parametron.Variable(i) for i = 1 : nv]
    qpmodel = mock_model()

    centroidalframe = CartesianFrame3D("centroidal")
    task = MomentumRateTask(mechanism, centroidalframe)
    @test QPC.dimension(task) == 6
    err = QPC.task_error(task, qpmodel, state, v̇)

    angular, linear = SVector(1., 2., 3.), SVector(4., 5., 6.)
    desired = Wrench(centroidalframe, angular, linear)
    QPC.setdesired!(task, desired)
    zero_velocity!(state)
    setdirty!(qpmodel)
    v̇0 = zeros(length(v̇))
    @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == -SVector(desired)

    QPC.setdesired!(task, zero(desired))
    rand_velocity!(state)
    setdirty!(qpmodel)
    world_to_centroidal = Transform3D(root_frame(mechanism), centroidalframe, -center_of_mass(state).v)
    Ȧv = transform(momentum_rate_bias(state), world_to_centroidal)
    @test map(f -> f(Dict(zip(v̇, v̇0))), err()) == SVector(Ȧv)

    zero_velocity!(state)
    setdirty!(qpmodel)
    v̇rand = rand(nv)
    expected = transform(Wrench(momentum_matrix(state), v̇rand), world_to_centroidal)
    @test map(f -> f(Dict(zip(v̇, v̇rand))), err()) ≈ SVector(expected) atol = 1e-12

    allocs = @allocated err()
    @test allocs == 0
end


text:
# UTILITY FUNCTIONS AND DEFINITIONS, INCLUDING FOR CONVERTING USER INPUT TO AMENABLE FORM

#*========== NETWORK TOPOLOGY ===========

# list of regular generators at a particular bus
const regGenAtBus = Array[]

# list of wind generators at a particular bus
const windGenAtBus = Array[]

# list of loads at a particular bus
const loadAtBus = Array[]

# initialize Arrays
for i = 1:numBuses
	push!(regGenAtBus,Int64[])
	push!(windGenAtBus,Int64[])
	push!(loadAtBus,Int64[])
end

# populate regular generators first
for i = 1:numRegGen
	push!(regGenAtBus[regGenToBus[i]],i)
end

# next, populate wind generators
# offset the indices by numRegGen to account for regular generators first
for i = 1:numWindGen
	push!(windGenAtBus[windGenToBus[i]],i+numRegGen)
end

# finally, populate load indices
for j = 1:numLoads
	push!(loadAtBus[loadToBus[j]],j)
end

# store the number of lines
const numLines = size(lines,1)

# store the indices of buses that share an edge/line with current bus
# also store the corresponding line susceptances
const linesAdjBus = Array[]
const betaAdjBus = Array[]

for i = 1:numBuses
	push!(linesAdjBus,Int64[])
	push!(betaAdjBus, Float64[])
end

for k = 1:numLines
	push!(linesAdjBus[lines[k][1]],lines[k][2])
	push!(linesAdjBus[lines[k][2]],lines[k][1])

	push!(betaAdjBus[lines[k][1]],beta[k])
	push!(betaAdjBus[lines[k][2]],beta[k])
end

#*========== GENERATOR BOUNDS ===========

# minimum and maximum generator power outputs
const pmin = zeros(Float64,numGen)
const pmax = zeros(Float64,numGen)

# include regular generators first followed by wind generators
pmin[1:numRegGen] = regGenMinPow
pmin[numRegGen+1:end] = windGenMinPow

# ignore the upper bounds for the wind generators since they are random
pmax[1:numRegGen] = regGenMaxPow

# upper bounds for wind generator outputs in the deterministic setting
const pmax_det = 1.0*pmax
for i = 1:numWindGen
	pmax_det[numRegGen+i] = windPredMean[i]
end

# upper bounds for generator outputs to make first-stage decisions
const pmax_FS = 1.0*pmax
for i = 1:numWindGen
	pmax_FS[numRegGen+i] = windPredMean[i] + windBoundFactor*windPredStdev[i]
end

#*========== GENERATOR COST COEFFICIENTS ===========

# generator cost coefficients, including costs of reserves
const genCost = zeros(Float64,numGen)
const posResCost = zeros(Float64,numGen)
const negResCost = zeros(Float64,numGen)

# include regular generators first followed by wind generators
genCost[1:numRegGen] = regGenCost
genCost[numRegGen+1:end] = windGenCost

posResCost[1:numRegGen] = regGenPosResCost
posResCost[numRegGen+1:end] = windGenPosResCost

negResCost[1:numRegGen] = regGenNegResCost
negResCost[numRegGen+1:end] = windGenNegResCost

#*========== GENERATOR RESERVES INFORMATION ===========

# which generators are ready to provide reserves?
const genRes = falses(numGen)

# which generators are ALWAYS READY TO PROVIDE RESERVES?
const genGuarRes = falses(numGen)

# populate the regular generator options followed by the wind generator options
genRes[1:numRegGen] = regGenRes
genRes[numRegGen+1:end] = windGenRes

genGuarRes[1:numRegGen] = regGenGuarRes
genGuarRes[numRegGen+1:end] = windGenGuarRes

#*========== INITIAL GUESSES ===========

# power commitment variables for regular and wind generators
const p0_init = zeros(Float64,numGen)

# positive reserve variables for regular and wind generators
const rp_init = zeros(Float64,numGen)

# negative reserve variables for regular and wind generators
const rm_init = zeros(Float64,numGen)

# participation factor variables for regular and wind generators
const alpha_init = ones(Float64,numGen)/numGen

#*========== OTHER UTILITIES ===========

# update generator upper bounds based on wind levels
function updateGenBounds(omega_w::Array{Float64})

	for i = 1:numWindGen
		if(omega_w[i] < pmin[numRegGen+i])
			println("Wind availability at the ",i,"th generator = ",omega_w[i],"   < corresponding pmin = ",pmin[numRegGen+i])
			throw(ErrorException("Invalid wind generator upper bound!"))
		end
		pmax[numRegGen+i] = omega_w[i]
	end
end

# compute the variance and stdev of sum of demand deviations for the CAP model
const sumDemandDeviationVar = ones(Float64,numLoads)'*demandCovMat*ones(Float64,numLoads)
const sumDemandDeviationStdev = sqrt(sumDemandDeviationVar)

#*========== FACTORIZE AND STORE MATRICES FOR LINEAR SOLVES ===========

# pre-factorize and store matrix corresponding to DC-OPF equations
# the last bus is chosen as the reference bus and substituted out
const rowIndices = []
const colIndices = []
const matValues = []

const sumBeta = zeros(Float64,numBuses-1)

# also construct a matrix of lines with the reference bus ignored
const Line_mat = zeros(Float64,numLines,numBuses-1)

for k = 1:numLines
	fromBus::Int64 = lines[k][1]
	toBus::Int64 = lines[k][2]

	if(fromBus < numBuses)
		Line_mat[k,fromBus] = 1.0
		if(toBus < numBuses)
			push!(rowIndices,fromBus)
			push!(colIndices,toBus)
			push!(matValues,-beta[k])
		end

		sumBeta[fromBus] += beta[k]
	end

	if(toBus < numBuses)
		Line_mat[k,toBus] = -1.0
		if(fromBus < numBuses)
			push!(rowIndices,toBus)
			push!(colIndices,fromBus)
			push!(matValues,-beta[k])
		end

		sumBeta[toBus] += beta[k]
	end
end

for i = 1:numBuses-1
	push!(rowIndices,i)
	push!(colIndices,i)
	push!(matValues,sumBeta[i])
end

const B_mat = sparse(rowIndices,colIndices,matValues)
const B_fact = lufact(B_mat)

# construct matrices for generating the rhs of the DCOPF equations
# it appears that storing these in a sparse format is not worth it
# first, construct the matrix corresponding to the generators
const Gen_mat = zeros(Float64,numBuses-1,numGen)

for i = 1:numBuses-1
	for k = 1:size(regGenAtBus[i],1)
		Gen_mat[i,regGenAtBus[i][k]] = 1.0
	end

	for k = 1:size(windGenAtBus[i],1)
		Gen_mat[i,windGenAtBus[i][k]] = 1.0
	end
end

# next, construct the matrix corresponding to the loads
const Load_mat = zeros(Float64,numBuses-1,numLoads)

for i = 1:numBuses-1
	for k = 1:size(loadAtBus[i],1)
		Load_mat[i,loadAtBus[i][k]] = 1.0
	end
end

# store the solution of B_mat*x = Gen_mat
const B_over_G = B_fact\Gen_mat

# store the solution of B_mat*x = Load_mat
const B_over_L = B_fact\Load_mat

# store (Line_mat*B_over_G)'
const Line_mat_times_B_over_G_trans = (B_over_G')*(Line_mat')

max_stars_repo_name: rohitkannan/DCOPF-reserve-saturation

max_issues_repo_name: rohitkannan/DCOPF-reserve-saturation

max_forks_repo_name: rohitkannan/DCOPF-reserve-saturation


text:
module optim_mnfctr

export run_sequential, run_threaded

include("./misc.jl")

# functionality definitons

"""
    pairing(sequence::Union{Array{T, 1}, UnitRange{T}}) where T <: Integer

The function returns a vector of tuples of 2 integers that present a more suitable representation for matrix indexing with `matrix[elt...]`

Return `Array{Tuple{T, T}} where T <: Integer`

# Arguments
- `sequence::Union{Array{T, 1}, UnitRange{T}}`: A vector that that should e turned into sequence of consequitive tuples packaged in a vector.

# Examples
```jldoctest
julia> a = [1, 2, 3, 4]
4-element Vector{Int64}:
 1
 2
 3
 4
julia> pairing(a)
3-element Vector{Tuple{Int64, Int64}}:
 (1, 2)
 (2, 3)
 (3, 4)
```
"""
function pairing(sequence::Union{Array{T, 1}, UnitRange{T}})::Array{Tuple{T, T}} where T <: Integer
    L = []
    for s in 1:(length(sequence)-1)
        @inbounds push!(L, (sequence[s], sequence[s+1]))
    end
    return L
end

function run_sequential(matrix)

    @info "Started finding the minimal sequence of production orders"

    #global MIN, MIN_SEQUENCE, vec_

    x = size(matrix, 1) #given the matrix has the same number of rows and colums
    vec_ = 1:x
    perms = permutations(vec_)
    l = length(perms)
    MIN = 99999999
    MIN_SEQUENCE = Int64[]

    #@floop ThreadedEx() for i in 1:l
        #global MIN, MIN_SEQUENCE, vec_
    #@threads for i in 1:l
    for i in 1:l #perms
        nthp = nthperm(vec_, i)
        p = pairing(nthp)
        #@info @sprintf "Permutation %s" p
        s = Int64(0)
        #s = Threads.Atomic{Int}(0)

        for j in p
            #@info @sprintf "The j iterator value within the J loop is %s " j
            #println("Cost: ", matrix[j...])
            @inbounds s += matrix[j...]
            #println("Sum: ", s)
        end

        #@debug println("s: $s")

        if s < MIN
            MIN = s
            MIN_SEQUENCE = nthp
            #@debug "Resetting MIN to s: new min is $MIN"
        end
        #@debug "s < MIN: s=$s, MIN=$MIN"
        #@debug "#-----#"
    end
    return (MIN, MIN_SEQUENCE)
end

function run_threaded_no_simd(matrix)

    @info "Started finding the minimal sequence of production orders"

    #global MIN, MIN_SEQUENCE, vec_

    x = size(matrix, 1) #given the matrix has the same number of rows and colums
    vec_ = 1:x
    perms = permutations(vec_)
    l = length(perms)
    MIN = 99999999
    MIN_SEQUENCE = Int64[]

    #@floop ThreadedEx() for i in 1:l
        #global MIN, MIN_SEQUENCE, vec_
    @threads for i in 1:l
#    for i in 1:l #perms
        nthp = nthperm(vec_, i)
        p = pairing(nthp)
        #@info @sprintf "Permutation %s" p
        s = Int64(0)
        #s = Threads.Atomic{Int}(0)

        @simd for j in p
            #@info @sprintf "The j iterator value within the J loop is %s " j
            #println("Cost: ", matrix[j...])
            @inbounds s += matrix[j...]
            #println("Sum: ", s)
        end

        #@debug println("s: $s")

        if s < MIN
            MIN = s
            MIN_SEQUENCE = nthp
            #@debug "Resetting MIN to s: new min is $MIN"
        end
        #@debug "s < MIN: s=$s, MIN=$MIN"
        #@debug "#-----#"
    end
    return (MIN, MIN_SEQUENCE)
end

"""
    run_threaded(matrix)

Return the minimum path sum from the available cost matrix and the path sequence that leads to the minimum sum.
"""
function run_threaded(matrix)

    @info "Started the process of finding the minimal sequence of production orders"

    #global MIN, MIN_SEQUENCE, vec_

    x = size(matrix, 1) #given the matrix has the same number of rows and colums

    @info "matrix has the size $x x $x"

    vec_ = 1:x
    perms = permutations(vec_)
    l = length(perms)

    @info "The number of permutations to calculate is $l"

    MIN = 99999999
    MIN_SEQUENCE = Int64[]

    #@floop ThreadedEx() for i in 1:l
        #global MIN, MIN_SEQUENCE, vec_
    @threads for i in 1:l
#    for i in 1:l #perms
        nthp = nthperm(vec_, i)
        p = pairing(nthp)
        #@info @sprintf "Permutation %s" p
        s = Int64(0)
        #s = Threads.Atomic{Int}(0)

        for j in p
            #@info @sprintf "The j iterator value within the J loop is %s " j
            #println("Cost: ", matrix[j...])
            @inbounds s += matrix[j...]
            #println("Sum: ", s)
        end

        #@debug println("s: $s")

        if s < MIN
            MIN = s
            MIN_SEQUENCE = nthp
            #@debug "Resetting MIN to s: new min is $MIN"
        end
        #@debug "s < MIN: s=$s, MIN=$MIN"
        #@debug "#-----#"
    end
    return (MIN, MIN_SEQUENCE)
end

end #of module


text:
# This code license is MIT: https://github.com/vtjnash/JuliaCon2019Threading/blob/master/LICENSE

using Base.Threads: @spawn

function psort(v::AbstractVector)
    hi = length(v)
    if hi < 100_000 # below some cutoff, run in serial
        return sort(v, alg = MergeSort)
    end
    # split the range and sort the halves in parallel recursively
    mid = (1 + hi) >>> 1
    half = @spawn psort(view(v, 1:mid))
    right = psort(view(v, (mid + 1):hi))
    left = fetch(half)::typeof(right)
    # perform the merge on the result
    out = similar(v)
    pmerge!(out, left, right)
    return out
end

function merge!(out, left, right)
    ll, lr = length(left), length(right)
    @assert ll + lr == length(out)
    i, il, ir = 1, 1, 1
    @inbounds while il <= ll && ir <= lr
        l, r = left[il], right[ir]
        if isless(r, l)
            out[i] = r
            ir += 1
        else
            out[i] = l
            il += 1
        end
        i += 1
    end
    @inbounds while il <= ll
        out[i] = left[il]
        il += 1
        i += 1
    end
    @inbounds while ir <= lr
        out[i] = right[ir]
        ir += 1
        i += 1
    end
    return out
end

function pmerge!(out, left, right)
    ll, lr = length(left), length(right)
    @assert ll + lr == length(out)
    if length(out) < 100_000
        # below some threshold, just do the merge
        merge!(out, left, right)
    else
        # split the larger chunk in half, then binary search the
        # smaller half to split it
        if ll > lr
            jl = ll ÷ 2
            # stable sort: find the last entry in right
            # strictly smaller than l
            jr = searchsortedfirst(right, left[jl]) - 1
        else
            jr = lr ÷ 2
            # stable sort: find the last entry in left not bigger
            # than r
            jl = searchsortedlast(left, right[jr])
        end
        @sync begin
            let left = view(left, 1:jl),
                right = view(right, 1:jr),
                out = view(out, 1:(jl + jr))
                @spawn pmerge!(out, left, right)
            end
            let left = view(left, (jl + 1):ll),
                right = view(right, (jr + 1):lr),
                out = view(out, (jl + jr + 1):length(out))
                pmerge!(out, left, right)
           end
        end
    end
    nothing
end