text:
function gcdgn(p::AbstractVector{T}, q::AbstractVector{T}, g0::AbstractVector{T}, u0::AbstractVector{T}, v0::AbstractVector{T}) where {T<:Number}
#
#  Finds extended GCD of polynomial p and q by Gauss-Newton
#  iteration, such that
#
#         convolute(g,u) = p,      convolute(g,v) = q
#
#  Calling syntax:
#    g,u,v,res = gcdgn(p, q, g0, u0, v0)
#
#        INPUT:  p, q -- polynomial coefficients (hight coeff first)
#                g0, u0, v0 -- initial iterates
#        OUTPUT: g, u, v as described above
#                res
#
	E = real(one(T))
    m = length(g0) - 1; m1 = m+1;   # degree of g (i.e. gcd)
    n = length(u0) - 1; n1 = n+1;   # degree of u
    k = length(v0) - 1; k1 = k+1;   # degree of v
    lp = length(p);                 # length of p
    lq = length(q);                 # length of q = p'

    # making all polynomials monic and make a copy
    p  = p / p[1]
    q  = q / q[1]
    g0 = g0 / g0[1]
    u0 = u0 / u0[1]
    v0 = v0 / v0[1]

    s = convolute(g0, u0) - p
    t = convolute(g0, v0) - q
    b = [s[2:lp]; t[2:lq]]
    x = [g0[2:m1]; u0[2:n1]; v0[2:k1]]
    w = ones(T, length(b))
    for j = 2:lp
	    apj = abs(p[j])
        if apj > E
            w[j-1] = E / apj
		end
    end

    for j = 2:lq
	    aqj = abs(q[j])
        if aqj > E
            w[lp-2+j] = E / aqj
        end
    end

    bke0 = norm(b .* w, Inf)
    bke = bke0
    #@printf("      g-n %g \n", bke)
	g::AbstractVector{T} = []
	u::AbstractVector{T} = []
	v::AbstractVector{T} = []

    j = 1
    while j > 0

        A = sylmat(g0, u0, v0)
        d = scalsq(A, b, w)
		y = x
        tau = 1.0
		bkej = bke
		while tau > 1e-4 && bkej > bke * (1-tau*0.25)
            y = x - d * tau

            g = [E; y[1:m]]
	        u = [E; y[m+1:m+n]]
            v = [E; y[m+n+1:m+n+k]]
            s = convolute(g, u) - p
		    t = convolute(g, v) - q
            b = [s[2:lp]; t[2:lq]]
		    bkej = norm(b .* w, Inf)
            tau *= 0.5
		end
        #@printf("      g-n %g %g %g \n", bkej, tau, norm(d))

        if bkej >= bke ||  bke - bkej < (bke0 - bkej) * 0.05 || tau <= 1e-4
            g = g0
			u = u0
			v = v0
            break
        end

        g0 = g
		u0 = u
		v0 = v
        x = y
		bke = bkej
        j = j + 1;
    end
    g, u, v, bke0, bke
end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct ServiceEndpointPropertiesFormat <: SwaggerModel
    service::Any # spec type: Union{ Nothing, String } # spec name: service
    locations::Any # spec type: Union{ Nothing, Vector{String} } # spec name: locations
    provisioningState::Any # spec type: Union{ Nothing, ProvisioningState } # spec name: provisioningState

    function ServiceEndpointPropertiesFormat(;service=nothing, locations=nothing, provisioningState=nothing)
        o = new()
        validate_property(ServiceEndpointPropertiesFormat, Symbol("service"), service)
        setfield!(o, Symbol("service"), service)
        validate_property(ServiceEndpointPropertiesFormat, Symbol("locations"), locations)
        setfield!(o, Symbol("locations"), locations)
        validate_property(ServiceEndpointPropertiesFormat, Symbol("provisioningState"), provisioningState)
        setfield!(o, Symbol("provisioningState"), provisioningState)
        o
    end
end # type ServiceEndpointPropertiesFormat

const _property_map_ServiceEndpointPropertiesFormat = Dict{Symbol,Symbol}(Symbol("service")=>Symbol("service"), Symbol("locations")=>Symbol("locations"), Symbol("provisioningState")=>Symbol("provisioningState"))
const _property_types_ServiceEndpointPropertiesFormat = Dict{Symbol,String}(Symbol("service")=>"String", Symbol("locations")=>"Vector{String}", Symbol("provisioningState")=>"ProvisioningState")
Base.propertynames(::Type{ ServiceEndpointPropertiesFormat }) = collect(keys(_property_map_ServiceEndpointPropertiesFormat))
Swagger.property_type(::Type{ ServiceEndpointPropertiesFormat }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_ServiceEndpointPropertiesFormat[name]))}
Swagger.field_name(::Type{ ServiceEndpointPropertiesFormat }, property_name::Symbol) =  _property_map_ServiceEndpointPropertiesFormat[property_name]

function check_required(o::ServiceEndpointPropertiesFormat)
    true
end

function validate_property(::Type{ ServiceEndpointPropertiesFormat }, name::Symbol, val)
end

ext: jl


text:
struct WalkerIdealParam <: EoSParam
    Mw::SingleParam{Float64}
    Nrot::SingleParam{Int}
    theta1::SingleParam{Float64}
    theta2::SingleParam{Float64}
    theta3::SingleParam{Float64}
    theta4::SingleParam{Float64}
    deg1::SingleParam{Int}
    deg2::SingleParam{Int}
    deg3::SingleParam{Int}
    deg4::SingleParam{Int}
end

abstract type WalkerIdealModel <: IdealModel end
@newmodelsimple WalkerIdeal WalkerIdealModel WalkerIdealParam

export WalkerIdeal
function WalkerIdeal(components::Array{String,1}; userlocations::Array{String,1}=String[], verbose=false)
    params = getparams(components, ["ideal/WalkerIdeal.csv"]; userlocations=userlocations, verbose=verbose)
    Mw = params["Mw"]
    Nrot = params["Nrot"]
    theta1 = params["theta_1"]
    theta2 = params["theta_2"]
    theta3 = params["theta_3"]
    theta4 = params["theta_4"]
    deg1 = params["deg_1"]
    deg2 = params["deg_2"]
    deg3 = params["deg_3"]
    deg4 = params["deg_4"]
    packagedparams = WalkerIdealParam(Mw, Nrot, theta1, theta2, theta3, theta4, deg1, deg2, deg3, deg4)
    references = ["10.1021/acs.jced.0c00723"]
    return WalkerIdeal(packagedparams; references=references)
end

function a_ideal(model::WalkerIdealModel,V,T,z)
    x = z/sum(z)
    Mw = model.params.Mw.values
    Λ = @. h/√(k_B*T*Mw/N_A)
    Nrot = model.params.Nrot.values
    θ1 = model.params.theta1.values
    θ2 = model.params.theta2.values
    θ3 = model.params.theta3.values
    θ4 = model.params.theta4.values
    g1 = model.params.deg1.values
    g2 = model.params.deg2.values
    g3 = model.params.deg3.values
    g4 = model.params.deg4.values
    θ_vib = [θ1, θ2, θ3, θ4]
    g_vib = [g1, g2, g3, g4]
    return sum(x[i]*(log(z[i]*N_A/V*Λ[i]^3)-Nrot[i]/2*log(T)+sum(g_vib[v][i]*(θ_vib[v][i]/2/T+log(1-exp(-θ_vib[v][i]/T))) for v in 1:4)) for i in @comps)-1
end


text:
### Convenience functions

export body_as_dict
"""
    body_as_dict(req::HTTP.Request)

Endpoints that expect a `POST` request with a json-encoded body can use this.
"""
function body_as_dict(req::HTTP.Request)
    JSON.parse(String(req.body))
end

export has_all_required_keys
"""
    has_all_required_keys(required_keys::Array{String, 1}, json::T) where {T <: AbstractDict}

Returns true if the dict `j` contains all the required `keys`, false otherwise.  This is a convenience function to make endpoints more concise and readable.
"""
function has_all_required_keys(required_keys::Array{String, 1}, json::T) where {T <: AbstractDict}
    return count(in.(required_keys, Ref(keys(json)))) == length(required_keys)
end


text:
using subpop
using Documenter

makedocs(;
    modules=[subpop],
    authors="Drew Dolgert <adolgert@uw.edu> and contributors",
    repo="https://github.com/adolgert/subpop.jl/blob/{commit}{path}#L{line}",
    sitename="subpop.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://adolgert.github.io/subpop.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
    ],
)

deploydocs(;
    repo="github.com/adolgert/subpop.jl",
)


text:
using Cbc
using Test
using LinearAlgebra
solver = CbcSolver(logLevel=0, integerTolerance=1e-9, primalTolerance=1e-9, ratioGap=1e-8)

# using Gurobi
# solver = GurobiSolver(OutputFlag=0)

# using CPLEX
# solver = CplexSolver(CPX_PARAM_SCRIND=0)

using JuMP
using PiecewiseLinearOpt

methods_1D = (:CC,:MC,:Logarithmic,:LogarithmicIB,:ZigZag,:ZigZagInteger,:SOS2,:GeneralizedCelaya,:SymmetricCelaya,:Incremental,:DisaggLogarithmic)
methods_2D = (:CC,:MC,:Logarithmic,:LogarithmicIB,:ZigZag,:ZigZagInteger,:SOS2,:GeneralizedCelaya,:SymmetricCelaya,:DisaggLogarithmic)
patterns_2D = (:Upper,:Lower,:BestFit,:UnionJack,:K1,:Random) # :OptimalTriangleSelection and :Stencil not supported currently

println("\nunivariate tests")
@testset "1D: $method" for method in methods_1D
    model = Model(solver=solver)
    @variable(model, x)
    z = piecewiselinear(model, x, range(1,stop =2π, length =8), sin, method=method)
    @objective(model, Max, z)

    @test solve(model) == :Optimal
    @test getvalue(x) ≈ 1.75474 rtol=1e-4
    @test getvalue(z) ≈ 0.98313 rtol=1e-4

    @constraint(model, x ≤ 1.5z)

    @test solve(model) == :Optimal
    @test getvalue(x) ≈ 1.36495 rtol=1e-4
    @test getvalue(z) ≈ 0.90997 rtol=1e-4
end

println("\nbivariate tests")
@testset "2D: $method, $pattern" for method in methods_2D, pattern in patterns_2D
    model = Model(solver=solver)
    @variable(model, x)
    @variable(model, y)
    d = range(0,stop=1,length=8)
    f = (x,y) -> 2*(x-1/3)^2 + 3*(y-4/7)^4
    z = piecewiselinear(model, x, y, BivariatePWLFunction(d, d, f, pattern=pattern), method=method, subsolver=solver)
    @objective(model, Min, z)

    @test solve(model) == :Optimal
    @test getvalue(x) ≈ 0.285714 rtol=1e-4
    @test getvalue(y) ≈ 0.571429 rtol=1e-4
    @test getvalue(z) ≈ 0.004535 rtol=1e-3

    @constraint(model, x ≥ 0.6)

    @test solve(model) == :Optimal
    @test getvalue(x) ≈ 0.6 rtol=1e-4
    @test getvalue(y) ≈ 0.571428 rtol=1e-4
    @test getvalue(z) ≈ 0.148753 rtol=1e-4
end

println("\nbivariate optimal IB scheme tests")
@testset "2D: optimal IB, UnionJack" begin
    model = Model(solver=solver)
    @variable(model, x)
    @variable(model, y)
    d = range(0,stop=1,length=3)
    f = (x,y) -> 2*(x-1/3)^2 + 3*(y-4/7)^4
    z = piecewiselinear(model, x, y, BivariatePWLFunction(d, d, f, pattern=:UnionJack), method=:OptimalIB, subsolver=solver)
    @objective(model, Min, z)

    @test solve(model) == :Optimal
    @test getvalue(x) ≈ 0.5 rtol=1e-4
    @test getvalue(y) ≈ 0.5 rtol=1e-4
    @test getvalue(z) ≈ 0.055634 rtol=1e-3

    @constraint(model, x ≥ 0.6)

    @test solve(model) == :Optimal
    @test getvalue(x) ≈ 0.6 rtol=1e-4
    @test getvalue(y) ≈ 0.5 rtol=1e-4
    @test getvalue(z) ≈ 0.222300 rtol=1e-3
end


text:
using LinearAlgebra, StaticArrays
@testset "code gen" begin
    a = Vector{Number}(undef, 6)
    a[1] = 0.11
    a[2] = 0.11 + 0.1im
    a[3] = Float32(0.11)
    a[4] = ComplexF32(0.11 + 0.1im)
    a[5] = big"0.11"
    a[6] = parse(Complex{BigFloat}, "0.11+0.1im")

    # Test julia code generation
    for i = 1:length(a)
        (graph, crefs) = graph_ps([3 4 2 a[i]])
        add_ldiv!(graph, :R0, :A2, :P0)
        clear_outputs!(graph)
        add_output!(graph, :R0)
        for t3 in (true, false)
            for t2 in (true, false)
                for t1 in (true, false)
                    TT = eltype(a);
                    A = convert.(TT,[3 4.0; 5.5 0.1]);
                    lang = LangJulia(t1,t2,t3)
                    fname = tempname() * ".jl"
                    ti = time_ns()
                    gen_code(fname, graph, lang = lang, funname = "dummy_$(ti)")
                    # and execution
                    include(fname)
                    @test eval_graph(graph, A) ≈ eval(Symbol("dummy_$(ti)"))(A)
                    rm(fname)
                end
            end
        end

    end

    # Test Statically sized matrix
    (graph, crefs) = graph_ps([3 4 2 10.0])
    fname = tempname() * ".jl"
    gen_code(fname, graph, funname = "thisfunction")
    # and execution
    include(fname)
    rm(fname)

    A=[  0.704017  -0.358008   0.0649856;  -1.50413    0.0251634  0.0170085;  0.348764   0.334011   0.0915101]
    Am=MMatrix{3,3}(A);
    @test thisfunction(A)≈thisfunction(Am)

    # Test precomputed nodes
    fname = tempname() * ".jl"
    gen_code(fname, graph, funname = "thisfunction2",precomputed_nodes=[:A,:A2])
    # and execution
    include(fname)
    rm(fname)
    @test thisfunction2(Am,Am*Am)≈thisfunction(Am)

    for i = 1:4 #Not high-precision test for Matlab and C
        (graph, crefs) = graph_ps([3 4 2 a[i]])
        add_ldiv!(graph, :R0, :A2, :P0)
        clear_outputs!(graph)
        add_output!(graph, :R0)

        # Test Matlab code generation (not execution)
        fname = tempname() * ".m"
        gen_code(fname, graph, lang = LangMatlab())
        rm(fname)

        # Test C code generation
        fname = tempname() * ".c"
        gen_code(fname, graph, lang = LangC_MKL())
        rm(fname)

        fname = tempname() * ".c"
        gen_code(fname, graph, lang = LangC_MKL(true))
        rm(fname)

        fname = tempname() * ".c"
        gen_code(fname, graph, lang = LangC_OpenBLAS())
        rm(fname)

        fname = tempname() * ".c"
        gen_code(fname, graph, lang = LangC_OpenBLAS(true))
        rm(fname)
    end
