text:
Base.@kwdef mutable struct PublisherFlags
    "Is the publisher currently sending data"
    has_published::Bool = false

    "Did the publisher exit with an error"
    diderror::Bool = false

    "# Of bytes of last message sent"
    bytespublished::Int64 = 0
end

abstract type Publisher end

Base.isopen(sub::Publisher)::Nothing =
    error("The `isopen` method hasn't been implemented for your Publisher yet!")
Base.close(sub::Publisher)::Nothing =
    error("The `close` method hasn't been implemented for your Publisher yet!")
@inline getname(pub::Publisher)::String = pub.name
@inline getflags(pub::Publisher)::PublisherFlags = pub.flags
portstring(sub::Publisher)::String =
    error("The `portstring` method hasn't been implemented for your Publisher yet!")

"""
Write out the byte data into the message container buf. Returns the number of bytes written
"""
function encode!(buf::ProtoBuf.ProtoType, bin_data::IOBuffer)
    bytes_written = ProtoBuf.writeproto(bin_data, buf)

    return bytes_written
end

function encode!(buf::AbstractVector{UInt8}, bin_data::IOBuffer)
    bytes_written = min(length(buf), bin_data.size)
    copyto!(bin_data.data, 1, buf, 1, bytes_written)

    return bytes_written
end

function publish(pub::Publisher, msg::MercuryMessage)::Nothing
    throw(
        MercuryException(
            "The `publish` method hasn't been implemented for your Publisher yet!",
        ),
    )
end

"""
Specifies a publisher along with specific message type.
This is useful for tracking multiple messages at once
"""
struct PublishedMessage
    msg::MercuryMessage
    pub::Publisher
    name::String
    function PublishedMessage(msg::MercuryMessage, pub::Publisher; name = getname(pub))
        new(msg, pub, name)
    end
end
@inline publish(pubmsg::PublishedMessage) = publish(pubmsg.pub, pubmsg.msg)
@inline getname(pubmsg::PublishedMessage) = pubmsg.name
@inline getcomtype(pub::PublishedMessage) = getcomtype(pub.pub)

# TODO: add a `close` method and modify the constructor to automatically create a subscriber

function printstatus(pub::PublishedMessage; indent = 0)
    prefix = " "^indent
    println(prefix, "Publisher: ", getname(pub))
    println(prefix, "  Type: ", getcomtype(pub))
    println(prefix, "  Message Type: ", typeof(pub.msg))
    println(prefix, "  Has published? ", getflags(pub.pub).has_published[])
    println(prefix, "  Is Open? ", isopen(pub.pub))
end


text:
using DBI
using PostgreSQL
using Base.Test

include("testutils.jl")

include("connection.jl")
include("dbi_impl.jl")
include("data.jl")
include("postgres.jl")
include("dataframes_impl.jl")

ext: jl

max_stars_repo_name: beffaCo/updatePostgresql

max_forks_repo_name: beffaCo/updatePostgresql


text:
"""

Get the number of chains from a CmdStanModels object.

$(SIGNATURES)

# Extended help

Used to retrieve the current setting for number of chains as an `Int` number.
"""
function get_n_chains(model::T) where {T <: CmdStanModels}
  model.n_chains[1]
end

"""

Set the number of chains in a CmdStanModels object.

$(SIGNATURES)

# Extended help

Used to update the current setting for the number of chains ('n_chains[1]'). In the model
n_chains is defined as a Vector with a single element to allow this update when calling
`stan_sample()` and other methods.
"""
function set_n_chains(model::T, n_chains) where {T <: CmdStanModels}
  model.n_chains[1] = n_chains
end


text:
workspace()

using EAGOSmoothMcCormickGrad
using IntervalArithmetic
using StaticArrays

# create seed gradient
a = seed_g(Float64,1,2)
b = seed_g(Float64,2,2)
# create SmoothMcCormick seed object for x1 = 2.0 on [1.0,3.0] for relaxing
# a function f(x1,x2) on the interval box xIbox using mBox as a reference point
x = 2.0
xIntv1 = Interval(1.0,3.0)
xIBox = [xIntv1;xIntv1]
mBox = mid.(xIBox)
SMCg = SMCg{2,Float64}(x,x,a,a,xIntv1,false,xIBox,mBox)

# resets gradient to seed gradient with seed at j=2
grad(SMCg,2)
println("convex gradient: ", SMCg.cv_grad)
println("concave gradient: ", SMCg.cc_grad)

# sets gradients to zero
zgrad(SMCg)
println("convex gradient: ", SMCg.cv_grad)
println("concave gradient: ", SMCg.cc_grad)

# checks that mid3 returns midpoint
mid_return = mid3(9.0,-3.0,5.0)

# checks that mid_grad is working
mg_return1 = mid_grad(a, b, 1)
mg_return2 = mid_grad(a, b, 2)
mg_return3 = mid_grad(a, b, 3)

# generates line segment value and derivative
y0 = line_seg(2,1,0,6,10)
dy0 = dline_seg(2,1,0,6,10)

# converts float/integer to SMCg
promoted1 = promote_rule(EAGOSmoothMcCormickGrad.SMCg{3,Float64}, Int64)
promoted2 = promote_rule(EAGOSmoothMcCormickGrad.SMCg{3,Int64}, Float64)
promoted3 = promote_rule(EAGOSmoothMcCormickGrad.SMCg{3,Float64}, Interval{Float64})
promoted4 = promote_rule(EAGOSmoothMcCormickGrad.SMCg{3,Float64}, Real)

conv_float = convert(EAGOSmoothMcCormickGrad.SMCg{3,Float64},1.0)
conv_int = convert(EAGOSmoothMcCormickGrad.SMCg{3,Float64},3)

# test subgradient refinement
Intv1 = tighten_subgrad(2.0,1.0,b,b,Interval(-100.0,100.0),[Interval(-1.0,1.0)],[0.0])
Intv2 = tighten_subgrad(2.0,1.0,b,b,Interval(-100.0,100.0),[∅],[0.0])

# tests outer rounding
rnd_chk = Interval(-1.0,1.0)
rnd_chk_out = outer_rnd(rnd_chk)


text:
# # Example
# Lets try to find a sparse representation for a matrix, so that the Frobeniusnorm of the difference
# is as small as possible.
# Lets consider a symmetric matrix $M$:
using SubspacePreservingSparsification
using SparseArrays
using LinearAlgebra
M = [17.05 16.98 0.3 6.99 7; 16.98 0.2 7.1 6.9 0; 0.3 7.1 -12 0.01 17; 6.99 6.9 0.01 -11.97 0; 7 0 17 0 -0.1]

# First we calculate a sparsity pattern:
M_id = sparsity_pattern(M, 0.6, 2)
# For every column and every row of the Matrix the function solves the optimization problem
# ```math
# max_{Z}\, ||x - x\circ Z(x)||_{0}\,\, s.t. \\
# ```
# ```math
# \begin{align*}
# (Z(x))_{i} &= 0 \, \text{or}\, 1 \\
# ||Z(x)||_{0} &\ge N \\
# ||x - x\circ Z(x)||_{p} 	\,&\le\,  (1-q)||x||_{p},
# \end{align*}
# ```
# where $Z$ is the sparsity pattern for the column or row. $N$ is a maximum number for non zero entries,
# $q$ is a factor that controls how sparse the the row or column should be. All the individual row and column
# patter are overlayed, if either row or column or both return a one for an entry the entry is one.
# This ensures that the pattern will preserve different Subspaces of the Matrix.

# Than we can take the sparsity pattern and modify it to a binning pattern:
bin_sparse_matrix!(M, M_id, 200)
# The function looks at the maximum and minimum values of the matrix and then finds a partition
# of the negative and positive area according to the specified maximum number of bins.
# For each entry of the matrix it is checked to which bin it belongs to. The binning controls the
# number of unknowns and so the computation cost to solve the optimization problem. It also typically
# improves the conditioning of the optimization problem.

# With the binning pattern we can find the Matrix so that the norm of the difference
# is as small as possible and so that the binning constrains are fullfilled:
binned_minimization(M_id, zeros(5, 5), Matrix{Float64}(I, 5, 5), M)

# The function solves the optimization problem
# ```math
# min ||M - X||_{F} \,\, s.t.
# ```
# ```math
# X\, \text{has the specified sparsity pattern}\, B(M) = M_{id}
# ```
# Of course our example optimization problem is not too interesting, because without the binning
# only some entries are set to zero, while the others remain the same. However,
# more sophisticated optimization problems can be used here.

# We can also use the sparsify function on $M$:
sparsify(M, 0.6, 2, 200)
# This function calculates the sparsity and binning pattern like we did and uses as optimization problem

# ```math
# \min\limits_{X} \frac{1}{2} \sum\limits_{i=1}^r \frac{1}{\sigma_i^2} ||\left( X - M\right) v_i||_2^2
# + \frac{1}{2} \sum\limits_{i=1}^r \frac{1}{\sigma_i^2} ||\left( X^* - M^*\right) u_i||_2^2,
# ```

# where $r$ is the rank, $\sigma_i$ are the $r$ biggest singular values, $v_i$ the corresponding right singular vectors and $u_i$
# the corresponding left singular vectors of $M$. $M^*$ denotes the conjugate transpose of $M$. The function compares the action of
# the unknown matrix $X$ with the action of $M$ on the singular vectors of $M$ and penalizes the differences in near null-space with
# larger weights. It can be formulatet in the form

# ```math
# X M^+(M^+)^* + (M^+)^*M^+X = MM^+(M^+)^* (M^+)^*M^+M,
# ```

# where $M^+$ is the pseudo inverse of $M$.
# We can also set `impose_null_spaces` true:
sparsify(M, 0.6, 2, 200, true)
# Then after the described optimization problem was solved the function also solves an additional optimization problem that
# ensures that the left and right null-spaces are preserved exactly. Because our matrix has full rank this makes no difference in our case.
#


text:
"""
    blosc2_io

Input/Output parameters.
"""
struct blosc2_io
  id ::UInt8 #!< The IO identifier.
  params ::Ref{Cvoid} #!< The IO parameters.
  blosc2_io(;id = BLOSC2_IO_FILESYSTEM, params = C_NULL) = new(id, params)
end


text:
function save(file,model)
    weights=params(cpu(model))
    BSON.@save file weights
end

function load(file)
    BSON.@load file weights
    return weights
end

max_stars_repo_name: yeruoforever/DrugRepositioning

max_issues_repo_name: yeruoforever/DrugRepositioning

max_forks_repo_name: yeruoforever/DrugRepositioning


text:
struct Vertex
  position::Point
  value::Point
end
Base.isequal(v::Vertex, p::Point) = isequal(v.position, p)
function periodicindex(iterable, i::Int)
    l = Base.length(iterable)
    i < 1 && return l + i
    i > l && return i - l
    return i
end

max_stars_repo_name: jwscook/WindingNumbers

max_issues_repo_name: jwscook/WindingNumbers

max_forks_repo_name: jwscook/WindingNumbers


text:
@testset "chainrules" begin
    models = (OU,OUUnknown{3},TwoOU,CorrelatedOU,CorrelatedOUUnknown{3},TwoCorrelatedOU)
    pars = (ones(2),ones(2),ones(4),[1,1,0.5],[1,1,0.5],[1,1,0.5,1,1,0.5])
    series = [fill(rand(10),3);fill(rand(10,2),3)]
    for (model,par,ts) in zip(models,pars,series)
        w = WhittleLikelihood(model,ts,1)
        dw = DebiasedWhittleLikelihood(model,ts,1)
        test_rrule(w ⊢ NoTangent(),par)
        test_rrule(dw ⊢ NoTangent(),par)
    end
end


text:
""" Diagrams of a given shape.
"""
module ShapeDiagrams
export AbstractFunctor, AbstractLaxator, LaxMonoidalFunctor,
  Span, Cone, Cospan, DecoratedCospan, Cocone, Diagram, left, right, leg, nlegs, apex, base,
  decorator, decoration, undecorate

using ...Theories: dom, codom

abstract type AbstractFunctor end
abstract type AbstractLaxator end

struct LaxMonoidalFunctor{Ftr <: AbstractFunctor, Lxr <: AbstractLaxator} <: AbstractFunctor
  F::Ftr
  L::Lxr
end

""" Span of morphisms in a category.
"""
struct Span{Left,Right}
  left::Left
  right::Right

  function Span(left::Left, right::Right; strict::Bool=true) where {Left,Right}
    if strict && dom(left) != dom(right)
      error("Domains of legs in span do not match: $left vs $right")
    end
    new{Left,Right}(left, right)
  end
end

apex(span::Span) = dom(span.left) # == dom(span.right)
left(span::Span) = span.left
right(span::Span) = span.right

""" Cone of morphisms in a category.
"""
struct Cone{S,T}
  apex::S # We store this separately because legs might be empty
  legs::Vector{T}

  function Cone(apex::S,legs::Vector{T}, strict::Bool=true) where {S,T}
    if strict && !all(dom(leg) == apex for leg in legs)
      error("Domain of legs in cone do not match")
    end
    new{S,T}(apex,legs)
  end
end

apex(cone::Cone) = cone.apex
leg(cone::Cone,n) = cone.legs[n]
legs(cone::Cone) = cone.legs
nlegs(cone::Cone) = length(cone.legs)

""" Cospan of morphisms in a category.
"""
struct Cospan{Left,Right}
  left::Left
  right::Right

  function Cospan(left::Left, right::Right; strict::Bool=true) where {Left,Right}
    if strict && codom(left) != codom(right)
      error("Codomains of legs in cospan do not match: $left vs $right")
    end
    new{Left,Right}(left, right)
  end
end

base(cospan::Cospan) = codom(cospan.left) # == codom(cospan.right)
left(cospan::Cospan) = cospan.left
right(cospan::Cospan) = cospan.right

""" Decorate Cospan of morphisms for representing open networks.
"""
struct DecoratedCospan{Decorator <: AbstractFunctor,Decoration}
  cospan::Cospan
  decorator::Decorator
  decoration::Decoration
end

decorator(m::DecoratedCospan) = m.decorator
decoration(m::DecoratedCospan) = m.decoration
undecorate(m::DecoratedCospan) = m.cospan
base(m::DecoratedCospan) = base(m.cospan)
left(m::DecoratedCospan) = left(m.cospan)
right(m::DecoratedCospan) = right(m.cospan)

