text:
# T , TSSM_HANDLE
println("including tssm_schroedinger_hermite.jl for type ", T)
for (METHOD, SUF, COMPLEX_METHOD, DIM) in (
                 (:SchroedingerHermite1D, :_schroedinger_hermite_1d, true, 1 ),
                 (:SchroedingerHermite2D, :_schroedinger_hermite_2d, true, 2 ),
                 (:SchroedingerHermite3D, :_schroedinger_hermite_3d, true, 3 ),
                 (:SchroedingerHermiteReal1D, :_schroedinger_hermite_real_1d, false, 1 ),
                 (:SchroedingerHermiteReal2D, :_schroedinger_hermite_real_2d, false, 2 ),
                 (:SchroedingerHermiteReal3D, :_schroedinger_hermite_real_3d, false, 3 ),
                )
println("    ", METHOD)
if T == :Float128
    SUF = Symbol(SUF, "_wf128")
end

if DIM==1
@eval begin
    function ($METHOD)(T::Type{$T}, nx::Integer, omega_x::Real;
                       hbar::Real=1.0, mass::Real=1.0, potential::Function=none_1D,
                       potential_t::Function=none_2D,
                       potential_t_derivative::Function=none_2D,
                       cubic_coupling::Real=0.0)
        with_potential = potential!=none_1D
        with_potential_t = potential_t!=none_2D
        with_potential_t_derivative = potential_t_derivative!=none_2D
        V_c = cfunction_check_return_type(potential, ($T), (($T),))
        V_t_c = cfunction_check_return_type(potential_t, ($T), (($T),($T)))
        V_t_derivative_c = cfunction_check_return_type(potential_t_derivative, ($T), (($T),($T)))
        c = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"new",SUF))), Ptr{Nothing},
                   (Int32, ($T), ($T), ($T), Ptr{Nothing}, Bool, Ptr{Nothing}, Bool, Ptr{Nothing}, Bool, ($T)),
                   nx, omega_x,
                   hbar, mass, V_c, with_potential,
                   V_t_c, with_potential_t, V_t_derivative_c, with_potential_t_derivative,
                   cubic_coupling)
        m = ($METHOD){$T}(c)
        finalizer(x -> ccall( Libdl.dlsym(($TSSM_HANDLE),
                       $(string(PRE,"finalize",SUF))), Nothing, (Ptr{Nothing},), x.m), m)
       m
    end
end # eval
if T == :Float64
@eval begin
    function ($METHOD)(nx::Integer, omega_x::Real;
                       hbar::Real=1.0, mass::Real=1.0, potential::Function=none_1D,
                       potential_t::Function=none_2D,
                       potential_t_derivative::Function=none_2D,
                       cubic_coupling::Real=0.0)
        ($METHOD)(($T), nx, omega_x,
                       hbar=hbar, mass=mass, potential=potential,
                       potential_t=potential_t, potential_t_derivative=potential_t_derivative,
                       cubic_coupling=cubic_coupling)
    end
end # eval
end #if
elseif DIM==2
@eval begin
    function ($METHOD)(T::Type{($T)}, nx::Integer, omega_x::Real,
                                      ny::Integer, omega_y::Real;
                       hbar::Real=1.0, mass::Real=1.0, potential::Function=none_2D,
                       potential_t::Function=none_3D,
                       potential_t_derivative::Function=none_3D,
                       cubic_coupling::Real=0.0)
        with_potential = potential!=none_2D
        with_potential_t = potential_t!=none_3D
        with_potential_t_derivative = potential_t_derivative!=none_3D
        V_c = cfunction_check_return_type(potential, ($T), (($T),($T)))
        V_t_c = cfunction_check_return_type(potential_t, ($T), (($T),($T),($T)))
        V_t_derivative_c = cfunction_check_return_type(potential_t_derivative, ($T), (($T),($T),($T)))
        c = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"new",SUF))), Ptr{Nothing},
                   (Int32, ($T), Int32, ($T),
                   ($T), ($T), Ptr{Nothing}, Bool, Ptr{Nothing}, Bool, Ptr{Nothing}, Bool, ($T)),
                   nx, omega_x, ny, omega_y,
                   hbar, mass, V_c, with_potential,
                   V_t_c, with_potential_t, V_t_derivative_c, with_potential_t_derivative,
                   cubic_coupling)
        m = ($METHOD){$T}(c)
        finalizer(x -> ccall( Libdl.dlsym(($TSSM_HANDLE),
                       $(string(PRE,"finalize",SUF))), Nothing, (Ptr{Nothing},), x.m), m)
        m
    end
end # eval
if T == :Float64
@eval begin
    function ($METHOD)(nx::Integer, omega_x::Real,
                       ny::Integer, omega_y::Real;
                       hbar::Real=1.0, mass::Real=1.0, potential::Function=none_2D,
                       potential_t::Function=none_3D,
                       potential_t_derivative::Function=none_3D,
                       cubic_coupling::Real=0.0)
        ($METHOD)(($T), nx, omega_x,  ny, omega_y,
                       hbar=hbar, mass=mass, potential=potential,
                       potential_t=potential_t, potential_t_derivative=potential_t_derivative,
                       cubic_coupling=cubic_coupling)
    end
end # eval
end #if
elseif DIM==3
@eval begin
    function ($METHOD)(T::Type{($T)}, nx::Integer, omega_x::Real,
                                      ny::Integer, omega_y::Real,
                                      nz::Integer, omega_z::Real;
                       hbar::Real=1.0, mass::Real=1.0, potential::Function=none_3D,
                       potential_t::Function=none_4D,
                       potential_t_derivative::Function=none_4D,
                       cubic_coupling::Real=0.0)
        with_potential = potential!=none_3D
        with_potential_t = potential_t!=none_4D
        with_potential_t_derivative = potential_t_derivative!=none_4D
        V_c = cfunction_check_return_type(potential, ($T), (($T),($T),($T)))
        V_t_c = cfunction_check_return_type(potential_t, ($T), (($T),($T),($T),($T)))
        V_t_derivative_c = cfunction_check_return_type(potential_t_derivative, ($T), (($T),($T),($T)))
        c = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"new",SUF))), Ptr{Nothing},
                   (Int32, ($T), Int32, ($T), Int32, ($T),
                   ($T), ($T), Ptr{Nothing}, Bool, Ptr{Nothing}, Bool, Ptr{Nothing}, Bool, ($T)),
                   nx, omega_x, ny, omega_y, nz, omega_z,
                   hbar, mass, V_c, with_potential,
                   V_t_c, with_potential_t, V_t_derivative_c, with_potential_t_derivative,
                   cubic_coupling)
        m = ($METHOD){$T}(c)
        finalizer(x -> ccall( Libdl.dlsym(($TSSM_HANDLE),
                       $(string(PRE,"finalize",SUF))), Nothing, (Ptr{Nothing},), x.m), m)
        m
    end
end # eval
if T == :Float64
@eval begin
    function ($METHOD)(nx::Integer, omega_x::Real,
                       ny::Integer, omega_y::Real,
                       nz::Integer, omega_z::Real;
                       hbar::Real=1.0, mass::Real=1.0, potential::Function=none_3D,
                       potential_t::Function=none_4D,
                       potential_t_derivative::Function=none_4D,
                       cubic_coupling::Real=0.0)
        ($METHOD)(($T), nx, omega_x, ny, omega_y, nz, omega_z,
                       hbar=hbar, mass=mass, potential=potential,
                       potential_t=potential_t, potential_t_derivative=potential_t_derivative,
                       cubic_coupling=cubic_coupling)
    end
end # eval
end #if

end # if

@eval begin
    function get_nx(m::($METHOD){$T})
       ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_nx",SUF))), Int32,
             (Ptr{Nothing}, ), m.m )
    end

    function get_omega_x(m::($METHOD){$T})
       ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_omega_x",SUF))), ($T),
             (Ptr{Nothing}, ), m.m )
    end
end # eval

if DIM>=2
    @eval begin

        function get_ny(m::($METHOD){$T})
           ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_ny",SUF))), Int32,
                 (Ptr{Nothing}, ), m.m )
        end

        function get_omega_y(m::($METHOD){$T})
           ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_omega_y",SUF))), ($T),
                 (Ptr{Nothing}, ), m.m )
        end
    end # eval
end

if DIM>=3
    @eval begin
        function get_nz(m::($METHOD){$T})
           ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_nz",SUF))), Int32,
                 (Ptr{Nothing}, ), m.m )
        end

        function get_omega_z(m::($METHOD){$T})
           ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_omega_z",SUF))), ($T),
                 (Ptr{Nothing}, ), m.m )
        end
    end # eval
end

if DIM==1
    @eval begin

        function get_weights(m::($METHOD){$T})
           dim =Array(Int32, 1)
           np = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_weights",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dim, 1 )
           n = pointer_to_array(np, dim[1], false)
           copy(n)
        end

        function get_transformation_matrices(m::($METHOD){$T}, unsafe_access::Bool=false)
           dims =Array(Int32, 2)
           Hp = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_H",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dims, 1 )
           H = pointer_to_array(Hp1, (dims[1], dims[2]), false)
           if unsafe_access
               return H
           else
               return copy(H)
           end
        end

    end
elseif DIM==2
    @eval begin

        function get_weights(m::($METHOD){$T})
           dim =Array(Int32, 1)
           np1 = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_weights",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dim, 1 )
           n1 = pointer_to_array(n1p, dim[1], false)
           np2 = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_weights",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dim, 2 )
           n2 = pointer_to_array(n2p, dim[1], false)
           copy(n1), copy(n2)
        end

        function get_transformation_matrices(m::($METHOD){$T}, unsafe_access::Bool=false)
           dims =Array(Int32, 2)
           Hp1 = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_H",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dims, 1 )
           H1 = pointer_to_array(Hp1, (dims[1], dims[2]), false)
           Hp2 = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_H",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dims, 2 )
           H2 = pointer_to_array(Hp2, (dims[1], dims[2]), false)
           if unsafe_access
               return H1, H2
           else
               return copy(H1), copy(H2)
           end
        end

    end
elseif DIM==2
    @eval begin

        function get_weights(m::($METHOD){$T})
           dim =Array(Int32, 1)
           np1 = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_weights",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dim, 1 )
           n1 = pointer_to_array(n1p, dim[1], false)
           np2 = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_weights",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dim, 2 )
           n2 = pointer_to_array(n2p, dim[1], false)
           np3 = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_weights",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dim, 3 )
           n3 = pointer_to_array(n3p, dim[1], false)
           copy(n1), copy(n2), copy(n3)
        end

        function get_transformation_matrices(m::($METHOD){$T}, unsafe_access::Bool=false)
           dims =Array(Int32, 2)
           Hp1 = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_H",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dims, 1 )
           H1 = pointer_to_array(Hp1, (dims[1], dims[2]), false)
           Hp2 = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_H",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dims, 2 )
           H2 = pointer_to_array(Hp2, (dims[1], dims[2]), false)
           Hp3 = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_H",SUF))), Ptr{$T},
                 (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dims, 3 )
           H3 = pointer_to_array(Hp3, (dims[1], dims[2]), false)
           if unsafe_access
               return H1, H2, H3
           else
               return copy(H1), copy(H2), copy(H3)
           end
        end

    end #eval