end


text:
export CaseSpec, BaseMods, XpMods
export make_case_spec, has_mods, get_mods, has_modifier, find_main_mod, replace_mods, base_name, modifier_string, add_modifier
export has_xp_mods, get_xp_mods, has_xp_modifier, replace_xp_mods, remove_xp_mods, exper_string
export case_fn

struct BaseMods end
struct XpMods end

"""
	$(SIGNATURES)

Contains base name and a list of (sorted) modifications.

Note: The order of modifiers does not matter. They are always sorted.
"""
struct CaseSpec
    baseName :: Symbol
    mods :: Vector{Modifier}
    xpMods :: Vector{Modifier}

    # Inner constructor ensures that mods are sorted
    function CaseSpec(bn :: Symbol, modInV :: AbstractVector,
        xpModV :: AbstractVector)
        cn = new(bn, make_modifier_vector(modInV), make_modifier_vector(xpModV));
        return cn
    end
end

# No modifiers. No experiment.
# Symbol first. Then the rest is experiment.
function CaseSpec(bn :: Symbol, xpModV = Vector{Modifier}())
    return CaseSpec(bn, Vector{Modifier}(), xpModV);
end

CaseSpec(bn :: Symbol, xpMod :: Modifier{T}) where T =
    CaseSpec(bn, [xpMod]);

# 2 vectors are interpreted as [base], [experiment]
function CaseSpec(cv :: AbstractVector, xpV :: AbstractVector = Vector{Modifier}())
    baseName = cv[1];
    @assert (baseName isa Symbol)  "Invalid CaseSpec: $cv";
    if length(cv) > 1
        return CaseSpec(baseName,  cv[2 : end], xpV);
    else
        return CaseSpec(baseName, Vector{Modifier}(), xpV);
    end
end

# Nested vectors are interpreted as ([base], [experiment])
function CaseSpec(vv :: Tuple{T1, Vector{T2}}) where {T1, T2}
    return CaseSpec(vv...);
end

# function CaseSpec(vv :: Tuple{Vector{T1}, Vector{T2}}) where {T1, T2}
#     return CaseSpec(vv...);
# end

"""
	$(SIGNATURES)

A simple pass-through function that makes a `CaseSpec` if needed and passes it through otherwise.
"""
make_case_spec(cn :: CaseSpec) = cn;
# make_case_spec(cn :: Case) = cn.name;
make_case_spec(cn) = CaseSpec(cn);

## --------  Properties

get_mods(cn :: CaseSpec) = cn.mods;
get_xp_mods(cn :: CaseSpec) = cn.xpMods;
get_modifiers(cn :: CaseSpec, ::Type{BaseMods}) = get_mods(cn);
get_modifiers(cn :: CaseSpec, ::Type{XpMods}) = get_xp_mods(cn);

"""
	$(SIGNATURES)

Base name of a CaseSpec.
"""
base_name(cn :: CaseSpec) = cn.baseName;

"""
	$(SIGNATURES)

Does CaseSpec contain modifiers?
"""
has_mods(cn :: CaseSpec) = !isempty(get_mods(cn));

has_xp_mods(cn :: CaseSpec) = !isempty(get_xp_mods(cn));

has_modifiers(cn :: CaseSpec, ::Type{BaseMods}) = has_mods(cn);
has_modifiers(cn :: CaseSpec, ::Type{XpMods}) = has_xp_mods(cn);

"""
	$(SIGNATURES)

Does CaseSpec have a given Modifier?
"""
has_modifier(cn :: CaseSpec, modName) =
    make_modifier(modName) ∈ get_mods(cn);

has_xp_modifier(cn :: CaseSpec, modName) =
    make_modifier(modName) ∈ get_xp_mods(cn);

has_modifier(cn :: CaseSpec, ::Type{BaseMods}, modName) =
    has_modifier(cn, modName);
has_modifier(cn :: CaseSpec, ::Type{XpMods}, modName) =
    has_xp_modifier(cn, modName);

"""
	$(SIGNATURES)

Find modifier that has the target main modifier. Returns `nothing if not found`.
"""
function find_main_mod(cn :: CaseSpec, mainMod :: Symbol)
    if has_mods(cn)
        return find_main_mod(get_mods(cn), mainMod);
    else
        return nothing
    end
end

function Base.isequal(cn1 :: CaseSpec, cn2 :: CaseSpec)
    return equal_base_names(cn1, cn2)  &&  equal_mods(cn1, cn2)  &&
        equal_xp_mods(cn1, cn2);
end

function equal_base_names(cnV...)
    areEqual = true;
    for cn in cnV
        areEqual = areEqual  &&  isequal(base_name(cn), base_name(cnV[1]));
    end
    return areEqual
end

function equal_modifiers(::Type{T}, cnV...) where T
    areEqual = true;
    hasMods = has_mods(cnV[1]);
    for cn in cnV
        if !hasMods
            areEqual = areEqual  &&  !has_mods(cn);
        else
            areEqual = areEqual  &&
                isequal(get_modifiers(cn, T), get_modifiers(cnV[1], T));
        end
    end
    return areEqual
end

equal_mods(cnV...) = equal_modifiers(BaseMods, cnV...);
equal_xp_mods(cnV...) = equal_modifiers(XpMods, cnV...);

## -----------  Apply modifiers

replace_mods(cn :: CaseSpec, newMods) =
    CaseSpec(base_name(cn), newMods, get_xp_mods(cn));
replace_xp_mods(cn :: CaseSpec, newMods) =
    CaseSpec(base_name(cn), get_mods(cn), newMods);
remove_xp_mods(cn :: CaseSpec) = replace_xp_mods(cn, Vector{Modifier}());

"""
	$(SIGNATURES)

Add modifiers to an existing CaseSpec. Errors if any of the modifiers already exist.
"""
function add_modifier(cn :: CaseSpec, modName; ignoreExisting = false)
    newMod = make_modifier(modName);
    if has_modifier(cn, newMod)
        if !ignoreExisting
            error("Modifier $modName already exists.");
        end
    else
        return CaseSpec(base_name(cn), vcat(get_mods(cn), newMod), get_xp_mods(cn));
    end
end

## ---------- Show (as string)

"""
	$(SIGNATURES)

String representation of a Case's name. Not used for file names. See `case_fn`.
E.g.: `[Base, Mod1, (Mod2, 2)][xp1, (xp2, 3)]`
"""
function make_string(cn :: CaseSpec)
    return base_case_string(cn) * exper_string(cn);
end

function base_case_string(cn :: CaseSpec; brackets = true)
    s = string(base_name(cn));
    if has_mods(cn)
        s = s * "_" * make_string(get_mods(cn));
    end
    if brackets
        s = "[" * s * "]";
    end
    return s
end

function modifier_string(cn :: CaseSpec; brackets = true)
    if has_mods(cn)
        s = make_string(get_mods(cn));
        if brackets
            s = "[" * s * "]";
        end
    else
        s = "";
    end
    return s
end

function exper_string(cn :: CaseSpec; brackets = true)
    if has_xp_mods(cn)
        s = make_string(get_xp_mods(cn));
    else
        s = "Base";
    end
    if brackets
        s = "[" * s * "]";
    end
    return s
end

Base.show(io :: IO, cn :: CaseSpec) = print(io, make_string(cn));

# Used for file names
function case_fn(cn :: CaseSpec)
    return base_case_string(cn; brackets = false) * "_XP_" *
        exper_string(cn; brackets = false);
end

# """
# 	$(SIGNATURES)

# Return modifiers as a string of the form "mod1_mod2". Only for the base Case, excluding the experiments.
# """
# function modifier_string(cn)
#     cn = make_case_spec(cn);
#     if !has_mods(cn)
#         return ""
#     else
#         modStr = join(make_string.(cn.mods), "_");
#         return modStr
#     end
# end

# function command_string(symV :: AbstractVector{Symbol})
#     if length(symV) == 1
#         return command_string(symV[1]);
#     else
#         return "[" * join(command_string.(symV), ",") * "]";
#     end
# end

# command_string(s :: Symbol) = ":" * string(s);

# function command_argument(cn :: CaseSpec)
    # strV = string_vector(cn, prefixStr = ":");
    # str1 = strV[1];
    # if length(strV) > 1
    #     str1 = "[" * str1;
    #     for j = 2 : length(strV)
    #         str1 = str1 * ", " * strV[j];
    #     end
    #     str1 = str1 * "]";
    # end
    # return str1
# end

# function string_vector(cn :: CaseSpec; prefixStr = "")
#     n = 1 + length(cn.mods);
#     strV = Vector{String}(undef, n);
#     strV[1] = prefixStr * String(cn.CaseSpec);
#     if n > 1
#         for j = 2 : n
#             strV[j] = prefixStr * make_string(cn.mods[j-1]);
#         end
#     end
#     return strV
# end

# ---------------


text:
# AUTO GENERATED FILE - DO NOT EDIT

export dcc_tabs

"""
    dcc_tabs(;kwargs...)
    dcc_tabs(children::Any;kwargs...)
    dcc_tabs(children_maker::Function;kwargs...)

A Tabs component.
A Dash component that lets you render pages with tabs - the Tabs component's children
can be dcc.Tab components, which can hold a label that will be displayed as a tab, and can in turn hold
children components that will be that tab's content.
Keyword arguments:
- `children` (Array of a list of or a singular dash component, string or numbers | a list of or a singular dash component, string or number; optional): Array that holds Tab components
- `id` (String; optional): The ID of this component, used to identify dash components
in callbacks. The ID needs to be unique across all of the
components in an app.
- `value` (String; optional): The value of the currently selected Tab
- `className` (String; optional): Appends a class to the Tabs container holding the individual Tab components.
- `content_className` (String; optional): Appends a class to the Tab content container holding the children of the Tab that is selected.
- `parent_className` (String; optional): Appends a class to the top-level parent container holding both the Tabs container and the content container.
- `style` (Dict; optional): Appends (inline) styles to the Tabs container holding the individual Tab components.
- `parent_style` (Dict; optional): Appends (inline) styles to the top-level parent container holding both the Tabs container and the content container.
- `content_style` (Dict; optional): Appends (inline) styles to the tab content container holding the children of the Tab that is selected.
- `vertical` (Bool; optional): Renders the tabs vertically (on the side)
- `mobile_breakpoint` (Real; optional): Breakpoint at which tabs are rendered full width (can be 0 if you don't want full width tabs on mobile)
- `colors` (optional): Holds the colors used by the Tabs and Tab components. If you set these, you should specify colors for all properties, so:
colors: {
   border: '#d6d6d6',
   primary: '#1975FA',
   background: '#f9f9f9'
 }. colors has the following type: lists containing elements 'border', 'primary', 'background'.
Those elements have the following types:
  - `border` (String; optional)
  - `primary` (String; optional)
  - `background` (String; optional)
- `loading_state` (optional): Object that holds the loading state object coming from dash-renderer. loading_state has the following type: lists containing elements 'is_loading', 'prop_name', 'component_name'.
Those elements have the following types:
  - `is_loading` (Bool; optional): Determines if the component is loading or not
  - `prop_name` (String; optional): Holds which property is loading
  - `component_name` (String; optional): Holds the name of the component that is loading
- `persistence` (Bool | String | Real; optional): Used to allow user interactions in this component to be persisted when
the component - or the page - is refreshed. If `persisted` is truthy and
hasn't changed from its previous value, a `value` that the user has
changed while using the app will keep that change, as long as
the new `value` also matches what was given originally.
Used in conjunction with `persistence_type`.
- `persisted_props` (Array of a value equal to: 'value's; optional): Properties whose user interactions will persist after refreshing the
component or the page. Since only `value` is allowed this prop can
normally be ignored.
- `persistence_type` (a value equal to: 'local', 'session', 'memory'; optional): Where persisted user changes will be stored:
memory: only kept in memory, reset on page refresh.
local: window.localStorage, data is kept after the browser quit.
session: window.sessionStorage, data is cleared once the browser quit.
"""
function dcc_tabs(; kwargs...)
        available_props = Symbol[:children, :id, :value, :className, :content_className, :parent_className, :style, :parent_style, :content_style, :vertical, :mobile_breakpoint, :colors, :loading_state, :persistence, :persisted_props, :persistence_type]
        wild_props = Symbol[]
        return Component("dcc_tabs", "Tabs", "dash_core_components", available_props, wild_props; kwargs...)
end

dcc_tabs(children::Any; kwargs...) = dcc_tabs(;kwargs..., children = children)
dcc_tabs(children_maker::Function; kwargs...) = dcc_tabs(children_maker(); kwargs...)

max_stars_repo_name: asc-csa/dash-core-components

max_issues_repo_name: asc-csa/dash-core-components

max_forks_repo_name: asc-csa/dash-core-components


text:
sharpness(img::AbstractArray{CT,N}) where {CT<:ImageCore.NumberLike,N} = var(imfilter(img, Kernel.Laplacian(ntuple(i->true, Val(N)))))

function adaptive_thres(img::AbstractArray{CT,N}, block::NTuple{N,Int}) where {CT<:ImageCore.NumberLike,N}
    threshold = zeros(Float64, block)
    block_length = CartesianIndex(ntuple(i->ceil(Int,length(axes(img,i))/block[i]),Val(N)))
    net_s = sharpness(img)
    net_var = var(img)
    net_end = last(CartesianIndices(axes(img)))
    for i in CartesianIndices(block)
        si = CartesianIndex(ntuple(j->(i[j]-1)*block_length[j]+1,Val(N)))
        ei = min(si + block_length - _oneunit(si), net_end)
        wi = view(img, map((i,j)->i:j, si.I, ei.I)...)
        threshold[i] = 0.02 + min(sharpness(wi)/net_s*0.04,0.1) + min(var(wi)/net_var*0.04,0.1)
    end
    threshold
end

getscalar(A::AbstractArray{T,N}, i::CartesianIndex{N}, block_length::CartesianIndex{N}) where {T<:Real,N} =
    A[CartesianIndex(ntuple(j->(i[j]-1)÷block_length[j]+1, Val(N)))]

getscalar(a::Real, i...) = a