""" Cocone of morphisms in a category.
"""
struct Cocone{S,T}
  base::S # We store this separately because legs might be empty
  legs::Vector{T}

  function Cocone(base::S,legs::Vector{T}, strict::Bool=true) where {S,T}
    if strict && !all(codom(leg) == base for leg in legs)
      error("Codomain of legs in cocone do not match")
    end
    new{S,T}(base,legs)
  end
end

base(cocone::Cocone) = cocone.base
leg(cocone::Cocone,n) = cocone.legs[n]
nlegs(cocone::Cocone) = length(cocone.legs)

struct Diagram{Ob,Hom}
  obs::Vector{Ob}
  homs::Vector{Tuple{Int64,Int64,Hom}}

  function Diagram(obs::Vector{Ob}, homs::Vector{Tuple{Int64,Int64,Hom}}) where {Ob, Hom}
    for (s,t,f) in homs
      @assert obs[s] == dom(f)
      @assert obs[t] == codom(f)
    end
    new{Ob,Hom}(obs,homs)
  end
end

end


text:
@testset "Finds the eigenvalue 5 when choosing an estimate near it" begin

    matrix = [20 0;0 5]
    guessshift = 4.8
    guess = [1;1]
    stoppingcriteria = Eigen.stoppingcriteria(0.1, 30)

    actual = Eigen.inverseiteration(matrix, guessshift, guess, stoppingcriteria)
    expected = [0; 1]

    @test LinearAlgebra.norm(actual.eigenvector - expected) <= 0.1
    @test actual.isverified == true
end


text:
using .Tracker: TrackedArray, TrackedReal

if !usetyped
  unwrap(x::Union{TrackedArray,TrackedReal}) = Tracker.data(x)
end

forward(f, ps::Tracker.Params) = forward(f, Params(ps))


text:
import Compat
using Colors, GeometryTypes, Requires
export mesh, box, sphere, pyramid, cylinder, torus, parametric, meshlines,
       material, camera, pointlight, spotlight, ambientlight, line,
       linematerial, geometry, dodecahedron, icosahedron, octahedron,
       tetrahedron, plane, grid, pointcloud, pointmaterial, text, raycastable

"""
Creates a Three-js mesh at position (`x`,`y`,`z`).
Keyword arguments for rotation are available, being `rx`, `ry` and `rz` for
rotation about X, Y and Z axes respectively. These are to be specified in
degrees.
Geometry and Material tags are added as children to this Elem, to render a mesh.
"""
function mesh(
        x::Float64,
        y::Float64,
        z::Float64;
        rx::Float64 = 0.0,
        ry::Float64 = 0.0,
        rz::Float64 = 0.0,
    )
    Elem(
        :"three-js-mesh",
        attributes = Dict(
            :x => x, :y => y, :z => z, :rx => rx, :ry => ry, :rz => rz
        )
    )
end

"""
Creates a Box geometry of `width`, `height` and `depth`.
Should be put in a `mesh` along with another material Elem to render.
"""
function box(width::Real, height::Real, depth::Real)
   Elem(:"three-js-box", attributes = Dict(:width=>width, :height=>height, :depth=>depth))
end

"""
Creates a Sphere geometry of radius `r`.
Should be put in a `mesh` along with another material Elem to render.
"""
function sphere(r::Float64)
    Elem(:"three-js-sphere", attributes = Dict(:r=>r))
end

"""
Creates a square base Pyramid geometry of base `b` and height `h`.
Should be put in a `mesh` along with another material Elem to render.
"""
function pyramid(b::Float64,h::Float64)
    Elem(:"three-js-pyramid", attributes = Dict(:base => b, :height => h))
end

"""
Creates a Cylinder geometry of bottom radius `bottom`, top radius `top` and
height `h`.
Should be put in a `mesh` along with another material Elem to render.
"""
function cylinder(top::Float64,bottom::Float64,height::Float64)
    Elem(
        :"three-js-cylinder",
        attributes = Dict(:top => top, :bottom => bottom, :height => height)
    )
end

"""
Creates a Torus geometry of radius `radius` and tube radius `tube`.
Should be put in a `mesh` along with another material Elem to render.
"""
function torus(radius::Float64,tube::Float64)
    Elem(
        :"three-js-torus",
        attributes = Dict(:r => radius, :tube => tube)
    )
end

"""
Creates a Dodecahedron geometry of radius `radius`.
Should be put in a `mesh` along with another material Elem to render.
"""
function dodecahedron(radius::Float64)
    Elem(
        :"three-js-dodecahedron",
        attributes = Dict(:r => radius)
    )
end

"""
Creates a icosahedron geometry of radius `radius`.
Should be put in a `mesh` along with another material Elem to render.
"""
function icosahedron(radius::Float64)
    Elem(
        :"three-js-icosahedron",
        attributes = Dict(:r => radius)
    )
end

"""
Creates a icosahedron geometry of radius `radius`.
Should be put in a `mesh` along with another material Elem to render.
"""
function octahedron(radius::Float64)
    Elem(
        :"three-js-octahedron",
        attributes = Dict(:r => radius)
    )
end

"""
Creates a tetrahedron geometry of radius `radius`.
Should be put in a `mesh` along with another material Elem to render.
"""
function tetrahedron(radius::Float64)
    Elem(
        :"three-js-tetrahedron",
        attributes = Dict(:r => radius)
    )
end

"""
Creates a plane in the XY plane with specified width and height centered
around the origin.
Should be put in a `mesh` along with another material Elem to render.
"""
function plane(width::Real, height::Real)
    Elem(
        :"three-js-plane",
        attributes = Dict(:w => width, :h => height)
    )
end

"""
Creates a geometry.
This should be a child of a `mesh`.
Vertices of the geometry are passed in as a vector of `Tuples` of the coordinates
along with faces of the geometry which are again passed in as a vector of `Tuples`
of `Int` representing the indices of the vertices to be joined.
"""
function geometry(
    vertices::Vector{Tuple{Float64, Float64, Float64}},
    faces::Vector{Tuple{Int, Int, Int}}
    )
    #TODO: Add Vectors accepting facecolors and vertexcolors as keywords
    x = [coords[1] for coords in vertices]
    y = [coords[2] for coords in vertices]
    z = [coords[3] for coords in vertices]
    face = zeros(size(faces,1) * 3)
    for i=1:size(faces, 1)
        face[3i - 2] = faces[i][1] - 1
        face[3i - 1] = faces[i][2] - 1
        face[3i] = faces[i][3] - 1
    end
    geom = Elem(
        :"three-js-geometry",
        attributes = Dict(
            :x => x,
            :y => y,
            :z => z,
            :faces => face,
        )
    )
    geom
end

"""
Create a geometry from an AbstractMesh (via GeometryTypes).
The scale parameter will scale the mesh vertices in the corresponding axis.
"""
function ThreeJS.geometry{VT,N,T,O}(m::AbstractMesh{VT,Face{N,T,O}};scale=(1,1,1))
    vs = [(Float64(i[1])*scale[1],
           Float64(i[2])*scale[2],
           Float64(i[3])*scale[3]) for i in m.vertices]
    fs = [(Int(i[1])-O,Int(i[2])-O,Int(i[3])-O) for i in m.faces]
    ThreeJS.geometry(vs,fs)
end

"""
Creates a parametric surface.
Takes `x` values between `xrange` divided into `slices+1` equal intervals.
Takes `y` values between `yrange` divided into `stacks+1` equal intervals.
Applies a function `f` passed to all such `x` and `y` values and creates vertices
of coordinates `(x,y,z)` and a surface containing these vertices.

A colormap can also be passed to set the vertice colors to a corresponding color
using the keyword argument `colormap`.
NOTE: Such colors will be displayed only with a `material` with `colorkind` set
to `"vertex"` and `color` to `"white"`.
"""
function parametric{T<:Colors.Color}(
    slices::Int,
    stacks::Int,
    xrange::Range,
    yrange::Range,
    f::Function;
    colormap::AbstractVector{T} = Colors.colormap("RdBu")
    )
    xrange = linspace(xrange.start, xrange.stop, slices+1)
    yrange = linspace(yrange.start, yrange.stop, stacks+1)
    xs = [x for x=xrange, y=yrange]
    ys = [y for x=xrange, y=yrange]
    zs = Float64[f(x,y) for x=xrange, y=yrange]
    zrange = maximum(zs) - minimum(zs)
    zmax = maximum(zs)
    colormaplength = length(colormap)
    colors = [
        "#"*hex(colormap[ceil(Int,(zmax - f(x,y))/zrange * (colormaplength-1)+1)])
        for x=xrange, y=yrange
    ]
    geom = Elem(
        :"three-js-parametric",
        attributes = Dict(
            :slices => slices,
            :stacks => stacks,
            :x => xs,
            :y => zs,
            :z => ys,
            :vertexcolors => colors
        )
    )
end

"""
Creates a mesh plot.
Takes `x` values between `xrange` divided into `slices+1` equal intervals.
Takes `y` values between `yrange` divided into `stacks+1` equal intervals.
Applies a function `f` passed to all such `x` and `y` values and creates
vertices of coordinates `(x,y,z)` and a joins them horizontally and vertically,
creating a mesh.

Returns an array of `line` elements which should be under the `scene`.

A colormap can also be passed to set the vertice colors to a corresponding color
using the keyword argument `colormap`.
"""
function meshlines{T<:Colors.Color}(
    slices::Int,
    stacks::Int,
    xrange::Range,
    yrange::Range,
    f::Function;
    colormap::AbstractVector{T} = Colors.colormap("RdBu")
    )
    xrange = linspace(xrange.start, xrange.stop, slices+1)
    yrange = linspace(yrange.start, yrange.stop, stacks+1)
    zs = [f(x,y) for x=xrange, y=yrange]
    zrange = maximum(zs) - minimum(zs)
    zmax = maximum(zs)
    colormaplength = length(colormap)
    findcolor(z::Float64) = colormap[
        ceil(Int,(zmax - z)/zrange * (colormaplength-1)+1)
    ]
    meshmaterial = linematerial(Dict(:color => "white", :colorkind => "vertex"))
    xlines = Elem[
        line(Tuple{Float64, Float64, Float64, Color}[(x, f(x,y), y, findcolor(f(x,y))) for x=xrange]) << meshmaterial
        for y=yrange
    ]
    ylines = Elem[
        line(Tuple{Float64, Float64, Float64, Color}[(x, f(x,y), y, findcolor(f(x,y))) for y=yrange]) << meshmaterial
        for x=xrange
    ]
    [xlines; ylines] #Return all the line elements as an array
end

"""
Creates a material tag with properties passed in as a dictionary.
"""
function material(props::Dict=Dict())
    Elem(:"three-js-material", attributes = filter((k,v)->v!=false, props))
end

"""
Creates a camera tag.
Perspective camera at position `(x,y,z)` created. Keyword arguments of `near`,
`far`,`aspect`, and `fov` is accepted.
"""
function camera(
    x::Float64,
    y::Float64,
    z::Float64;
    fov::Float64=45.0,
    aspect=nothing,
    near::Float64=1.0,
    far::Float64=1000.0
    )
    Elem(
        :"three-js-camera",
        attributes = Dict(
            :x => x, :y => y,:z => z,
            :fov => fov, :aspect => aspect, :near => near, :far => far
        )
    )
end

"""
Creates a point light tag.
A point light at position `(x,y,z)` is created. Keyword arguments of `color`
setting the color of the light, `intensity` and `distance` for setting the
intensity and distance properties are also accepted.
"""
function pointlight(
    x::Float64,
    y::Float64,
    z::Float64;
    color::Colors.RGB{U8}=colorant"white",
    intensity::Float64=1.0,
    distance::Float64=0.0
    )
    colorString = string("#"*hex(color))
    Elem(
        :"three-js-light",
        attributes = Dict(
            :x => x, :y => y, :z => z,
            :kind => "point",
            :color => colorString,
            :intensity => intensity,
            :distance => distance
        )
    )
end

"""
Creates a spot light tag.
A spot light at position `(x,y,z)` is created. Keyword arguments of `color`
setting the color of the light, `intensity`, `distance`, `angle`, `exponent`,
`shadow` for setting the intensity, distance, angle(in degrees) and exponent
properties are also accepted. `Shadow` is a `Bool` to set if shadows are
enabled or not.
"""
function spotlight(
    x::Float64,
    y::Float64,
    z::Float64;
    color::Colors.RGB{U8}=colorant"white",
    intensity::Float64=1.0,
    distance::Float64=0.0,
    angle::Float64=60.0,
    exponent::Float64=8.0,
    shadow::Bool=false
    )
    colorString = string("#"*hex(color))
    Elem(
        :"three-js-light",
        attributes = Dict(
            :x => x, :y => y, :z => z,
            :kind => "spot",
            :color => colorString,
            :intensity => intensity,
            :distance => distance,
            :angle => angle,
            :exponent => exponent,
            :shadow => shadow
        )
    )
end

"""
Creates an ambient light tag.
Ambient light is applied equally to all objects.
The color of the light is set using the `color` argument.
"""
function ambientlight(color::Colors.RGB{U8}=colorant"white")
    colorString = string("#"*hex(color))
    Elem(
        :"three-js-light",
        attributes = Dict(:kind => "ambient", :color => colorString)
    )
end

"""
Creates a line tag.
Line tags should be a child of the scene tag created by `initscene`.

Vertices of the line to be drawn should be passed in as a `Vector` of
`Tuple{Float64, Float64, Float64}`.
The material to be associated with the line can be set using
`linematerial` which should be a child of the line tag.

A keyword argument, `kind` is also provided to set how the lines
should be drawn. `"strip"` and `"pieces"` are the possible values.

The line can be translated and rotated using keyword arguments,
`x`,`y`,`z` for the (x, y, z) coordinate and `rx`, `ry` and `rz`
as the rotation about the X, Y and Z axes respectively.

Colors for the vertices can be set by passing in a `Vector` of
`Color` as the `vertexcolors` kwarg.
"""
function line{T <: Color}(
        vertices::Vector{Tuple{Float64, Float64, Float64}};
        x::Float64 = 0.0,
        y::Float64 = 0.0,
        z::Float64 = 0.0,
        rx::Float64 = 0.0,
        ry::Float64 = 0.0,
        rz::Float64 = 0.0,
        kind::AbstractString = "strip",
        vertexcolors::Vector{T} = Color[]
    )
    xs = [coords[1] for coords in vertices]
    ys = [coords[2] for coords in vertices]
    zs = [coords[3] for coords in vertices]
    colors = map(x -> "#"*hex(x), vertexcolors)
    Elem(
        :"three-js-line",
        attributes = Dict(
            :xs => xs,
            :ys => ys,
            :zs => zs,
            :x => x,
            :y => y,
            :z => z,
            :rx => rx,
            :ry => ry,
            :rz => rz,
            :kind => kind,
            :vertexcolors => colors
        )
    )