end

end # for


text:
# <---- Chi Distribution --->
@doc """
      FUNCTION NOT YET WRITTEN\n
      Chi Distribution in another well-known distribution well known for being
      used in statistical tests.\n
      --------------------\n
      array = [5,10,15]\n
      r = Lathe.stats.anova(array)\n
       """
function chidist(x,e)
    #
end
function bernoulli_dist()
    # P(x) = P^x(1-P)^1-x for x=0 eller 1
end
@doc """
      Binomial Distribution is a distribution well known for its use in
           statistical tests and decision making models.\n
      --------------------\n
      array = [5,10,15]\n
      r = Lathe.stats.anova(array)\n
       """
function binomial_dist(positives,size)
    # p = n! / x!(n-x!)*π^x*(1-π)^N-x
    n = size
    x = positives
    factn = factorial(big(n))
    factx = factorial(big(x))
    nx = factn / (factx * (n-x))
    return(nx)
end
# ---- Z Normalization ----
@doc """
      Standard Scalar z-score normalizes a feature.\n
      --------------------\n
      array = [5,10,15]\n
      scaled_feature = Lathe.preprocess.StandardScalar(array)\n
       """
function normal(array)
    q = Lathe.stats.std(array)
    avg = Lathe.stats.mean(array)
    v = [i = (i-avg) / q for i in array]
    return(v)
end
export normal
export chidist
export binomial_dist
export bernoulli_dist

ext: jl


text:
@testset "DFS" begin

  g5 = SimpleDiGraph(4)
  add_edge!(g5, 1, 2); add_edge!(g5, 2, 3); add_edge!(g5, 1, 3); add_edge!(g5, 3, 4)
  gx = cycle_digraph(3)

  @testset "dfs_tree" begin
    for g in testdigraphs(g5)
      z = @inferred(dfs_tree(g, 1))
      @test ne(z) == 3 && nv(z) == 4
      @test !has_edge(z, 1, 3)
      @test !is_cyclic(g)
    end
  end

  @testset "topological_sort_by_dfs" begin
    for g in testdigraphs(g5)
      @test @inferred(topological_sort_by_dfs(g)) == [1, 2, 3, 4]
    end

    for g in testdigraphs(gx)
      @test @inferred(is_cyclic(g))
      @test_throws ErrorException topological_sort_by_dfs(g)
    end
  end

  @testset "is_cyclic" begin
    for g in testgraphs(path_graph(2))
      @test @inferred(is_cyclic(g))
      @test @inferred(!is_cyclic(zero(g)))
    end
  end

end


text:
using Test

@testset "PATH" begin
    @testset "$(file)" for file in ["C_API.jl", "MOI_wrapper.jl"]
        println("Running: $(file)")
        include(file)
    end
end


text:
using GeodesyGPX
using Test

@testset "GeodesyGPX.jl" begin
    # Write your tests here.
end


text:
struct JC69rel <: JC69 end

function show(io::IO, object::JC69rel)
  print(io, "\r\e[0m\e[1mJ\e[0mukes and \e[1mC\e[0mantor 19\e[1m69\e[0m model (relative rate form)")
end

JC69() = JC69rel()

@inline function Q(mod::JC69rel)
  Q₁ =  0.25
  Q₂ = -(Q₁ * 3)
  return SMatrix{4, 4, Float64}(Q₂, Q₁, Q₁, Q₁,
                                Q₁, Q₂, Q₁, Q₁,
                                Q₁, Q₁, Q₂, Q₁,
                                Q₁, Q₁, Q₁, Q₂)
end

@inline function P(mod::JC69rel, t::Float64)
  if t < 0.0
    error("t must be positive")
  end
  e₁ = exp(-t)
  P₁ = 0.25 + 0.75 * e₁
  P₂ = 0.25 - 0.25 * e₁
  return Pmatrix(P₁, P₂, P₂, P₂,
                 P₂, P₁, P₂, P₂,
                 P₂, P₂, P₁, P₂,
                 P₂, P₂, P₂, P₁)
end


text:
"""
    struct GOCNullImpedance_notransformer <: AbstractLinkLabel

Structure descendant of AbstractLinkLabel

# Fields
- `link::Link`
- `id::String`
- `susceptance::Float64`: coefficient bc
- `power_magnitude_max::Float64`: Smax

"""
struct GOCNullImpedance_notransformer <: AbstractLinkLabel
    orig_id::Int64
    dest_id::Int64
    id::Any
    susceptance::Float64 #bc
    power_magnitude_max::Float64 #Smax
end

"""
    create_vars!(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::SortedDict{String, Variable}, scenario::String) where T <: GOCNullImpedance_notransformer

Create voltage variables and power variables for origin and destination of `link` in `link_vars`.
Return nothing.
"""
function create_vars!(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::SortedDict{String, Variable}, scenario::String) where T <: GOCNullImpedance_notransformer
    origid, destid = link.orig, link.dest
    link_vars["Volt_orig"] = Variable(variable_name("VOLT", origid, "", scenario), Complex)
    link_vars["Volt_dest"] = Variable(variable_name("VOLT", destid, "", scenario), Complex)

    link_vars[elemid*"_Sorig"] = Variable(variable_name("Sorig", origid, "", scenario), Complex)
    link_vars[elemid*"_Sdest"] = Variable(variable_name("Sdest", destid, "", scenario), Complex)
    #elem_formulation modified ?
    return
end

"""
    Sorig(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::SortedDict{String, Variable}) where T<:GOCNullImpedance_notransformer

Return power variable Sorig * baseMVA.
"""
function Sorig(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::SortedDict{String, Variable}) where T<:GOCNullImpedance_notransformer
    return get_baseMVA(link.orig)*link_vars[elemid*"_Sorig"]
end

"""
    Sdest(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::SortedDict{String, Variable}) where T<:GOCNullImpedance_notransformer

Return power variable Sdest * baseMVA.
"""
function Sdest(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::SortedDict{String, Variable}) where T<:GOCNullImpedance_notransformer
   return get_baseMVA(link.dest)*link_vars[elemid*"_Sdest"]
end

## 3. Constraints creation
# function constraint(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::SortedDict{String, Variable}, scenario::String, OPFpbs::OPFProblems) where T <: MyType
#   return SortedDict{String, Constraint}()
# end


text:
module ReactiveMPStandardBasisVectorTest

using Test
using ReactiveMP
using Random

using LinearAlgebra

@testset "StandardBasisVector" begin

    rng = MersenneTwister(1234)

    @testset begin
        @test_throws AssertionError StandardBasisVector(0, 1)
        @test_throws AssertionError StandardBasisVector(-10, 1)
        @test_throws AssertionError StandardBasisVector(10, 11)
        @test_throws AssertionError StandardBasisVector(10, -2)

        for T in (Int, Float64, Float32)
            r = rand(rng, T)
            e = StandardBasisVector(2, 1, r)
            @test eltype(e) === T
            @test e[1] === r
            @test e[2] === zero(r)
        end
    end

    # Same sizes
    @testset begin

        for N in 1:8
            for I in 1:N
                for T in (Int, Float64, Float32)
                    scale  = rand(rng, T)
                    e      = StandardBasisVector(N, I, scale)
                    e_c    = zeros(T, N)
                    e_c[I] = scale

                    m = rand(rng, T)
                    v = rand(rng, T, N)
                    A = rand(rng, T, N, N)
                    a = rand(rng, T, N, 1)

                    @test m * e == m * e_c
                    @test m * e' == m * e_c'
                    @test e * m == e_c * m
                    @test e' * m == e_c' * m

                    @test (A * e) == (A * e_c)
                    @test (A' * e) == (A' * e_c)
                    @test (e * e') == (e_c * e_c')
                    @test (e' * e) == (e_c' * e_c)
                    @test (v' * e) == (v' * e_c)
                    @test (e' * v) == (e_c' * v)
                    @test (e' * v) == (e_c' * v)
                    @test (a' * e) == (a' * e_c)
                    @test (a * e') == (a * e_c')

                    t = rand(rng, T)

                    @test ReactiveMP.v_a_vT(e, t)    ≈ ReactiveMP.v_a_vT(e_c, t)
                    @test ReactiveMP.v_a_vT(e, t, e) ≈ ReactiveMP.v_a_vT(e_c, t, e_c)

                    @test dot(e, A, e) === dot(e_c, A, e_c)
                    @test dot(e, e) === dot(e_c, e_c)
                    @test dot(e, e_c) === dot(e_c, e_c)
                    @test dot(e_c, e) === dot(e_c, e_c)
                    @test dot(v, e) === dot(v, e_c)
                    @test dot(e, v) === dot(e_c, v)
                    @test dot(v, e') === dot(v, e_c')
                    @test dot(e', v) === dot(e_c', v)
                    @test dot(v', e) === dot(v', e_c)
                    @test dot(e, v') === dot(e_c, v')
                    @test dot(v', e') === dot(v', e_c')
                    @test dot(e', v') === dot(e_c', v')
                end
            end
        end
    end
    # Different sizes
    @testset begin

        for N1 in 1:4, N2 in 1:4
            if N1 !== N2
                for I1 in 1:N1, I2 in 1:N2
                    for T in (Int, Float64, Float32)
                        scale1   = rand(rng, T)
                        scale2   = rand(rng, T)
                        e1       = StandardBasisVector(N1, I1, scale1)
                        e2       = StandardBasisVector(N2, I2, scale2)
                        e_c1     = zeros(T, N1)
                        e_c1[I1] = scale1
                        e_c2     = zeros(T, N2)
                        e_c2[I2] = scale2

                        @test_throws AssertionError dot(e1, e2)
                        @test_throws AssertionError dot(e_c1, e2)
                        @test_throws AssertionError dot(e1, e_c2)
                        @test_throws AssertionError dot(e2, e1)
                        @test_throws AssertionError dot(e_c2, e1)
                        @test_throws AssertionError dot(e2, e_c1)

                        @test e1 * e2' == e_c1 * e_c2'
                        @test e2 * e1' == e_c2 * e_c1'
                        @test e_c1 * e2' == e_c1 * e_c2'
                        @test e_c2 * e1' == e_c2 * e_c1'
                        @test e1 * e_c2' == e_c1 * e_c2'
                        @test e2 * e_c1' == e_c2 * e_c1'
                        @test_throws AssertionError e1' * e2
                        @test_throws AssertionError e1' * e_c2
                        @test_throws AssertionError e2' * e1
                        @test_throws AssertionError e2' * e_c1
                    end
                end
            end
        end

    end

end

end


text:
function correction_field(N, V)
    pl, wl = tri_quadrature(N)
    pf, wf = triface_quadrature(N)

    Np = (N + 1) * (N + 2) ÷ 2
    ψf = zeros(3, N + 1, Np)
    for i = 1:3
        ψf[i, :, :] .= vandermonde_matrix(Tri, N, pf[i, :, 1], pf[i, :, 2])
    end

    σ = zeros(3, N + 1, Np)
    for k = 1:Np
        for j = 1:N+1
            for i = 1:3
                σ[i, j, k] = wf[i, j] * ψf[i, j, k]
            end
        end
    end

    V = vandermonde_matrix(Tri, N, pl[:, 1], pl[:, 2])

    ϕ = zeros(3, N + 1, Np)
    for f = 1:3, j = 1:N+1, i = 1:Np
        ϕ[f, j, i] = sum(σ[f, j, :] .* V[i, :])
    end

    return ϕ