"""
    seg_img = fast_scanning(img, threshold, [diff_fn])

Segments the N-D image using a fast scanning algorithm and returns a
[`SegmentedImage`](@ref) containing information about the segments.

# Arguments:
* `img`         : N-D image to be segmented (arbitrary axes are allowed)
* `threshold`   : Upper bound of the difference measure (δ) for considering
                  pixel into same segment; an `AbstractArray` can be passed
                  having same number of dimensions as that of `img` for adaptive
                  thresholding
* `diff_fn`     : (Optional) Function that returns a difference measure (δ)
                  between the mean color of a region and color of a point

# Examples:

```jldoctest; setup = :(using ImageCore, ImageMorphology, ImageSegmentation)
julia> img = zeros(Float64, (3,3));

julia> img[2,:] .= 0.5;

julia> img[:,2] .= 0.6;

julia> seg = fast_scanning(img, 0.2);

julia> labels_map(seg)
3×3 $(Matrix{Int}):
 1  4  5
 4  4  4
 3  4  6
```

# Citation:

Jian-Jiun Ding, Cheng-Jin Kuo, Wen-Chih Hong,
"An efficient image segmentation technique by fast scanning and adaptive merging"
"""
fast_scanning(img::AbstractArray{CT,N}, block::NTuple{N,Int} = ntuple(i->4,Val(N))) where {CT<:ImageCore.NumberLike,N} =
    fast_scanning(img, adaptive_thres(img, block))

fast_scanning(img::AbstractArray{CT,N}, threshold::Union{AbstractArray,Real}, diff_fn::Function = default_diff_fn) where {CT<:Union{Colorant,Real},N} =
    fast_scanning!(fill(-1, axes(img)), img, threshold, diff_fn)

function fast_scanning!(result, img::AbstractArray{CT,N}, threshold::Union{AbstractArray,Real}, diff_fn::DF = default_diff_fn) where {CT<:Union{Colorant,Real},N,DF<:Function}
    if threshold isa AbstractArray
        ndims(img) == ndims(threshold) || error("Dimension count of image and threshold do not match")
    end

    # Neighbourhood function
    _diagmN = Diagonal([1 for i in 1:N])
    half_region::NTuple{N,CartesianIndex{N}} = ntuple(i-> CartesianIndex{N}(ntuple(j->_diagmN[j,i], Val(N))), Val(N))
    neighbourhood(x) = ntuple(i-> x-half_region[i], Val(N))

    # Required data structures
    TM = meantype(CT)
    region_means        =   Dict{Int, TM}()                                 # A map conatining (label, mean) pairs
    region_pix_count    =   Dict{Int, Int}()                                # A map conatining (label, count) pairs
    temp_labels         =   IntDisjointSets(0)                              # Disjoint set to map labels to their equivalence class
    v_neigh             =   MVector{N,Int}(undef)                           # MVector to store valid neighbours

    block_length = CartesianIndex(ntuple(i->ceil(Int,length(axes(img,i))/size(threshold,i)), Val(N)))

    for point in CartesianIndices(axes(img))
        sz = 0
        same_label = true
        prev_label = 0
        for p in neighbourhood(point)
            if checkbounds(Bool, img, p)
                root_p = find_root!(temp_labels, result[p])
                if diff_fn(region_means[root_p], img[point]) < getscalar(threshold, point, block_length)
                    if prev_label == 0
                        prev_label = root_p
                    elseif prev_label != root_p
                        same_label = false
                    end
                    sz += 1
                    v_neigh[sz] = find_root!(temp_labels, root_p)
                end
            end
        end

        # If no valid label found
        if sz == 0
            # Assign a new label
            new_label = push!(temp_labels)
            result[point] = new_label
            region_means[new_label] = img[point]
            region_pix_count[new_label] = 1

        # If all labels are same
        elseif same_label
            result[point] = prev_label
            region_pix_count[prev_label] += 1
            region_means[prev_label] += (img[point] - region_means[prev_label])/(region_pix_count[prev_label])
        else
            # Merge segments and assign to this new label
            union_label = v_neigh[1]
            for i in 1:sz
                union_label = union!(temp_labels, union_label, v_neigh[i])
            end
            result[point] = union_label
            region_pix_count[union_label] += 1
            region_means[union_label] += (img[point] - region_means[union_label])/(region_pix_count[union_label])

            for i in 1:sz
                if v_neigh[i] != union_label && haskey(region_pix_count, v_neigh[i])
                    region_pix_count[union_label] += region_pix_count[v_neigh[i]]
                    region_means[union_label] += (region_means[v_neigh[i]] - region_means[union_label])*region_pix_count[v_neigh[i]]/region_pix_count[union_label]

                    # Remove label v_neigh[i] from region_means, region_pix_count
                    delete!(region_pix_count,v_neigh[i])
                    delete!(region_means,v_neigh[i])
                end
            end
        end
    end

    for point in CartesianIndices(axes(img))
        result[point] = find_root!(temp_labels, result[point])
    end

    SegmentedImage(result, unique(temp_labels.parents), region_means, region_pix_count)
end


text:
using Test
using SymDiff

@test differentiate(:(1 + x), :x) == :(0 + 1)
@test differentiate(:(x - 1), :x) == :(1 - 0)


text:
@testset "ID registry" begin
    @test_call PNML.IDRegistry()
    reg = PNML.IDRegistry()
    @test_call PNML.register_id!(reg, :p)
    @test_call PNML.register_id!(reg, "p")
    @test_call PNML.reset_registry!(reg)
    @test_call PNML.duplicate_id_action(:p; action=:bogus)

    PNML.register_id!(reg, "p")
    @test @inferred PNML.isregistered(reg, "p")
    @test @inferred PNML.isregistered(reg, :p)
    PNML.reset_registry!(reg)
    @test !PNML.isregistered(reg, "p")
    @test !PNML.isregistered(reg, :p)

    @test_logs (:warn,"ID 'p' already registered") PNML.duplicate_id_action(:p)
    @test_logs (:warn,"ID 'p' already registered") PNML.duplicate_id_action(:p; action=:warn)
    @test_throws ErrorException PNML.duplicate_id_action(:p; action=:error)
    @test @inferred( PNML.duplicate_id_action(:p; action=:bogus) ) === nothing
end

header("GETFIRST")
@testset "getfirst iteratible" begin
    v = [string(i) for i in 1:9]
    @test_call PNML.getfirst(==("3"), v)
    @test "3" == @inferred Maybe{String} PNML.getfirst(==("3"), v)
    @test nothing === @inferred Maybe{String} PNML.getfirst(==("33"), v)
end

@testset "getfirst XMLNode" begin
    node = xml"""<test>

        <c name="c1"/>
        <c name="c2"/>
    </test>
    """
    @test_call nodename(PNML.getfirst("a", node))
    @test nodename(PNML.getfirst("a", node)) == "a"
    @test PNML.getfirst("b", node) === nothing
    @test nodename(PNML.getfirst("c", node)) == "c"
end


text:
using PolyChaos, FastGaussQuadrature, Test, LinearAlgebra

mytol = 1e-10
N = 5:10:100

names = ["hermite", "legendre", "laguerre"]
funs = [gausshermite, gausslegendre, gausslaguerre]

@testset "Compare $(names...) against FastGaussQuadrature" begin
    for i=1:length(names), n in N
        opq = OrthoPolyQ(names[i],n-1)
        mynw = nw(opq)
        n, w = funs[i](n)
        @test isapprox(norm(n-mynw[:,1],Inf),0;atol=mytol)
        @test isapprox(norm(w-mynw[:,2],Inf),0;atol=mytol)
    end
end

a = -0.5:0.1:2.0
b = copy(a)

@testset "Compare Jacobi against FastGaussQuadrature" begin
    for aa in a, bb in b, n in N
        opq = OrthoPolyQ("jacobi",n-1,Dict(:shape_a=>aa,:shape_b=>bb))
        mynw = nw(opq)
        n, w = gaussjacobi(n,aa,bb)
        @test isapprox(norm(n-mynw[:,1],Inf),0;atol=mytol)
        @test isapprox(norm(w-mynw[:,2],Inf),0;atol=mytol)
    end
end


text:
#=
Problem description

When you were a little kid, was indiscriminately flicking light switches super fun?
I know it was for me. Let's tap into that and try to recall that feeling with today's
challenge.
Imagine a row of N light switches, each attached to a light bulb. All the bulbs
are off to start with. You are going to release your inner child so they can run
back and forth along this row of light switches, flipping bunches of switches from
on to off or vice versa. The challenge will be to figure out the state of the lights
after this fun happens.

Input description

The input will have two parts. First, the number of switches/bulbs (N) is specified.
On the remaining lines, there will be pairs of integers indicating ranges of switches
that your inner child toggles as they run back and forth. These ranges are inclusive
(both their end points, along with everything between them is included), and the
positions of switches are zero-indexed (so the possible positions range from 0 to N-1).

Example input:
10
3 6
0 4
7 3
9 9

There is a more thorough explanation of what happens below.

Output description

The output is a single number: the number of switches that are on after all the running around.
Example output:
7

Explanation of example

Below is a step by step rendition of which switches each range toggled in order to get the output described above.

    0123456789
    ..........
3-6    ||||
    ...XXXX...
0-4 |||||
    XXX..XX...
7-3    |||||
    XXXXX..X..
9-9          |
    XXXXX..X.X
As you can see, 7 of the 10 bulbs are on at the end.

Challenge input

1000
616 293
344 942
27 524
716 291
860 284
74 928
970 594
832 772
343 301
194 882
948 912
533 654
242 792
408 34
162 249
852 693
526 365
869 303
7 992
200 487
961 885
678 828
441 152
394 453

Bonus points

Make a solution that works for extremely large numbers of switches with very numerous
ranges to flip. In other words, make a solution that solves this input quickly
(in less than a couple seconds): lots_of_switches.txt (3 MB). So you don't have
to download it, here's what the input is: 5,000,000 switches, with 200,000 randomly
generated ranges to switch.

Lastly...

Have a cool problem that you would like to challenge others to solve? Come by
/r/dailyprogrammer_ideas and let everyone know about it!