end

"""
Helper function to make creating `line` easier.
`Tuples` of vertices with their color also as part of the `Tuple`
is expected as the argument.
"""
function line{T <: Color}(
        verticeswithcolor::Vector{Tuple{Float64, Float64, Float64, T}};
        x::Float64 = 0.0,
        y::Float64 = 0.0,
        z::Float64 = 0.0,
        rx::Float64 = 0.0,
        ry::Float64 = 0.0,
        rz::Float64 = 0.0,
        kind::AbstractString = "strip"
    )
    vertexcolors = [vertex[4] for vertex in verticeswithcolor]
    vertices = [(vertex[1], vertex[2], vertex[3]) for vertex in verticeswithcolor]
    line(
        vertices,
        x = x,
        y = y,
        z = z,
        rx = rx,
        ry = ry,
        rz = rz,
        kind = kind,
        vertexcolors = vertexcolors
    )
end

"""
Creates a line material tag.
These tags should be the child of a line tag.
Possible properties that can be set are:
    - `kind` - `"basic"` or `"dashed"`
    - `color` - Any CSS color value.
    - `linewidth` - Sets the width of the line.
    - `scale` - For `"dashed"` only. Scale of the dash.
    - `dashSize` -  For `"dashed"` only. Sets size of the dash.
    - `linecap` - Ends of the line. Possible values are `"round"`, `"butt"`, and
    `"square"`.
    - `linejoin` - Appearance of line joins. Possible values are `"round"`,
    `"bevel"` and `"miter"`.
Refer the ThreeJS docs for [`LineDashedMaterial`](http://threejs.org/docs/#Reference/Materials/LineDashedMaterial)
and [`LineBasicMaterial`](http://threejs.org/docs/#Reference/Materials/LineBasicMaterial)
for more details.

These properties should be passed in as a `Dict`.
"""
function linematerial(props = Dict())
    Elem(:"three-js-line-material", attributes = filter((k,v)-> v!=false, props))
end

"""
Creates a shader material tag.
These tags should be the child of a mesh tag.

The WebGL programs should be passed to `vert` and `frag`. The `defines` and `uniforms`
are dictionaries that map to declarations in the programs. Refer to the ThreeJS docs
for [`ShaderMaterial`](http://threejs.org/docs/api/materials/ShaderMaterial.html)
for more details.
"""
function shadermaterial(vert::AbstractString, frag::AbstractString; defines = Dict(), uniforms = Dict(), kwds...)
    Elem(:"three-js-shader-material"; :vert => vert, :frag => frag,
        :defines => Patchwork.PropHook("escher-property-hook", defines),
        :uniforms => Patchwork.PropHook("escher-property-hook", uniforms),
        kwds...)
end

"""
Creates a data texture tag.
These tags should be the child of a shader material.

The name should be a `sampler2D` in the WebGL programs. The data should be a base64-encoded
string.
"""
function datatexture(name::AbstractString, data::AbstractString, width::Int, height::Int; kwds...)
    Elem(:"three-js-data-texture"; name = name,
        attributes = Dict(
            :data => data,
            :width => width,
            :height => height,
            Dict(kwds)...
        )
    )
end

"""
Convenience function that serializes an array as a base64 string.
"""
function datatexture(name::ASCIIString, data::Array{UInt8, 2}; kwds...)
    datatexture(name, base64encode(data), size(data, 1), size(data, 2);
        :format => "LuminanceFormat", :type => "UnsignedByteType", kwds...)
end

"""
Creates a point cloud tag.
Line tags should be a child of the scene tag created by `initscene`.

Vertices of the points to be drawn should be passed in as a `Vector` of
`Tuple{Float64, Float64, Float64}`.
The material to be associated with the line can be set using
`pointmaterial` which should be a child of the line tag.

The point system can be translated and rotated using keyword arguments,
`x`,`y`,`z` for the (x, y, z) coordinate and `rx`, `ry` and `rz`
as the rotation about the X, Y and Z axes respectively.

Colors for the vertices can be set by passing in a `Vector` of
`Color` as the `vertexcolors` kwarg.
"""
function pointcloud{T <: Color}(
        vertices::Vector{Tuple{Float64, Float64, Float64}};
        x::Float64 = 0.0,
        y::Float64 = 0.0,
        z::Float64 = 0.0,
        rx::Float64 = 0.0,
        ry::Float64 = 0.0,
        rz::Float64 = 0.0,
        vertexcolors::Vector{T} = Color[]
    )
    xs = [coords[1] for coords in vertices]
    ys = [coords[2] for coords in vertices]
    zs = [coords[3] for coords in vertices]
    colors = map(x -> "#"*hex(x), vertexcolors)
    Elem(
        :"three-js-points",
        attributes = Dict(
            :xs => xs,
            :ys => ys,
            :zs => zs,
            :x => x,
            :y => y,
            :z => z,
            :rx => rx,
            :ry => ry,
            :rz => rz,
            :vertexcolors => colors
        )
    )
end

"""
Helper function to make creating `pointcloud`s easier.
`Tuples` of vertices with their color also as part of the `Tuple`
is expected as the argument.
"""
function pointcloud{T<: Color}(
        verticeswithcolor::Vector{Tuple{Float64, Float64, Float64, T}};
        x::Float64 = 0.0,
        y::Float64 = 0.0,
        z::Float64 = 0.0,
        rx::Float64 = 0.0,
        ry::Float64 = 0.0,
        rz::Float64 = 0.0,
    )
    vertexcolors = [vertex[4] for vertex in verticeswithcolor]
    vertices = [(vertex[1], vertex[2], vertex[3]) for vertex in verticeswithcolor]
    pointcloud(
        vertices,
        x = x,
        y = y,
        z = z,
        rx = rx,
        ry = ry,
        rz = rz,
        vertexcolors = vertexcolors
    )
end

"""
Creates a point material tag.
These tags should be the child of a point tag.
Possible properties that can be set are:
    - `color` - Any CSS color value.
    - `size` - Set's size of the points
    - `noattenuation` -  `Bool`. Decides if points should become smaller with
    distance or not.
    - `texture` - Image to be used as texture.
    - `colorkind` - Possible values `"no"`, `"face"`,`"vertex"`
These properties should be passed in as a `Dict`.
    - `alphatest` - Used to discard some fragments when below this value.
"""
function pointmaterial(props = Dict())
    Elem(:"three-js-point-material", attributes = filter((k,v)->v!=false, props))
end

"""
Creates a grid element.
These should be a child of the scene tag created by `initscene`.
The `size` represents the total size and the `step` represents the distance
between consecutive lines of the grid.

The grid can be translated and rotated using keyword arguments,
`x`,`y`,`z` for the (x, y, z) coordinate and `rx`, `ry` and `rz`
as the rotation about the X, Y and Z axes respectively.
"""
function grid(
        size::Float64,
        step::Float64;
        x::Float64 = 0.0,
        y::Float64 = 0.0,
        z::Float64 = 0.0,
        rx::Float64 = 0.0,
        ry::Float64 = 0.0,
        rz::Float64 = 0.0,
        colorcenter::Colors.RGB{U8}=colorant"black",
        colorgrid::Colors.RGB{U8}=colorant"black"
    )
    Elem(
        :"three-js-grid",
        attributes = Dict(
            :size => size,
            :step => step,
            :x => x,
            :y => y,
            :z => z,
            :rx => rx,
            :ry => ry,
            :rz => rz,
            :colorcenter => "#" * hex(colorcenter),
            :colorgrid => "#" * hex(colorgrid)
        )
    )
end

"""
Create a Text Sprite with `content` at position `(x,y,z)`.
"""
function text(x::Float64, y::Float64, z::Float64, content::AbstractString)
   Elem(
        :"three-js-text",
        attributes = Dict(:x=>x, :y=>y, :z=>z, :content=>content)
   )
end

@require Escher begin
    import Escher: Behavior

    immutable Raycaster <: Behavior
        camera
        event
    end

    Escher.render(r::Raycaster, state) = Escher.render(r.camera, state) << Elem(:"three-js-raycaster"; :event => r.event)
    Escher.default_intent(x::Raycaster) = Escher.ToType{Dict{UTF8String, Float64}}()

    """
    Create a raycaster that triggers on the JavaScript event `event`.
    """
    function raycastable(camera::Elem, event::AbstractString = "")
        Raycaster(camera, event)
    end
end


text:
"""
siceで使用する平面冗長ロボットアーム
"""
module SiceDynamics

export calc_torque
export  calc_real_ddq

using LinearAlgebra

const m1 = 1.0
const m2 = 1.0
const m3 = 1.0
const m4 = 1.0

const l1 = 1.0
const l2 = 1.0
const l3 = 1.0
const l4 = 1.0

const lg1 = 0.5
const lg2 = 0.5
const lg3 = 0.5
const lg4 = 0.5

const g = 9.81

const I1 = 1.0
const I2 = 1.0
const I3 = 1.0
const I4 = 1.0