end


text:
export spqr_pinv

"""
    SPQR_PINV approx pseudoinverse solution to min(norm(B-A*X))

usage: x,stats,N,NT = spqr_pinv(A, B, opts)
This function returns an approximate pseudoinverse solution to
                 min || B - A x ||                     (1)
for rank deficient matrices A.  The pseudoinverse solution is the minimum
norm solution to the least squares problem (1).  Also, optionally, the
routine returns statistics including the numerical rank of the matrix A for
tolerance tol (i.e. the number of singular values > tol) and other statistics
(see below), as well as, if requested, an orthonormal basis for the numerical
null space to A and an orthonormal basis for the null space of A transpose.
The pseudoinverse solution is approximate since the algorithm allows small
perturbations in A (columns of A may be changed by no more than a user
defined value in tol).

Input:  A -- an m by n matrix
        B -- an m by p right hand side matrix
        opts (optional) -- see below
Output: x -- this n by p matrix contains pseudoinverse solutions to (1).
             If B is empty then x will also be empty.
        stats (optional) -- statistics including:
"""
function spqr_pinv(A::AbstractMatrix{T}, B::AbstractMatrix{T}; tol::T, nargout=4, get_details::Int=0) where T
#=
 Examples:
    A = sparse(gallery('kahan',100))
    B = randn(100,1) ; B = B / norm(B)
    x = spqr_pinv(A,B)
    x_pinv = pinv(full(A))*B
    rel_error_in_x = norm(x - x_pinv) / norm(x_pinv)
    # or
    [x,stats,N,NT] = spqr_pinv(A,B)
    norm_A_times_N = norm(full(spqr_null_mult(N,A,3)))
    norm_N_transpose_times_A = norm(full(spqr_null_mult(NT,A,0)))
    # or
    opts = struct('tol',1.e-5)
    [x,stats] = spqr_pinv(A,B,opts)
    stats

See also spqr_basic, spqr_null, spqr_pinv, spqr_cod.

Copyright 2012, Leslie Foster and Timothy A Davis.