( source: https://redd.it/46zm8m )
=#

function main( )
    x::Integer = y::Integer = sum::Integer = 0
    n::Integer = parse( Int, chomp( readline( STDIN ) ) )
    arr::Array = zeros( n )

    @time while !eof( STDIN )
        ( tmp_x, tmp_y ) = sort( split( chomp( readline( STDIN ) ) ) )
        x = parse( Int , tmp_x ) + 1
        y = parse( Int , tmp_y ) + 1

        for i in x:y
            arr[ i ] = ( 0 == arr[ i ] ) ? 1 : 0
        end
    end

    for i in 1:n
        sum += arr[ i ]
    end

    println( sum )
end

main( )

max_stars_repo_name: farmfirst/dailyprogrammer

max_issues_repo_name: farmfirst/dailyprogrammer

max_forks_repo_name: farmfirst/dailyprogrammer


text:
# # Calculus on the reference triangle
# In this example, we sample a bivariate function:
# ```math
# f(x,y) = \frac{1}{1+x^2+y^2},
# ```
# on the reference triangle with vertices $(0,0)$, $(0,1)$, and $(1,0)$ and analyze it
# in a Proriol series. Then, we find Proriol series for each component of its
# gradient by term-by-term differentiation of our expansion, and we compare them
# with the true Proriol series by sampling an exact expression for the gradient.
#
# We analyze $f(x,y)$ on an $N\times M$ mapped tensor product grid defined by:
# ```math
# \begin{aligned}
# x & = (1+u)/2,\quad{\rm and}\quad y = (1-u)(1+v)/4,\quad {\rm where:}\\
# u_n & = \cos\left[(n+\tfrac{1}{2})\pi/N\right],\quad{\rm for}\quad 0\le n < N,\quad{\rm and}\\
# v_m & = \cos\left[(m+\tfrac{1}{2})\pi/M\right],\quad{\rm for}\quad 0\le m < M;
# \end{aligned}
# ```
# we convert the function samples to mapped Chebyshev² coefficients using
# `plan_tri_analysis`; and finally, we transform the mapped Chebyshev²
# coefficients to Proriol coefficients using `plan_tri2cheb`.
#
# For the storage pattern of the arrays, please consult the
# [documentation](https://MikaelSlevinsky.github.io/FastTransforms).

using FastTransforms, LinearAlgebra, Plots
const GENFIGS = joinpath(pkgdir(FastTransforms), "docs/src/generated")
!isdir(GENFIGS) && mkdir(GENFIGS)
plotlyjs()

# Our function $f$ and the Cartesian components of its gradient:
f = (x,y) -> 1/(1+x^2+y^2)
fx = (x,y) -> -2x/(1+x^2+y^2)^2
fy = (x,y) -> -2y/(1+x^2+y^2)^2

# The polynomial degree:
N = 15
M = N

# The parameters of the Proriol series:
α, β, γ = 0, 0, 0

# The $u$ grid:
u = [sinpi((N-2n-1)/(2N)) for n in 0:N-1]

# And the $v$ grid:
v = [sinpi((M-2m-1)/(2M)) for m in 0:M-1]

# Instead of using the $u\times v$ grid, we use one with more accuracy near the origin.
# Defining $x$ by:
x = [sinpi((2N-2n-1)/(4N))^2 for n in 0:N-1]

# And $w$ by:
w = [sinpi((2M-2m-1)/(4M))^2 for m in 0:M-1]

# We see how the two grids are related:
((1 .+ u)./2 ≈ x) * ((1 .- u).*(1 .+ v')/4 ≈ reverse(x).*w')

# On the mapped tensor product grid, our function samples are:
F = [f(x[n+1], x[N-n]*w[m+1]) for n in 0:N-1, m in 0:M-1]

# We superpose a surface plot of $f$ on top of the grid:
X = [x for x in x, w in w]
Y = [x[N-n]*w[m+1] for n in 0:N-1, m in 0:M-1]
scatter3d(vec(X), vec(Y), vec(0F); markersize=0.75, markercolor=:blue)
surface!(X, Y, F; legend=false, xlabel="x", ylabel="y", zlabel="f")
savefig(joinpath(GENFIGS, "proriol.html"))
###```@raw html
###<object type="text/html" data="../proriol.html" style="width:100%;height:400px;"></object>
###```

# We precompute a Proriol--Chebyshev² plan:
P = plan_tri2cheb(F, α, β, γ)

# And an FFTW Chebyshev² plan on the triangle:
PA = plan_tri_analysis(F)

# Its Proriol-$(α,β,γ)$ coefficients are:
U = P\(PA*F)

# Similarly, our function's gradient samples are:
Fx = [fx(x[n+1], x[N-n]*w[m+1]) for n in 0:N-1, m in 0:M-1]

# and:
Fy = [fy(x[n+1], x[N-n]*w[m+1]) for n in 0:N-1, m in 0:M-1]

# For the partial derivative with respect to $x$, [Olver et al.](https://doi.org/10.1137/19M1245888)
# derive simple expressions for the representation of this component
# using a Proriol-$(α+1,β,γ+1)$ series.
Gx = zeros(Float64, N, M)
for m = 0:M-2
    for n = 0:N-2
        cf1 = m == 0 ? sqrt((n+1)*(n+2m+α+β+γ+3)/(2m+β+γ+2)*(m+γ+1)*8) : sqrt((n+1)*(n+2m+α+β+γ+3)/(2m+β+γ+1)*(m+β+γ+1)/(2m+β+γ+2)*(m+γ+1)*8)
        cf2 = sqrt((n+α+1)*(m+1)/(2m+β+γ+2)*(m+β+1)/(2m+β+γ+3)*(n+2m+β+γ+3)*8)
        Gx[n+1, m+1] = cf1*U[n+2, m+1] + cf2*U[n+1, m+2]
    end
end
Px = plan_tri2cheb(Fx, α+1, β, γ+1)
Ux = Px\(PA*Fx)

# For the partial derivative with respect to y, the analogous formulae result
# in a Proriol-$(α,β+1,γ+1)$ series.
Gy = zeros(Float64, N, M)
for m = 0:M-2
    for n = 0:N-2
        Gy[n+1, m+1] = 4*sqrt((m+1)*(m+β+γ+2))*U[n+1, m+2]
    end
end
Py = plan_tri2cheb(Fy, α, β+1, γ+1)
Uy = Py\(PA*Fy)

# The $2$-norm relative error in differentiating the Proriol series
# for $f(x,y)$ term-by-term and its sampled gradient is:
hypot(norm(Ux-Gx), norm(Uy-Gy))/hypot(norm(Ux), norm(Uy))

# This error can be improved upon by increasing $N$ and $M$.


text:
# This is a sample setup for a test case with an explicit QDE/DAE
# function.  Fill in the ...

# First , document the test case here!

export mytest

# create an instance of TestCaseExplicit by filling in the ...:
mytest = let
    tcname = ...::Symbol # name should be same as variable name (except for upper/lower case)

    T = ... # the datatype used, probably Float64
    Tarr = [Matrix, SparseMatrixCSC][1] # the container datatype used
                                        # for the Jacobian and mass
                                        # matrix, probably Matrix
                                        # (default) or
                                        # SparseMatrixCSC.
    dof = ...::Int # degrees of freedom
    dae = ...::Int  # index of DAE, ==0 for ODE
    # stiffness of system, one of the three constants
    stiffness = [nonstiff, mildlystiff, stiff][...]

    ## the problem function
    function fn!(t::T,y::Vector{T},dydt::Vector{T})
        # The ode function dydt = f(t,y) modifying dydt in-place.
        # Note that all indices of dydt need to be written!
        ...
        return nothing
    end
    # initializes storage for y:
    fn!( ; T_::Type=T, dof_=dof) = zeros(T_,dof_)

    # NOTE, using keyword arguments more intuitively like:
    # fn!( ; T::Type=T, dof=dof) = zeros(T,dof)
    # does not work: https://github.com/JuliaLang/julia/issues/9948

    ## Jacobian of fn
    function jac!(t::T,y::Vector{T},dfdy::Tarr)
        # the Jacobian of fn, inplace
        #
        # Set jac=nothing if it is not known.
        #
        # Note that jac! should write all indices of given in
        # jpattern.
        ...
        return nothing
    end
    # Returns a matrix which can hold the Jacobian of selected
    # type, initialized to zero.  Can also be used to make a
    # Matlab-style JPattern matrix with jac!(Bool)
    jac!( ; T_::Type=T, dof_=dof) = zeros(T_,dof_,dof_)  # if the problem is large better return an appropriate sparse matrix

    ## Mass matrix
    function mass!(t::T,y::Vector{T},m::Tarr)
        # mass matrix:  M(t,y) * dydt = f(t,y)
        #
        # Set to nothing if it is I, i.e. mass=nothing
        ...
        return nothing
    end
    # Returns a matrix which can hold the mass matrix.
    # Can also be used to make a Matlab-style MvPattern matrix with mass!(Bool)
    mass!( ; T_::Type=T, dof_=dof) = zeros(T_,dof_,dof_)  # if the problem is large better return an appropriate sparse matrix

    ic = T[...] # vector of initial conditions
    tspan = T[start, stop] # integration interval
    refsol = T[...] # reference solution at tspan[2]

    refsolinds = trues(dof)   # if refsol does not contain all indices
                              # then specify which indices of the
                              # solution are to be compared to refsol

    scd_absinds = Int[]       # set where refsol is very small or
                              # zero. To avoid it dominating the
                              # relative error

    tc = TestCaseExplicit{tcname, T, Tarr}(
                             stiffness,
                             dae,
                             dof,
                             fn!,
                             jac!,
                             mass!,
                             ic,
                             tspan,
                             refsol,
                             refsolinds,
                             scd_absinds)

    # put into the right buckets
    tc_all[tcname] = tc
    tc_stiff[tcname] = tc
    # Note that the return-result of the last statement of the let
    # block needs to be tc!
    tc
end


text:
"""

    UniformMesh(start, stop, length)

    1D uniform mesh data.

    length   : number of points
    length-1 : number of cells

    To remove the last point, set endpoint=false

"""
struct UniformMesh

   start    :: Float64
   stop     :: Float64
   length   :: Int
   step     :: Float64
   points   :: Vector{Float64}
   endpoint :: Bool

   function UniformMesh(start, stop, length::Int; endpoint=true)

       if (endpoint)
           points = range(start, stop=stop, length=length)
       else
           points = range(start, stop=stop, length=length+1)[1:end-1]
       end
       step = points[2]-points[1]

       new( start, stop, length, step, points, endpoint)

   end

end


text:
using Roots
using Compat.Test
import SpecialFunctions.erf

include("./test_find_zero.jl")
include("./test_fzero.jl")
include("./test_find_zeros.jl")
include("./test_newton.jl")
include("./test_simple.jl")
include("./RootTesting.jl")

#include("./test_composable.jl")

#run_benchmark_tests()

#include("./test_fzero3.jl")
#run_robustness_test()

#include("./test_derivative_free.jl")


text:
@testset "Trajectory" begin

function get_states_to_indices(game)
    state_index = StdMap{StdString, Cint}()
    to_visit = []
    push!(to_visit, new_initial_state(game))
    i = 0
    while length(to_visit) != 0
        state = pop!(to_visit)
        if (!is_chance_node(state)) && (!is_terminal(state))
            state_index[information_state_string(state)] = Cint(i)
        end
        i += 1
        for action in legal_actions(state)
            push!(to_visit, child(state, action))
        end
    end
    state_index
end

@testset "BatchedTrajectory" begin
    for game_name in ["kuhn_poker", "leduc_poker", "liars_dice"]
        game = load_game(game_name)
        batch_size = 32
        states_to_inds = get_states_to_indices(game)
        policies = StdVector([get_uniform_policy(game) for _ in 1:2])
        t = record_batched_trajectories(game, policies, states_to_inds, batch_size, false, 123, -1)
        @test length(legal_actions(t)) == batch_size
        @test length(actions(t)) == batch_size
        @test length(player_policies(t)) == batch_size
        @test length(player_ids(t)) == batch_size
        @test length(next_is_terminal(t)) == batch_size
    end
end

end


text:
# # Fractional Poynting-Thomson
#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__/notebooks/model_pt.ipynb)
#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/notebooks/model_pt.ipynb)

using RHEOS
## include a helper function for plotting
include("assets/plothelper.jl");
#-

Fract_PT
#-

# #### Constitutive Equation
# ```math
# \sigma(t) + \frac{c_\alpha}{c_\gamma} \frac{d^{\alpha-\gamma} \sigma(t)}{dt^{\alpha-\gamma}}+ \frac{c_\beta}{c_\gamma} \frac{d^{\beta-\gamma} \sigma(t)}{dt^{\beta-\gamma}}= c_{\alpha} \frac{d^\alpha \epsilon(t)}{dt^\alpha} + c_\beta \frac{d^\beta \epsilon(t)}{dt^\beta}
# ```

# ```math
# \text{for}\; \ 0 \leq \beta \leq \alpha \leq 1
# ```

# #### Relaxation Modulus
# ```math
# \tilde{G}(s) = \frac{1}{s}\frac{c_\gamma s^\gamma \cdot \left[c_\alpha s^\alpha + c_\beta s^{\beta}\right]}{c_\gamma s^\gamma+c_\alpha s^{\alpha}+c_\beta s^{\beta}}
# ```

# #### Creep Modulus
# ```math
# J(t)= \frac{t^{\alpha}}{c_\alpha} E_{\alpha-\beta,1+\alpha}\left(-\frac{c_\beta}{c_\alpha} t^{\alpha-\beta}\right) + \frac{1}{c_\gamma \Gamma(1+\gamma)}t^\gamma
# ```

# #### Storage Modulus
# ```math
# G^{\prime}(\omega) = \frac{c_\gamma \omega^\gamma \cos\left(\gamma \frac{\pi}{2}\right) \left[\left(c_\alpha \omega^\alpha\right)^2+\left(c_\beta \omega^\beta\right)^2 \right]+\left(c_\gamma \omega^\gamma\right)^2 \left[c_\alpha \omega^\alpha \cos\left(\alpha \frac{\pi}{2}\right)+c_\beta \omega^\beta \cos\left(\beta \frac{\pi}{2}\right) \right] + c_\alpha \omega^\alpha \cdot c_\beta\omega^\beta \cdot c_\gamma \omega^\gamma \left[\cos\left((\alpha-\beta-\gamma) \frac{\pi}{2}\right)+\cos\left((\beta-\alpha-\gamma) \frac{\pi}{2}\right) \right]}{\left(c_\alpha \omega^\alpha\right)^2+\left(c_\beta \omega^\beta\right)^2+\left(c_\gamma \omega^\gamma\right)^2+2c_\alpha \omega^\alpha \cdot c_\beta \omega^\beta \cos((\alpha-\beta)\frac{\pi}{2})+2c_\alpha \omega^\alpha \cdot c_\gamma \omega^\gamma \cos((\alpha-\gamma)\frac{\pi}{2})+2c_\beta \omega^\beta \cdot c_\gamma \omega^\gamma \cos((\beta-\gamma)\frac{\pi}{2})}
# ```

# #### Loss Modulus
# ```math
# G^{\prime\prime}(\omega) = \frac{c_\gamma \omega^\gamma \sin\left(\gamma \frac{\pi}{2}\right) \left[\left(c_\alpha \omega^\alpha\right)^2+\left(c_\beta \omega^\beta\right)^2 \right]+\left(c_\gamma \omega^\gamma\right)^2 \left[c_\alpha \omega^\alpha \sin\left(\alpha \frac{\pi}{2}\right)+c_\beta \omega^\beta \sin\left(\beta \frac{\pi}{2}\right) \right] + c_\alpha \omega^\alpha \cdot c_\beta\omega^\beta \cdot c_\gamma \omega^\gamma \left[\sin\left((\alpha-\beta-\gamma) \frac{\pi}{2}\right)+\sin\left((\beta-\alpha-\gamma) \frac{\pi}{2}\right) \right]}{\left(c_\alpha \omega^\alpha\right)^2+\left(c_\beta \omega^\beta\right)^2+\left(c_\gamma \omega^\gamma\right)^2+2c_\alpha \omega^\alpha \cdot c_\beta \omega^\beta \cos((\alpha-\beta)\frac{\pi}{2})+2c_\alpha \omega^\alpha \cdot c_\gamma \omega^\gamma \cos((\alpha-\gamma)\frac{\pi}{2})+2c_\beta \omega^\beta \cdot c_\gamma \omega^\gamma \cos((\beta-\gamma)\frac{\pi}{2})}
# ```

# # Fractional SLS (PT)

FractSLS_PT
#-

models = Vector{RheoModel}()

## plot moduli for varying α
for alpha in [0.1, 0.25, 0.5, 0.74, 0.9]

    push!(models, RheoModel(FractSLS_PT, (cₐ = 1, a = alpha, kᵦ = 1, kᵧ = 1)))

end

plotmodel(models)

# # Fractional Jeffreys (PT)

FractJeffreys_PT
#-

models = Vector{RheoModel}()

## plot moduli for varying β
for beta in [0.1, 0.25, 0.5, 0.74, 0.9]

    push!(models, RheoModel(FractJeffreys_PT, (ηₐ = 1, cᵦ = 1, β = beta, ηᵧ = 1)))

end

plotmodel(models, ymaxG = 0.5)

# # Standard Linear Solid (PT)

SLS_PT
#-

models = Vector{RheoModel}()

## plot moduli for varying kᵦ
for k in [1.0, 3.0, 5.0]

    push!(models, RheoModel(SLS_PT, (η = 1, kᵦ = k, kᵧ = 1)))

end

plotmodel(models)

# # Jeffreys (Zener)

Jeffreys_PT
#-

models = Vector{RheoModel}()

## plot moduli for varying ηₐ
for eta in [1.0, 5.0, 8.0]

    push!(models, RheoModel(Jeffreys_PT, (ηₐ = eta, k = 3, ηᵧ = 1)))

end

plotmodel(models)


text:
using ImageQuilting
using GeoStatsImages
using PkgBenchmark

srand(2017)

@benchgroup "2D simulation" begin
  Herten = training_image("Herten")
  Strebelle = training_image("Strebelle")
  @bench "Herten" iqsim(Herten, 20, 20, 1, 100, 100, 1, nreal=3)
  @bench "Strebelle" iqsim(Strebelle, 20, 20, 1, 200, 200, 1, nreal=3)
end

@benchgroup "3D simulation" begin
  TI = training_image("Flumy")[:,1:200,:]
  nx, ny, nz = size(TI)

  shape = HardData()
  for idx in find(isnan.(TI))
      i,j,k = ind2sub(size(TI), idx)
      push!(shape, (i,j,k)=>NaN)
  end

  AUX = [i for i in 1:nx, j in 1:ny, k in 1:nz]

  @bench "Flumy" iqsim(TI, 50, 50, 20, size(TI)..., hard=shape, soft=[(AUX,AUX)], tol=.01)
end


text:
using ApproxFun

#The following samples a 2D Cauchy Distribution
f = LowRankFun((x,y)->1/(2π*(x^2+y^2+1)^(3/2)),JacobiWeight(2.,2.,Line())^2)
@time x = ApproxFun.sample(f,100)

max_stars_repo_path: Sampling/2D Cauchy Distribution.jl

max_issues_repo_path: Sampling/2D Cauchy Distribution.jl

max_forks_repo_path: Sampling/2D Cauchy Distribution.jl


text:
using CmdStan

ProjDir = dirname(@__FILE__);
cd(ProjDir) do

  isdir("tmp") && rm("tmp", recursive=true);

  ar1 = "
  data {
    int T;
    real y0;
    real phi;
    real sigma;
  }
  parameters{}
  model{}
  generated quantities {
    vector[T] yhat;
    yhat[1] = y0;
    for (t in 2:T)
      yhat[t] = normal_rng(phi*yhat[t-1],sigma);
  }
  "

  #
  T = 100;
  y0 = 1;
  phi = 0.95;
  sigma = 1;

  # make the data dictionary
  dat = Dict("T"=>T,"y0"=>y0,"phi"=>phi,"sigma"=>sigma);

  stanmodel= Stanmodel(name = "ar1", model = ar1,  Sample(algorithm=CmdStan.Fixed_param()));
  rc, sim1 = stan(stanmodel, [dat], ProjDir, CmdStanDir=CMDSTAN_HOME);

  isdir("tmp") && rm("tmp", recursive=true);

end


text:
using Fermionic
using SparseArrays
using Test

@testset "Fermionic.jl" begin
    @test dim(Op(8)) == 8
    @test basis(Op(4))[24] == 1.0
    @test basis(Op(6))[1] == 0.0
    @test aad(Op(4),1,2)[5,9] == -1.0
    @test ada(Op(4),3,2)[3,5] == 1
    @test aa(Op(4),4,2)[9,14] == 1.0
    @test adad(Op(4),2,3)[15,9] == 1.0
    @test vacuum(Op(4))[1] == 1.0
    @test basis_m(8,2)[2][4] == 10.0
    @test ada(6,2,3,3)[6,6] == 1.0
    @test ada(6,2,3,2)[14,15] == 1.0
    @test ada(basis_m(4,2)[1],basis_m(4,2)[2],1,2)[4,2] == 1
    @test aad(basis_m(4,2)[1],basis_m(4,2)[2],1,2)[2,4] == -1
    @test aad(6,2,1,2)[8,12] == -1.0
    @test ada(basis_m(4,2)[1],basis_m(4,2)[2],3,3)[5,5] == 1
    @test fixed(ad(Op(6),1)*a(Op(6),1),2)[11,11] == 1.0
    @test fixed_state([0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0],2)[6] == 1
    @test unfixed_state([0,0,0,0,1/sqrt(2),1/sqrt(2)],4,2)[13] == 1/sqrt(2)
    @test st(unfixed_state(State_fixed([0,0,0,0,0,1],Op_fixed(4,2))))[13] == 1
    @test ada(Op_fixed(4,2),1,2)[4,2] == 1
    @test aad(Op_fixed(4,2),1,2)[2,4] == 1
    @test dim(Op_fixed(8,2)) == 8
    @test nume(Op_fixed(8,2)) == 2
    @test basis(Op_fixed(4,2))[4,1] == 1
    @test ad(6,3,2)[13,14] == -1
    @test ad(6,3,7)[29,19] == -1
    @test a(6,3,2)[12,18] == -1
    @test a(4,3,5)[1] == 0
    @test ad(6,2,[1,2])[10,1] == -1
    @test a(6,3,[1,2])[2,18] == 1
    @test af(4,2)[1] == a(4,2,1)
    @test adf(4,2)[2] == ad(4,2,2)
    #@test Op_semifixed(6).d == 6
    #@test ad(Op_semifixed(6),4,2)[3,6] == -1
    #@test a(Op_semifixed(6),4,2)[13,12] == -1
    #@test a(Op_semifixed(6),4,7)[1] == 0
    #@test ad(Op_semifixed(6),2,[1,2])[10,1] == -1
    #@test a(Op_semifixed(6),4,[1,2])[3,12] == 1
end


text:
###########################################################
### Proximal Gradient
###########################################################
@with_kw struct WholespaceProximalGradient <: WholespaceUpdate
    backtracking::Bool = true
    γ_init = 1e5
end
@with_kw mutable struct WholespaceProximalGradientState <: AbstractUpdateState
    γ::Float64
end

Base.summary(::WholespaceProximalGradient) = "ProxGrad"

initial_state(o::WholespaceProximalGradient, x, reg; manifold=nothing) = WholespaceProximalGradientState(γ = o.γ_init)

str_updatelog(o::WholespaceProximalGradient, t::WholespaceProximalGradientState) = @sprintf "γ: %.3e" t.γ

function update_iterate!(state::PartlySmoothOptimizerState, pb, m::WholespaceProximalGradient)
    γ = state.update_to_updatestate[m].γ

    @assert state.x.repr == ambiant_repr

    if m.backtracking
        ncalls_f, γ = backtrack_f_lipschitzgradient!(state, pb, γ)
    end

    state.temppoint_amb .= state.x.amb_repr .- γ .* state.∇f_x

    state.x.man_repr, M = prox_αg(pb, state.temppoint_amb, γ); state.ncalls_proxg += 1
    state.x.repr = manifold_repr
    state.x.M = M

    state.M = M
    state.update_to_updatestate[m].γ = γ

    return
end

function display_logs()
    # γ          %.3e  state.γ
end

function backtrack_f_lipschitzgradient!(state::PartlySmoothOptimizerState, pb, γ)
    τ = 1.2

    ∇f_norm2 = norm(state.∇f_x)^2

    itmax = 200
    ncalls_f = 0

    it_ls = 0
    while it_ls <= itmax
        state.temppoint_amb .= state.x.amb_repr .- γ .* state.∇f_x

        # f(pb, state.temp) ≤ state.f_x - 1/(2*γ) * norm(state.temp-state.x)^2 && break
        state.ncalls_f += 1
        f(pb, state.temppoint_amb) ≤ state.f_x - γ / 2 * ∇f_norm2 && break

        ncalls_f += 1
        γ = γ / τ
        it_ls += 1
    end

    if it_ls > itmax
        @warn "Gradient backtracking: reached iterations limits."
    end

    return ncalls_f, γ
end


text:
"""
ispangram(input)

Program to determine the sentence is pangram or not.The program will return true if it is pangram and false if it is not.A full description of the algorithm can be found on [exercism](https://exercism.org/tracks/julia/exercises/pangram)

# Arguments:
- `input`: The sentence to find if its pangram or not.

# Examples/Tests
```julia
julia> ispangram(Pack my box with five dozen liquor jugs)
true

julia> ispangram(The quick brown fox jumps over the lazy dog)
true

julia> wordcount(hello world!!!)
false

```

# Algorithm:

```julia

for letter in input
    if 'A' <= letter <= 'Z'
        x &= ~(1<<(letter-'A'))
    elseif 'a' <= letter <= 'z'
        x &= ~(1<<(letter-'a'))
    end
    x == 0 && return true
end

```

# References:
(https://exercism.org/tracks/julia/exercises/pangram)

```

# Contributed by:- [Ihjass Thasbekha](https://github.com/Ihjass)
"""
function ispangram(input)
    x = 2^26 - 1
    for letter in input
        if 'A' <= letter <= 'Z'
            x &= ~(1 << (letter - 'A'))
        elseif 'a' <= letter <= 'z'
            x &= ~(1 << (letter - 'a'))
        end
        x == 0 && return true
    end
    return false
end

max_issues_repo_name: AugustoCL/Julia

max_forks_repo_name: AugustoCL/Julia


text:
function plan_R0_step(u::Fun,V,ε,Δt)
    itransplan = plan_itransform(space(u),coefficients(u))
    Vmultiplier = exp.(-1im*(Δt/ε)*V.(points(u)))
    transplan = plan_transform(space(u),values(u))
    return transplan, itransplan, Vmultiplier
end

function R0_step(u::Fun, transplan, itransplan, Vmultiplier)
    vals = itransplan*coefficients(u)
    newcoeffs = transplan*(Vmultiplier.*vals)
    return Fun(space(u),newcoeffs)
end

function plan_R1_step(u::Fun,ε,Δt,order = 0)
    n = length(coefficients(u))
    D2 = Derivative(space(u),2)[1:n,1:n]
    if order == 2
        R1D2top = 2I + 1im*ε*Δt*D2
        R1D2bottom = 2I - 1im*ε*Δt*D2
    elseif order == 4
        R1D2top = 12I + 6im*ε*Δt*D2 - (ε*Δt*D2)^2
        R1D2bottom = 12I - 6im*ε*Δt*D2 - (ε*Δt*D2)^2
    elseif order == 6
        R1D2top = 120I + 60im*ε*Δt*D2 - 12*(ε*Δt*D2)^2 - 1im*(ε*Δt*D2)^3
        R1D2bottom = 120I - 60im*ε*Δt*D2 - 12*(ε*Δt*D2)^2 + 1im*(ε*Δt*D2)^3
    elseif order == 0
        if bandwidths(D2) == (0,0) # for example, Fourier
            R1D2top = complex(D2)
            R1D2top.data = exp.(1im*ε*Δt*R1D2top.data)
        else
            R1D2top = exp(Matrix(1im*ε*Δt*D2))
        end
        R1D2bottom = I
    end
    return (R1D2bottom, R1D2top)
end

function R1_step(u::Fun,R1D2)
    newcoeffs = R1D2[1] \ (R1D2[2] * coefficients(u))
    return Fun(space(u),newcoeffs)
end

function plan_R2_step(u0::Fun,V1,V2,ε,Δt)
    n = length(coefficients(u0))
    R2D2 = (Δt^3 * ε / 6 ) * Derivative(space(u0),2)[1:n,1:n]
    # it is assumed that the transforms were produced in plan_R1_step
    #itransplan = plan_itransform(space(u0),coefficients(u0))
    #transplan = plan_transform(space(u0),values(u0))
    R2V1 = (Δt^3 / 12ε) * V1.(points(u0)).^2
    R2V2 = V2.(points(u0))
    return R2D2, R2V1, R2V2
end

function R2_step(u::Fun, transplan, itransplan, R2D2, R2V1, R2V2, Krylov_dim=10)
    q1 = complex(coefficients(u))
    T = eltype(q1)
    normq1 = norm(q1)
    n = length(q1)
    m = Krylov_dim
    Q = zeros(T,n,m)
    Q[:,1] = q1/normq1
    H = zeros(T,m,m)

    for k=1:m
        z = one(T)im * R2D2 * (transplan * (R2V2 .* (itransplan * Q[:,k])))
        z = z + one(T)im * transplan * (R2V2 .* (itransplan * (R2D2 * Q[:,k])))
        z = z + one(T)im * transplan * (R2V1 .* (itransplan * Q[:,k]))

        for i=1:k
            H[i,k] = Q[:,i]'*z
            z = z - H[i,k]*Q[:,i]
        end
        if k < m
            H[k+1,k] = norm(z)
            Q[:,k+1] = z / H[k+1,k]
        end
    end
    newcoeffs = normq1*(Q*exp(H))[:,1]
    return Fun(space(u), newcoeffs)
end

function plan_Lie_Trotter_step(u::Fun,V,ε,Δt,order=0)
    transplan, itransplan, Vmultiplier = plan_R0_step(u,V,ε,Δt)
    R1D2 = plan_R1_step(u,ε,Δt,order)
    return transplan, itransplan, Vmultiplier, R1D2
end

function Lie_Trotter_step(u::Fun, transplan, itransplan, Vmultiplier, R1D2)
    newu = R0_step(u,transplan, itransplan, Vmultiplier)
    newu = R1_step(newu, R1D2)
    return newu
end

function Lie_Trotter_evolve(u0::Fun,V,ε,Δt,T,order=0)
    M = Integer(floor(T/Δt))
    u0 = Fun(space(u0),complex(coefficients(u0)))
    retFuns = Vector{typeof(u0)}(undef,M+1)
    retFuns[1] = u0
    transplan, itransplan, Vmultiplier, R1D2 = plan_Lie_Trotter_step(retFuns[1],V,ε,Δt,order)
    for k = 1:M
        retFuns[k+1] = Lie_Trotter_step(retFuns[k], transplan, itransplan, Vmultiplier, R1D2)
    end
    return 0:Δt:T, retFuns
end

function plan_Strang_step(u::Fun,V,ε,Δt,order=0)
    transplan, itransplan, Vmultiplier = plan_R0_step(u,V,ε,Δt/2)
    R1D2 = plan_R1_step(u,ε,Δt,order)
    return transplan, itransplan, Vmultiplier, R1D2
end

function Strang_step(u::Fun, transplan, itransplan, Vmultiplier, R1D2)
    newu = R0_step(u, transplan, itransplan, Vmultiplier)
    newu = R1_step(newu, R1D2)
    newu = R0_step(newu, transplan, itransplan, Vmultiplier)
    return newu
end

function Strang_evolve(u0::Fun,V,ε,Δt,T,order=0)
    M = Integer(floor(T/Δt))
    u0 = Fun(space(u0),complex(coefficients(u0)))
    retFuns = Vector{typeof(u0)}(undef,M+1)
    retFuns[1] = u0
    transplan, itransplan, Vmultiplier, R1D2 = plan_Strang_step(retFuns[1],V,ε,Δt,order)
    for k = 1:M
        retFuns[k+1] = Strang_step(retFuns[k], transplan, itransplan, Vmultiplier, R1D2)
    end
    return 0:Δt:T, retFuns
end

function plan_Zassenhaus2_step(u::Fun,V,V1,V2,ε,Δt,order=0)
    transplan, itransplan, Vmultiplier = plan_R0_step(u,V,ε,Δt/2)
    R1D2 = plan_R1_step(u,ε,Δt/2,order)
    R2D2, R2V1, R2V2 = plan_R2_step(u,V1,V2,ε,Δt)
    return transplan, itransplan, Vmultiplier, R1D2, R2D2, R2V1, R2V2
end

function Zassenhaus2_step(u::Fun, transplan, itransplan, Vmultiplier, R1D2, R2D2, R2V1, R2V2, Krylov_dim = 10)
    newu = R0_step(u, transplan, itransplan, Vmultiplier)
    newu = R1_step(newu,R1D2)
    newu = R2_step(newu, transplan, itransplan, R2D2, R2V1, R2V2, Krylov_dim)
    newu = R1_step(newu, R1D2)
    newu = R0_step(newu, transplan, itransplan, Vmultiplier)
    return newu
end

function Zassenhaus2_evolve(u0::Fun,V,V1,V2,ε,Δt,T,order=0, Krylov_dim = 10)
    M = Integer(floor(T/Δt))
    u0 = Fun(space(u0), complex(coefficients(u0)))
    retFuns = Vector{typeof(u0)}(undef,M+1)
    retFuns[1] = u0
    transplan, itransplan, Vmultiplier, R1D2, R2D2, R2V1, R2V2 = plan_Zassenhaus2_step(retFuns[1],V,V1,V2,ε,Δt,order)
    for k = 1:M
        retFuns[k+1] = Zassenhaus2_step(retFuns[k], transplan, itransplan, Vmultiplier, R1D2, R2D2, R2V1, R2V2, Krylov_dim)
    end
    return 0:Δt:T, retFuns
end


text:
# This file is auto-generated by AWSMetadata.jl

module AWSServices

using AWS
using OrderedCollections: LittleDict

const accessanalyzer = AWS.RestJSONService(
    "access-analyzer", "access-analyzer", "2019-11-01"
)
const account = AWS.RestJSONService("account", "account", "2021-02-01")
const acm = AWS.JSONService("acm", "acm", "2015-12-08", "1.1", "CertificateManager")
const acm_pca = AWS.JSONService("acm-pca", "acm-pca", "2017-08-22", "1.1", "ACMPrivateCA")
const alexa_for_business = AWS.JSONService(
    "a4b", "a4b", "2017-11-09", "1.1", "AlexaForBusiness"
)
const amp = AWS.RestJSONService("aps", "aps", "2020-08-01")
const amplify = AWS.RestJSONService("amplify", "amplify", "2017-07-25")
const amplifybackend = AWS.RestJSONService("amplifybackend", "amplifybackend", "2020-08-11")
const api_gateway = AWS.RestJSONService("apigateway", "apigateway", "2015-07-09")
const apigatewaymanagementapi = AWS.RestJSONService(
    "execute-api", "execute-api", "2018-11-29"
)
const apigatewayv2 = AWS.RestJSONService("apigateway", "apigateway", "2018-11-29")
const app_mesh = AWS.RestJSONService("appmesh", "appmesh", "2019-01-25")
const appconfig = AWS.RestJSONService("appconfig", "appconfig", "2019-10-09")
const appflow = AWS.RestJSONService("appflow", "appflow", "2020-08-23")
const appintegrations = AWS.RestJSONService(
    "app-integrations", "app-integrations", "2020-07-29"
)
const application_auto_scaling = AWS.JSONService(
    "application-autoscaling",
    "application-autoscaling",
    "2016-02-06",
    "1.1",
    "AnyScaleFrontendService",
)
const application_discovery_service = AWS.JSONService(
    "discovery", "discovery", "2015-11-01", "1.1", "AWSPoseidonService_V2015_11_01"
)
const application_insights = AWS.JSONService(
    "applicationinsights",
    "applicationinsights",
    "2018-11-25",
    "1.1",
    "EC2WindowsBarleyService",
)
const applicationcostprofiler = AWS.RestJSONService(
    "application-cost-profiler", "application-cost-profiler", "2020-09-10"
)
const apprunner = AWS.JSONService(
    "apprunner", "apprunner", "2020-05-15", "1.0", "AppRunner"
)
const appstream = AWS.JSONService(
    "appstream", "appstream2", "2016-12-01", "1.1", "PhotonAdminProxyService"
)
const appsync = AWS.RestJSONService("appsync", "appsync", "2017-07-25")
const athena = AWS.JSONService("athena", "athena", "2017-05-18", "1.1", "AmazonAthena")
const auditmanager = AWS.RestJSONService("auditmanager", "auditmanager", "2017-07-25")
const auto_scaling = AWS.QueryService("autoscaling", "autoscaling", "2011-01-01")
const auto_scaling_plans = AWS.JSONService(
    "autoscaling-plans",
    "autoscaling-plans",
    "2018-01-06",
    "1.1",
    "AnyScaleScalingPlannerFrontendService",
)
const backup = AWS.RestJSONService("backup", "backup", "2018-11-15")
const batch = AWS.RestJSONService("batch", "batch", "2016-08-10")
const braket = AWS.RestJSONService("braket", "braket", "2019-09-01")
const budgets = AWS.JSONService(
    "budgets", "budgets", "2016-10-20", "1.1", "AWSBudgetServiceGateway"
)
const chime = AWS.RestJSONService("chime", "chime", "2018-05-01")
const chime_sdk_identity = AWS.RestJSONService("chime", "identity-chime", "2021-04-20")
const chime_sdk_messaging = AWS.RestJSONService("chime", "messaging-chime", "2021-05-15")
const cloud9 = AWS.JSONService(
    "cloud9", "cloud9", "2017-09-23", "1.1", "AWSCloud9WorkspaceManagementService"
)
const cloudcontrol = AWS.JSONService(
    "cloudcontrolapi", "cloudcontrolapi", "2021-09-30", "1.0", "CloudApiService"
)
const clouddirectory = AWS.RestJSONService("clouddirectory", "clouddirectory", "2017-01-11")
const cloudformation = AWS.QueryService("cloudformation", "cloudformation", "2010-05-15")
const cloudfront = AWS.RestXMLService("cloudfront", "cloudfront", "2020-05-31")
const cloudhsm = AWS.JSONService(
    "cloudhsm", "cloudhsm", "2014-05-30", "1.1", "CloudHsmFrontendService"
)
const cloudhsm_v2 = AWS.JSONService(
    "cloudhsm", "cloudhsmv2", "2017-04-28", "1.1", "BaldrApiService"
)
const cloudsearch = AWS.QueryService("cloudsearch", "cloudsearch", "2013-01-01")
const cloudsearch_domain = AWS.RestJSONService(
    "cloudsearch", "cloudsearchdomain", "2013-01-01"
)
const cloudtrail = AWS.JSONService(
    "cloudtrail",
    "cloudtrail",
    "2013-11-01",
    "1.1",
    "com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101",
)
const cloudwatch = AWS.QueryService("monitoring", "monitoring", "2010-08-01")
const cloudwatch_events = AWS.JSONService(
    "events", "events", "2015-10-07", "1.1", "AWSEvents"
)
const cloudwatch_logs = AWS.JSONService(
    "logs", "logs", "2014-03-28", "1.1", "Logs_20140328"
)
const codeartifact = AWS.RestJSONService("codeartifact", "codeartifact", "2018-09-22")
const codebuild = AWS.JSONService(
    "codebuild", "codebuild", "2016-10-06", "1.1", "CodeBuild_20161006"
)
const codecommit = AWS.JSONService(
    "codecommit", "codecommit", "2015-04-13", "1.1", "CodeCommit_20150413"
)
const codedeploy = AWS.JSONService(
    "codedeploy", "codedeploy", "2014-10-06", "1.1", "CodeDeploy_20141006"
)
const codeguru_reviewer = AWS.RestJSONService(
    "codeguru-reviewer", "codeguru-reviewer", "2019-09-19"
)
const codeguruprofiler = AWS.RestJSONService(
    "codeguru-profiler", "codeguru-profiler", "2019-07-18"
)
const codepipeline = AWS.JSONService(
    "codepipeline", "codepipeline", "2015-07-09", "1.1", "CodePipeline_20150709"
)
const codestar = AWS.JSONService(
    "codestar", "codestar", "2017-04-19", "1.1", "CodeStar_20170419"
)
const codestar_connections = AWS.JSONService(
    "codestar-connections",
    "codestar-connections",
    "2019-12-01",
    "1.0",
    "com.amazonaws.codestar.connections.CodeStar_connections_20191201",
)
const codestar_notifications = AWS.RestJSONService(
    "codestar-notifications", "codestar-notifications", "2019-10-15"
)
const cognito_identity = AWS.JSONService(
    "cognito-identity", "cognito-identity", "2014-06-30", "1.1", "AWSCognitoIdentityService"
)
const cognito_identity_provider = AWS.JSONService(
    "cognito-idp", "cognito-idp", "2016-04-18", "1.1", "AWSCognitoIdentityProviderService"
)
const cognito_sync = AWS.RestJSONService("cognito-sync", "cognito-sync", "2014-06-30")
const comprehend = AWS.JSONService(
    "comprehend", "comprehend", "2017-11-27", "1.1", "Comprehend_20171127"
)
const comprehendmedical = AWS.JSONService(
    "comprehendmedical",
    "comprehendmedical",
    "2018-10-30",
    "1.1",
    "ComprehendMedical_20181030",
)
const compute_optimizer = AWS.JSONService(
    "compute-optimizer", "compute-optimizer", "2019-11-01", "1.0", "ComputeOptimizerService"
)
const config_service = AWS.JSONService(
    "config", "config", "2014-11-12", "1.1", "StarlingDoveService"
)
const connect = AWS.RestJSONService("connect", "connect", "2017-08-08")
const connect_contact_lens = AWS.RestJSONService("connect", "contact-lens", "2020-08-21")
const connectparticipant = AWS.RestJSONService(
    "execute-api", "participant.connect", "2018-09-07"
)
const cost_and_usage_report_service = AWS.JSONService(
    "cur", "cur", "2017-01-06", "1.1", "AWSOrigamiServiceGatewayService"
)
const cost_explorer = AWS.JSONService(
    "ce", "ce", "2017-10-25", "1.1", "AWSInsightsIndexService"
)
const customer_profiles = AWS.RestJSONService("profile", "profile", "2020-08-15")
const data_pipeline = AWS.JSONService(
    "datapipeline", "datapipeline", "2012-10-29", "1.1", "DataPipeline"
)
const database_migration_service = AWS.JSONService(
    "dms", "dms", "2016-01-01", "1.1", "AmazonDMSv20160101"
)
const databrew = AWS.RestJSONService("databrew", "databrew", "2017-07-25")
const dataexchange = AWS.RestJSONService("dataexchange", "dataexchange", "2017-07-25")
const datasync = AWS.JSONService("datasync", "datasync", "2018-11-09", "1.1", "FmrsService")
const dax = AWS.JSONService("dax", "dax", "2017-04-19", "1.1", "AmazonDAXV3")
const detective = AWS.RestJSONService("detective", "api.detective", "2018-10-26")
const device_farm = AWS.JSONService(
    "devicefarm", "devicefarm", "2015-06-23", "1.1", "DeviceFarm_20150623"
)
const devops_guru = AWS.RestJSONService("devops-guru", "devops-guru", "2020-12-01")
const direct_connect = AWS.JSONService(
    "directconnect", "directconnect", "2012-10-25", "1.1", "OvertureService"
)
const directory_service = AWS.JSONService(
    "ds", "ds", "2015-04-16", "1.1", "DirectoryService_20150416"
)
const dlm = AWS.RestJSONService("dlm", "dlm", "2018-01-12")
const docdb = AWS.QueryService("rds", "rds", "2014-10-31")
const dynamodb = AWS.JSONService(
    "dynamodb", "dynamodb", "2012-08-10", "1.0", "DynamoDB_20120810"
)
const dynamodb_streams = AWS.JSONService(
    "dynamodb", "streams.dynamodb", "2012-08-10", "1.0", "DynamoDBStreams_20120810"
)
const ebs = AWS.RestJSONService("ebs", "ebs", "2019-11-02")
const ec2 = AWS.QueryService("ec2", "ec2", "2016-11-15")
const ec2_instance_connect = AWS.JSONService(
    "ec2-instance-connect",
    "ec2-instance-connect",
    "2018-04-02",
    "1.1",
    "AWSEC2InstanceConnectService",
)
const ecr = AWS.JSONService(
    "ecr", "api.ecr", "2015-09-21", "1.1", "AmazonEC2ContainerRegistry_V20150921"
)
const ecr_public = AWS.JSONService(
    "ecr-public", "api.ecr-public", "2020-10-30", "1.1", "SpencerFrontendService"
)
const ecs = AWS.JSONService(
    "ecs", "ecs", "2014-11-13", "1.1", "AmazonEC2ContainerServiceV20141113"
)
const efs = AWS.RestJSONService("elasticfilesystem", "elasticfilesystem", "2015-02-01")
const eks = AWS.RestJSONService("eks", "eks", "2017-11-01")
const elastic_beanstalk = AWS.QueryService(
    "elasticbeanstalk", "elasticbeanstalk", "2010-12-01"
)
const elastic_inference = AWS.RestJSONService(
    "elastic-inference", "api.elastic-inference", "2017-07-25"
)
const elastic_load_balancing = AWS.QueryService(
    "elasticloadbalancing", "elasticloadbalancing", "2012-06-01"
)
const elastic_load_balancing_v2 = AWS.QueryService(
    "elasticloadbalancing", "elasticloadbalancing", "2015-12-01"
)
const elastic_transcoder = AWS.RestJSONService(
    "elastictranscoder", "elastictranscoder", "2012-09-25"
)
const elasticache = AWS.QueryService("elasticache", "elasticache", "2015-02-02")
const elasticsearch_service = AWS.RestJSONService("es", "es", "2015-01-01")
const emr = AWS.JSONService(
    "elasticmapreduce", "elasticmapreduce", "2009-03-31", "1.1", "ElasticMapReduce"
)
const emr_containers = AWS.RestJSONService("emr-containers", "emr-containers", "2020-10-01")
const eventbridge = AWS.JSONService("events", "events", "2015-10-07", "1.1", "AWSEvents")
const finspace = AWS.RestJSONService("finspace", "finspace", "2021-03-12")
const finspace_data = AWS.RestJSONService("finspace-api", "finspace-api", "2020-07-13")
const firehose = AWS.JSONService(
    "firehose", "firehose", "2015-08-04", "1.1", "Firehose_20150804"
)
const fis = AWS.RestJSONService("fis", "fis", "2020-12-01")
const fms = AWS.JSONService("fms", "fms", "2018-01-01", "1.1", "AWSFMS_20180101")
const forecast = AWS.JSONService(
    "forecast", "forecast", "2018-06-26", "1.1", "AmazonForecast"
)
const forecastquery = AWS.JSONService(
    "forecast", "forecastquery", "2018-06-26", "1.1", "AmazonForecastRuntime"
)
const frauddetector = AWS.JSONService(
    "frauddetector", "frauddetector", "2019-11-15", "1.1", "AWSHawksNestServiceFacade"
)
const fsx = AWS.JSONService(
    "fsx", "fsx", "2018-03-01", "1.1", "AWSSimbaAPIService_v20180301"
)
const gamelift = AWS.JSONService("gamelift", "gamelift", "2015-10-01", "1.1", "GameLift")
const glacier = AWS.RestJSONService(
    "glacier", "glacier", "2012-06-01", LittleDict("x-amz-glacier-version" => "2012-06-01")
)
const global_accelerator = AWS.JSONService(
    "globalaccelerator",
    "globalaccelerator",
    "2018-08-08",
    "1.1",
    "GlobalAccelerator_V20180706",
)
const glue = AWS.JSONService("glue", "glue", "2017-03-31", "1.1", "AWSGlue")
const grafana = AWS.RestJSONService("grafana", "grafana", "2020-08-18")
const greengrass = AWS.RestJSONService("greengrass", "greengrass", "2017-06-07")
const greengrassv2 = AWS.RestJSONService("greengrass", "greengrass", "2020-11-30")
const groundstation = AWS.RestJSONService("groundstation", "groundstation", "2019-05-23")
const guardduty = AWS.RestJSONService("guardduty", "guardduty", "2017-11-28")
const health = AWS.JSONService(
    "health", "health", "2016-08-04", "1.1", "AWSHealth_20160804"
)
const healthlake = AWS.JSONService(
    "healthlake", "healthlake", "2017-07-01", "1.0", "HealthLake"
)
const honeycode = AWS.RestJSONService("honeycode", "honeycode", "2020-03-01")
const iam = AWS.QueryService("iam", "iam", "2010-05-08")
const identitystore = AWS.JSONService(
    "identitystore", "identitystore", "2020-06-15", "1.1", "AWSIdentityStore"
)
const imagebuilder = AWS.RestJSONService("imagebuilder", "imagebuilder", "2019-12-02")
const importexport = AWS.QueryService("importexport", "importexport", "2010-06-01")
const inspector = AWS.JSONService(
    "inspector", "inspector", "2016-02-16", "1.1", "InspectorService"
)
const iot = AWS.RestJSONService("execute-api", "iot", "2015-05-28")
const iot_1click_devices_service = AWS.RestJSONService(
    "iot1click", "devices.iot1click", "2018-05-14"
)
const iot_1click_projects = AWS.RestJSONService(
    "iot1click", "projects.iot1click", "2018-05-14"
)
const iot_data_plane = AWS.RestJSONService("iotdata", "data.iot", "2015-05-28")
const iot_events = AWS.RestJSONService("iotevents", "iotevents", "2018-07-27")
const iot_events_data = AWS.RestJSONService("ioteventsdata", "data.iotevents", "2018-10-23")
const iot_jobs_data_plane = AWS.RestJSONService(
    "iot-jobs-data", "data.jobs.iot", "2017-09-29"
)
const iot_wireless = AWS.RestJSONService("iotwireless", "api.iotwireless", "2020-11-22")
const iotanalytics = AWS.RestJSONService("iotanalytics", "iotanalytics", "2017-11-27")
const iotdeviceadvisor = AWS.RestJSONService(
    "iotdeviceadvisor", "api.iotdeviceadvisor", "2020-09-18"
)
const iotfleethub = AWS.RestJSONService("iotfleethub", "api.fleethub.iot", "2020-11-03")
const iotsecuretunneling = AWS.JSONService(
    "IoTSecuredTunneling", "api.tunneling.iot", "2018-10-05", "1.1", "IoTSecuredTunneling"
)
const iotsitewise = AWS.RestJSONService("iotsitewise", "iotsitewise", "2019-12-02")
const iotthingsgraph = AWS.JSONService(
    "iotthingsgraph", "iotthingsgraph", "2018-09-06", "1.1", "IotThingsGraphFrontEndService"
)
const ivs = AWS.RestJSONService("ivs", "ivs", "2020-07-14")
const kafka = AWS.RestJSONService("kafka", "kafka", "2018-11-14")
const kafkaconnect = AWS.RestJSONService("kafkaconnect", "kafkaconnect", "2021-09-14")
const kendra = AWS.JSONService(
    "kendra", "kendra", "2019-02-03", "1.1", "AWSKendraFrontendService"
)
const kinesis = AWS.JSONService(
    "kinesis", "kinesis", "2013-12-02", "1.1", "Kinesis_20131202"
)
const kinesis_analytics = AWS.JSONService(
    "kinesisanalytics", "kinesisanalytics", "2015-08-14", "1.1", "KinesisAnalytics_20150814"
)
const kinesis_analytics_v2 = AWS.JSONService(
    "kinesisanalytics", "kinesisanalytics", "2018-05-23", "1.1", "KinesisAnalytics_20180523"
)
const kinesis_video = AWS.RestJSONService("kinesisvideo", "kinesisvideo", "2017-09-30")
const kinesis_video_archived_media = AWS.RestJSONService(
    "kinesisvideo", "kinesisvideo", "2017-09-30"
)
const kinesis_video_media = AWS.RestJSONService(
    "kinesisvideo", "kinesisvideo", "2017-09-30"
)
const kinesis_video_signaling = AWS.RestJSONService(
    "kinesisvideo", "kinesisvideo", "2019-12-04"
)
const kms = AWS.JSONService("kms", "kms", "2014-11-01", "1.1", "TrentService")
const lakeformation = AWS.JSONService(
    "lakeformation", "lakeformation", "2017-03-31", "1.1", "AWSLakeFormation"
)
const lambda = AWS.RestJSONService("lambda", "lambda", "2015-03-31")
const lex_model_building_service = AWS.RestJSONService("lex", "models.lex", "2017-04-19")
const lex_models_v2 = AWS.RestJSONService("lex", "models-v2-lex", "2020-08-07")
const lex_runtime_service = AWS.RestJSONService("lex", "runtime.lex", "2016-11-28")
const lex_runtime_v2 = AWS.RestJSONService("lex", "runtime-v2-lex", "2020-08-07")
const license_manager = AWS.JSONService(
    "license-manager", "license-manager", "2018-08-01", "1.1", "AWSLicenseManager"
)
const lightsail = AWS.JSONService(
    "lightsail", "lightsail", "2016-11-28", "1.1", "Lightsail_20161128"
)
const location = AWS.RestJSONService("geo", "geo", "2020-11-19")
const lookoutequipment = AWS.JSONService(
    "lookoutequipment",
    "lookoutequipment",
    "2020-12-15",
    "1.0",
    "AWSLookoutEquipmentFrontendService",
)
const lookoutmetrics = AWS.RestJSONService("lookoutmetrics", "lookoutmetrics", "2017-07-25")
const lookoutvision = AWS.RestJSONService("lookoutvision", "lookoutvision", "2020-11-20")
const machine_learning = AWS.JSONService(
    "machinelearning", "machinelearning", "2014-12-12", "1.1", "AmazonML_20141212"
)
const macie = AWS.JSONService("macie", "macie", "2017-12-19", "1.1", "MacieService")
const macie2 = AWS.RestJSONService("macie2", "macie2", "2020-01-01")
const managedblockchain = AWS.RestJSONService(
    "managedblockchain", "managedblockchain", "2018-09-24"
)
const marketplace_catalog = AWS.RestJSONService(
    "aws-marketplace", "catalog.marketplace", "2018-09-17"
)
const marketplace_commerce_analytics = AWS.JSONService(
    "marketplacecommerceanalytics",
    "marketplacecommerceanalytics",
    "2015-07-01",
    "1.1",
    "MarketplaceCommerceAnalytics20150701",
)
const marketplace_entitlement_service = AWS.JSONService(
    "aws-marketplace",
    "entitlement.marketplace",
    "2017-01-11",
    "1.1",
    "AWSMPEntitlementService",
)
const marketplace_metering = AWS.JSONService(
    "aws-marketplace", "metering.marketplace", "2016-01-14", "1.1", "AWSMPMeteringService"
)
const mediaconnect = AWS.RestJSONService("mediaconnect", "mediaconnect", "2018-11-14")
const mediaconvert = AWS.RestJSONService("mediaconvert", "mediaconvert", "2017-08-29")
const medialive = AWS.RestJSONService("medialive", "medialive", "2017-10-14")
const mediapackage = AWS.RestJSONService("mediapackage", "mediapackage", "2017-10-12")
const mediapackage_vod = AWS.RestJSONService(
    "mediapackage-vod", "mediapackage-vod", "2018-11-07"
)
const mediastore = AWS.JSONService(
    "mediastore", "mediastore", "2017-09-01", "1.1", "MediaStore_20170901"
)
const mediastore_data = AWS.RestJSONService("mediastore", "data.mediastore", "2017-09-01")
const mediatailor = AWS.RestJSONService("mediatailor", "api.mediatailor", "2018-04-23")
const memorydb = AWS.JSONService(
    "memorydb", "memory-db", "2021-01-01", "1.1", "AmazonMemoryDB"
)
const mgn = AWS.RestJSONService("mgn", "mgn", "2020-02-26")
const migration_hub = AWS.JSONService("mgh", "mgh", "2017-05-31", "1.1", "AWSMigrationHub")
const migrationhub_config = AWS.JSONService(
    "mgh", "migrationhub-config", "2019-06-30", "1.1", "AWSMigrationHubMultiAccountService"
)
const mobile = AWS.RestJSONService("AWSMobileHubService", "mobile", "2017-07-01")
const mobile_analytics = AWS.RestJSONService(
    "mobileanalytics", "mobileanalytics", "2014-06-05"
)
const mq = AWS.RestJSONService("mq", "mq", "2017-11-27")
const mturk = AWS.JSONService(
    "mturk-requester",
    "mturk-requester",
    "2017-01-17",
    "1.1",
    "MTurkRequesterServiceV20170117",
)
const mwaa = AWS.RestJSONService("airflow", "airflow", "2020-07-01")
const neptune = AWS.QueryService("rds", "rds", "2014-10-31")
const network_firewall = AWS.JSONService(
    "network-firewall", "network-firewall", "2020-11-12", "1.0", "NetworkFirewall_20201112"
)
const networkmanager = AWS.RestJSONService("networkmanager", "networkmanager", "2019-07-05")
const nimble = AWS.RestJSONService("nimble", "nimble", "2020-08-01")
const opensearch = AWS.RestJSONService("es", "es", "2021-01-01")
const opsworks = AWS.JSONService(
    "opsworks", "opsworks", "2013-02-18", "1.1", "OpsWorks_20130218"
)
const opsworkscm = AWS.JSONService(
    "opsworks-cm", "opsworks-cm", "2016-11-01", "1.1", "OpsWorksCM_V2016_11_01"
)
const organizations = AWS.JSONService(
    "organizations", "organizations", "2016-11-28", "1.1", "AWSOrganizationsV20161128"
)
const outposts = AWS.RestJSONService("outposts", "outposts", "2019-12-03")
const panorama = AWS.RestJSONService("panorama", "panorama", "2019-07-24")
const personalize = AWS.JSONService(
    "personalize", "personalize", "2018-05-22", "1.1", "AmazonPersonalize"
)
const personalize_events = AWS.RestJSONService(
    "personalize", "personalize-events", "2018-03-22"
)
const personalize_runtime = AWS.RestJSONService(
    "personalize", "personalize-runtime", "2018-05-22"
)
const pi = AWS.JSONService("pi", "pi", "2018-02-27", "1.1", "PerformanceInsightsv20180227")
const pinpoint = AWS.RestJSONService("mobiletargeting", "pinpoint", "2016-12-01")
const pinpoint_email = AWS.RestJSONService("ses", "email", "2018-07-26")
const pinpoint_sms_voice = AWS.RestJSONService(
    "sms-voice", "sms-voice.pinpoint", "2018-09-05"
)
const polly = AWS.RestJSONService("polly", "polly", "2016-06-10")
const pricing = AWS.JSONService(
    "pricing", "api.pricing", "2017-10-15", "1.1", "AWSPriceListService"
)
const proton = AWS.JSONService("proton", "proton", "2020-07-20", "1.0", "AwsProton20200720")
const qldb = AWS.RestJSONService("qldb", "qldb", "2019-01-02")
const qldb_session = AWS.JSONService(
    "qldb", "session.qldb", "2019-07-11", "1.0", "QLDBSession"
)
const quicksight = AWS.RestJSONService("quicksight", "quicksight", "2018-04-01")
const ram = AWS.RestJSONService("ram", "ram", "2018-01-04")
const rds = AWS.QueryService("rds", "rds", "2014-10-31")
const rds_data = AWS.RestJSONService("rds-data", "rds-data", "2018-08-01")
const redshift = AWS.QueryService("redshift", "redshift", "2012-12-01")
const redshift_data = AWS.JSONService(
    "redshift-data", "redshift-data", "2019-12-20", "1.1", "RedshiftData"
)
const rekognition = AWS.JSONService(
    "rekognition", "rekognition", "2016-06-27", "1.1", "RekognitionService"
)
const resource_groups = AWS.RestJSONService(
    "resource-groups", "resource-groups", "2017-11-27"
)
const resource_groups_tagging_api = AWS.JSONService(
    "tagging", "tagging", "2017-01-26", "1.1", "ResourceGroupsTaggingAPI_20170126"
)
const robomaker = AWS.RestJSONService("robomaker", "robomaker", "2018-06-29")
const route53_recovery_cluster = AWS.JSONService(
    "route53-recovery-cluster",
    "route53-recovery-cluster",
    "2019-12-02",
    "1.0",
    "ToggleCustomerAPI",
)
const route53_recovery_control_config = AWS.RestJSONService(
    "route53-recovery-control-config", "route53-recovery-control-config", "2020-11-02"
)
const route53_recovery_readiness = AWS.RestJSONService(
    "route53-recovery-readiness", "route53-recovery-readiness", "2019-12-02"
)
const route53resolver = AWS.JSONService(
    "route53resolver", "route53resolver", "2018-04-01", "1.1", "Route53Resolver"
)
const route_53 = AWS.RestXMLService("route53", "route53", "2013-04-01")
const route_53_domains = AWS.JSONService(
    "route53domains", "route53domains", "2014-05-15", "1.1", "Route53Domains_v20140515"
)
const s3 = AWS.RestXMLService("s3", "s3", "2006-03-01")
const s3_control = AWS.RestXMLService("s3", "s3-control", "2018-08-20")
const s3outposts = AWS.RestJSONService("s3-outposts", "s3-outposts", "2017-07-25")
const sagemaker = AWS.JSONService(
    "sagemaker", "api.sagemaker", "2017-07-24", "1.1", "SageMaker"
)
const sagemaker_a2i_runtime = AWS.RestJSONService(
    "sagemaker", "a2i-runtime.sagemaker", "2019-11-07"
)
const sagemaker_edge = AWS.RestJSONService("sagemaker", "edge.sagemaker", "2020-09-23")
const sagemaker_featurestore_runtime = AWS.RestJSONService(
    "sagemaker", "featurestore-runtime.sagemaker", "2020-07-01"
)
const sagemaker_runtime = AWS.RestJSONService(
    "sagemaker", "runtime.sagemaker", "2017-05-13"
)
const savingsplans = AWS.RestJSONService("savingsplans", "savingsplans", "2019-06-28")
const schemas = AWS.RestJSONService("schemas", "schemas", "2019-12-02")
const secrets_manager = AWS.JSONService(
    "secretsmanager", "secretsmanager", "2017-10-17", "1.1", "secretsmanager"
)
const securityhub = AWS.RestJSONService("securityhub", "securityhub", "2018-10-26")
const serverlessapplicationrepository = AWS.RestJSONService(
    "serverlessrepo", "serverlessrepo", "2017-09-08"
)
const service_catalog = AWS.JSONService(
    "servicecatalog", "servicecatalog", "2015-12-10", "1.1", "AWS242ServiceCatalogService"
)
const service_catalog_appregistry = AWS.RestJSONService(
    "servicecatalog", "servicecatalog-appregistry", "2020-06-24"
)
const service_quotas = AWS.JSONService(
    "servicequotas", "servicequotas", "2019-06-24", "1.1", "ServiceQuotasV20190624"
)
const servicediscovery = AWS.JSONService(
    "servicediscovery",
    "servicediscovery",
    "2017-03-14",
    "1.1",
    "Route53AutoNaming_v20170314",
)
const ses = AWS.QueryService("ses", "email", "2010-12-01")
const sesv2 = AWS.RestJSONService("ses", "email", "2019-09-27")
const sfn = AWS.JSONService("states", "states", "2016-11-23", "1.0", "AWSStepFunctions")
const shield = AWS.JSONService(
    "shield", "shield", "2016-06-02", "1.1", "AWSShield_20160616"
)
const signer = AWS.RestJSONService("signer", "signer", "2017-08-25")
const simpledb = AWS.QueryService("sdb", "sdb", "2009-04-15")
const sms = AWS.JSONService(
    "sms", "sms", "2016-10-24", "1.1", "AWSServerMigrationService_V2016_10_24"
)
const snow_device_management = AWS.RestJSONService(
    "snow-device-management", "snow-device-management", "2021-08-04"
)
const snowball = AWS.JSONService(
    "snowball", "snowball", "2016-06-30", "1.1", "AWSIESnowballJobManagementService"
)
const sns = AWS.QueryService("sns", "sns", "2010-03-31")
const sqs = AWS.QueryService("sqs", "sqs", "2012-11-05")
const ssm = AWS.JSONService("ssm", "ssm", "2014-11-06", "1.1", "AmazonSSM")
const ssm_contacts = AWS.JSONService(
    "ssm-contacts", "ssm-contacts", "2021-05-03", "1.1", "SSMContacts"
)
const ssm_incidents = AWS.RestJSONService("ssm-incidents", "ssm-incidents", "2018-05-10")
const sso = AWS.RestJSONService("awsssoportal", "portal.sso", "2019-06-10")
const sso_admin = AWS.JSONService("sso", "sso", "2020-07-20", "1.1", "SWBExternalService")
const sso_oidc = AWS.RestJSONService("awsssooidc", "oidc", "2019-06-10")
const storage_gateway = AWS.JSONService(
    "storagegateway", "storagegateway", "2013-06-30", "1.1", "StorageGateway_20130630"
)
const sts = AWS.QueryService("sts", "sts", "2011-06-15")
const support = AWS.JSONService(
    "support", "support", "2013-04-15", "1.1", "AWSSupport_20130415"
)
const swf = AWS.JSONService("swf", "swf", "2012-01-25", "1.0", "SimpleWorkflowService")
const synthetics = AWS.RestJSONService("synthetics", "synthetics", "2017-10-11")
const textract = AWS.JSONService("textract", "textract", "2018-06-27", "1.1", "Textract")
const timestream_query = AWS.JSONService(
    "timestream", "query.timestream", "2018-11-01", "1.0", "Timestream_20181101"
)
const timestream_write = AWS.JSONService(
    "timestream", "ingest.timestream", "2018-11-01", "1.0", "Timestream_20181101"
)
const transcribe = AWS.JSONService(
    "transcribe", "transcribe", "2017-10-26", "1.1", "Transcribe"
)
const transfer = AWS.JSONService(
    "transfer", "transfer", "2018-11-05", "1.1", "TransferService"
)
const translate = AWS.JSONService(
    "translate", "translate", "2017-07-01", "1.1", "AWSShineFrontendService_20170701"
)
const voice_id = AWS.JSONService("voiceid", "voiceid", "2021-09-27", "1.0", "VoiceID")
const waf = AWS.JSONService("waf", "waf", "2015-08-24", "1.1", "AWSWAF_20150824")
const waf_regional = AWS.JSONService(
    "waf-regional", "waf-regional", "2016-11-28", "1.1", "AWSWAF_Regional_20161128"
)
const wafv2 = AWS.JSONService("wafv2", "wafv2", "2019-07-29", "1.1", "AWSWAF_20190729")
const wellarchitected = AWS.RestJSONService(
    "wellarchitected", "wellarchitected", "2020-03-31"
)
const wisdom = AWS.RestJSONService("wisdom", "wisdom", "2020-10-19")
const workdocs = AWS.RestJSONService("workdocs", "workdocs", "2016-05-01")
const worklink = AWS.RestJSONService("worklink", "worklink", "2018-09-25")
const workmail = AWS.JSONService(
    "workmail", "workmail", "2017-10-01", "1.1", "WorkMailService"
)
const workmailmessageflow = AWS.RestJSONService(
    "workmailmessageflow", "workmailmessageflow", "2019-05-01"
)
const workspaces = AWS.JSONService(
    "workspaces", "workspaces", "2015-04-08", "1.1", "WorkspacesService"
)
const xray = AWS.RestJSONService("xray", "xray", "2016-04-12")

end


text:
#
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons, Josef Kircher
# Licensed under the MIT license. See LICENSE file in the project root for details.
#

###############
# Prepare FMU #
###############

cd(dirname(@__FILE__))
pathToFMU = joinpath(pwd(), "../model/IO.fmu")

myFMU = fmiLoad(pathToFMU)

#################################
# Testing independent functions #
#################################

@test fmiGetVersion(myFMU) == "2.0"
@test fmiGetTypesPlatform(myFMU) == "default"

c1 = fmiInstantiate!(myFMU; loggingOn=true)
@test typeof(c1) == FMI.fmi2Component
@test fmiEnterInitializationMode(myFMU) == 0
@test fmiExitInitializationMode(myFMU) == 0
@test fmiSetupExperiment(myFMU) == 0

@test fmiReset(myFMU) == 0
@test fmiTerminate(myFMU) == 0

############
# Clean up #
############

fmiUnload(myFMU)


text:
"""
    sample_observables(x₀, sampler, observables; options=MDOptions())

Run the `sampler` starting at `x₀`, evaluating the trajectory on a tuple of
`observables` scalar functions.  Number of iterations and interval between saves
are set using the `options` argument.  Only the computed observables are returned.

### Fields
* `x`         - Starting position for sampler, modified in place
* `sampler`   - Desired sampler
* `observables` - Observables on which to evaluate the trajectory
### Optional Fields
* `TO`- Observable data type, if needed, should be entered as the first argument
* `options`   - Sampling options, including number of iteration
"""
function sample_observables(x₀::Tx, sampler::S, observables::Tuple{Vararg{<:Function,NO}};
    options = MDOptions()) where {Tx,S<:AbstractSampler,NO}

    state = InitState(x₀, sampler)
    observable_samples = zeros(NO, options.n_save)
    save_index = 1
    for i = 1:options.n_iters
        UpdateState!(state, sampler)
        if (mod(i, options.n_save_iters) == 0)
            ntuple(k -> observable_samples[k, save_index] = (observables[k])(state.x), NO)
            save_index += 1
        end
    end
    return observable_samples

end

function sample_observables(TO::Type, x₀::Tx, sampler::S, observables::Tuple{Vararg{<:Function,NO}};
    options = MDOptions()) where {Tx,S<:AbstractSampler,NO}

    state = InitState(x₀, sampler)
    observable_samples = zeros(TO, NO, options.n_save)
    save_index = 1
    for i = 1:options.n_iters
        UpdateState!(state, sampler)
        if (mod(i, options.n_save_iters) == 0)
            ntuple(k -> observable_samples[k, save_index] = (observables[k])(state.x), NO)
            save_index += 1
        end
    end
    return observable_samples
end


text:
sites(lattice::AbstractLattice) = (Coordinate(s.I) for s in CartesianIndices(axes(lattice)))

checkbounds(::Type{Bool}, L::AbstractLattice, I::Int...) = Base.checkbounds_indices(Bool, axes(L), I)
checkbounds(L::AbstractLattice, I::Int...) = checkbounds(Bool, L, I...) || throw(BoundsError(L, I))

@inline function to_site_id(lattice::AbstractLattice, coords::NTuple{N}) where N
    @boundscheck begin
        (N == ncoordinates(lattice)) || throw(ArgumentError("Incorrect number of coordinates! $(typeof(lattice)) expects $(ncoordinates(lattice)), got $N"))
        checkbounds(lattice, coords...)
    end

    sizes = (1, size(lattice)...)
    id = 0
    @inbounds for d in N:-1:1
        id += coords[d] - 1
        id *= sizes[d]
    end
    return id + 1  # 1-based indexing
end
Base.@propagate_inbounds to_site_id(lattice::AbstractLattice, coords::Coordinate) = to_site_id(lattice, coords.coordinates)

@inline function to_coordinate(lattice::AbstractLattice, site_id::Int)
    @boundscheck checkindex(Bool, 1:nsites(lattice), site_id) || throw(BoundsError(lattice, site_id))

    id = site_id - 1
    sizes = size(lattice)
    N = ncoordinates(lattice)
    coords = zeros(Int, N)

    @inbounds for d in 1:N-1
        id, c = divrem(id, sizes[d])
        coords[d] = c + 1
    end
    @inbounds coords[N] = id + 1

    return Coordinate(coords...)
end


text:
"""
This function takes in some reactance (at frequency fₒ) and determines the values for a series LC pair that resonates at fᵣ and has the same reactance,X at fₒ

    For future reference, see Everitt, Communication Engineering, P. 267
"""
function findEquivLC(X,fₒ,fᵣ)
    ωₒ = 2*π*fₒ
    ωᵣ = 2*π*fᵣ
    L = ωₒ/(ωₒ^2 - ωᵣ^2)*X
    C = (ωₒ^2 - ωᵣ^2) / (ωₒ*ωᵣ^2*X)
    return L,C
end


text:
# A single rating. The user and item are both represented by integer ids. A map
# between ids and user/item names is stored elsewhere, both in the rating set
# and the model.
struct Rating
    user::Int32
    item::Int32
    value::Float32
end

# An internal struct used only by the train function for caching between epochs.
mutable struct Residual
    value::Float32
    curr_error::Float32
    prev_error::Float32
end

# A set of ratings.
struct RatingSet
    # The set of ratings that the model should be trained on.
    training_set::Array{Rating, 1}
    # The set of ratings that the model should be tested on. This is a hold-out
    # set, the model will never see these while being trained.
    test_set::Array{Rating, 1}
    # An index between human-readable user names and an interval of integer ids.
    user_to_index::Dict{AbstractString, Int32}
    # An index between human-readable item names and an interval of integer ids.
    item_to_index::Dict{AbstractString, Int32}
end

# An SVD model.
struct RatingsModel
    # An index between human-readable user names and an interval of integer ids.
    user_to_index::Dict{AbstractString, Int32}
    # An index between human-readable item names and an interval of integer ids.
    item_to_index::Dict{AbstractString, Int32}
    # U, S, and V form the SVD decomposition of the original matrix, so
    # U * diagm(S) * V' will yield the model's approximation of the original
    # matrix. U is a (number of users) x (number of features) matrix, S is
    # a list of (number of features) singular values, and V is a (number of
    # items) x (number of features) matrix.
    U::Array{Float32,2}
    S::Array{Float32,1}
    V::Array{Float32,2}
end


text:
# # Hard spheres in periodic domain

using Plots
using Random
using ProgressMeter
using Revise

# +
using Uchiyama

n = 100 # number of particles
ϵ = 0.02
c = trunc(Int, 200ϵ) # marker size

rng = MersenneTwister(1234)

hs = HardSpheres(rng, n, ϵ)
pc = PeriodicCollisions(hs)

# +

steps = 1000
pbar = Progress(steps)

anim = @animate for _ in 1:steps

    dt = step!(hs, pc)

    p = plot(size  = (200,200),
             xlims = (0,1),
             ylims = (0,1),
             grid  = false,
             axis  = nothing,
             framestyle= :none,
             legend=false,
             widen = false)

    scatter!( getindex.(hs.q,1),
              getindex.(hs.q,2),
              markershape  = :circle,
              markersize   = c,
              aspect_ratio = :equal)

    next!(pbar)

end every 10
# -

gif(anim, joinpath(@__DIR__, "periodic_hard_spheres.gif"), fps = 20)


text:
using Soss: logdensity, xform, ConditionalModel
using ZigZagBoomerang
using ForwardDiff
using ForwardDiff: gradient!
using LinearAlgebra
using SparseArrays
using StructArrays
using TransformVariables

kappa(m::SpikeMixture{WeightedMeasure{Float64,Lebesgue{ℝ}},Float64}) = exp(m.m.logweight)/(1/m.w-1)
kappa(m::WeightedMeasure{Float64,Lebesgue{ℝ}}) = Inf
Soss.xform(m::SpikeMixture) = Soss.xform(m.m)

function sparse_zigzag(m::ConditionalModel, T = 1000.0; c=10.0, adapt=false)

    ℓ(pars) = logdensity(m, pars)

    t = xform(m)

    function f(x)
        (θ, logjac) = TransformVariables.transform_and_logjac(t, x)
        -ℓ(θ) - logjac
    end

    d = t.dimension

    function partiali()
        ith = zeros(d)
        function (x,i)
            ith[i] = 1
            sa = StructArray{ForwardDiff.Dual{}}((x, ith))
            δ = f(sa).partials[]
            ith[i] = 0
            return δ
        end
    end

    ∇ϕi = partiali()

    # Draw a random starting points and velocity
    tkeys = keys(t(zeros(d)))
    vars = Soss.select(rand(m), tkeys)

    bm_ = Soss.basemeasure(m, vars)
    bm = getindex.(Ref(bm_.data), (keys(vars)))
    κ = kappa.(bm)

    t0 = 0.0
    x0 = inverse(t, vars)
    θ0 = randn(d)

    sspdmp(∇ϕi, t0, x0, θ0, T, c*ones(d), ZigZag(sparse(I(d)), 0*x0), κ; adapt=adapt)
end