"""慣性行列"""
function M(q::Vector{T}) where T
    m_1_1 = I1 + I2 + I3 + I4 + l1^2*m2*sin(q[1])^2 + l1^2*m2*cos(q[1])^2 + l1^2*m3*sin(q[1])^2 + l1^2*m3*cos(q[1])^2 + l1^2*m4*sin(q[1])^2 + l1^2*m4*cos(q[1])^2 + 2.0*l1*l2*m3*sin(q[1])*sin(q[1] + q[2]) + 2.0*l1*l2*m3*cos(q[1])*cos(q[1] + q[2]) + 2.0*l1*l2*m4*sin(q[1])*sin(q[1] + q[2]) + 2.0*l1*l2*m4*cos(q[1])*cos(q[1] + q[2]) + 2.0*l1*l3*m4*sin(q[1])*sin(q[1] + q[2] + q[3]) + 2.0*l1*l3*m4*cos(q[1])*cos(q[1] + q[2] + q[3]) + 2.0*l1*lg2*m2*sin(q[1])*sin(q[1] + q[2]) + 2.0*l1*lg2*m2*cos(q[1])*cos(q[1] + q[2]) + 2.0*l1*lg3*m3*sin(q[1])*sin(q[1] + q[2] + q[3]) + 2.0*l1*lg3*m3*cos(q[1])*cos(q[1] + q[2] + q[3]) + 2.0*l1*lg4*m4*sin(q[1])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l1*lg4*m4*cos(q[1])*cos(q[1] + q[2] + q[3] + q[4]) + l2^2*m3*sin(q[1] + q[2])^2 + l2^2*m3*cos(q[1] + q[2])^2 + l2^2*m4*sin(q[1] + q[2])^2 + l2^2*m4*cos(q[1] + q[2])^2 + 2.0*l2*l3*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + 2.0*l2*l3*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + 2.0*l2*lg3*m3*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + 2.0*l2*lg3*m3*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + 2.0*l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3^2*m4*sin(q[1] + q[2] + q[3])^2 + l3^2*m4*cos(q[1] + q[2] + q[3])^2 + 2.0*l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg1^2*m1*sin(q[1])^2 + lg1^2*m1*cos(q[1])^2 + lg2^2*m2*sin(q[1] + q[2])^2 + lg2^2*m2*cos(q[1] + q[2])^2 + lg3^2*m3*sin(q[1] + q[2] + q[3])^2 + lg3^2*m3*cos(q[1] + q[2] + q[3])^2 + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_1_2 = I2 + I3 + I4 + l1*l2*m3*sin(q[1])*sin(q[1] + q[2]) + l1*l2*m3*cos(q[1])*cos(q[1] + q[2]) + l1*l2*m4*sin(q[1])*sin(q[1] + q[2]) + l1*l2*m4*cos(q[1])*cos(q[1] + q[2]) + l1*l3*m4*sin(q[1])*sin(q[1] + q[2] + q[3]) + l1*l3*m4*cos(q[1])*cos(q[1] + q[2] + q[3]) + l1*lg2*m2*sin(q[1])*sin(q[1] + q[2]) + l1*lg2*m2*cos(q[1])*cos(q[1] + q[2]) + l1*lg3*m3*sin(q[1])*sin(q[1] + q[2] + q[3]) + l1*lg3*m3*cos(q[1])*cos(q[1] + q[2] + q[3]) + l1*lg4*m4*sin(q[1])*sin(q[1] + q[2] + q[3] + q[4]) + l1*lg4*m4*cos(q[1])*cos(q[1] + q[2] + q[3] + q[4]) + l2^2*m3*sin(q[1] + q[2])^2 + l2^2*m3*cos(q[1] + q[2])^2 + l2^2*m4*sin(q[1] + q[2])^2 + l2^2*m4*cos(q[1] + q[2])^2 + 2.0*l2*l3*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + 2.0*l2*l3*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + 2.0*l2*lg3*m3*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + 2.0*l2*lg3*m3*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + 2.0*l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3^2*m4*sin(q[1] + q[2] + q[3])^2 + l3^2*m4*cos(q[1] + q[2] + q[3])^2 + 2.0*l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg2^2*m2*sin(q[1] + q[2])^2 + lg2^2*m2*cos(q[1] + q[2])^2 + lg3^2*m3*sin(q[1] + q[2] + q[3])^2 + lg3^2*m3*cos(q[1] + q[2] + q[3])^2 + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_1_3 = I3 + I4 + l1*l3*m4*sin(q[1])*sin(q[1] + q[2] + q[3]) + l1*l3*m4*cos(q[1])*cos(q[1] + q[2] + q[3]) + l1*lg3*m3*sin(q[1])*sin(q[1] + q[2] + q[3]) + l1*lg3*m3*cos(q[1])*cos(q[1] + q[2] + q[3]) + l1*lg4*m4*sin(q[1])*sin(q[1] + q[2] + q[3] + q[4]) + l1*lg4*m4*cos(q[1])*cos(q[1] + q[2] + q[3] + q[4]) + l2*l3*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + l2*l3*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + l2*lg3*m3*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + l2*lg3*m3*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3^2*m4*sin(q[1] + q[2] + q[3])^2 + l3^2*m4*cos(q[1] + q[2] + q[3])^2 + 2.0*l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg3^2*m3*sin(q[1] + q[2] + q[3])^2 + lg3^2*m3*cos(q[1] + q[2] + q[3])^2 + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_1_4 = I4 + l1*lg4*m4*sin(q[1])*sin(q[1] + q[2] + q[3] + q[4]) + l1*lg4*m4*cos(q[1])*cos(q[1] + q[2] + q[3] + q[4]) + l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_2_1 = I2 + I3 + I4 + l1*l2*m3*sin(q[1])*sin(q[1] + q[2]) + l1*l2*m3*cos(q[1])*cos(q[1] + q[2]) + l1*l2*m4*sin(q[1])*sin(q[1] + q[2]) + l1*l2*m4*cos(q[1])*cos(q[1] + q[2]) + l1*l3*m4*sin(q[1])*sin(q[1] + q[2] + q[3]) + l1*l3*m4*cos(q[1])*cos(q[1] + q[2] + q[3]) + l1*lg2*m2*sin(q[1])*sin(q[1] + q[2]) + l1*lg2*m2*cos(q[1])*cos(q[1] + q[2]) + l1*lg3*m3*sin(q[1])*sin(q[1] + q[2] + q[3]) + l1*lg3*m3*cos(q[1])*cos(q[1] + q[2] + q[3]) + l1*lg4*m4*sin(q[1])*sin(q[1] + q[2] + q[3] + q[4]) + l1*lg4*m4*cos(q[1])*cos(q[1] + q[2] + q[3] + q[4]) + l2^2*m3*sin(q[1] + q[2])^2 + l2^2*m3*cos(q[1] + q[2])^2 + l2^2*m4*sin(q[1] + q[2])^2 + l2^2*m4*cos(q[1] + q[2])^2 + 2.0*l2*l3*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + 2.0*l2*l3*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + 2.0*l2*lg3*m3*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + 2.0*l2*lg3*m3*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + 2.0*l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3^2*m4*sin(q[1] + q[2] + q[3])^2 + l3^2*m4*cos(q[1] + q[2] + q[3])^2 + 2.0*l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg2^2*m2*sin(q[1] + q[2])^2 + lg2^2*m2*cos(q[1] + q[2])^2 + lg3^2*m3*sin(q[1] + q[2] + q[3])^2 + lg3^2*m3*cos(q[1] + q[2] + q[3])^2 + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_2_2 = I2 + I3 + I4 + l2^2*m3*sin(q[1] + q[2])^2 + l2^2*m3*cos(q[1] + q[2])^2 + l2^2*m4*sin(q[1] + q[2])^2 + l2^2*m4*cos(q[1] + q[2])^2 + 2.0*l2*l3*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + 2.0*l2*l3*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + 2.0*l2*lg3*m3*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + 2.0*l2*lg3*m3*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + 2.0*l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3^2*m4*sin(q[1] + q[2] + q[3])^2 + l3^2*m4*cos(q[1] + q[2] + q[3])^2 + 2.0*l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg2^2*m2*sin(q[1] + q[2])^2 + lg2^2*m2*cos(q[1] + q[2])^2 + lg3^2*m3*sin(q[1] + q[2] + q[3])^2 + lg3^2*m3*cos(q[1] + q[2] + q[3])^2 + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_2_3 = I3 + I4 + l2*l3*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + l2*l3*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + l2*lg3*m3*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + l2*lg3*m3*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3^2*m4*sin(q[1] + q[2] + q[3])^2 + l3^2*m4*cos(q[1] + q[2] + q[3])^2 + 2.0*l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg3^2*m3*sin(q[1] + q[2] + q[3])^2 + lg3^2*m3*cos(q[1] + q[2] + q[3])^2 + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_2_4 = I4 + l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_3_1 = I3 + I4 + l1*l3*m4*sin(q[1])*sin(q[1] + q[2] + q[3]) + l1*l3*m4*cos(q[1])*cos(q[1] + q[2] + q[3]) + l1*lg3*m3*sin(q[1])*sin(q[1] + q[2] + q[3]) + l1*lg3*m3*cos(q[1])*cos(q[1] + q[2] + q[3]) + l1*lg4*m4*sin(q[1])*sin(q[1] + q[2] + q[3] + q[4]) + l1*lg4*m4*cos(q[1])*cos(q[1] + q[2] + q[3] + q[4]) + l2*l3*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + l2*l3*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + l2*lg3*m3*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + l2*lg3*m3*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3^2*m4*sin(q[1] + q[2] + q[3])^2 + l3^2*m4*cos(q[1] + q[2] + q[3])^2 + 2.0*l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg3^2*m3*sin(q[1] + q[2] + q[3])^2 + lg3^2*m3*cos(q[1] + q[2] + q[3])^2 + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_3_2 = I3 + I4 + l2*l3*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + l2*l3*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + l2*lg3*m3*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3]) + l2*lg3*m3*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3]) + l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3^2*m4*sin(q[1] + q[2] + q[3])^2 + l3^2*m4*cos(q[1] + q[2] + q[3])^2 + 2.0*l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg3^2*m3*sin(q[1] + q[2] + q[3])^2 + lg3^2*m3*cos(q[1] + q[2] + q[3])^2 + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_3_3 = I3 + I4 + l3^2*m4*sin(q[1] + q[2] + q[3])^2 + l3^2*m4*cos(q[1] + q[2] + q[3])^2 + 2.0*l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + 2.0*l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg3^2*m3*sin(q[1] + q[2] + q[3])^2 + lg3^2*m3*cos(q[1] + q[2] + q[3])^2 + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_3_4 = I4 + l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_4_1 = I4 + l1*lg4*m4*sin(q[1])*sin(q[1] + q[2] + q[3] + q[4]) + l1*lg4*m4*cos(q[1])*cos(q[1] + q[2] + q[3] + q[4]) + l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_4_2 = I4 + l2*lg4*m4*sin(q[1] + q[2])*sin(q[1] + q[2] + q[3] + q[4]) + l2*lg4*m4*cos(q[1] + q[2])*cos(q[1] + q[2] + q[3] + q[4]) + l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_4_3 = I4 + l3*lg4*m4*sin(q[1] + q[2] + q[3])*sin(q[1] + q[2] + q[3] + q[4]) + l3*lg4*m4*cos(q[1] + q[2] + q[3])*cos(q[1] + q[2] + q[3] + q[4]) + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2
    m_4_4 = I4 + lg4^2*m4*sin(q[1] + q[2] + q[3] + q[4])^2 + lg4^2*m4*cos(q[1] + q[2] + q[3] + q[4])^2

    [
        m_1_1 m_1_2 m_1_3 m_1_4
        m_2_1 m_2_2 m_2_3 m_2_4
        m_3_1 m_3_2 m_3_3 m_3_4
        m_4_1 m_4_2 m_4_3 m_4_4
    ]
end

"""コリオリ項と重力項の和"""
function C_and_G(q::Vector{T}, dq::Vector{T}) where T
    u_all1 = g*lg1*m1*cos(q[1]) + g*m2*(l1*cos(q[1]) + lg2*cos(q[1] + q[2])) + g*m3*(l1*cos(q[1]) + l2*cos(q[1] + q[2]) + lg3*cos(q[1] + q[2] + q[3])) + g*m4*(l1*cos(q[1]) + l2*cos(q[1] + q[2]) + l3*cos(q[1] + q[2] + q[3]) + lg4*cos(q[1] + q[2] + q[3] + q[4])) - 0.5*m2*((-2*dq[1]*l1*sin(q[1]) - 2*lg2*(dq[1] + dq[2])*sin(q[1] + q[2]))*(dq[1]*l1*cos(q[1]) + lg2*(dq[1] + dq[2])*cos(q[1] + q[2])) + (-dq[1]*l1*sin(q[1]) - lg2*(dq[1] + dq[2])*sin(q[1] + q[2]))*(-2*dq[1]*l1*cos(q[1]) - 2*lg2*(dq[1] + dq[2])*cos(q[1] + q[2]))) + 0.5*m2*((-2*l1*sin(q[1]) - 2*lg2*sin(q[1] + q[2]))*(-dq[1]^2*l1*cos(q[1]) - lg2*(dq[1] + dq[2])^2*cos(q[1] + q[2])) + (2*l1*cos(q[1]) + 2*lg2*cos(q[1] + q[2]))*(-dq[1]^2*l1*sin(q[1]) - lg2*(dq[1] + dq[2])^2*sin(q[1] + q[2])) + (-2*dq[1]*l1*sin(q[1]) - 2*lg2*(dq[1] + dq[2])*sin(q[1] + q[2]))*(dq[1]*l1*cos(q[1]) + lg2*(dq[1] + dq[2])*cos(q[1] + q[2])) + (-dq[1]*l1*sin(q[1]) - lg2*(dq[1] + dq[2])*sin(q[1] + q[2]))*(-2*dq[1]*l1*cos(q[1]) - 2*lg2*(dq[1] + dq[2])*cos(q[1] + q[2]))) - 0.5*m3*((-2*dq[1]*l1*sin(q[1]) - 2*l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - 2*lg3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]))*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + lg3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3])) + (-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]))*(-2*dq[1]*l1*cos(q[1]) - 2*l2*(dq[1] + dq[2])*cos(q[1] + q[2]) - 2*lg3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]))) + 0.5*m3*((-2*l1*sin(q[1]) - 2*l2*sin(q[1] + q[2]) - 2*lg3*sin(q[1] + q[2] + q[3]))*(-dq[1]^2*l1*cos(q[1]) - l2*(dq[1] + dq[2])^2*cos(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])^2*cos(q[1] + q[2] + q[3])) + (2*l1*cos(q[1]) + 2*l2*cos(q[1] + q[2]) + 2*lg3*cos(q[1] + q[2] + q[3]))*(-dq[1]^2*l1*sin(q[1]) - l2*(dq[1] + dq[2])^2*sin(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])^2*sin(q[1] + q[2] + q[3])) + (-2*dq[1]*l1*sin(q[1]) - 2*l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - 2*lg3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]))*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + lg3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3])) + (-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]))*(-2*dq[1]*l1*cos(q[1]) - 2*l2*(dq[1] + dq[2])*cos(q[1] + q[2]) - 2*lg3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]))) - 0.5*m4*((-2*dq[1]*l1*sin(q[1]) - 2*l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - 2*l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) + lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4])) + (-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))*(-2*dq[1]*l1*cos(q[1]) - 2*l2*(dq[1] + dq[2])*cos(q[1] + q[2]) - 2*l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4]))) + 0.5*m4*((-2*l1*sin(q[1]) - 2*l2*sin(q[1] + q[2]) - 2*l3*sin(q[1] + q[2] + q[3]) - 2*lg4*sin(q[1] + q[2] + q[3] + q[4]))*(-dq[1]^2*l1*cos(q[1]) - l2*(dq[1] + dq[2])^2*cos(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])^2*cos(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])^2*cos(q[1] + q[2] + q[3] + q[4])) + (2*l1*cos(q[1]) + 2*l2*cos(q[1] + q[2]) + 2*l3*cos(q[1] + q[2] + q[3]) + 2*lg4*cos(q[1] + q[2] + q[3] + q[4]))*(-dq[1]^2*l1*sin(q[1]) - l2*(dq[1] + dq[2])^2*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])^2*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])^2*sin(q[1] + q[2] + q[3] + q[4])) + (-2*dq[1]*l1*sin(q[1]) - 2*l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - 2*l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) + lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4])) + (-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))*(-2*dq[1]*l1*cos(q[1]) - 2*l2*(dq[1] + dq[2])*cos(q[1] + q[2]) - 2*l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4])))
    u_all2 = g*lg2*m2*cos(q[1] + q[2]) + g*m3*(l2*cos(q[1] + q[2]) + lg3*cos(q[1] + q[2] + q[3])) + g*m4*(l2*cos(q[1] + q[2]) + l3*cos(q[1] + q[2] + q[3]) + lg4*cos(q[1] + q[2] + q[3] + q[4])) - 0.5*m2*(-2*lg2*(dq[1] + dq[2])*(-dq[1]*l1*sin(q[1]) - lg2*(dq[1] + dq[2])*sin(q[1] + q[2]))*cos(q[1] + q[2]) - 2*lg2*(dq[1] + dq[2])*(dq[1]*l1*cos(q[1]) + lg2*(dq[1] + dq[2])*cos(q[1] + q[2]))*sin(q[1] + q[2])) + 0.5*m2*(-2*lg2*(dq[1] + dq[2])*(-dq[1]*l1*sin(q[1]) - lg2*(dq[1] + dq[2])*sin(q[1] + q[2]))*cos(q[1] + q[2]) - 2*lg2*(dq[1] + dq[2])*(dq[1]*l1*cos(q[1]) + lg2*(dq[1] + dq[2])*cos(q[1] + q[2]))*sin(q[1] + q[2]) + 2*lg2*(-dq[1]^2*l1*sin(q[1]) - lg2*(dq[1] + dq[2])^2*sin(q[1] + q[2]))*cos(q[1] + q[2]) - 2*lg2*(-dq[1]^2*l1*cos(q[1]) - lg2*(dq[1] + dq[2])^2*cos(q[1] + q[2]))*sin(q[1] + q[2])) - 0.5*m3*((-2*l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - 2*lg3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]))*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + lg3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3])) + (-2*l2*(dq[1] + dq[2])*cos(q[1] + q[2]) - 2*lg3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]))*(-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]))) + 0.5*m3*((-2*l2*sin(q[1] + q[2]) - 2*lg3*sin(q[1] + q[2] + q[3]))*(-dq[1]^2*l1*cos(q[1]) - l2*(dq[1] + dq[2])^2*cos(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])^2*cos(q[1] + q[2] + q[3])) + (2*l2*cos(q[1] + q[2]) + 2*lg3*cos(q[1] + q[2] + q[3]))*(-dq[1]^2*l1*sin(q[1]) - l2*(dq[1] + dq[2])^2*sin(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])^2*sin(q[1] + q[2] + q[3])) + (-2*l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - 2*lg3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]))*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + lg3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3])) + (-2*l2*(dq[1] + dq[2])*cos(q[1] + q[2]) - 2*lg3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]))*(-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]))) - 0.5*m4*((-2*l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - 2*l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) + lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4])) + (-2*l2*(dq[1] + dq[2])*cos(q[1] + q[2]) - 2*l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4]))*(-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))) + 0.5*m4*((-2*l2*sin(q[1] + q[2]) - 2*l3*sin(q[1] + q[2] + q[3]) - 2*lg4*sin(q[1] + q[2] + q[3] + q[4]))*(-dq[1]^2*l1*cos(q[1]) - l2*(dq[1] + dq[2])^2*cos(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])^2*cos(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])^2*cos(q[1] + q[2] + q[3] + q[4])) + (2*l2*cos(q[1] + q[2]) + 2*l3*cos(q[1] + q[2] + q[3]) + 2*lg4*cos(q[1] + q[2] + q[3] + q[4]))*(-dq[1]^2*l1*sin(q[1]) - l2*(dq[1] + dq[2])^2*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])^2*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])^2*sin(q[1] + q[2] + q[3] + q[4])) + (-2*l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - 2*l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) + lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4])) + (-2*l2*(dq[1] + dq[2])*cos(q[1] + q[2]) - 2*l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4]))*(-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4])))
    u_all3 = g*lg3*m3*cos(q[1] + q[2] + q[3]) + g*m4*(l3*cos(q[1] + q[2] + q[3]) + lg4*cos(q[1] + q[2] + q[3] + q[4])) - 0.5*m3*(-2*lg3*(dq[1] + dq[2] + dq[3])*(-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]))*cos(q[1] + q[2] + q[3]) - 2*lg3*(dq[1] + dq[2] + dq[3])*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + lg3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]))*sin(q[1] + q[2] + q[3])) + 0.5*m3*(-2*lg3*(dq[1] + dq[2] + dq[3])*(-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]))*cos(q[1] + q[2] + q[3]) - 2*lg3*(dq[1] + dq[2] + dq[3])*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + lg3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]))*sin(q[1] + q[2] + q[3]) + 2*lg3*(-dq[1]^2*l1*sin(q[1]) - l2*(dq[1] + dq[2])^2*sin(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])^2*sin(q[1] + q[2] + q[3]))*cos(q[1] + q[2] + q[3]) - 2*lg3*(-dq[1]^2*l1*cos(q[1]) - l2*(dq[1] + dq[2])^2*cos(q[1] + q[2]) - lg3*(dq[1] + dq[2] + dq[3])^2*cos(q[1] + q[2] + q[3]))*sin(q[1] + q[2] + q[3])) - 0.5*m4*((-2*l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) + lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4])) + (-2*l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4]))*(-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))) + 0.5*m4*((-2*l3*sin(q[1] + q[2] + q[3]) - 2*lg4*sin(q[1] + q[2] + q[3] + q[4]))*(-dq[1]^2*l1*cos(q[1]) - l2*(dq[1] + dq[2])^2*cos(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])^2*cos(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])^2*cos(q[1] + q[2] + q[3] + q[4])) + (2*l3*cos(q[1] + q[2] + q[3]) + 2*lg4*cos(q[1] + q[2] + q[3] + q[4]))*(-dq[1]^2*l1*sin(q[1]) - l2*(dq[1] + dq[2])^2*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])^2*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])^2*sin(q[1] + q[2] + q[3] + q[4])) + (-2*l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) + lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4])) + (-2*l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4]))*(-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4])))
    u_all4 = g*lg4*m4*cos(q[1] + q[2] + q[3] + q[4]) - 0.5*m4*(-2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*(-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))*cos(q[1] + q[2] + q[3] + q[4]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) + lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4]))*sin(q[1] + q[2] + q[3] + q[4])) + 0.5*m4*(-2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*(-dq[1]*l1*sin(q[1]) - l2*(dq[1] + dq[2])*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])*sin(q[1] + q[2] + q[3] + q[4]))*cos(q[1] + q[2] + q[3] + q[4]) - 2*lg4*(dq[1] + dq[2] + dq[3] + dq[4])*(dq[1]*l1*cos(q[1]) + l2*(dq[1] + dq[2])*cos(q[1] + q[2]) + l3*(dq[1] + dq[2] + dq[3])*cos(q[1] + q[2] + q[3]) + lg4*(dq[1] + dq[2] + dq[3] + dq[4])*cos(q[1] + q[2] + q[3] + q[4]))*sin(q[1] + q[2] + q[3] + q[4]) + 2*lg4*(-dq[1]^2*l1*sin(q[1]) - l2*(dq[1] + dq[2])^2*sin(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])^2*sin(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])^2*sin(q[1] + q[2] + q[3] + q[4]))*cos(q[1] + q[2] + q[3] + q[4]) - 2*lg4*(-dq[1]^2*l1*cos(q[1]) - l2*(dq[1] + dq[2])^2*cos(q[1] + q[2]) - l3*(dq[1] + dq[2] + dq[3])^2*cos(q[1] + q[2] + q[3]) - lg4*(dq[1] + dq[2] + dq[3] + dq[4])^2*cos(q[1] + q[2] + q[3] + q[4]))*sin(q[1] + q[2] + q[3] + q[4]))

    [
        u_all1
        u_all2
        u_all3
        u_all4
    ]