Algorithm:  a basic solution is calculated using spqr_basic. Following
   this an orthogonal basis, stored in N, for the numerical null space
   of A is calculated using spqr_null. The psuedoinverse solution is
   then x - N*(N'*x) which is calculated using the routine spqr_null_mult.
=#

#-------------------------------------------------------------------------------
# set tolerance and number of singular values to estimate
#-------------------------------------------------------------------------------
start_tic = time_ns()
stats = SpqrStats()

if nargout > 4
    error("usage: x, stats, N, NT = spqr_pinv(A, B, opts...)")
end

# get the options
get_details = opts.get_details

if get_details == 1
    stats.opts_used = opts
end

# set the order of the stats fields
#     stats.flag, stats.rank, stats.rank_spqr, stats.rank_spqr(if get_details
#     >= 1), stats.tol, stats.tol_alt, stats.normest_A (if calculated),
#     stats.est_sval_upper_bounds, stats.est_sval_lower_bounds, and
#     stats.sval_numbers_for_bounds already initialized in spqr_rank_get_inputs
if nargout >= 3
    stats.est_norm_A_times_N = -1
end
if nargout == 4
   stats.est_norm_A_transpose_times_NT = -1
end
# order for the additional stats fields needed when get_details is 1 will be
#     set using spqr_rank_order_fields at the end of the routine

#-------------------------------------------------------------------------------
# find basic solution
#-------------------------------------------------------------------------------

if get_details == 0
    # opts2 used to include a few extra statistics in stats_ssi
    opts2 = opts
    opts2.get_details = 2
else
    opts2 = opts
end
if nargout == 4
    # save basis for null space of A', if there are four output
    #   parameters.  This will require more memory.
    x, stats_spqr_basic, NT = spqr_basic(A, B, nargout=3, tol=tol, get_details=2)
else
    # do not save the basis for the null space of A'. Saves memory.
    x, stats_spqr_basic = spqr_basic(A, B, nargout=2, tol=tol, get_details=2)
end

stats.rank = stats_spqr_basic.rank

# save the stats
if get_details == 1 || get_details == 2
    stats.rank_spqr = stats_spqr_basic.rank_spqr
end

#-------------------------------------------------------------------------------
# check for early return
#-------------------------------------------------------------------------------

if stats_spqr_basic.flag == 4
    # overflow in spqr_ssi, called by spqr_basic.
    # spqr_basic has already issued a warning regarding overflow
    return spqr_failure(4, stats, get_details, start_tic)
end

#-------------------------------------------------------------------------------
# calculate basis for the null space of A
#-------------------------------------------------------------------------------

# spqr_null calls spqr_ssi.  Set the block size in spqr_ssi based on the
# difference in the numerical rank calculated by spqr_basic and by spqr.  Note
# that this overwrites the user-provided value of opts.ssi_min_block, if any.
opts.ssi_min_block = max(2, stats_spqr_basic.rank_spqr - stats.rank + 1)

opts.ssi_min_block = min(opts.ssi_min_block, stats_spqr_basic.stats_ssi.ssi_max_block_used)

N, stats_spqr_null = spqr_null(A, opts2)

if get_details == 1
    stats.stats_spqr_basic = stats_spqr_basic
    stats.stats_spqr_null = stats_spqr_null
end

#-------------------------------------------------------------------------------
# check for early return
#-------------------------------------------------------------------------------

# spqr_basic and spqr_null both return error flags.  Since both must be correct
# to calculate the psuedoinverse solution, choose the largest (worst) error.

stats.flag = max(stats_spqr_basic.flag, stats_spqr_null.flag)

if stats_spqr_basic.flag == 0 && stats_spqr_null.flag == 0  && stats_spqr_basic.rank ~= stats_spqr_null.rank
    # Rank from spqr_basic and spqr_null differ.  This is so rare that we know
    # of no matrices that trigger this condition.  This block of code is thus
    # untested.
    error("spqr_rank:inconsistent", "inconsistent rank estimates") ; # untested
    # an alternative, which would cause a return in the code below.
    #   stats.flag = 5
end

if stats.flag >= 4
    # early return: overflow in inverse power method in ssi,
    # or inconsistent rank estimates by spqr_basic and spqr_null.
    return spqr_failure(stats.flag, stats, get_details, start_tic)
end

#-------------------------------------------------------------------------------
# calculate the psuedoinverse solution
#-------------------------------------------------------------------------------

x = x - spqr_null_mult(N, spqr_null_mult(N, x, 0), 1)

#-------------------------------------------------------------------------------
# select from two estimates of numerical rank and two sets of bounds
#-------------------------------------------------------------------------------

# Strategy -- the choice of stats.flag above was the
#     max(stats_spqr_basic.flag, stats_spqr_null.flag)
# We will choose the bounds and rank corresponding to this choice of flag.
# When the flags are the same we will use spqr_basic results for
# the bounds, except when the flags are both 1 we will choose the bounds
# corresponding to the maximum of stats_spqr_basic.tol_alt and
# stats_spqr_null.tol_alt (the conservative choice).

if stats_spqr_basic.flag == 1 && stats_spqr_null.flag == 1
    if stats_spqr_basic.tol_alt >= stats_spqr_null.tol_alt
        st = stats_spqr_basic
    else
        st = stats_spqr_null
    end
elseif stats_spqr_basic.flag >= stats_spqr_null.flag
        st = stats_spqr_basic
else
        st = stats_spqr_null
end
stats.rank = st.rank
stats.tol_alt = st.tol_alt
stats.sval_numbers_for_bounds = st.sval_numbers_for_bounds
stats.est_sval_upper_bounds  = st.est_sval_upper_bounds
stats.est_sval_lower_bounds  = st.est_sval_lower_bounds

#-------------------------------------------------------------------------------
# return statistics
#-------------------------------------------------------------------------------

if get_details == 1 || nargout >= 3
   stats.est_norm_A_times_N = stats_spqr_null.est_norm_A_times_N
end
if get_details == 1
    stats.est_err_bound_norm_A_times_N = stats_spqr_null.est_err_bound_norm_A_times_N
end
if nargout == 4
    stats.est_norm_A_transpose_times_NT = stats_spqr_basic.est_norm_A_transpose_times_NT
    if get_details == 1
        stats.est_err_bound_norm_A_transpose_times_NT = stats_spqr_basic.est_err_bound_norm_A_transpose_times_NT
    end
end

if get_details == 1
    stats.time_svd = stats_spqr_basic.time_svd + stats_spqr_basic.stats_ssi.time_svd + stats_spqr_null.time_svd + stats_spqr_null.stats_ssi.time_svd + stats_spqr_null.stats_ssp_N.time_svd
    if nargout == 4
        stats.time_svd = stats.time_svd+stats_spqr_basic.stats_ssp_NT.time_svd
    end
    stats.time_basis = stats_spqr_basic.time_basis + stats_spqr_null.time_basis
end

if get_details == 1
    stats.time = time_ns() - start_tic
end

return x, stats, N, NT
end


text:
# Compute graphs from entity edge data.

using JLD, PyPlot

file_dir = joinpath(Base.source_dir(),"./Entity.jld")
E = load(file_dir)["E"]
#E = loadassoc(joinpath(Base.source_dir(),"./Entity.jld"))
E = logical(E)

# Computing adjacency matrix for the Entity-Entity graph.
Ae = sqIn(E)
figure()
spy(Ae)

# Entity-entity graphs that preserve original values.
# Limit to people with names starting with j
p = StartsWith("PERSON/j,")
Ep = E[:,p]

# Correlate while preserving pedigree
Ap = CatKeyMul(Ep',Ep)
figure()
spy(Ap)

# Create document-document graph: documents that contain the same entities.
Ad = sqOut(Ep)
figure()
spy(Ad)


text:
immutable SplineSparse{T,I} <: AbstractSparseMatrix{T,I}
    n_chunks::Int
    chunk_len::Int
    ncol::Int
    vals::Vector{T}
    cols::Vector{I}

    function SplineSparse(n_chunks, chunk_len, ncol, vals, cols)
        if length(cols)*chunk_len != length(vals)
            error("vals and cols not conformable")
        end
        new(n_chunks, chunk_len, ncol, vals, cols)
    end
end

function SplineSparse{T,I}(N, len, ncol::Int, vals::AbstractVector{T},
                           cols::AbstractVector{I})
    SplineSparse{T,I}(N, len, ncol, vals, cols)
end

n_chunks(s::SplineSparse) = s.n_chunks
chunk_len(s::SplineSparse) = s.chunk_len
Base.eltype{T}(::SplineSparse{T}) = T
ind_type{T,I}(::SplineSparse{T,I}) = I

@inline val_ix{T,I}(s::SplineSparse{T,I}, row, chunk, n) =
    s.n_chunks*s.chunk_len*(row-1) + s.chunk_len*(chunk-1) + n

@inline col_ix{N}(s::SplineSparse{N}, row, chunk) =
    s.n_chunks*(row-1) + chunk

function Base.full{T}(s::SplineSparse{T})
    nrow = _nrows(s)
    out = zeros(T, nrow, s.ncol)

    for row in 1:nrow
        for chunk in 1:s.n_chunks
            first_col = s.cols[col_ix(s, row, chunk)]
            @simd for n in 1:s.chunk_len
                out[row, first_col+n-1] = s.vals[val_ix(s, row, chunk, n)]
            end
        end
    end

    out
end

function Base.findnz{T,I}(s::SplineSparse{T,I})
    nrow = _nrows(s)
    rows = repeat(collect(I, 1:nrow), inner=[s.n_chunks*s.chunk_len])
    cols = Array(I, length(s.vals))

    for row in 1:nrow
        for chunk in 1:s.n_chunks
            first_col = s.cols[col_ix(s, row, chunk)]
            for n in 1:s.chunk_len
                cols[val_ix(s, row, chunk, n)] = first_col+n-1
            end
        end
    end

    rows, cols, s.vals
end

function Base.convert(::Type{SparseMatrixCSC}, s::SplineSparse)
    I, J, V = findnz(s)
    sparse(I, J, V, _nrows(s), s.ncol)
end

Base.sparse(s::SplineSparse) = convert(SparseMatrixCSC, s)

function Base.getindex{T}(s::SplineSparse{T}, row::Integer, cols::Integer)
    first_cols = s.cols[row]

    for chunk in 1:s.n_chunks
        first_col = s.cols[col_ix(s, row, chunk)]

        if cols < first_col || cols > (first_col + s.chunk_len-1)
            continue
        end

        n = cols-first_col+1
        return s.vals[val_ix(s, row, chunk, n)]

    end

    zero(T)
end

_nrows(s::SplineSparse) = Int(length(s.vals) / (s.n_chunks*s.chunk_len))
Base.size(s::SplineSparse) = (_nrows(s), s.ncol)
Base.size(s::SplineSparse, i::Integer) = i == 1 ? _nrows(s) :
                                         i == 2 ? s.ncol :
                                         1

function row_kron{T1,I1,T2,I2}(s1::SplineSparse{T1,I1}, s2::SplineSparse{T2,I2})

    nrow = _nrows(s1)
    _nrows(s2) == nrow || error("s1 and s2 must have same number of rows")
    N1 = s1.n_chunks
    len1 = s1.chunk_len
    N2 = s2.n_chunks
    len2 = s2.chunk_len

    # new number of chunks the length chunks times the number of chunks in
    # first matrix times number of chunks in second matrix
    N = len1*N1*N2

    # new chunk length is the chunk length from the second matrix
    len = len2

    # T and I are  easy...
    T = promote_type(T1, T2)
    I = promote_type(I1, I2)

    cols = Array(I, N*nrow)
    vals = Array(T, N*len*nrow)

    ix = 0
    c_ix = 0
    @inbounds for row in 1:nrow
        for chunk1 in 1:N1
            first_col1 = s1.cols[col_ix(s1, row, chunk1)]

            for n1 in 1:len1
                v1 = s1.vals[val_ix(s1, row, chunk1, n1)]

                for chunk2 in 1:N2
                    first_col2 = s2.cols[col_ix(s2, row, chunk2)]

                    cols[c_ix+=1] = (first_col1+n1-2)*s2.ncol+first_col2

                    @simd for n2 in 1:len2
                        vals[ix+=1] = v1*s2.vals[val_ix(s2, row, chunk2, n2)]
                    end
                end
            end
        end
    end

    SplineSparse(N, len, s1.ncol*s2.ncol, vals, cols)

end

function matvec!{T}(out::AbstractVector{T}, s::SplineSparse, v::AbstractVector)
    @inbounds for row in eachindex(out)
        val = zero(T)
        for chunk in 1:s.n_chunks
            first_col = s.cols[col_ix(s, row, chunk)]

            @simd for n in 1:s.chunk_len
                val += s.vals[val_ix(s, row, chunk, n)] * v[first_col+(n-1)]
            end
        end

        out[row] = val
    end
    out
end

function *{T,I,T2}(s::SplineSparse{T,I},
                             v::AbstractVector{T2})
    size(s, 2) == size(v, 1) || throw(DimensionMismatch())

    out_T = promote_type(T, T2)
    out = Array(out_T, size(s, 1))
    matvec!(out, s, v)
end

function *{T,I,T2}(s::SplineSparse{T,I},
                             m::AbstractMatrix{T2})
    size(s, 2) == size(m, 1) || throw(DimensionMismatch())

    out_T = promote_type(T, T2)
    out = Array(out_T, size(s, 1), size(m, 2))

    @inbounds for row in 1:size(s, 1)
        vals = zeros(out_T, size(m, 2))
        for chunk in 1:s.n_chunks
            first_col = s.cols[col_ix(s, row, chunk)]

            for n in 1:s.chunk_len
                s_val = s.vals[val_ix(s, row, chunk, n)]
                s_col = first_col+(n-1)

                for m_col in 1:size(m, 2)
                    vals[m_col] += s_val * m[s_col, m_col]
                end

            end
        end

        out[row, :] = vals
    end

    out

end

# TODO: implement me for real to avoid conversion to CSC
function \(s::SplineSparse, x::Union{AbstractVector,AbstractMatrix})
    sparse(s) \ x
end


text:
module PeriodicDataToolbox
    using NCDatasets
    using SparseArrays
    mutable struct Bundle
        interpolate_mtx :: AbstractArray{Float64, 2}

        fine_time       :: AbstractArray{Float64, 1}
        coarse_time     :: AbstractArray{Float64, 1}

        var_names       :: AbstractArray

        fine_data       :: Dict
        coarse_data     :: Dict
    end

    function readCoarseNCFile(filename, varnames, fine_time, )
        ds = Dataset(filename, "r")

        coarse_data = Dict()
        fine_data   = Dict()

        for varname in varnames
            coarse_data[varname] = nomissing(ds[varname][:], NaN)
            coarse_data[varname]
        end

        close(ds)
    end

    function interpolate!(
        fine_data       :: AbstractArray{Float64, 1},
        coarse_data     :: AbstractArray{Float64, 1},
        interpolate_mtx :: AbstractArray{Float64, 2},
    )

        for i = 1:length(fine_data)
            fine_data[i] = interpolate_mtx[i, 1] * coarse_data[1]
            for j = 2:length(coarse_data)
                fine_data[i] += interpolate_mtx[i, j] * coarse_data[j]
            end
        end

    end

    function genInterpolateMatrix(
        time1 :: AbstractArray{Float64, 1},  # coarse
        time2 :: AbstractArray{Float64, 1},  # fine
        period :: Float64,
    )

        N_ext = length(time1)+2
        time1_ext = zeros(Float64, N_ext)

        time1_ext[1]       = time1[end] - period

        if length(time1) > 1
            time1_ext[2:end-1] = time1[1:end]
        end

        time1_ext[end]     = time1[1] + period

        mtx = spzeros(Float64, length(time2), length(time1))

        if length(time1) == 1
            mtx .= 1.0
            return mtx
        end

        # The algorithm below assume length(time1) > 1
        i_2 = 1
        done = false
        for i = 1:N_ext-1

            ta = time1_ext[i]
            tb = time1_ext[i+1]
            while ta <= time2[i_2] && time2[i_2] < tb
                Δt = tb - ta
                ia = (i   ==     1  ) ? length(time1) : i-1
                ib = (i   == N_ext-1) ? 1             : i

                mtx[i_2, ia] = (tb - time2[i_2]) / Δt
                mtx[i_2, ib] = (time2[i_2] - ta) / Δt

                #println(tb - time2[i_2], "; ", time2[i_2] - ta, "; ", Δt, "; ", ia, " , ", ib)

                if i_2 < length(time2)
                    i_2 += 1
                else
                    done = true
                    break
                end
            end

            if done
                break
            end
        end

        if !done
            throw(ErrorException("Not all element of time2 is within [0, period]"))
        end

        return mtx

    end

end

max_stars_repo_name: meteorologytoday/IOM

max_issues_repo_name: meteorologytoday/IOM

max_forks_repo_name: meteorologytoday/IOM


text:
module HeresChannel

using Genie.WebChannels, Genie.Router

function subscribe()
  WebChannels.subscribe(wsclient(@params), :heres)
  "OK"
end

end

max_stars_repo_name: huaxk/rlservice

max_issues_repo_name: huaxk/rlservice

max_forks_repo_name: huaxk/rlservice


text:
"""
    MetaWeights{InnerMetaGraph<:MetaGraph,U<:Real} <: AbstractMatrix{U}

Matrix-like wrapper for edge weights on a metagraph of type `InnerMetaGraph`.
"""

struct MetaWeights{InnerMetaGraph<:MetaGraph,U<:Real} <: AbstractMatrix{U}
    g::InnerMetaGraph
end

Base.show(io::IO, mv::MetaWeights) = print(io, "MetaWeights of size $(size(mv))")
Base.show(io::IO, ::MIME"text/plain", x::MetaWeights) = show(io, x)

MetaWeights(g::MetaGraph) = MetaWeights{typeof(g),weighttype(g)}(g)

"""
    weigths(g)

Return a matrix-like `MetaWeights` object containing the edge weights for graph `g`.
"""
Graphs.weights(g::MetaGraph) = MetaWeights(g)

function Base.size(w::MetaWeights)
    vertices = nv(w.g)
    return (vertices, vertices)
end

"""
    weighttype(g)

Return the weight type for metagraph `g`.
"""
function weighttype(
    g::MetaGraph{<:Any,<:Any,<:Any,<:Any,<:Any,<:Any,<:Any,Weight}
) where {Weight}
    return Weight
end

"""
    weight_function(g)

Return the weight function for metagraph `g`.
"""
weight_function(g::MetaGraph) = g.weight_function

"""
    default_weight(g)

Return the default weight for metagraph `g`.
"""
default_weight(g::MetaGraph) = g.default_weight

"""
    getindex(w::MetaWeights, v1, v2)

Get the weight of edge `(v1, v2)`.
"""
function Base.getindex(w::MetaWeights, v1::Integer, v2::Integer)
    g = w.g
    if has_edge(g, v1, v2)
        labels = g.vertex_labels
        wf = weight_function(g)
        return wf(g[arrange(g, labels[v1], labels[v2], v1, v2)...])
    else
        dw = default_weight(g)
        return dw
    end
end


text:
export ϵr2nκ!

function ϵr2nκ!(ϵ1::VecIO, ϵ2::VecIO)
    @inbounds for i in eachindex(ϵ1)
        e1 = ϵ1[i]
        e2 = ϵ2[i]
        # modulus
        em = apy2(e1, e2)
        ϵ1[i] = sqrt(0.5 * (em + e1))
        ϵ2[i] = sqrt(0.5 * (em - e1))
    end
end


text:
import Base.Threads.atomic_and!
import Base.Threads.atomic_or!

include("console.jl")
include("apu.jl")
include("cpu.jl")
include("mapper.jl")
include("ppu.jl")

function reset!(console::Console)
  cpureset!(console)
  ppureset!(console.ppu)
end

# Load a game into a new Console instance.
function loadgame(path::String)::Console
  cartridge = fromfile(path)
  mapper = createmapper(cartridge)
  c = createconsole(cartridge, mapper)
  reset!(c)
  c
end

# Single step of emulation: one CPU instruction, three PPU and Mapper cycles
# per CPU cycle, and one APU cycle per CPU cycle. Each component is passed
# seperately because fetching them from console on every call incurs a small
# performance hit.
function step!(console::Console, cpu::CPU, ppu::PPU, apu::APU)::Int32
  cpuCycles = cpustep!(console, cpu)
  ppuCycles = cpuCycles * Int32(3)
  for i = 1:ppuCycles
    ppustep!(console, ppu)
    mapperstep!(console)
  end
  for i = 1:cpuCycles
    apustep!(console, apu)
  end
  cpuCycles
end

step!(console::Console)::Int32 = step!(console, console.cpu, console.ppu, console.apu)

# Execute emulation steps until the next frame.
function stepframe!(console::Console)::Int32
  reset!(console.apu.channel)
  cpuCycles = Int32(0)
  cpu = console.cpu
  ppu = console.ppu
  apu = console.apu
  frame = ppu.frame
  while ppu.frame == frame
    cpuCycles += step!(console, cpu, ppu, apu)
  end
  cpuCycles
end

function stepframes!(console::Console, numFrames::Integer)::Int64
  cpuCycles = Int64(0)
  for i = 1:numFrames
    cpuCycles += Int64(stepframe!(console))
  end
  cpuCycles
end

function stepframes!(console::Console, input::UInt8, numFrames::Integer)::Int64
  setbuttons1!(console, input)
  stepframes!(console, numFrames)
end

function stepframes!(console::Console, inputs::Vector{Tuple{UInt8, UInt8}})::Int64
  cpuCycles = Int64(0)
  for (input, numFrames) in inputs
    cpuCycles += stepframes!(console, input, numFrames)
  end
  cpuCycles
end

# Frame number of the current state.
function framenumber(console::Console)::UInt64
  console.ppu.frame
end

# Current frame, where pixels are represented as palette indices.
function frame(console::Console)::Frame
  copy(console.ppu.front)
end

# Current frame rendered as a screen with palette RGB values.
function screen(console::Console)::Screen
  Screen(console.ppu.front)
end

# Set the input for controller 1.
function setbuttons1!(console::Console, buttons::UInt8)
  console.controller1.buttons[] = buttons
end

# Update the input for controller 1 by adding the indicated button, leaving
# previous inputs set.
function setbutton1!(console::Console, index::UInt8)
  atomic_or!(console.controller1.buttons, 0x01 << index)
end

# Update the input for controller 1 by removing the indicated button, leaving
# previous inputs set.
function removebutton1!(console::Console, index::UInt8)
  atomic_and!(console.controller1.buttons, ~(0x01 << index))
end

# Set the input for controller 2.
function setbuttons2!(console::Console, buttons::UInt8)
  console.controller2.buttons[] = buttons
end

# Update the input for controller 2 by adding the indicated button, leaving
# previous inputs set.
function setbutton2!(console::Console, index::UInt8)
  atomic_or!(console.controller2.buttons, 0x01 << index)
end

# Update the input for controller 2 by removing the indicated button, leaving
# previous inputs set.
function removebutton2!(console::Console, index::UInt8)
  atomic_and!(console.controller1.buttons, ~(0x01 << index))
end

# Update the sample rate for the audio component.
function setaudiosamplesperframe!(console::Console, samplesPerFrame::UInt32)
  setsamplesperframe!(console.apu, samplesPerFrame)
end

# Private functions for performing emulation that need interactions between
# components.

function steptimer!(console::Console, apu::APU)
  if (apu.cycle & 1) == 0
    steptimer!(apu.pulse1)
    steptimer!(apu.pulse2)
    steptimer!(apu.noise)
    steptimer!(apu.dmc, console)
  end
  steptimer!(apu.triangle)
end

function fireirq!(console::Console)
  if console.apu.frameIRQ
    triggerirq!(console.cpu)
  end
end

function steptimer!(dmc::DMC, console::Console)
  if !dmc.enabled
    return
  end
  stepreader!(console)
  if dmc.tickValue == 0
    dmc.tickValue = dmc.tickPeriod
    stepshifter!(dmc)
  else
    dmc.tickValue -= 1
  end
end

function stepreader!(console::Console)
  dmc = console.apu.dmc
  if dmc.currentLength > 0 && dmc.bitCount == 0
    console.cpu.stall += 4
    dmc.shiftRegister = cpuread(console, dmc.currentAddress)
    dmc.bitCount = 8
    dmc.currentAddress += 1
    if dmc.currentAddress == 0
      dmc.currentAddress = 0x8000
    end
    dmc.currentLength -= 1
    if dmc.currentLength == 0 && dmc.loop
      restart!(dmc)
    end
  end
end


text:
using Documenter, BernsteinExpansions

makedocs(
    doctest = true,  # use this flag to skip doctests (saves time!)
    modules = [BernsteinExpansions],
    format = :html,
    assets = ["assets/juliareach.css"],
    sitename = "BernsteinExpansions.jl",
    pages = [
        "Home" => "index.md",
        "Manual" => Any[
        "Bernstein expansion" => "man/bernstein_expansion.md",
        "Benchmarks" => "man/benchmarks.md"],
        "Library" => Any[
        "Implicit Bernstein form" => "lib/implicit_bernstein_form.md",
        "Tensorial Bernstein form" => "lib/tensorial_bernstein_form.md"],
        "About" => "about.md"
    ]
)

deploydocs(
    repo = "github.com/JuliaReach/BernsteinExpansions.jl.git",
    target = "build",
    osname = "linux",
    julia  = "0.6",
    deps = nothing,
    make = nothing
)


text:
##### Beginning of file

module Run # Begin submodule MirrorUpdater.Run

__precompile__(true)

import ArgParse
import Dates
import HTTP
import Pkg
import TimeZones

import ..Types
import ..Utils
import ..Common

import ..process_delayed_error_list

function run_mirror_updater!!(
        ;
        registry_list::Vector{Types.Registry},
        delete_gists_older_than_minutes::Int = 0,
        git_hosting_providers::AbstractVector =
            Any[],
        task::String =
            "all",
        gist_description::String =
            "",
        is_dry_run::Bool =
            false,
        additional_repos::Vector{Types.SrcDestPair} =
            Types.SrcDestPair[],
        do_not_push_to_these_destinations::Vector{String} =
            String[],
        do_not_try_url_list::Vector{String} =
            String[],
        try_but_allow_failures_url_list::Vector{String} =
            String[],
        time_zone::Dates.TimeZone =
            Dates.TimeZone("America/New_York"),
        )::Nothing
    @info("Running MirrorUpdater.Run.run_mirror_updater!!")

    if length(git_hosting_providers) == 0
        delayederror(
            string(
                "You must supply at least one git hosting provider",
                )
            )
    elseif length(git_hosting_providers) == 1
        @info(
            string(
                "I will push to one git hosting provider.",
                ),
            )
    else
        @info(
            string(
                "I will push to $(length(git_hosting_providers)) ",
                "git hosting providers.",
                ),
            )
    end

    has_gist_description::Bool = length(gist_description) > 0

    if task == "all" || task == "make-list"
        @info("Starting stage 1...")
        @info("Making list of repos to mirror...")

        all_repos_to_mirror_stage1::Vector{Types.SrcDestPair} =
            Common._make_list(
                registry_list,
                additional_repos;
                do_not_try_url_list =
                    do_not_try_url_list,
                try_but_allow_failures_url_list =
                    try_but_allow_failures_url_list,
                )
        gist_content_stage1::String = Common._src_dest_pair_list_to_string(
            all_repos_to_mirror_stage1
            )
        @info(
            string(
                "The full list has ",
                "$(length(all_repos_to_mirror_stage1)) ",
                "unique pairs.",
                )
            )
        if has_gist_description
            for p in 1:length(git_hosting_providers)
                @info(
                    string(
                        "Git hosting provider ",
                        "$(p) of $(length(git_hosting_providers))",
                        ),
                    )
                provider = git_hosting_providers[p]
                @info(
                    string(
                        "Creating gist on git hosting provider $(p).",
                        )
                    )
                args = Dict(
                    :gist_description => gist_description,
                    :gist_content => gist_content_stage1,
                    )
                provider(:create_gist)(args)
            end
        end
        @info("SUCCESS: Stage 1 completed successfully.")
    end

    if task == "all" || Types._is_interval(task)
        @info("Starting stage 2...")
        if has_gist_description
            correct_gist_content_stage2::String = ""
            @info("looking for the correct gist")
            args = Dict(
                :gist_description => gist_description,
                )
            for p = 1:length(git_hosting_providers)
                @info(
                    string(
                        "Git hosting provider ",
                        "$(p) of $(length(git_hosting_providers))",
                        ),
                    )
                provider = git_hosting_providers[p]
                if length(correct_gist_content_stage2) == 0
                    @info(
                        string(
                            "Searching git hosting provider $(p) ",
                            "for the correct gist.",
                            )
                        )
                    correct_gist_content_stage2 = try
                        provider(:retrieve_gist)(args)
                    catch exception
                        @warn("Ignored exception", exception,)
                        ""
                    end
                end
            end
            if length(strip(correct_gist_content_stage2)) == 0
                delayederror("I could not find the correct gist on any host")
            end
            all_repos_to_mirror_stage2 =
                Common._string_to_src_dest_pair_list(
                    correct_gist_content_stage2
                    )
        else
            @info("no need to download any gists: I already have the list")
            all_repos_to_mirror_stage2 =
                all_repos_to_mirror_stage1
        end
        @info(
            string(
                "The full list has ",
                "$(length(all_repos_to_mirror_stage2)) ",
                "unique pairs.",
                )
            )
        if Types._is_interval(task)
            task_interval::Types.AbstractInterval =
                Types._construct_interval(task)
            @info(
                string("Using interval for stage 2: "),
                task_interval,
                )
            selected_repos_to_mirror_stage2 =
                Common._pairs_that_fall_in_interval(
                    all_repos_to_mirror_stage2,
                    task_interval,
                    )
        else
            selected_repos_to_mirror_stage2 =
                all_repos_to_mirror_stage2
        end
        @info(
            string(
                "The selected subset of the list ",
                "for this particular job has ",
                "$(length(selected_repos_to_mirror_stage2)) ",
                "unique pairs.",
                )
            )
        Common._push_mirrors!!(
            ;
            src_dest_pairs = selected_repos_to_mirror_stage2,
            git_hosting_providers = git_hosting_providers,
            is_dry_run = is_dry_run,
            do_not_try_url_list =
                do_not_try_url_list,
            try_but_allow_failures_url_list =
                try_but_allow_failures_url_list,
            do_not_push_to_these_destinations =
                do_not_push_to_these_destinations,
            time_zone = time_zone,
            )
        @info("SUCCESS: Stage 2 completed successfully.")
    end

    if task == "all" || task == "clean-up"
        @info("Starting stage 3...")
        if has_gist_description
            args = Dict(
                :gist_description => gist_description
                )
            for p = 1:length(git_hosting_providers)
                @info(
                    string(
                        "Git hosting provider ",
                        "$(p) of $(length(git_hosting_providers))",
                        ),
                    )
                provider = git_hosting_providers[p]
                @info(
                    string(
                        "Deleting gists from git hosting provider $(p) ",
                        "that match the provided ",
                        "gist description.",
                        ),
                    gist_description,
                    )
                try
                    provider(:delete_gists)(args)
                catch exception
                    @warn("ignoring exception: ", exception)
                end
            end
        end

        if delete_gists_older_than_minutes > 0
            time::TimeZones.ZonedDateTime = Dates.now(
                TimeZones.localzone()
                )
            args = Dict(
                :delete_gists_older_than_minutes =>
                    delete_gists_older_than_minutes,
                :time =>
                    time,
                )
            for p = 1:length(git_hosting_providers)
                provider = git_hosting_providers[p]
                @info(
                    string(
                        "Deleting gists from git hosting provider $(p) ",
                        "that are older than the provided ",
                        "age in minutes.",
                        ),
                    delete_gists_older_than_minutes,
                    )
                try
                    provider(:delete_gists_older_than_minutes)(args)
                catch exception
                    @warn("ignoring exception: ", exception)
                end
            end
        end
        @info("SUCCESS: Stage 3 completed successfully.")
    end

    @info(
        string(
            "SUCCESS: run_mirror_updater completed ",
            "successfully :) Good-bye!",
            )
        )

    process_delayed_error_list()
    return nothing
end

end # End submodule MirrorUpdater.Run

##### End of file


text:
struct RandomVariableSelection{TakeObjective} <: AbstractVariableSelection{TakeObjective} end

RandomVariableSelection(;take_objective=true) = RandomVariableSelection{take_objective}()

function (::RandomVariableSelection{false})(cpmodel::CPModel; rng=nothing)
    var_ids = keys(branchable_variables(cpmodel))
    acceptable_ids = String[]
    for id in var_ids
        x = cpmodel.variables[id]
        if !isbound(x) && x !== cpmodel.objective
            push!(acceptable_ids, id)
        end
    end

    if isempty(acceptable_ids)
        return cpmodel.objective
    end

    if !isnothing(rng)
        return cpmodel.variables[acceptable_ids[rand(rng, 1:length(acceptable_ids))]]
    end
    cpmodel.variables[acceptable_ids[rand(1:length(acceptable_ids))]]
end

function (::RandomVariableSelection{true})(cpmodel::CPModel; rng=nothing)
    var_ids = keys(branchable_variables(cpmodel))
    acceptable_ids = String[]
    for id in var_ids
        x = cpmodel.variables[id]
        if !isbound(x)
            push!(acceptable_ids, id)
        end
    end

    if !isnothing(rng)
        return cpmodel.variables[acceptable_ids[rand(rng, 1:length(acceptable_ids))]]
    end
    cpmodel.variables[acceptable_ids[rand(1:length(acceptable_ids))]]
end


text:
# Unit tests for judiRHS and judiWavefield (without PDE solves)
# Philipp Witte (pwitte.slim@gmail.com)
# May 2018
#
# Mathias Louboutin, mlouboutin3@gatech.edu
# Updated July 2020

########################################################### judiRHS ####################################################

@testset "judiRHS Unit Tests with $(nsrc) sources" for nsrc=[1, 2]

    # Constructor
    info = example_info(nsrc=nsrc)
    rec_geometry = example_rec_geometry(nsrc=nsrc)
    data = Array{Array}(undef, nsrc)
    for j=1:nsrc
        data[j] = randn(Float32, rec_geometry.nt[j], length(rec_geometry.xloc[j]))
    end
    datacell = process_input_data(vec(hcat(data...)), rec_geometry, info)
    @test isequal(datacell, data)

    rhs = judiRHS(info, rec_geometry, data)
    Pr = judiProjection(info, rec_geometry)

    @test isequal(typeof(rhs), judiRHS{Float32})
    @test isequal(rhs.geometry, rec_geometry)

    rhs2 = Pr'*vec(hcat(data...))
    @test isequal(typeof(rhs2), judiRHS{Float32})
    @test isequal(rhs2.geometry, rec_geometry)
    @test isequal(rhs2.geometry, rhs.geometry)
    @test isequal(rhs2.data, rhs.data)

    # conj, transpose, adjoint
    @test isequal(size(rhs), size(conj(rhs)))
    @test isequal(reverse(size(rhs)), size(transpose(rhs)))
    @test isequal(reverse(size(rhs)), size(adjoint(rhs)))

    # +, -
    info = example_info(nsrc=nsrc)
    rec_geometry = example_rec_geometry(nsrc=nsrc)
    src_geometry = example_src_geometry(nsrc=nsrc)
    data1 = Array{Array}(undef, nsrc)
    data2 = Array{Array}(undef, nsrc)
    for j=1:nsrc
        data1[j] = randn(Float32, rec_geometry.nt[j], length(rec_geometry.xloc[j]))
        data2[j] = randn(Float32, src_geometry.nt[j], length(src_geometry.xloc[j]))
    end
    rhs1 = judiRHS(info, rec_geometry, data1)
    rhs2 = judiRHS(info, src_geometry, data2)

    rhs_sum = rhs1 + rhs2
    rhs_sub = rhs1 - rhs2

    @test isequal(size(rhs_sum), size(rhs1))
    @test isequal(size(rhs_sub), size(rhs1))

    @test isequal(length(rhs_sum.geometry.xloc[1]), length(rhs1.geometry.xloc[1]) + length(rhs2.geometry.xloc[1]))
    @test isequal(length(rhs_sub.geometry.xloc[1]), length(rhs1.geometry.xloc[1]) + length(rhs2.geometry.xloc[1]))

    @test isequal(size(rhs_sum.data[1])[2], size(rhs1.data[1])[2] + size(rhs2.data[1])[2])
    @test isequal(size(rhs_sub.data[1])[2], size(rhs1.data[1])[2] + size(rhs2.data[1])[2])

    # get index
    rhs_sub = rhs[1]
    @test isequal(rhs_sub.info.nsrc, 1)
    @test isequal(typeof(rhs_sub.geometry), GeometryIC{Float32})
    @test isequal(typeof(rhs.data), Array{Array, 1})
    @test isequal(length(rhs_sub), Int(length(rhs)/nsrc))

    inds = nsrc > 1 ? (1:nsrc) : 1
    rhs_sub = rhs[inds]
    @test isequal(rhs_sub.info.nsrc, nsrc)
    @test isequal(typeof(rhs_sub.geometry), GeometryIC{Float32})
    @test isequal(typeof(rhs.data), Array{Array, 1})
    @test isequal(length(rhs_sub), length(rhs))

end

max_stars_repo_name: nogueirapeterson/JUDI

max_issues_repo_name: nogueirapeterson/JUDI

max_forks_repo_name: nogueirapeterson/JUDI


text:
struct CartesianVIndex{N,T} <: Base.AbstractCartesianIndex{N}
    I::T
    @inline CartesianVIndex(I::T) where {N, T <: Tuple{Vararg{Integer,N}}} = new{N,T}(I)
end
Base.length(::CartesianVIndex{N}) where {N} = N
ArrayInterface.known_length(::Type{<:CartesianVIndex{N}}) where {N} = N
Base.Tuple(i::CartesianVIndex) = i.I
function Base.:(:)(I::CartesianVIndex{N}, J::CartesianVIndex{N}) where {N}
   CartesianIndices(map((i,j) -> i:j, I.I, J.I))
end
Base.@propagate_inbounds Base.getindex(I::CartesianVIndex, i) = I.I[i]
_ndim(::Type{<:Base.AbstractCartesianIndex{N}}) where {N} = N
# _ndim(::Type{<:AbstractArray{N}}) where {N} = N
@generated function CartesianVIndex(I::T) where {T <: Tuple{Vararg{Union{Integer,CartesianIndex,CartesianVIndex}}}}
    iexpr = Expr(:tuple)
    Tp = T.parameters
    q = Expr(:block)
    for i in eachindex(Tp)
        I_i = Symbol(:I_, i)
        push!(q.args, Expr(:(=), I_i, Expr(:ref, :I, i)))
        if Tp[i] <: Base.AbstractCartesianIndex
            for n in 1:_ndim(Tp[i])
                push!(iexpr.args, Expr(:ref, I_i, n))
            end
        else
            push!(iexpr.args, I_i)
        end
    end
    push!(q.args, Expr(:call, :CartesianVIndex, iexpr))
    Expr(:block, Expr(:meta, :inline), Expr(:macrocall, Symbol("@inbounds"), LineNumberNode(@__LINE__, Symbol(@__FILE__)), q))
end

# @inline Base.CartesianIndex(I::Tuple{Vararg{Union{Integer,CartesianIndex,CartesianVIndex,StaticInt}}}) = CartesianVIndex(I)

@generated function _maybestaticfirst(a::Tuple{Vararg{Any,N}}) where {N}
    quote
        $(Expr(:meta,:inline))
        Base.Cartesian.@ntuple $N n -> maybestaticfirst(a[n])
    end
end
@generated function _maybestaticlast(a::Tuple{Vararg{Any,N}}) where {N}
    quote
        $(Expr(:meta,:inline))
        Base.Cartesian.@ntuple $N n -> maybestaticlast(a[n])
    end
end
@inline maybestaticfirst(A::CartesianIndices) = CartesianVIndex(_maybestaticfirst(A.indices))
@inline maybestaticlast(A::CartesianIndices) = CartesianVIndex(_maybestaticlast(A.indices))


text:
using Documenter, QuasiMonteCarlo

include("pages.jl")

makedocs(
    sitename="QuasiMonteCarlo.jl",
    authors="Chris Rackauckas",
    modules=[QuasiMonteCarlo],
    clean=true,doctest=false,
    format = Documenter.HTML(analytics = "UA-90474609-3",
                             assets = ["assets/favicon.ico"],
                             canonical="https://quasimontecarlo.sciml.ai/stable/"),
    pages=pages
)

deploydocs(
   repo = "github.com/SciML/QuasiMonteCarlo.jl.git";
   push_preview = true
)


text:
@testset "Norm" begin
    n = 1_000
    ν = 1.2
    p = 2.7

    a_geo = Sequence(Taylor(n), [inv(ν^abs(i)) for i ∈ 0:n])
    a_alg = Sequence(Taylor(n), [inv((1.0 + abs(i))^p) for i ∈ 0:n])
    @test rate(geometricweights(a_geo)) ≈ ν
    @test rate(algebraicweights(a_alg)) ≈ p
    @test norm(a_geo, Weightedℓ¹Norm(GeometricWeights(ν))) ≈
        opnorm(project(Multiplication(a_geo), space(a_geo), space(a_geo), Float64), Weightedℓ¹Norm(GeometricWeights(ν))) ≈
        n+1
    @test norm(a_alg, Weightedℓ¹Norm(AlgebraicWeights(p))) ≈
        opnorm(project(Multiplication(a_alg), space(a_alg), space(a_alg), Float64), Weightedℓ¹Norm(AlgebraicWeights(p))) ≈
        n+1

    a_geo = Sequence(Fourier(n, 1.), [inv(ν^abs(i)) for i ∈ -n:n])
    a_alg = Sequence(Fourier(n, 1.), [inv((1.0 + abs(i))^p) for i ∈ -n:n])
    @test rate(geometricweights(a_geo)) ≈ ν
    @test rate(algebraicweights(a_alg)) ≈ p
    @test norm(a_geo, Weightedℓ¹Norm(GeometricWeights(ν))) ≈
        opnorm(project(Multiplication(a_geo), space(a_geo), space(a_geo), Float64), Weightedℓ¹Norm(GeometricWeights(ν))) ≈
        2n+1
    @test norm(a_alg, Weightedℓ¹Norm(AlgebraicWeights(p))) ≈
        opnorm(project(Multiplication(a_alg), space(a_alg), space(a_alg), Float64), Weightedℓ¹Norm(AlgebraicWeights(p))) ≈
        2n+1

    a_geo = Sequence(Chebyshev(n), [inv(ν^abs(i)) for i ∈ 0:n])
    a_alg = Sequence(Chebyshev(n), [inv((1.0 + abs(i))^p) for i ∈ 0:n])
    @test rate(geometricweights(a_geo)) ≈ ν
    @test rate(algebraicweights(a_alg)) ≈ p
    @test norm(a_geo, Weightedℓ¹Norm(GeometricWeights(ν))) ≈ n+1 ≤
        opnorm(project(Multiplication(a_geo), space(a_geo), space(a_geo), Float64), Weightedℓ¹Norm(GeometricWeights(ν)))
    @test norm(a_alg, Weightedℓ¹Norm(AlgebraicWeights(p))) ≈ n+1 ≤
        opnorm(project(Multiplication(a_alg), space(a_alg), space(a_alg), Float64), Weightedℓ¹Norm(AlgebraicWeights(p)))

    a_geo = Sequence(Taylor(10) ⊗ Fourier(10, 1.) ⊗ Chebyshev(10),
        vec([inv(ν^abs(α[1]) * ν^abs(α[2]) * ν^abs(α[3])) for α ∈ indices(Taylor(10) ⊗ Fourier(10, 1.) ⊗ Chebyshev(10))]))
    a_alg = Sequence(Taylor(10) ⊗ Fourier(10, 1.) ⊗ Chebyshev(10),
        vec([inv((1.0 + abs(α[1]))^p * (1.0 + abs(α[2]))^p * (1.0 + abs(α[3]))^p) for α ∈ indices(Taylor(10) ⊗ Fourier(10, 1.) ⊗ Chebyshev(10))]))
    @test all( rate.(geometricweights(a_geo)) .≈ (ν, ν, ν) )
    @test all( rate.(algebraicweights(a_alg)) .≈ (p, p, p) )
    @test norm(a_geo, Weightedℓ¹Norm( (GeometricWeights(ν), GeometricWeights(ν), GeometricWeights(ν)) )) ≈ length(a_geo) ≤
        opnorm(project(Multiplication(a_geo), space(a_geo), space(a_geo), Float64), Weightedℓ¹Norm( (GeometricWeights(ν), GeometricWeights(ν), GeometricWeights(ν)) ))
    @test norm(a_alg, Weightedℓ¹Norm( (AlgebraicWeights(p), AlgebraicWeights(p), AlgebraicWeights(p)) )) ≈ length(a_alg) ≤
        opnorm(project(Multiplication(a_alg), space(a_alg), space(a_alg), Float64), Weightedℓ¹Norm( (AlgebraicWeights(p), AlgebraicWeights(p), AlgebraicWeights(p)) ))

    s1 = ParameterSpace() × (Taylor(1) ⊗ Fourier(1, 1.0) ⊗ Chebyshev(1))^1
    s2 = ParameterSpace() × (Taylor(2) ⊗ Fourier(0, 1.0) ⊗ Chebyshev(1))^1
    a_ = Sequence(s1, collect(1.0:13.0))
    A_ = LinearOperator(s1, s2, ones(dimension(s2), dimension(s1)))

    metric = CartesianProductNorm((ℓᵖNorm(Inf), CartesianPowerNorm(Weightedℓ¹Norm((GeometricWeights(1.0), GeometricWeights(1.0), GeometricWeights(1.0))), ℓᵖNorm(Inf))), ℓᵖNorm(Inf))

    @test norm(a_, metric) == sum(2.0:13.0)
    @test opnorm(A_, metric, metric) == 12.0
end


text:
using Base.Test

@test 1 == 1


text:
module GraphBlasAlgorithmsFinal

end # module


text:
"""シミュレーション"""

using LinearAlgebra  # 逆行列とノルムの計算に使用
using Plots  # グラフ作成
#using ProgressBars
#using Parameters
using DifferentialEquations  # 微分方程式のソルバ
using LaTeXStrings
using ProgressBars

include("utils.jl")
include("kinematics.jl")
include("differential_kinematics.jl")
#include("controller.jl")
#include("plot_utils.jl")

using .Kinematics
using .DifferentialKinematics
#using .PlotTool
#using .Controller

const sec_n = 3

const R = 0.15
const ω = 0.1
const offset_z = 0.45

"""適当な目標位置変位"""
function calc_xd(t::T) where T
    # [
    #     R * sin(ω*t),
    #     R * cos(ω*t),
    #     offset_z,
    # ]
    # [
    #     0.2cos(ω*2*t)*cos(ω*t)
    #     0.2cos(ω*2*t)*sin(ω*t)
    #     offset_z
    # ]
    Phi_2([0.01, -0.02, 0, 0.02, 0, 0, 0.0, 0.02, 0.01], 1.0)
end

"""適当な目標位置速度"""
function calc_xd_dot(t::T) where T
    [
        R * 3cos(3t),
        R * -3sin(3t),
        0,
    ]
end

"""適当な目標位置加速度"""
function calc_xd_dot_dot(t::T) where T
    [
        R * -9sin(3t),
        R * -9cos(3t),
        0,
    ]
end

"""ソフトマックス関数"""
function soft_max(s::T, α::T) where T
    s + 1/α * log(1 + exp(-2 * α * s))
end

"""ソフト正規化関数"""
function soft_normal(v, alpha)
    return v ./ soft_max(norm(v), alpha)
end

"""空間を一方向に伸ばす計量"""
function metric_stretch(v, alpha)
    xi = soft_normal(v, alpha)
    return xi * xi'
end

"""基本の計量"""
function basic_metric_H(f::Vector{T}, alpha::T, beta::T) where T
    dim = length(f)
    return beta .* metric_stretch(f, alpha) + (1 - beta) .* Matrix{T}(I, dim, dim)
end

function pullbacked_rmp(f, M, J)
    pulled_f = J' * f
    pulled_M = J' * M * J
    return pulled_f, pulled_M
end

global error = [0.0, 0.0, 0.0]

function state_eq!(
    X_dot::Vector{T}, X::Vector{T},
    p,
    t::T
    ) where T
    X_dot[1:9] = X[10:18]
    #println("t = ", t)
    J = J_2(X[1:9], 1.0, sec_n)

    #println(pinv(J))
    #println(J*X[10:18])
    # A = pinv(J) * calc_xd_dot_dot(t)
    # B = pinv(J) * (-p.D*(J*X[10:18] .- calc_xd_dot(t)))
    # C = pinv(J) * (-p.K*(Phi_2(X[1:9], 1.0) - calc_xd(t)))
    # X_dot[10:18] =  A .+ B .+ C
    # println("A = ", norm(A))
    # println("B = ", norm(B))
    #println("C = ", norm(C))

    # 目標制御
    gain = 300.0
    max_speed = 10.0
    sigma_H = 1.0
    sigma_W = 1.0
    damp_r = 0.01
    ddq_damp_r = 0.05

    z0 = calc_xd(t)
    z = Phi_2(X[1:9], 1.0)
    dz = J * X[10:18]
    damp = gain / max_speed
    a = gain .* soft_normal(z0.-z, damp_r) .- damp*dz# .- 0.05*error

    dis = norm(z0 .- z)

    #global error += (z0 .- z)

    weight = exp(-dis ./ sigma_W)
    beta = 1.0 - exp(-1/2 * (dis / sigma_H)^2)
    M = weight .* basic_metric_H(a, ddq_damp_r, beta)

    pulled_f, pulled_M = pullbacked_rmp(M*a, M, J)
    root_f = pulled_f
    root_M = pulled_M

    # ジョイント制限回避
    gamma_p = 5.0
    gamma_d = 1.0
    lambda = 1.0
    q = X[1:9]
    dq = X[10:18]

    q_max = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
    q_min = -[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
    diags = (q_max .- q_min) .* (exp.(-q) ./ (1.0 .+ exp.(-q)).^2)
    D_sigma =  diagm(diags)

    z = gamma_p .* (-q) .- gamma_d .* dq
    ajl = inv(D_sigma) * z
    Mjl = lambda .* Matrix{T}(I, 9, 9)

    #println(root_f)
    #println(M*a)
    root_f += Mjl*ajl
    @. root_M += Mjl

    ddq = pinv(root_M) * root_f

    X_dot[10:18] = ddq

end

"""1フレームを描写"""
function draw_frame(
    t::T, q::Vector{T}, xd::Union{Vector{T}, Nothing},
    fig_shape::Union{
        NamedTuple{(:xl, :xu, :yl, :yu, :zl, :zu), Tuple{T, T, T, T, T, T}},
        Nothing
    }
    ) where T

    fig = plot()
    arm = Vector{Vector{T}}(undef, length(Ξ))
    for (i, ξ) in enumerate(Ξ)
        arm[i] = Phi_0(q, ξ)
    end
    x, y, z = split_vec_of_arrays(arm)
    plot!(
        fig,
        x, y, z,
        #marker=:circle,
        aspect_ratio = 1,
        #markersize=2,
        label="1",
        xlabel = "X[m]", ylabel = "Y[m]", zlabel = "Z[m]",
    )

    arm = Vector{Vector{T}}(undef, length(Ξ))
    for (i, ξ) in enumerate(Ξ)
        arm[i] = Phi_1(q, ξ)
    end
    x, y, z = split_vec_of_arrays(arm)
    plot!(
        fig,
        x, y, z,
        #marker=:circle,
        aspect_ratio = 1,
        #markersize=2,
        label="2",
        xlabel = "X[m]", ylabel = "Y[m]", zlabel = "Z[m]",
    )

    arm = Vector{Vector{T}}(undef, length(Ξ))
    for (i, ξ) in enumerate(Ξ)
        arm[i] = Phi_2(q, ξ)
    end
    x, y, z = split_vec_of_arrays(arm)
    plot!(
        fig,
        x, y, z,
        #marker=:circle,
        aspect_ratio = 1,
        #markersize=2,
        label="3",
        xlabel = "X[m]", ylabel = "Y[m]", zlabel = "Z[m]",
    )

    if !isnothing(xd)
        scatter!(
            fig,
            [xd[1]], [xd[2]], [xd[3]],
            label="xd",
            markershape=:star6,
        )
    end

    # scatter!(
    #     fig,
    #     [xd[1]], [xd[2]],
    #     label="xd_true",
    #     markershape=:star6,
    # )

    plot!(
        fig,
        xlims=(fig_shape.xl, fig_shape.xu),
        ylims=(fig_shape.yl, fig_shape.yu),
        zlims=(fig_shape.zl, fig_shape.zu),
        legend = true,
        size=(600, 600),
        title = string(round(t, digits=2)) * "[s]"
    )

    return fig
end

# fig = draw_frame(
#     0.0,
#     [
#         0.0, 0.0, 0.0,
#         0.0, 0.0, 0.00,
#         0.0, 0.15, 0.1
#     ], nothing, nothing)

"""アニメ作成"""
function make_animation(sol, xd_func)
    println("アニメ作成中...")
    # 枚数決める
    #println(data.t)
    epoch_max = 100
    epoch = length(sol.t)
    if epoch < epoch_max
        step = 1
    else
        step = div(epoch, epoch_max)
    end

    #println(step)

    x_max = 0.2
    x_min = -0.2
    y_max = 0.2
    y_min = -0.2
    z_max = 0.55
    z_min = 0.0
    max_range = max(x_max-x_min, y_max-y_min, z_max-z_min)*0.5
    x_mid = (x_max + x_min) / 2
    y_mid = (y_max + y_min) / 2
    z_mid = (z_max + z_min) / 2
    fig_shape = (
        xl = x_mid-max_range, xu = x_mid+max_range,
        yl = y_mid-max_range, yu = y_mid+max_range,
        zl = z_mid-max_range, zu = z_mid+max_range,
    )

    xd_all = [xd_func(t) for t in sol.t]
    x, y, z = split_vec_of_arrays(xd_all)

    anim = Animation()
    @gif for i in tqdm(1:step:length(sol.t))
        _fig = draw_frame(sol.t[i], sol.u[i], xd_func(sol.t[i]), fig_shape)
        plot!(_fig, x, y, z, label="xd line",)
        frame(anim, _fig)
    end

    gif(anim, "julianasi.gif", fps = 60)

    println("アニメ作成完了")
end

"""微分方程式を解く"""
function run_simulation(
    TIME_SPAN::T
    ) where T

    #X₀ = zeros(T, 18)
    X₀ = [
        0, 0, 0,
        0, 0, 0,
        0.01, 0, 0,
        0, 0, 0,
        0, 0, 0,
        0, 0, 0
    ]
    t_span = (0.0, TIME_SPAN)
    p = (
        K = Matrix{T}(I, 3, 3)*0.1,
        D = Matrix{T}(I, 3, 3)*1,
    )
    prob = ODEProblem(state_eq!, X₀, t_span, p)
    solve(prob)#, tstops=[10000])
end

"""実行"""
function exmample()

    TIME_SPAN = 80.0

    fig0 = plot(xlims=(0.0, TIME_SPAN),) #ylims=(0,0.02))

    fig1 = plot(xlims=(0.0, TIME_SPAN))
    fig2 = plot(xlims=(0.0, TIME_SPAN))

    @time sol = run_simulation(TIME_SPAN)

    error = Vector{Vector{Float64}}(undef, length(sol.t))
    for (i, t) in enumerate(sol.t)
        error[i] = calc_xd(t) .- Phi_2(sol.u[i][1:9], 1.)
    end
    L2_error = norm.(error)
    plot!(
        fig0,
        sol.t, L2_error,
        label="err",
        legend=:outerright,
        #c=param.color,
        ylabel="error [m]",
        ylims=(0.0, maximum(L2_error))
    )

    plot!(
        fig1,
        sol, vars=[(0,1), (0,2), (0,3), (0,4), (0,5), (0,6), (0,7), (0,8), (0,9)],
        label=["l1_1" "l1_2" "l1_3" "l2_1" "l2_2" "l2_3" "l3_1" "l3_2" "l3_3"],
        legend=:outerright,
        #c=param.color,
        #linestyle=[:solid :dash :dot],
        ylabel="l [m]"
    )
    plot!(
        fig2,
        sol, vars=[(0,10), (0,11), (0,12), (0,13), (0,14), (0,15), (0,16), (0,17), (0,18)],
        label=["l1_1" "l1_2" "l1_3" "l2_1" "l2_2" "l2_3" "l3_1" "l3_2" "l3_3"],
        legend=:outerright,
        #c=param.color,
        #linestyle=[:solid :dash :dot],
        ylabel="l_dot  [m/s]"
    )

    fig_I = plot(
        fig0, fig1, fig2,
        layout=(3,1), size=(800, 1600),
        margin = 1.2Plots.cm,
    )
    savefig(fig_I, "sol.png")

    println(length(sol.t))
    println("done!")
    make_animation(sol, calc_xd)
    sol
end

@time sol = exmample();


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

struct VirtualMachineScaleSetVMsApi <: SwaggerApi
    client::Swagger.Client
end

"""

Deallocates a specific virtual machine in a VM scale set. Shuts down the virtual machine and releases the compute resources it uses. You are not billed for the compute resources of this virtual machine once it is deallocated.
Param: resourceGroupName::String (required)
Param: vmScaleSetName::String (required)
Param: instanceId::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: OperationStatusResponse
"""
function virtualMachineScaleSetVMsDeallocate(_api::VirtualMachineScaleSetVMsApi, resourceGroupName::String, vmScaleSetName::String, instanceId::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", OperationStatusResponse, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/deallocate", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmScaleSetName", vmScaleSetName)  # type String
    Swagger.set_param(_ctx.path, "instanceId", instanceId)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Deletes a virtual machine from a VM scale set.
Param: resourceGroupName::String (required)
Param: vmScaleSetName::String (required)
Param: instanceId::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: OperationStatusResponse
"""
function virtualMachineScaleSetVMsDelete(_api::VirtualMachineScaleSetVMsApi, resourceGroupName::String, vmScaleSetName::String, instanceId::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", OperationStatusResponse, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmScaleSetName", vmScaleSetName)  # type String
    Swagger.set_param(_ctx.path, "instanceId", instanceId)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Gets a virtual machine from a VM scale set.
Param: resourceGroupName::String (required)
Param: vmScaleSetName::String (required)
Param: instanceId::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachineScaleSetVM
"""
function virtualMachineScaleSetVMsGet(_api::VirtualMachineScaleSetVMsApi, resourceGroupName::String, vmScaleSetName::String, instanceId::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualMachineScaleSetVM, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmScaleSetName", vmScaleSetName)  # type String
    Swagger.set_param(_ctx.path, "instanceId", instanceId)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Gets the status of a virtual machine from a VM scale set.
Param: resourceGroupName::String (required)
Param: vmScaleSetName::String (required)
Param: instanceId::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachineScaleSetVMInstanceView
"""
function virtualMachineScaleSetVMsGetInstanceView(_api::VirtualMachineScaleSetVMsApi, resourceGroupName::String, vmScaleSetName::String, instanceId::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualMachineScaleSetVMInstanceView, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/instanceView", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmScaleSetName", vmScaleSetName)  # type String
    Swagger.set_param(_ctx.path, "instanceId", instanceId)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Gets a list of all virtual machines in a VM scale sets.
Param: resourceGroupName::String (required)
Param: virtualMachineScaleSetName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Param: filter::String
Param: select::String
Param: expand::String
Return: VirtualMachineScaleSetVMListResult
"""
function virtualMachineScaleSetVMsList(_api::VirtualMachineScaleSetVMsApi, resourceGroupName::String, virtualMachineScaleSetName::String, api_version::String, subscriptionId::String; filter=nothing, select=nothing, expand=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualMachineScaleSetVMListResult, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "virtualMachineScaleSetName", virtualMachineScaleSetName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "\$filter", filter)  # type String
    Swagger.set_param(_ctx.query, "\$select", select)  # type String
    Swagger.set_param(_ctx.query, "\$expand", expand)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Power off (stop) a virtual machine in a VM scale set. Note that resources are still attached and you are getting charged for the resources. Instead, use deallocate to release resources and avoid charges.
Param: resourceGroupName::String (required)
Param: vmScaleSetName::String (required)
Param: instanceId::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: OperationStatusResponse
"""
function virtualMachineScaleSetVMsPowerOff(_api::VirtualMachineScaleSetVMsApi, resourceGroupName::String, vmScaleSetName::String, instanceId::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", OperationStatusResponse, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/poweroff", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmScaleSetName", vmScaleSetName)  # type String
    Swagger.set_param(_ctx.path, "instanceId", instanceId)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Reimages (upgrade the operating system) a specific virtual machine in a VM scale set.
Param: resourceGroupName::String (required)
Param: vmScaleSetName::String (required)
Param: instanceId::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: OperationStatusResponse
"""
function virtualMachineScaleSetVMsReimage(_api::VirtualMachineScaleSetVMsApi, resourceGroupName::String, vmScaleSetName::String, instanceId::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", OperationStatusResponse, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimage", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmScaleSetName", vmScaleSetName)  # type String
    Swagger.set_param(_ctx.path, "instanceId", instanceId)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Allows you to re-image all the disks ( including data disks ) in the a VM scale set instance. This operation is only supported for managed disks.
Param: resourceGroupName::String (required)
Param: vmScaleSetName::String (required)
Param: instanceId::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: OperationStatusResponse
"""
function virtualMachineScaleSetVMsReimageAll(_api::VirtualMachineScaleSetVMsApi, resourceGroupName::String, vmScaleSetName::String, instanceId::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", OperationStatusResponse, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimageall", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmScaleSetName", vmScaleSetName)  # type String
    Swagger.set_param(_ctx.path, "instanceId", instanceId)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Restarts a virtual machine in a VM scale set.
Param: resourceGroupName::String (required)
Param: vmScaleSetName::String (required)
Param: instanceId::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: OperationStatusResponse
"""
function virtualMachineScaleSetVMsRestart(_api::VirtualMachineScaleSetVMsApi, resourceGroupName::String, vmScaleSetName::String, instanceId::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", OperationStatusResponse, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/restart", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmScaleSetName", vmScaleSetName)  # type String
    Swagger.set_param(_ctx.path, "instanceId", instanceId)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

Starts a virtual machine in a VM scale set.
Param: resourceGroupName::String (required)
Param: vmScaleSetName::String (required)
Param: instanceId::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: OperationStatusResponse
"""
function virtualMachineScaleSetVMsStart(_api::VirtualMachineScaleSetVMsApi, resourceGroupName::String, vmScaleSetName::String, instanceId::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", OperationStatusResponse, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/start", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmScaleSetName", vmScaleSetName)  # type String
    Swagger.set_param(_ctx.path, "instanceId", instanceId)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

export virtualMachineScaleSetVMsDeallocate, virtualMachineScaleSetVMsDelete, virtualMachineScaleSetVMsGet, virtualMachineScaleSetVMsGetInstanceView, virtualMachineScaleSetVMsList, virtualMachineScaleSetVMsPowerOff, virtualMachineScaleSetVMsReimage, virtualMachineScaleSetVMsReimageAll, virtualMachineScaleSetVMsRestart, virtualMachineScaleSetVMsStart