end

"""トルクを計算

計算トルク法です
q : 関節角度ベクトル
dq : 関節角速度ベクトル
desired_ddq : （所望の）関節角速度ベクトル
"""
function calc_torque(
    q::Vector{TU}, dq::Vector{TU}, desired_ddq::Vector{TU}
    ) where TU
    M(q)*desired_ddq .+ C_and_G(q, dq) |> vec
end

# """物体から受ける力を計算"""
# function calc_Fc(;
#     u::Vector{TU}, q::Vector{TU}, dq::Vector{TU},
#     F::Vector{TU},
#     Jend::Matrix{TU}
#     ) where TU

#     inv(transpose(Jend)) * (M(q)*desired_ddq .+ C_and_G(q, dq) .- u .- F) |> vec
# end

"""現実世界での加速度

u : 入力トルクベクトル R(7)
q : （現在の）関節角度ベクトル
dq : （現在の）関節角速度ベクトル
F : 外乱ベクトル R(7)
Fc : エンドエフェクタに加わる外力ベクトル
Jend : エンドエフェクタのヤコビ行列
"""
function calc_real_ddq(;
    u::Vector{TU}, q::Vector{TU}, dq::Vector{TU},
    F::Vector{TU}, Fc::Vector{TU},
    Jend::Matrix{TU}
    ) where TU

    # println(size(transpose(Jend)))
    # println(transpose(Jend) * Fc)
    # println(F)

    _Fc = transpose(Jend) * Fc
    @. F += _Fc

    #println(F)

    inv(M(q)) * (u .+ F .- (C_and_G(q, dq))) |> vec
end

end

# function test()
#     q = [
#         -90.0
#         0.0
#         0.0
#         0.0
#     ] * pi / 180
#     dq = zero(q)
#     ddq = zero(q)

#     println(M(q))

#     @time println(calc_torque(q, dq, ddq))
# end

# test()


text:
# grids.jl

using Adapt

mutable struct Grid{T}
    # grid_type::String
    nx::Int64
    ny::Int64
    nz::Int64
    Δx::Float64
    Δy::Float64
    Δz::Float64
    x::T
    y::T
    z::T
end

function grid_coords(n1, n2, n3, Δ1, Δ2, Δ3, useCUDA)
    # Create 3D structured grid
    # For now cell centered
    coord1 = Array{Float64,1}(undef, n1)
    for n = 1:n1
        coord1[n] = (n - 0.5) * Δ1
    end

    coord2 = Array{Float64,1}(undef, n2)
    for n = 1:n2
        coord2[n] = (n - 0.5) * Δ2
    end

    coord3 = Array{Float64,1}(undef, n3)
    for n = 1:n3
        coord3[n] = (n - 0.5) * Δ3
    end

    if useCUDA
        # Convert to CUDA Arrays
        println(typeof(coord1))
        coord1 = adapt(CuArray, coord1)
        coord2 = adapt(CuArray, coord2)
        coord3 = adapt(CuArray, coord3)
        println(typeof(coord1))
    end
    return coord1, coord2, coord3
end

# function sigma_grid!(grid, state)
#     nx  = grid[1]
#     nz  = grid[2]
#     Δx  = grid.Δx
#     Δz  = grid.Δz
#     xc  = grid.xc
#     zc  = grid.zc
#     xu  = grid.xu
#     zu  = grid.zu
#     xw  = grid.xw
#     zw  = grid.zw
#
#     dzs = state.Δzₛ
#     dzu = state.Δzᵤ
#
#     # Co-ordinates of the cell centres
#     zc[:,1] = 0.5*dzs[:,1]
#     for i = 1:nx
#         #for j = 1:ny
#         for k = 2:nz
#             xc[i,k] = (i-0.5)*Δx
#             zc[i,k] = zc[i,k-1] + 0.5*(dzs[i,k-1]+dzs[i,k])
#         end
#     end
#
#     # Co-ordinates of the horizontal velocity points
#     zu[:,1] = 0.5*dzu[:,1]
#     for i = 1:nx+1
#         #for j = 1:ny
#         for k = 2:nz
#             xu[i,k] = (i-1)*Δx
#             zu[i,k] = zu[i,k-1] + 0.5*(dzu[i,k-1]+dzu[i,k])
#         end
#     end
#
#     # Co-ordinates of the vertical velocity points
#     zw[:,1] .= 0.0
#     for i = 1:nx
#         #for j = 1:ny
#         for k = 2:nz+1
#             xw[i,k] = (i-0.5)*Δx
#             zw[i,k] = zw[i,k-1] + dzs[i,k-1]
#         end
#     end
#
# end


text:
using DelayEmbeddings
using DimensionalData
import DelayEmbeddings.selfmutualinfo
using Plots

function selfmutualinfo(P::Process, lags; vars=1:length(getX0(P)), kwargs...)
    dt = getsavedt(P)
    X = timeseries(P, vars)
    AMI = selfmutualinfo.(eachcol(X), (lags,); kwargs...)
    X isa AbstractVector ? DimArray(AMI[1], Dim{:τ}(lags.*dt), :AMI) : DimArray(hcat(AMI...), (Dim{:τ}(lags.*dt), dims(X, 2)), :AMI)
end
# ! The DelayEmbeddings.mincrossing isn't so greate, because any small noise will be counted as a local minimum if the sampling period is small.
function selfmutualinfo(P::Process; τmultiple=10, kwargs...) # This one automatically calculates some sensible lags and returns an AMI function over a nice range of lags
    ts = 1:length(times(P))÷10
    AMI = selfmutualinfo(P, ts; kwargs...)
    τ = round(Int, mean(DelayEmbeddings.mincrossing.(eachcol(AMI), (1:size(AMI, 1),))))
    return AMI isa AbstractVector ? AMI[1:τ*τmultiple] : AMI[1:τ*τmultiple, :]
end
export selfmutualinfo


text:
# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/AbaqusReader.jl/blob/master/LICENSE

using AbaqusReader
using Test

include("../docs/make.jl")

@testset "AbaqusReader.jl" begin
    @testset "test_parse_mesh" begin include("test_parse_mesh.jl") end
    @testset "test_parse_model" begin include("test_parse_model.jl") end
    @testset "test_create_surface_elements" begin include("test_create_surface_elements.jl") end
    @testset "test_download" begin include("test_download.jl") end
    @testset "test_parse_t2d2" begin include("test_parse_t2d2.jl") end
    @testset "test_parse_beams" begin include("test_parse_beams.jl") end
end

include("../docs/deploy.jl")


text:
module ASCIIByte

  ## Dependencies ##
  using Base.Intrinsics
  import Base.interp_parse_bytes

  ## Overwritten and/or extended methods ##
  importall Base

  ## Exported methods and types ##
  export ASCIIChar,
	uppercase!,
	lowercase!,
	swap!,
	swap,
	in,
	check,
	## 8-bit Char ##
	Char8,
	char8,
	@c8_str

  ## Load files ##
  include(Pkg.dir("ASCIIByte", "src", "asciichar.jl"))
  include(Pkg.dir("ASCIIByte", "src", "stringlike.jl"))
  include(Pkg.dir("ASCIIByte", "src", "alphabetsfunc.jl"))
  include(Pkg.dir("ASCIIByte", "src", "char8.jl"))

end


text:
"""
# Onda Corporation
# Hydrophone Calibration Data
#
Calibration_DATE	30-Sep-2021
#
# Hydrophone description
HYD_MFG	Onda
HYD_MODEL	HGL
HYD_APERTURE_NOM_UM	0200
HYD_SN	2512
HYD_POLARITY	Positive
#
# External preamplifier description
AMP_MFG	NONE
AMP_MODEL	NONE
AMP_SN	NONE
AMP_GAIN_NOM_DB	NONE
AMP_BW_MHZ	NONE
AMP_OUTPUT_IMP_NOM_OHMS	NONE
#
# Cable/adaptor between hydrophone and preamplifier
CA_BWT_HYD_AMP	NONE
#
# Environment
ELECTRICAL_LOAD	OpenCircuit
WATER_TEMP_DEGC	23.5
WATER_RESISTIVITY_MOHMS-CM	7.5
#
# Calibration data
# Freq(MHz) Sens(dB re. 1V/uPa) Sens(V/Pa) Sens(V^2cm^2/W) Cap(pF)
#
DATA_FIELDS	5
DATA_FIELD	FREQ_MHz
DATA_FIELD	SENS_DB
DATA_FIELD	SENS_VPERPA
DATA_FIELD	SENS_V2CM2PERW
DATA_FIELD	CAP_PF
# End of file header
HEADER_END	0
"""

@calibration :Onda_HGL0200_2512 [
 1.000	 -267.20	  4.365E-008	2.859E-005	      9.173
 1.050	 -267.45	  4.240E-008	2.696E-005	      9.164
 1.100	 -267.29	  4.319E-008	2.798E-005	      9.155
 1.150	 -267.11	  4.411E-008	2.919E-005	      9.147
 1.200	 -267.12	  4.407E-008	2.913E-005	      9.138
 1.250	 -267.00	  4.467E-008	2.993E-005	      9.130
 1.300	 -267.01	  4.460E-008	2.984E-005	      9.121
 1.350	 -267.16	  4.385E-008	2.884E-005	      9.113
 1.400	 -267.11	  4.410E-008	2.917E-005	      9.105
 1.450	 -267.09	  4.422E-008	2.933E-005	      9.097
 1.500	 -267.33	  4.302E-008	2.776E-005	      9.089
 1.550	 -267.15	  4.388E-008	2.888E-005	      9.081
 1.600	 -267.27	  4.331E-008	2.813E-005	      9.074
 1.650	 -267.70	  4.122E-008	2.549E-005	      9.066
 1.700	 -267.78	  4.083E-008	2.501E-005	      9.058
 1.750	 -267.82	  4.063E-008	2.476E-005	      9.051
 1.800	 -268.15	  3.911E-008	2.295E-005	      9.044
 1.850	 -268.34	  3.829E-008	2.199E-005	      9.036
 1.900	 -268.65	  3.695E-008	2.048E-005	      9.029
 1.950	 -268.91	  3.587E-008	1.930E-005	      9.022
 2.000	 -268.85	  3.608E-008	1.953E-005	      9.016
 2.050	 -268.72	  3.663E-008	2.012E-005	      9.009
 2.100	 -268.27	  3.858E-008	2.233E-005	      9.002
 2.150	 -267.93	  4.013E-008	2.416E-005	      8.995
 2.200	 -267.68	  4.131E-008	2.560E-005	      8.989
 2.250	 -267.87	  4.041E-008	2.450E-005	      8.982
 2.300	 -268.21	  3.886E-008	2.265E-005	      8.976
 2.350	 -268.02	  3.971E-008	2.366E-005	      8.970
 2.400	 -267.73	  4.105E-008	2.528E-005	      8.963
 2.450	 -267.45	  4.240E-008	2.697E-005	      8.957
 2.500	 -267.35	  4.293E-008	2.764E-005	      8.951
 2.550	 -267.22	  4.356E-008	2.846E-005	      8.945
 2.600	 -267.09	  4.423E-008	2.934E-005	      8.939
 2.650	 -266.91	  4.515E-008	3.057E-005	      8.934
 2.700	 -267.13	  4.399E-008	2.903E-005	      8.928
 2.750	 -267.54	  4.197E-008	2.642E-005	      8.922
 2.800	 -267.48	  4.228E-008	2.681E-005	      8.917
 2.850	 -267.23	  4.349E-008	2.837E-005	      8.911
 2.900	 -267.19	  4.369E-008	2.864E-005	      8.906
 2.950	 -267.27	  4.329E-008	2.811E-005	      8.901
 3.000	 -267.41	  4.261E-008	2.723E-005	      8.896
 3.050	 -267.69	  4.126E-008	2.553E-005	      8.890
 3.100	 -267.67	  4.137E-008	2.567E-005	      8.885
 3.150	 -267.37	  4.281E-008	2.749E-005	      8.880
 3.200	 -267.25	  4.342E-008	2.828E-005	      8.875
 3.250	 -267.47	  4.233E-008	2.687E-005	      8.871
 3.300	 -267.69	  4.124E-008	2.552E-005	      8.866
 3.350	 -267.54	  4.197E-008	2.642E-005	      8.861
 3.400	 -267.25	  4.338E-008	2.823E-005	      8.857
 3.450	 -267.12	  4.405E-008	2.910E-005	      8.852
 3.500	 -267.12	  4.406E-008	2.912E-005	      8.847
 3.550	 -267.20	  4.364E-008	2.856E-005	      8.843
 3.600	 -267.26	  4.337E-008	2.821E-005	      8.839
 3.650	 -267.31	  4.311E-008	2.787E-005	      8.834
 3.700	 -267.44	  4.246E-008	2.705E-005	      8.830
 3.750	 -267.55	  4.191E-008	2.634E-005	      8.826
 3.800	 -267.60	  4.169E-008	2.607E-005	      8.822
 3.850	 -267.46	  4.236E-008	2.691E-005	      8.818
 3.900	 -267.34	  4.294E-008	2.766E-005	      8.814
 3.950	 -267.48	  4.224E-008	2.677E-005	      8.810
 4.000	 -267.78	  4.083E-008	2.501E-005	      8.806
 4.050	 -267.82	  4.063E-008	2.476E-005	      8.802
 4.100	 -267.57	  4.184E-008	2.626E-005	      8.798
 4.150	 -267.25	  4.338E-008	2.823E-005	      8.795
 4.200	 -267.11	  4.411E-008	2.918E-005	      8.791
 4.250	 -267.24	  4.343E-008	2.829E-005	      8.788
 4.300	 -267.36	  4.284E-008	2.753E-005	      8.784
 4.350	 -267.29	  4.319E-008	2.799E-005	      8.781
 4.400	 -267.20	  4.364E-008	2.856E-005	      8.777
 4.450	 -267.18	  4.374E-008	2.870E-005	      8.774
 4.500	 -267.32	  4.304E-008	2.779E-005	      8.771
 4.550	 -267.52	  4.208E-008	2.656E-005	      8.767
 4.600	 -267.53	  4.202E-008	2.649E-005	      8.764
 4.650	 -267.52	  4.206E-008	2.654E-005	      8.761
 4.700	 -267.54	  4.195E-008	2.640E-005	      8.758
 4.750	 -267.57	  4.182E-008	2.623E-005	      8.755
 4.800	 -267.63	  4.153E-008	2.587E-005	      8.752
 4.850	 -267.66	  4.142E-008	2.574E-005	      8.749
 4.900	 -267.69	  4.126E-008	2.554E-005	      8.746
 4.950	 -267.76	  4.094E-008	2.515E-005	      8.743
 5.000	 -267.68	  4.129E-008	2.558E-005	      8.740
 5.050	 -267.57	  4.181E-008	2.622E-005	      8.737
 5.100	 -267.45	  4.242E-008	2.700E-005	      8.735
 5.150	 -267.30	  4.314E-008	2.791E-005	      8.732
 5.200	 -267.29	  4.322E-008	2.802E-005	      8.729
 5.250	 -267.30	  4.314E-008	2.791E-005	      8.727
 5.300	 -267.25	  4.341E-008	2.827E-005	      8.724
 5.350	 -267.17	  4.380E-008	2.877E-005	      8.722
 5.400	 -267.06	  4.434E-008	2.949E-005	      8.719
 5.450	 -267.00	  4.467E-008	2.993E-005	      8.717
 5.500	 -267.00	  4.467E-008	2.993E-005	      8.714
 5.550	 -266.95	  4.491E-008	3.026E-005	      8.712
 5.600	 -266.96	  4.489E-008	3.022E-005	      8.710
 5.650	 -266.97	  4.483E-008	3.015E-005	      8.707
 5.700	 -266.95	  4.492E-008	3.027E-005	      8.705
 5.750	 -267.04	  4.447E-008	2.967E-005	      8.703
 5.800	 -267.19	  4.372E-008	2.868E-005	      8.701
 5.850	 -267.26	  4.336E-008	2.820E-005	      8.699
 5.900	 -267.38	  4.277E-008	2.744E-005	      8.696
 5.950	 -267.34	  4.294E-008	2.766E-005	      8.694
 6.000	 -267.31	  4.308E-008	2.784E-005	      8.692
 6.050	 -267.25	  4.338E-008	2.823E-005	      8.690
 6.100	 -267.22	  4.356E-008	2.847E-005	      8.688
 6.150	 -267.31	  4.311E-008	2.787E-005	      8.686
 6.200	 -267.38	  4.277E-008	2.743E-005	      8.684
 6.250	 -267.36	  4.285E-008	2.754E-005	      8.682
 6.300	 -267.33	  4.298E-008	2.771E-005	      8.681
 6.350	 -267.25	  4.341E-008	2.826E-005	      8.679
 6.400	 -267.18	  4.377E-008	2.874E-005	      8.677
 6.450	 -267.15	  4.393E-008	2.894E-005	      8.675
 6.500	 -267.13	  4.403E-008	2.907E-005	      8.673
 6.550	 -267.10	  4.418E-008	2.928E-005	      8.672
 6.600	 -267.12	  4.408E-008	2.915E-005	      8.670
 6.650	 -267.18	  4.374E-008	2.870E-005	      8.668
 6.700	 -267.27	  4.332E-008	2.815E-005	      8.667
 6.750	 -267.29	  4.320E-008	2.799E-005	      8.665
 6.800	 -267.35	  4.290E-008	2.760E-005	      8.663
 6.850	 -267.41	  4.259E-008	2.721E-005	      8.662
 6.900	 -267.50	  4.216E-008	2.666E-005	      8.660
 6.950	 -267.56	  4.186E-008	2.628E-005	      8.659
 7.000	 -267.57	  4.183E-008	2.625E-005	      8.657
 7.050	 -267.56	  4.190E-008	2.633E-005	      8.656
 7.100	 -267.52	  4.209E-008	2.658E-005	      8.654
 7.150	 -267.52	  4.207E-008	2.654E-005	      8.653
 7.200	 -267.46	  4.238E-008	2.694E-005	      8.651
 7.250	 -267.43	  4.250E-008	2.710E-005	      8.650
 7.300	 -267.40	  4.267E-008	2.731E-005	      8.648
 7.350	 -267.45	  4.240E-008	2.697E-005	      8.647
 7.400	 -267.53	  4.203E-008	2.650E-005	      8.646
 7.450	 -267.52	  4.206E-008	2.654E-005	      8.644
 7.500	 -267.54	  4.199E-008	2.645E-005	      8.643
 7.550	 -267.56	  4.186E-008	2.629E-005	      8.642
 7.600	 -267.56	  4.189E-008	2.632E-005	      8.640
 7.650	 -267.53	  4.201E-008	2.647E-005	      8.639
 7.700	 -267.52	  4.209E-008	2.658E-005	      8.638
 7.750	 -267.47	  4.234E-008	2.688E-005	      8.637
 7.800	 -267.44	  4.244E-008	2.702E-005	      8.635
 7.850	 -267.39	  4.271E-008	2.736E-005	      8.634
 7.900	 -267.39	  4.272E-008	2.738E-005	      8.633
 7.950	 -267.38	  4.275E-008	2.741E-005	      8.632
 8.000	 -267.36	  4.284E-008	2.752E-005	      8.631
 8.050	 -267.34	  4.293E-008	2.765E-005	      8.629
 8.100	 -267.39	  4.273E-008	2.739E-005	      8.628
 8.150	 -267.40	  4.264E-008	2.727E-005	      8.627
 8.200	 -267.43	  4.253E-008	2.713E-005	      8.626
 8.250	 -267.42	  4.254E-008	2.714E-005	      8.625
 8.300	 -267.43	  4.250E-008	2.710E-005	      8.624
 8.350	 -267.47	  4.229E-008	2.683E-005	      8.623
 8.400	 -267.55	  4.194E-008	2.639E-005	      8.621
 8.450	 -267.56	  4.186E-008	2.628E-005	      8.620
 8.500	 -267.56	  4.190E-008	2.633E-005	      8.619
 8.550	 -267.53	  4.202E-008	2.649E-005	      8.618
 8.600	 -267.50	  4.217E-008	2.668E-005	      8.617
 8.650	 -267.50	  4.217E-008	2.668E-005	      8.616
 8.700	 -267.47	  4.231E-008	2.685E-005	      8.615
 8.750	 -267.42	  4.254E-008	2.715E-005	      8.614
 8.800	 -267.39	  4.273E-008	2.738E-005	      8.613
 8.850	 -267.30	  4.315E-008	2.793E-005	      8.612
 8.900	 -267.24	  4.345E-008	2.831E-005	      8.611
 8.950	 -267.21	  4.361E-008	2.852E-005	      8.610
 9.000	 -267.17	  4.382E-008	2.880E-005	      8.609
 9.050	 -267.12	  4.407E-008	2.913E-005	      8.608
 9.100	 -267.05	  4.441E-008	2.958E-005	      8.607
 9.150	 -267.01	  4.463E-008	2.988E-005	      8.606
 9.200	 -267.07	  4.433E-008	2.947E-005	      8.605
 9.250	 -267.14	  4.393E-008	2.895E-005	      8.604
 9.300	 -267.19	  4.368E-008	2.863E-005	      8.603
 9.350	 -267.19	  4.369E-008	2.864E-005	      8.602
 9.400	 -267.16	  4.387E-008	2.887E-005	      8.601
 9.450	 -267.17	  4.379E-008	2.877E-005	      8.600
 9.500	 -267.20	  4.367E-008	2.860E-005	      8.599
 9.550	 -267.21	  4.361E-008	2.853E-005	      8.598
 9.600	 -267.22	  4.355E-008	2.845E-005	      8.597
 9.650	 -267.21	  4.359E-008	2.850E-005	      8.596
 9.700	 -267.24	  4.347E-008	2.834E-005	      8.595
 9.750	 -267.27	  4.328E-008	2.810E-005	      8.594
 9.800	 -267.32	  4.304E-008	2.779E-005	      8.593
 9.850	 -267.44	  4.248E-008	2.707E-005	      8.592
 9.900	 -267.49	  4.222E-008	2.673E-005	      8.591
 9.950	 -267.43	  4.249E-008	2.709E-005	      8.590
10.000	 -267.38	  4.276E-008	2.742E-005	      8.589
10.050	 -267.36	  4.284E-008	2.753E-005	      8.588
10.100	 -267.33	  4.299E-008	2.773E-005	      8.587
10.150	 -267.34	  4.294E-008	2.766E-005	      8.586
10.200	 -267.34	  4.294E-008	2.765E-005	      8.585
10.250	 -267.37	  4.279E-008	2.746E-005	      8.584
10.300	 -267.43	  4.251E-008	2.710E-005	      8.583
10.350	 -267.41	  4.263E-008	2.726E-005	      8.582
10.400	 -267.42	  4.254E-008	2.715E-005	      8.581
10.450	 -267.48	  4.228E-008	2.682E-005	      8.580
10.500	 -267.51	  4.212E-008	2.662E-005	      8.580
10.550	 -267.58	  4.177E-008	2.617E-005	      8.579
10.600	 -267.63	  4.152E-008	2.586E-005	      8.578
10.650	 -267.68	  4.130E-008	2.559E-005	      8.577
10.700	 -267.78	  4.084E-008	2.501E-005	      8.576
10.750	 -267.83	  4.059E-008	2.471E-005	      8.575
10.800	 -267.86	  4.044E-008	2.453E-005	      8.574
10.850	 -267.92	  4.018E-008	2.422E-005	      8.573
10.900	 -267.98	  3.992E-008	2.391E-005	      8.572
10.950	 -268.07	  3.948E-008	2.337E-005	      8.571
11.000	 -268.15	  3.911E-008	2.295E-005	      8.570
11.050	 -268.20	  3.890E-008	2.270E-005	      8.569
11.100	 -268.21	  3.885E-008	2.264E-005	      8.568
11.150	 -268.22	  3.879E-008	2.258E-005	      8.567
11.200	 -268.16	  3.908E-008	2.291E-005	      8.566
11.250	 -268.14	  3.918E-008	2.303E-005	      8.565
11.300	 -268.12	  3.928E-008	2.315E-005	      8.563
11.350	 -268.02	  3.971E-008	2.365E-005	      8.562
11.400	 -267.97	  3.997E-008	2.396E-005	      8.561
11.450	 -267.87	  4.041E-008	2.449E-005	      8.560
11.500	 -267.77	  4.090E-008	2.509E-005	      8.559
11.550	 -267.72	  4.110E-008	2.533E-005	      8.558
11.600	 -267.67	  4.133E-008	2.563E-005	      8.557
11.650	 -267.65	  4.144E-008	2.576E-005	      8.556
11.700	 -267.63	  4.156E-008	2.591E-005	      8.555
11.750	 -267.54	  4.196E-008	2.641E-005	      8.554
11.800	 -267.51	  4.213E-008	2.662E-005	      8.553
11.850	 -267.46	  4.235E-008	2.691E-005	      8.552
11.900	 -267.47	  4.230E-008	2.684E-005	      8.551
11.950	 -267.46	  4.235E-008	2.690E-005	      8.550
12.000	 -267.43	  4.249E-008	2.708E-005	      8.549
12.050	 -267.39	  4.273E-008	2.739E-005	      8.548
12.100	 -267.36	  4.285E-008	2.754E-005	      8.546
12.150	 -267.34	  4.294E-008	2.766E-005	      8.545
12.200	 -267.33	  4.299E-008	2.772E-005	      8.544
12.250	 -267.31	  4.309E-008	2.785E-005	      8.543
12.300	 -267.22	  4.356E-008	2.846E-005	      8.542
12.350	 -267.23	  4.350E-008	2.839E-005	      8.541
12.400	 -267.20	  4.364E-008	2.856E-005	      8.540
12.450	 -267.20	  4.364E-008	2.857E-005	      8.539
12.500	 -267.23	  4.348E-008	2.836E-005	      8.537
12.550	 -267.20	  4.365E-008	2.858E-005	      8.536
12.600	 -267.19	  4.368E-008	2.862E-005	      8.535
12.650	 -267.18	  4.375E-008	2.871E-005	      8.534
12.700	 -267.17	  4.378E-008	2.875E-005	      8.533
12.750	 -267.18	  4.374E-008	2.869E-005	      8.532
12.800	 -267.11	  4.411E-008	2.918E-005	      8.530
12.850	 -267.13	  4.403E-008	2.908E-005	      8.529
12.900	 -267.10	  4.415E-008	2.924E-005	      8.528
12.950	 -267.08	  4.428E-008	2.941E-005	      8.527
13.000	 -267.12	  4.406E-008	2.912E-005	      8.526
13.050	 -267.11	  4.412E-008	2.920E-005	      8.524
13.100	 -267.13	  4.399E-008	2.903E-005	      8.523
13.150	 -267.20	  4.366E-008	2.859E-005	      8.522
13.200	 -267.12	  4.407E-008	2.913E-005	      8.521
13.250	 -267.17	  4.382E-008	2.881E-005	      8.520
13.300	 -267.19	  4.368E-008	2.863E-005	      8.518
13.350	 -267.19	  4.370E-008	2.864E-005	      8.517
13.400	 -267.21	  4.360E-008	2.852E-005	      8.516
13.450	 -267.24	  4.344E-008	2.830E-005	      8.515
13.500	 -267.26	  4.334E-008	2.817E-005	      8.513
13.550	 -267.24	  4.345E-008	2.832E-005	      8.512
13.600	 -267.34	  4.296E-008	2.769E-005	      8.511
13.650	 -267.28	  4.327E-008	2.809E-005	      8.510
13.700	 -267.25	  4.339E-008	2.824E-005	      8.509
13.750	 -267.25	  4.339E-008	2.824E-005	      8.507
13.800	 -267.33	  4.301E-008	2.774E-005	      8.506
13.850	 -267.30	  4.314E-008	2.791E-005	      8.505
13.900	 -267.20	  4.363E-008	2.855E-005	      8.503
13.950	 -267.21	  4.362E-008	2.854E-005	      8.502
14.000	 -267.28	  4.326E-008	2.808E-005	      8.501
14.050	 -267.28	  4.323E-008	2.804E-005	      8.500
14.100	 -267.22	  4.357E-008	2.848E-005	      8.498
14.150	 -267.16	  4.384E-008	2.883E-005	      8.497
14.200	 -267.12	  4.404E-008	2.909E-005	      8.496
14.250	 -267.10	  4.417E-008	2.927E-005	      8.495
14.300	 -267.11	  4.411E-008	2.918E-005	      8.493
14.350	 -267.12	  4.404E-008	2.909E-005	      8.492
14.400	 -267.11	  4.408E-008	2.915E-005	      8.491
14.450	 -267.09	  4.420E-008	2.931E-005	      8.489
14.500	 -267.08	  4.425E-008	2.937E-005	      8.488
14.550	 -267.09	  4.419E-008	2.929E-005	      8.487
14.600	 -267.08	  4.427E-008	2.940E-005	      8.486
14.650	 -267.11	  4.410E-008	2.918E-005	      8.484
14.700	 -267.14	  4.394E-008	2.896E-005	      8.483
14.750	 -267.16	  4.386E-008	2.886E-005	      8.482
14.800	 -267.11	  4.408E-008	2.915E-005	      8.480
14.850	 -267.14	  4.395E-008	2.897E-005	      8.479
14.900	 -267.11	  4.409E-008	2.916E-005	      8.478
14.950	 -267.18	  4.377E-008	2.873E-005	      8.477
15.000	 -267.15	  4.390E-008	2.891E-005	      8.475
15.050	 -267.17	  4.380E-008	2.878E-005	      8.474
15.100	 -267.17	  4.383E-008	2.881E-005	      8.473
15.150	 -267.11	  4.410E-008	2.918E-005	      8.472
15.200	 -267.12	  4.403E-008	2.908E-005	      8.470
15.250	 -267.19	  4.370E-008	2.865E-005	      8.469
15.300	 -267.11	  4.410E-008	2.918E-005	      8.468
15.350	 -267.11	  4.413E-008	2.921E-005	      8.466
15.400	 -267.12	  4.405E-008	2.911E-005	      8.465
15.450	 -267.07	  4.432E-008	2.946E-005	      8.464
15.500	 -267.10	  4.414E-008	2.922E-005	      8.463
15.550	 -267.13	  4.402E-008	2.906E-005	      8.461
15.600	 -267.04	  4.446E-008	2.965E-005	      8.460
15.650	 -266.99	  4.474E-008	3.003E-005	      8.459
15.700	 -267.02	  4.457E-008	2.980E-005	      8.458
15.750	 -266.97	  4.484E-008	3.016E-005	      8.457
15.800	 -267.05	  4.444E-008	2.962E-005	      8.455
15.850	 -267.05	  4.441E-008	2.958E-005	      8.454
15.900	 -267.04	  4.448E-008	2.968E-005	      8.453
15.950	 -266.94	  4.496E-008	3.032E-005	      8.452
16.000	 -266.93	  4.504E-008	3.042E-005	      8.451
16.050	 -266.97	  4.481E-008	3.012E-005	      8.449
16.100	 -266.87	  4.535E-008	3.084E-005	      8.448
16.150	 -266.84	  4.548E-008	3.103E-005	      8.447
16.200	 -266.82	  4.559E-008	3.117E-005	      8.446
16.250	 -266.81	  4.566E-008	3.127E-005	      8.445
16.300	 -266.81	  4.567E-008	3.128E-005	      8.444
16.350	 -266.83	  4.553E-008	3.109E-005	      8.442
16.400	 -266.80	  4.569E-008	3.132E-005	      8.441
16.450	 -266.79	  4.577E-008	3.142E-005	      8.440
16.500	 -266.88	  4.531E-008	3.079E-005	      8.439
16.550	 -266.85	  4.545E-008	3.098E-005	      8.438
16.600	 -266.78	  4.581E-008	3.148E-005	      8.437
16.650	 -266.86	  4.541E-008	3.094E-005	      8.436
16.700	 -266.85	  4.544E-008	3.097E-005	      8.435
16.750	 -266.79	  4.578E-008	3.144E-005	      8.434
16.800	 -266.79	  4.576E-008	3.141E-005	      8.433
16.850	 -266.79	  4.579E-008	3.144E-005	      8.432
16.900	 -266.86	  4.538E-008	3.089E-005	      8.431
16.950	 -266.84	  4.547E-008	3.102E-005	      8.430
17.000	 -266.75	  4.596E-008	3.168E-005	      8.429
17.050	 -266.85	  4.544E-008	3.097E-005	      8.428
17.100	 -266.86	  4.542E-008	3.094E-005	      8.427
17.150	 -266.79	  4.576E-008	3.141E-005	      8.426
17.200	 -266.80	  4.571E-008	3.134E-005	      8.425
17.250	 -266.77	  4.585E-008	3.154E-005	      8.424
17.300	 -266.95	  4.494E-008	3.029E-005	      8.423
17.350	 -266.94	  4.499E-008	3.037E-005	      8.423
17.400	 -266.88	  4.531E-008	3.079E-005	      8.422
17.450	 -266.85	  4.544E-008	3.097E-005	      8.421
17.500	 -266.85	  4.545E-008	3.098E-005	      8.420
17.550	 -266.82	  4.561E-008	3.120E-005	      8.419
17.600	 -266.78	  4.582E-008	3.149E-005	      8.419
17.650	 -266.86	  4.541E-008	3.093E-005	      8.418
17.700	 -266.94	  4.497E-008	3.034E-005	      8.417
17.750	 -266.91	  4.514E-008	3.056E-005	      8.417
17.800	 -266.93	  4.506E-008	3.045E-005	      8.416
17.850	 -266.93	  4.503E-008	3.042E-005	      8.415
17.900	 -267.02	  4.456E-008	2.978E-005	      8.415
17.950	 -267.01	  4.461E-008	2.985E-005	      8.414
18.000	 -266.93	  4.503E-008	3.042E-005	      8.414
18.050	 -266.89	  4.524E-008	3.071E-005	      8.413
18.100	 -266.89	  4.525E-008	3.071E-005	      8.413
18.150	 -266.92	  4.507E-008	3.047E-005	      8.412
18.200	 -267.03	  4.453E-008	2.974E-005	      8.412
18.250	 -267.01	  4.463E-008	2.988E-005	      8.411
18.300	 -267.00	  4.465E-008	2.991E-005	      8.411
18.350	 -266.88	  4.529E-008	3.077E-005	      8.410
18.400	 -266.87	  4.534E-008	3.084E-005	      8.410
18.450	 -266.92	  4.507E-008	3.046E-005	      8.410
18.500	 -266.96	  4.485E-008	3.017E-005	      8.410
18.550	 -267.09	  4.420E-008	2.930E-005	      8.409
18.600	 -267.12	  4.407E-008	2.913E-005	      8.409
18.650	 -267.05	  4.442E-008	2.959E-005	      8.409
18.700	 -266.97	  4.481E-008	3.012E-005	      8.409
18.750	 -266.89	  4.522E-008	3.067E-005	      8.409
18.800	 -266.88	  4.530E-008	3.078E-005	      8.409
18.850	 -266.80	  4.572E-008	3.135E-005	      8.408
18.900	 -266.70	  4.626E-008	3.210E-005	      8.408
18.950	 -266.82	  4.562E-008	3.121E-005	      8.408
19.000	 -267.10	  4.415E-008	2.924E-005	      8.409
19.050	 -267.05	  4.439E-008	2.956E-005	      8.409
19.100	 -266.80	  4.568E-008	3.130E-005	      8.409
19.150	 -266.95	  4.491E-008	3.025E-005	      8.409
19.200	 -267.01	  4.464E-008	2.989E-005	      8.409
19.250	 -266.84	  4.550E-008	3.105E-005	      8.409
19.300	 -266.79	  4.574E-008	3.138E-005	      8.410
19.350	 -266.85	  4.542E-008	3.095E-005	      8.410
19.400	 -266.90	  4.519E-008	3.063E-005	      8.410
19.450	 -266.97	  4.482E-008	3.013E-005	      8.411
19.500	 -266.96	  4.486E-008	3.018E-005	      8.411
19.550	 -266.92	  4.509E-008	3.049E-005	      8.412
19.600	 -266.84	  4.552E-008	3.108E-005	      8.412
19.650	 -266.83	  4.553E-008	3.110E-005	      8.413
19.700	 -266.83	  4.557E-008	3.115E-005	      8.414
19.750	 -267.01	  4.462E-008	2.986E-005	      8.414
19.800	 -266.99	  4.471E-008	2.999E-005	      8.415
19.850	 -266.84	  4.549E-008	3.103E-005	      8.416
19.900	 -266.81	  4.565E-008	3.126E-005	      8.416
19.950	 -266.82	  4.560E-008	3.119E-005	      8.416
20.000	 -266.83	  4.555E-008	3.112E-005	      8.417
]


text:
module MaxHelpingHandColorGradeFadeTrigger

using ..Ahorn, Maple

@mapdef Trigger "MaxHelpingHand/ColorGradeFadeTrigger" ColorGradeFadeTrigger(x::Integer, y::Integer, width::Integer=Maple.defaultTriggerWidth, height::Integer=Maple.defaultTriggerHeight,
    colorGradeA::String="none", colorGradeB::String="none", direction::String="LeftToRight", evenDuringReflectionFall::Bool=false)

const placements = Ahorn.PlacementDict(
    "Color Grade Fade (max480's Helping Hand)" => Ahorn.EntityPlacement(
        ColorGradeFadeTrigger,
        "rectangle",
    ),
)

const colorGrades = String["none", "oldsite", "panicattack", "templevoid", "reflection", "credits", "cold", "hot", "feelingdown", "golden"]

function Ahorn.editingOptions(trigger::ColorGradeFadeTrigger)
    return Dict{String, Any}(
        "direction" => String["LeftToRight", "TopToBottom"],
        "colorGradeA" => colorGrades,
        "colorGradeB" => colorGrades
    )
end

end

max_stars_repo_name: Kitty-Cats/MaxHelpingHand

max_issues_repo_name: Kitty-Cats/MaxHelpingHand

max_forks_repo_name: Kitty-Cats/MaxHelpingHand


text:
export susieGLM, fineQTL_glm
using GLM

function susieGLM(L::Int64,Π::Vector{Float64},y::Vector{Float64},X::Matrix{Float64},X₀::Union{Matrix{Float64},Vector{Float64}};tol=1e-4)

    n =size(X₀,1)
    y1= zeros(n)

    if(X₀!= ones(n,1)) #&&(size(X₀,2)>1)
        X₀ = hcat(ones(n),X₀)
    end

    y1 =y.-0.5 # centered y
#initialization :
 σ0 = ones(L);
#  β = rand(c)/sqrt(c)
#  ξ = rand(n)/sqrt(n)

 β0 = glm(X₀,y,Binomial()) |> coef
 ν0 =sum(repeat(Π,outer=(1,L)).*σ0',dims=2)[:,1] ; #ν²0
 ξ0 =sqrt.(getXy('N',X.^2.0,ν0)+getXy('N',X₀,β0).^2)

    result = emGLM(L,y1,X,X₀,β0,ξ0,σ0,Π;tol=tol)

return result

end

"""

fineQTL_glm(G::GenoInfo,y::Vector{Float64},X::Matrix{Float64},X₀::Union{Matrix{Float64},Vector{Float64}}=ones(length(y),1)
;L::Int64=10,Π::Vector{Float64}=[1/size(X,2)],tol=1e-4)

Performs SuSiE (Sum of Single Effects model) GLM fine-mapping analysis for a binary trait (logistic regression).

# Arguments

- `G` : a Type of struct, `GenoInfo`. See [`GenoInfo`](@ref).
- `y` : a n x 1 vector of  binary trait
- `X` : a n x p matrix of genetic markers selected from QTL analysis
- `X₀`: a n x 1 vector or n x c matrix of covariates.  The intercept is default if no covariate is added.

## Keyword Arguments

- `L` : an integer. The number of single effects for SuSiE implementation. Default is `10`.
- `Π` : a p x 1 vector of prior inclusion probabilities for SuSiE.  Default is `1/p`, where `p = size(X,2)`. If different probabilities are added to SNPs, the length of Π should be `p`.
- `tol`: tolerance. Default is `1e-4`.

# Output

 Returns a Type of struct, `ResGLM` per Chromosome (`p1 = # of SNP in a Chromosome`), which includes

-  `ξ` : a n x 1 vector of variational parameters to fit a logitstic function
-  `β` : a c x 1 vector of fixed effects for covariates
-  `σ0` : a L x 1 vector of hyper-parameters for prior variances for SuSiE
-  `elbo`: a p1 x 1 vector of evidence lower bound (ELBO)
-  `α` : a p1 x L matrix of posterior inclusion probabilities of SuSiE
-  `ν` : a p1 x L matrix of posterior mean of SuSiE
-  `Σ` : a p1 x L matrix of posterior variances of SuSiE

"""
function fineQTL_glm(G::GenoInfo,y::Vector{Float64},X::Matrix{Float64},
    X₀::Union{Matrix{Float64},Vector{Float64}}=ones(length(y),1);L::Int64=10,Π::Vector{Float64}=[1/size(X,2)],tol=1e-4)

    Chr=sort(unique(G.chr));
    est= @distributed (vcat) for j= eachindex(Chr)
                 midx= findall(G.chr.== Chr[j])
                  #check size of Π
                  if (Π==[1/size(X,2)]) #default value
                    m=length(midx)
                    Π1 =ones(m)/m #adjusting πⱼ
                   elseif (length(Π)!= size(X,2))
                      println("Error. The length of Π should match $(size(X,2)) SNPs!")
                   else
                    Π1 = Π[midx]
                 end

                 est0= susieGLM(L,Π1,y,X[:,midx],X₀;tol=tol)
                        est0
    end

   return est
end


text:
using DataFrames
using Chain
using DataFrameMacros

using CSV
using Arrow
using Downloads

using StatsBase
using Dates

using MacroTools: prettify

url = "https://github.com/RePsychLing/SMLP2021/raw/main/notebooks/data/fggk21.arrow"

df = DataFrame(Arrow.Table(Downloads.download(url)))

df = url |>
    Downloads.download |>
    Arrow.Table |>
    DataFrame |>
    x -> CSV.write("test.csv", x)

df = @chain url begin
    Downloads.download
    Arrow.Table
    DataFrame
    CSV.write("test.csv", _)
end

@macroexpand(@chain url begin
    Downloads.download
    Arrow.Table
    DataFrame
end) |> prettify

describe(df)

transform, select, groupby, combine, subset

transform(df, :Sex =>
    ByRow(bla -> bla == "female" ? "girl" : "boy") =>
    :type)

@transform(df, :type = :Sex == "female" ? "girl" : "boy")

@groupby(df, :age = round(Int, :age))

df.age
transform(df, :age => (col -> col .+ 1) => :ageplus)

@transform(df, :age + 1)
@transform(df, @c :age .- mean(:age))

@chain df begin
    @transform(:type = :Sex == "female" ? "girl" : "boy")
    @groupby(:half = :zScore > 0 ? "upper" : "lower", :type)
    combine(nrow => :n)
    # @aside CSV.write("test.csv", _)
    @transform(:nsquared = :n ^ 2)
end


text:
using Test
using DocumenterTools

@testset "DocumenterTools" begin
    @testset "generate" begin
        include("generate.jl")
    end

    @testset "genkeys-added" begin
        using Example
        DocumenterTools.genkeys(user="JuliaLang", repo="git@github.com:JuliaLang/Example.jl.git")
    end

    @testset "genkeys-deved" begin
        using Pkg;
        Pkg.develop("Example")
        using Example
        DocumenterTools.genkeys(Example)
    end

end


text:
using DynamicalSystemsBase
using Test, StaticArrays
using DynamicalSystemsBase: CDS, DDS
using DynamicalSystemsBase.Systems: hoop, hoop_jac, hiip, hiip_jac
using DynamicalSystemsBase.Systems: loop, loop_jac, liip, liip_jac
using BenchmarkTools

u0 = [0, 10.0, 0]
p = [10, 28, 8/3]
u0h = zeros(2)
ph = [1.4, 0.3]

FUNCTIONS = [liip, liip_jac, loop, loop_jac, hiip, hiip_jac, hoop, hoop_jac]
INITCOD = [u0, u0h]
PARAMS = [p, ph]

for i in 1:8
    println("Time to create & step! integrators, combination $i")
    sysindx = i < 5 ? 1 : 2
    if i < 5
        if isodd(i)
            ds = CDS(FUNCTIONS[i], INITCOD[sysindx], PARAMS[sysindx])
        else
            ds = CDS(FUNCTIONS[i-1], INITCOD[sysindx], PARAMS[sysindx], FUNCTIONS[i])
        end
    else
        if isodd(i)
            ds = DDS(FUNCTIONS[i], INITCOD[sysindx], PARAMS[sysindx])
        else
            ds = DDS(FUNCTIONS[i-1], INITCOD[sysindx], PARAMS[sysindx], FUNCTIONS[i])
        end
    end

    integ = integrator(ds)
    println("normal")
    @time integ = integrator(ds)
    step!(integ)
    @time step!(integ)
    te = tangent_integrator(ds, orthonormal(3,3))
    println("tangent")
    @time te = tangent_integrator(ds, orthonormal(3,3))
    step!(te); step!(te)
    @time step!(te)
    te = parallel_integrator(ds, [INITCOD[sysindx], INITCOD[sysindx]])
    println("parallel")
    @time te = parallel_integrator(ds, [INITCOD[sysindx], INITCOD[sysindx]])
    step!(te); step!(te)
    @time step!(te)
end


text:
using Plots, Symbolics

# environment points
pa = [0.0; 0.0]

pb = [1.0; 0.0]

pc = [1.0; 1.0]

pd = [2.0; 1.0]

pe = [2.0; 0.0]

pf = [3.0; 0.0]

pts_env = [pa, pb, pc, pd, pe, pf]
plot(hcat(pts_env...)[1, :], hcat(pts_env...)[2, :], aspect_ratio=:equal, color=:magenta, width=2.0)

function points_between(p1, p2; N = 100)
    dir = p2 - p1
    pts = [p1 + t * dir for t in range(0.0, stop=1.0, length=N)]
    return pts
end

N = 2
pts_ab = points_between(pa, pb, N=N)
pts_bc = points_between(pb, pc, N=N)
pts_cd = points_between(pc, pd, N=N)
pts_de = points_between(pd, pe, N=N)
pts_ef = points_between(pe, pf, N=N)

pts_data = [pts_ab..., pts_bc...]#, pts_cd..., pts_de..., pts_ef...]

plot!(hcat(pts_data...)[1, :], hcat(pts_data...)[2, :], aspect_ratio=:equal, color=:orange, width = 1.0)

# data set
X = hcat(pts_data...)[1, :]
Y = hcat(pts_data...)[2, :]

# model
l_input = 1
l_1 = 2
l_2 = 2
l_output = 1
p = l_1 * l_input + l_1 + l_2 * l_1 + l_2 + l_output * l_2 + l_output

function model(x, θ)
    W1 = reshape(θ[1:(l_1 * l_input)], l_1, l_input)
    b1 = θ[(l_1 * l_input) .+ (1:l_1)]

    W2 = reshape(θ[(l_1 * l_input + l_1) .+ (1:(l_2 * l_1))], l_2, l_1)
    b2 = θ[(l_1 * l_input + l_1 + l_2 * l_1) .+ (1:l_2)]

    W3 = reshape(θ[(l_1 * l_input + l_1 + l_2 * l_1 + l_2) .+ (1:(l_output * l_2))], l_output, l_2)
    b3 = θ[(l_1 * l_input + l_1 + l_2 * l_1 + l_2 + l_output * l_2) .+ (1:l_output)]

    z1 = W1 * x + b1
    return [sum(z1)]
    o1 = max.(z1, 0.0)

    z2 = W2 * o1 + b2
    o2 = max.(z2, 0.0)

    z3 = W3 * o2 + b3

    return z3
end

@variables x[1:1], θ[1:p]

m = model(x, θ)
dm = vec(Symbolics.jacobian(m, θ))

m_func = eval(Symbolics.build_function(m, x, θ)[1])
dm_func = eval(Symbolics.build_function(dm, x, θ)[1])

m_func([2.0], θ0)
function eval_obj(X, Y, θ)
    N = length(X)
    J = 0.0
    for i = 1:N
        J += (m_func(X[i:i], θ) - Y[i:i])[1]^2.0
    end
    return 0.5 * J / N
end

function eval_grad(X, Y, θ)
    N = length(X)
    ∇J = zero(θ)
    for i = 1:N
        ∇J .+= dm_func(X[i:i], θ) * (m_func(X[i:i], θ) - Y[i:i])[1]
    end
    return ∇J ./ N
end

θ0 = 0.01 * randn(p)
eval_obj(X, Y, θ0)
eval_grad(X, Y, θ0)

function optimize!(X, Y, θ; max_iter=1000, α=1.0e-6, epoch=10)
    println("obj (iter 1): $(eval_obj(X, Y, θ))")

    for i = 1:max_iter
        ∇J = eval_grad(X, Y, θ)
        θ .-= α * ∇J

        i % epoch == 0 && (println("obj (iter $i): $(eval_obj(X, Y, θ))"))
    end
    return θ
end

θ = 0.01 * randn(p)
θ = optimize!(X, Y, θ, α=1.0e-3, max_iter=100000, epoch=1000);

X_pred = range(0, stop=3.0, length = 100)
Y_pred = [model(X_pred[i:i], θ)[1] for i = 1:length(X_pred)]

plot(X_pred, Y_pred, aspect_ratio=:equal, color=:cyan, width = 1.0)

model([1.0], θ0)


text:
mutable struct Rule
    color::String
    containedBags::Dict{String,Int}
    Rule() = new("",Dict())
end

function parseLine(line)
    rule = Rule()
    containedBags = Dict()
    sections = split(line, "contain")
    colorsection = split(sections[1], ' ')
    rule.color = colorsection[1]*colorsection[2]
    rulesections = split(sections[2], ',')
    if rulesections[1] != " no other bags."
        for rulesection in rulesections
            words = split(rulesection, ' ')
            amount = parse(Int,words[2])
            rulecolor = words[3]*words[4]
            containedBags[rulecolor] = amount
        end
    end
    rule.containedBags = containedBags
    return rule
end

allRules = Dict()
open("data.txt") do file
    for line in eachline(file)
        rule = parseLine(line)
        allRules[rule.color] = rule
    end
end

function countMyBags(rule)
    # println("counting in ", rule.color, " bag")
    if(length(rule.containedBags) != 0)
        myBags = 0
        for bag in rule.containedBags
            color = bag[1]
            count = bag[2]
            # println(count, " " ,color)
            myBags += count * (1 + countMyBags(allRules[color]))
        end
        return myBags
    else
        return 0
    end
end

println(countMyBags(allRules["shinygold"]))


text:
# Autogenerated wrapper script for msolve_jll for armv6l-linux-musleabihf
export libmsolve, libneogb

using GMP_jll
using FLINT_jll
using MPFR_jll
using CompilerSupportLibraries_jll
JLLWrappers.@generate_wrapper_header("msolve")
JLLWrappers.@declare_library_product(libmsolve, "libmsolve-0.1.7.so")
JLLWrappers.@declare_library_product(libneogb, "libneogb-0.1.7.so")
function __init__()
    JLLWrappers.@generate_init_header(GMP_jll, FLINT_jll, MPFR_jll, CompilerSupportLibraries_jll)
    JLLWrappers.@init_library_product(
        libmsolve,
        "lib/libmsolve.so",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libneogb,
        "lib/libneogb.so",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()