text:
export CuArray, CuVector, CuMatrix, CuVecOrMat
export curand, curandn, device
export reshape3, shiftcopy!

type CuArray{T,N} <: AbstractCuArray{T,N}
    ptr::CuPtr{T}
    dims::NTuple{N,Int}
end

typealias CuVector{T} CuArray{T,1}
typealias CuMatrix{T} CuArray{T,2}
typealias CuVecOrMat{T} Union{CuVector{T},CuMatrix{T}}

CuArray{T,N}(::Type{T}, dims::NTuple{N,Int}) = CuArray(CUDA.malloc(T,prod(dims)), dims)
CuArray{T}(::Type{T}, dims::Int...) = CuArray(T, dims)
CuArray{T,N}(src::Array{T,N}) = copy!(CuArray(T,size(src)), src)

Base.length(a::CuArray) = prod(a.dims)

Base.size(a::CuArray) = a.dims
Base.size(a::CuArray, d::Int) = a.dims[d]

Base.ndims{T,N}(a::CuArray{T,N}) = N

Base.eltype{T}(a::CuArray{T}) = T

function Base.stride(a::CuArray, dim::Int)
    d = 1
    for i = 1:dim-1
        d *= size(a,i)
    end
    d
end

Base.strides{T}(a::CuArray{T,1}) = (1,)
Base.strides{T}(a::CuArray{T,2}) = (1,size(a,1))
Base.strides{T}(a::CuArray{T,3}) = (1,size(a,1),size(a,1)*size(a,2))
Base.strides{T}(a::CuArray{T,4}) = (1,size(a,1),size(a,1)*size(a,2),size(a,1)*size(a,2)*size(a,3))
function Base.strides{T,N}(a::CuArray{T,N})
    throw("Not implemented yet.")
end

Base.similar{T}(a::CuArray{T}) = CuArray(T, size(a))
Base.similar{T}(a::CuArray{T}, dims::NTuple) = CuArray(T, dims)
Base.similar{T}(a::CuArray{T}, dims::Int...) = similar(a, dims)

Base.convert{T}(::Type{Ptr{T}}, a::CuArray) = Ptr{T}(a.ptr)
Base.convert(::Type{CUDA.CUdeviceptr}, a::CuArray) = CUDA.CUdeviceptr(a.ptr)
Base.unsafe_convert{T}(::Type{Ptr{T}}, a::CuArray) = Ptr{T}(a.ptr)
Base.unsafe_convert(::Type{CUDA.CUdeviceptr}, a::CuArray) = CUDA.CUdeviceptr(a.ptr)

Base.zeros{T,N}(a::CuArray{T,N}) = zeros(CuArray{T}, a.dims)
Base.zeros{T}(::Type{CuArray{T}}, dims::Int...) = zeros(CuArray{T}, dims)
Base.zeros{T}(::Type{CuArray{T}}, dims) = fill(CuArray, T(0), dims)

Base.ones{T}(a::CuArray{T}) = ones(CuArray{T}, a.dims)
Base.ones{T}(::Type{CuArray{T}}, dims::Int...) = ones(CuArray{T}, dims)
Base.ones{T}(::Type{CuArray{T}}, dims) = fill(CuArray, T(1), dims)

function Base.copy!{T}(dest::Array{T}, src::CuArray{T}; stream=C_NULL)
    cucopy!(dest, src, CUDA.cuMemcpyDtoHAsync, length(src), stream)
end
function Base.copy!{T}(dest::CuArray{T}, src::Array{T}; stream=C_NULL)
    cucopy!(dest, src, CUDA.cuMemcpyHtoDAsync, length(src), stream)
end
function Base.copy!{T}(dest::CuArray{T}, src::CuArray{T}; stream=C_NULL)
    cucopy!(dest, src, CUDA.cuMemcpyDtoDAsync, length(src), stream)
end
function Base.copy!{T}(dest::CuArray{T}, doffs::Int, src::CuArray{T}, soffs::Int, n::Int; stream=C_NULL)
    CUDA.cuMemcpyDtoDAsync(cupointer(dest,doffs), cupointer(src,soffs), n*sizeof(T), stream)
    dest
end

Base.copy(src::CuArray) = copy!(similar(src),src)

Base.pointer{T}(a::CuArray{T}, index::Int=1) = Ptr{T}(a) + sizeof(T) * (index-1)

Base.Array{T,N}(src::CuArray{T,N}) = copy!(Array(T,size(src)), src)

Base.isempty(a::CuArray) = length(a) == 0

Base.vec(a::CuArray) = ndims(a) == 1 ? a : CuArray(a.ptr, (length(a),))

Base.fill{T}(::Type{CuArray}, value::T, dims::NTuple) = fill!(CuArray(T,dims), value)

@generated function Base.fill!{T}(x::CuArray{T}, value::T)
    CT = cstring(T)
    f = compile("""
    fill(Array<$CT,1> x, $CT value) {
        int idx = threadIdx.x + blockIdx.x * blockDim.x;
        if (idx < x.length()) x[idx] = value;
    }""")
    quote
        launch($f, (length(x),1,1), (vec(x),value))
        x
    end
end

Base.reshape{T,N}(a::CuArray{T}, dims::NTuple{N,Int}) = CuArray{T,N}(a.ptr, dims)
Base.reshape{T}(a::CuArray{T}, dims::Int...) = reshape(a, dims)

Base.getindex(a::CuArray, key...) = copy!(view(a, key...))

function Base.setindex!{T,N}(y::CuArray{T,N}, x::CuArray{T,N}, indexes...)
    if N <= 3
        shift = [0,0,0]
        for i = 1:length(indexes)
            idx = indexes[i]
            if typeof(idx) == Colon
            elseif typeof(idx) <: Range
                # TODO: more range check
                @assert length(idx) == size(x,i)
                shift[i] = start(idx) - 1
            else
                throw("Invalid range: $(idx)")
            end
        end
        shiftcopy!(reshape3(y), reshape3(x), (shift[1],shift[2],shift[3]))
    else
        throw("Not implemented yet.")
    end
    #xx = view(x, key...)
    #copy!(xx, value)
end
function Base.setindex!{T}(x::CuArray{T}, value::T, key::Int)
    throw("Not implemented yet.")
end

function curand{T,N}(::Type{T}, dims::NTuple{N,Int})
    # TODO: use curand library
    CuArray(rand(T, dims))
end
curand(T::Type, dims::Int...) = curand(T, dims)

function curandn{T,N}(::Type{T}, dims::NTuple{N,Int})
    # TODO: use curand library
    CuArray(Array{T}(randn(dims)))
end
curandn(T::Type, dims::Int...) = curandn(T, dims)

device(a::CuArray) = a.ptr.dev

cupointer{T}(a::CuArray{T}, index::Int=1) = CuPtr{T}(pointer(a,index), device(a))

function cucopy!(dest, src, f::Function, n::Int, stream)
    nbytes = n * sizeof(eltype(src))
    f(dest, src, nbytes, stream)
    dest
end

function reshape3(x::CuArray, dim::Int)
    d1, d2, d3 = 1, size(x,dim), 1
    for i = 1:dim-1
        d1 *= size(x,i)
    end
    for i = dim+1:ndims(x)
        d3 *= size(x,i)
    end
    reshape(x, (d1,d2,d3))
end
reshape3{T}(x::CuArray{T,1}) = reshape(x, size(x,1), 1, 1)
reshape3{T}(x::CuArray{T,2}) = reshape(x, size(x,1), size(x,2), 1)
reshape3{T}(x::CuArray{T,3}) = x

@generated function shiftcopy!{T}(dest::CuArray{T,3}, src::CuArray{T,3}, shift::NTuple{3,Int})
    CT = cstring(T)
    f = compile("""
    shiftcopy(Array<$CT,3> dest, Array<$CT,3> src, Dims<3> shift) {
        int idx0 = threadIdx.x + blockIdx.x * blockDim.x;
        int idx1 = threadIdx.y + blockIdx.y * blockDim.y;
        int idx2 = threadIdx.z + blockIdx.z * blockDim.z;
        if (idx0 >= src.dims[0] || idx1 >= src.dims[1] || idx2 >= src.dims[2]) return;
        dest(idx0+shift[0], idx1+shift[1], idx2+shift[2]) = src(idx0, idx1, idx2);
    }""")
    quote
        launch($f, size(src), (dest,src,shift))
        dest
    end
end


text:
using MPI, Test

include(joinpath("..", "..", "testhelpers.jl"))

@testset "Mesh BrickMesh" begin
    runmpi(joinpath(@__DIR__, "BrickMesh.jl"))
end

@testset "Mesh Elements" begin
    runmpi(joinpath(@__DIR__, "Elements.jl"))
end

@testset "Mesh Metrics" begin
    runmpi(joinpath(@__DIR__, "Metrics.jl"))
end

@testset "Mesh Topology" begin
    runmpi(joinpath(@__DIR__, "topology.jl"))
end

@testset "Mesh GridIntegral" begin
    runmpi(joinpath(@__DIR__, "grid_integral.jl"))
end

@testset "Mesh Filter" begin
    runmpi(joinpath(@__DIR__, "filter.jl"))
end

@testset "Mesh Geometry" begin
    runmpi(joinpath(@__DIR__, ("Geometry.jl")))
end

@testset "Mesh MPI Jobs" begin
    runmpi(joinpath(@__DIR__, "mpi_centroid.jl"), ntasks = 3)
    runmpi(joinpath(@__DIR__, "mpi_connect_ell.jl"), ntasks = 2)
    runmpi(joinpath(@__DIR__, "interpolation.jl"), ntasks = 3)
    runmpi(joinpath(@__DIR__, "mpi_connect.jl"), ntasks = 3)
    runmpi(joinpath(@__DIR__, "mpi_connect_stacked.jl"), ntasks = 3)
    runmpi(joinpath(@__DIR__, "mpi_connect_stacked_3d.jl"), ntasks = 2)
    runmpi(joinpath(@__DIR__, "mpi_getpartition.jl"), ntasks = 3)
    runmpi(joinpath(@__DIR__, "mpi_partition.jl"), ntasks = 3)
    runmpi(joinpath(@__DIR__, "mpi_sortcolumns.jl"), ntasks = 1)
end

ext: jl

max_stars_repo_name: leios/CLIMA

max_issues_repo_name: leios/CLIMA

max_forks_repo_name: leios/CLIMA


text:
using Compat

testfiles =["testdata",
		"testdatasocial",
		"populategraphtest",
        "compositequerytest",
		"socialgraphtest",
		"changetrackertest",
		"definetestgraphloader",
		"graphloadertest"
		]

println("Running tests:")

for t in testfiles
    testfilepath = joinpath(Pkg.dir("PropertyGraph"),"test","$(t).jl")
    println("running $(testfilepath) ...")
    include(testfilepath)
end


text:
using HTTPClient.HTTPC, JSON
cdb = "http://localhost:5984";
dbs = bytestring(get("$cdb/_all_dbs).body.data);
JSON.parse(dbs); # => ["_replicator", "_users", "_quotes"]

qc = cdb * "/quotes";
ropts = RequestOptions(content_type="application/json");

json =  "{category:\"Computing\",author:\"Scott's Law\",
\"quote\":\"Adding manpower to a late software project makes it later\"})";
HTTPC.post(qc, json, ropts);

json = JSON.parse(docs.body.data));

json["total_rows"]; # => 35
json["rows"][24];   # Pick out an specific record
Dict{String,Any} with 3 entries:
  "key"   => "d075d58c26d256c49b965a02cc00b77a"
  "id"    => "d075d58c26d256c49b965a02cc00b77a"
  "value" => ["rev"=>"1-524b4b2c577e2eaff31f4b665cd48055"]
key = json["rows"][24]["key"];
rev = json["rows"][24]["value"]["rev"];

JSON.parse(bytestring(get("$qc/$key").body.data))
Dict{String,Any} with 5 entries:
  "quote"    =>
      "To love oneself is the beginning of a lifelong romance"
  "_rev"     => "1-524b4b2c577e2eaff31f4b665cd48055"
  "author"   => "Oscar Wilde"
  "_id"      => "d075d58c26d256c49b965a02cc00b77a"
  "category" => "Books & Plays"

json =  "{category:\"Books & Plays\",author:\"Oscar Wilde\",
\"quote\":\"I can resist everything but temptation\"})";
HTTPC.post("$qc/$key", json, ropts);


text:
function tr13!(r::Robot)#главная функция
    SUD_ost(r)
    sud_west(r)
    nord_west(r)
    ost_nord(r)
    putmarker!(r)
end
function SUD_ost(r::Robot)#
    while isborder(r, Nord) == false
        if isborder(r, Sud) == false
            if isborder(r, Ost) == false
                move!(r, Ost)
                move!(r, Sud)
                putmarker!(r)
            else
                break
            end
        else
            break
        end
    end
    for i in 1:100
        move!(r, Nord)
        move!(r, West)
        if ismarker(r) == false
            break
        end
    end
end
function sud_west(r::Robot)
    while isborder(r, Nord) == false
        if isborder(r, Sud) == false
            if isborder(r, West) == false
                move!(r, West)
                move!(r, Sud)
                putmarker!(r)
            else
                break
            end
        else
            break
        end
    end
    for i in 1:100
        move!(r, Nord)
        move!(r, Ost)
        if ismarker(r) == false
            break
        end
    end
end
function nord_west(r::Robot)
    while isborder(r, Sud) == false
        if isborder(r, Nord) == false
            if isborder(r, West) == false
                move!(r, West)
                move!(r, Nord)
                putmarker!(r)
            else
                break
            end
        else
            break
        end
    end

    for i in 1:100
        move!(r, Sud)
        move!(r, Ost)
        if ismarker(r) == false
            break
        end
    end
end
function ost_nord(r::Robot)
    while isborder(r, Sud) == false
        if isborder(r, Nord) == false
            if isborder(r, Ost) == false
                move!(r, Ost)
                move!(r, Nord)
                putmarker!(r)
            else
                break
            end
        else
            break
        end
    end

    for i in 1:100
        move!(r, Sud)
        move!(r, West)
        if ismarker(r) == false
            break
        end
    end
end


text:
using SeaPearl

#

struct InputData
    A::Matrix{Int} #number of lines
end

"""
    model_latin(input_file; limit=1)

return the SeaPearl model for to the Latin completion problem using SeaPearl.AllDifferent
The input file can come from the Latin DataGen in SeaPearl.

# Arguments
- `InputData`: Matrix containting the uncompleted game
- 'limit' : Int, giving the number of solutions after which it will stop searching. if nothing given, it will looks for all the solutions
"""
function model_latin(input::InputData; limit=1)
    trailer = SeaPearl.Trailer()
    model = SeaPearl.CPModel(trailer)
    model.limit.numberOfSolutions = limit
    A = InputData.A
    N = size(A)[1]
    puzzle = Matrix{SeaPearl.AbstractIntVar}(undef, N,N)
    for i = 1:N
        for j in 1:N
            puzzle[i,j] = SeaPearl.IntVar(1, N, "puzzle_"*string(i)*","*string(j), trailer)
            SeaPearl.addVariable!(cpmodel, puzzle[i,j]; branchable=true)
            if A[i,j]>0 push!(model.constraints,SeaPearl.EqualConstant(puzzle[i,j], A[i,j], trailer)) end
        end
    end
    for i in 1:N
        push!(cpmodel.constraints, SeaPearl.AllDifferent(puzzle[i,:], cpmodel.trailer))
        push!(cpmodel.constraints, SeaPearl.AllDifferent(puzzle[:,i], cpmodel.trailer))
    end
    return model
end

"""
    solve_latin!(model::SeaPearl.CPModel; variableSelection=SeaPearl.MinDomainVariableSelection{false}(), valueSelection=SeaPearl.BasicHeuristic())

Solve the SeaPearl model for to the Latin Completion problem, using an existing model

# Arguments
- `model::SeaPearl.CPModel`: model (from model_latin)
- 'variableSelection': SeaPearl variable selection. By default: SeaPearl.MinDomainVariableSelection{false}().
- 'valueSelection': SeaPearl value selection. By default: =SeaPearl.BasicHeuristic().
"""
function solve_latin!(model::SeaPearl.CPModel; variableSelection=SeaPearl.MinDomainVariableSelection{false}(), valueSelection=SeaPearl.BasicHeuristic())
    status = @time SeaPearl.solve!(model; variableHeuristic=variableSelection, valueSelection=valueSelection)
    return model
end

"""
    print_latin(model::SeaPearl.CPModel)

Nice print the latin game when solved

# Arguments
- `model::SeaPearl.CPModel`: model (from model_latin)
"""
function print_latin(model)
    sol= model.statistics.solutions[1]
    n = oftype(1,sqrt(length(sol)))
    tableau = Matrix{Int}(undef,n,n)
    for i in 1:n, j in 1:n
        tableau[i, j]= sol["puzzle_"*string(i)*","*string(j)]
    end
    print(" ")
    for k in 1:5*n
        print("-")
    end
    println()
    for i in 1:n
        print("|")
        for j in 1:n
            printstyled(" "*string(tableau[i,j],pad=2)*" ", color=tableau[i,j])
            print("|")
        end
        println()
    end
    print(" ")
    for k in 1:5*n
        print("-")
    end
end

max_stars_repo_name: corail-research/SeaPearlZoo

max_issues_repo_name: corail-research/SeaPearlZoo

max_forks_repo_name: corail-research/SeaPearlZoo


text:
# 2D Heat Diffusion
# LBM
#
# This could only work on a rectangular region! To generalize to more
# complicated mesh, I need 1D indexing of lattices.
#
# Hongyang Zhou, hyzhou@umich.edu 05/01/2019

using PyPlot
include("Parameters.jl")
include("lattice.jl")
include("BC.jl")

using .Parameters, .BC, .lattice

function solveHeatDiffusion2D!(param::Param,lat::Lattice)

   # Set aliases
   nI,nJ,ω,Δt,TotalTime = param.nI,param.nJ,param.ω,param.Δt,param.TotalTime

   nw,w  = lat.nw, lat.w
   T     = zeros(1,nI,nJ)
   feq   = Array{Float64,3}(undef,nw,nI,nJ)
   ftemp = Array{Float64,3}(undef,nw,nI,nJ)
   t     = 0.0     # Current simulation time

   # Advance
   while t < TotalTime

      # Calculate equilibrium distribution
      for iw = 1:nw
         @. feq[iw,:,:] = w[iw]*T[1,:,:]
      end

      # Collision
      for iw = 1:nw
         @. lat.f[iw,:,:] = (1.0-ω)*lat.f[iw,:,:] + ω.*feq[iw,:,:]
      end

      # Streaming
      for j=1:nJ, i=1:nI, iw = 1:nw
         iNew = i + lat.c[1,iw]
         jNew = j + lat.c[2,iw]
         (iNew > nI || iNew < 1 || jNew > nJ || jNew < 1) && continue
         ftemp[iw,iNew,jNew] = lat.f[iw,i,j]
      end
      #copy!(lat.f,ftemp) # This does not work in Julia 1.0 (but 1.1+)!
      lat.f .= ftemp

      # Remaining BCs
      setBCs!(lat,param)

      # Calculate macroscopic T
      T = sum(lat.f, dims=1)

      t += Δt
   end

end

function init_lattice()

   param = setParameters()

   Δx,Δt,nI,nJ,LT = param.Δx,param.Δt,param.nI,param.nJ,param.LatticeType

   if LT == 1
      lat = LatticeD2Q4(Δx,Δt,nI,nJ)
   elseif LT == 2
      lat = LatticeD2Q5(Δx,Δt,nI,nJ)
   elseif LT == 3
      lat = LatticeD2Q9(Δx,Δt,nI,nJ)
   end

   return param,lat
end

function plotSol(lat::Lattice)
   # Visualization
   x = range(0,stop=lat.nI-1,length=lat.nI)
   y = range(0,stop=lat.nJ-1,length=lat.nJ)
   T = sum(lat.f, dims=1)

   # Python follows row major order
   contourf(x,y,T[1,:,:]'); colorbar()
   title("2D Heat Diffusion in a Plate")
   xlabel("x")
   ylabel("y")
   grid(true)

   # 1D cut plot
   #plot(0:nx-1,T[1,:,50],linestyle="-",marker="o",label="LBM")
   #xlim(0,30)
end

function main()
   param,lat = init_lattice()

   solveHeatDiffusion2D!(param,lat)

   plotSol(lat)

end


text:
module List

using Genie, Stipple, StippleUI, StippleUI.API
import Genie.Renderer.Html: HTMLString, normal_element

export list, item, item_section, itemsection, item_label, itemlabel

Genie.Renderer.Html.register_normal_element("q__list", context = @__MODULE__)
Genie.Renderer.Html.register_normal_element("q__item", context = @__MODULE__)
Genie.Renderer.Html.register_normal_element("q__item__section", context = @__MODULE__)
Genie.Renderer.Html.register_normal_element("q__item__label", context = @__MODULE__)

function list(args...;
              wrap::Function = StippleUI.DEFAULT_WRAPPER,
              kwargs...)
  wrap() do
    q__list(args...; kwargs...)
  end
end

function item(args...; kwargs...)
  q__item(args...; attributes([kwargs...], StippleUI.API.ATTRIBUTES_MAPPINGS)...)
end

function item_section(args...; kwargs...)
  q__item__section(args...; attributes([kwargs...], StippleUI.API.ATTRIBUTES_MAPPINGS)...)
end
const itemsection = item_section

function item_label(args...; kwargs...)
  q__item__label(args...; kwargs...)
end
const itemlabel = item_label

end


text:
abstract type GeometricConstraint end

struct Parallelism <: GeometricConstraint
    l::Segment
    r::Segment
end
const ∥ = Parallelism

struct Perpendicularity <: GeometricConstraint
    l::Segment
    r::Segment
end
const ⟂ = Perpendicularity

struct Congruence{T<:GeometricEntity} <: GeometricConstraint
    l::T
    r::T
end
const ≅ = Congruence

struct Appartenence{T<:GeometricEntity} <: GeometricConstraint
    l::Symbol
    r::T
end
Base.:∈(P::Symbol, obj::GeometricEntity) = Appartenence(P, obj)

for (op, sym) in [(Parallelism, :∥), (Perpendicularity, :⟂), (Congruence, :≅), (Appartenence{Segment}, :∈)]
    @eval show(io::IO, rel::$op) = print(io, rel.l, " ", $(QuoteNode(sym)), " ", rel.r)
end

show(io::IO, rel::Appartenence{Circle}) = print(io, rel.r.O, rel.l, " ≅ ", rel.r.O, rel.r.A)

struct Intersection{T <: GeometricEntity, S <: GeometricEntity} <: GeometricConstraint
    P::Symbol
    l::T
    r::S
end
const ∩ = Intersection

show(io::IO, rel::Intersection) = print(io, rel.P, " = ", rel.l, " ∩ ", rel.r)

struct Midpoint <: GeometricConstraint
    M::Symbol
    seg::Segment
end
Midpoint(M, A, B) = Midpoint(M, Segment(A, B))
const midpoint = Midpoint

show(io::IO, rel::Midpoint) = print(io, rel.M, " ∈ ", rel.seg, " ∧ ", rel.seg.l, rel.M, " ≅ ", rel.M, rel.seg.r)

struct Parallelogram <: GeometricConstraint
    A::Symbol
    B::Symbol
    C::Symbol
    D::Symbol
end
const parallelogram = Parallelogram
show(io::IO, rel::Parallelogram) = print(io, rel.A, rel.B, rel.C, rel.D, " parallelogram")

struct Projection <: GeometricConstraint
    H::Symbol
    P::Symbol
    seg::Segment
end
const ↓ = Projection
show(io::IO, rel::Projection) = print(io, rel.H, " ∈ ", rel.seg, " ∧ ", rel.P, rel.H, " ⟂ ", rel.seg)

struct CircleThreePoints <: GeometricConstraint
    O::Symbol
    A::Symbol
    B::Symbol
    C::Symbol
end
show(io::IO, rel::CircleThreePoints) = print(io, rel.O, rel.A, " ≅ ", rel.O, rel.B, " ≅ ", rel.O, rel.C)
Circle(O, A, B, C) = CircleThreePoints(O, A, B, C)


text:
using Test
using BSplineKit
using Random
using LinearAlgebra: dot

using BSplineKit.BSplines:
    find_knot_interval

function test_bsplines(B::AbstractBSplineBasis)
    N = length(B)
    ts = knots(B)
    a = first(ts)
    b = last(ts)
    @test (a, b) == boundaries(B)
    k = order(B)

    if B isa BSplineBasis
        @testset "Find interval" begin
            @inferred find_knot_interval(ts, 0.3)
            @test find_knot_interval(ts, a - 1) == (1, -1)
            @test find_knot_interval(ts, a) == (k, 0)
            @test find_knot_interval(ts, b) == (N, 0)
            @test find_knot_interval(ts, b + 1) == (N, 1)
            let x = (a + b) / 3  # test on a "normal" location
                @test find_knot_interval(ts, x) == (searchsortedlast(ts, x), 0)
            end
            let i = length(ts) ÷ 2  # test on a knot location
                @test find_knot_interval(ts, ts[i]) == (i, 0)
            end
        end
    end

    xs_eval = [
        ts[begin],                                          # at left boundary
        ts[begin + k + 2],                                  # on a knot
        0.2 * ts[begin + k + 2] + 0.8 * ts[begin + k + 3],  # between two knots
        ts[end],                                            # at right boundary
    ]

    derivs = Derivative.((0, 1, 2))
    _order(::Derivative{n}) where {n} = n

    S = Spline(B, randn(rng, length(B)))

    let x = 0.3
        @test evaluate_all(B, x) == @inferred B(x)  # alias for `evaluate_all`
    end

    @testset "Evaluate $op | x = $x" for x ∈ xs_eval, op ∈ derivs
        i, bs = @inferred evaluate_all(B, x, op)
        @test length(bs) == k
        @test eltype(bs) === Float64

        if B isa BSplineBasis
            i′, bs′ = @inferred evaluate_all(B, x, op, Float32)
            @test eltype(bs′) === Float32
            @test i === i′
            @test all(bs .≈ bs′)
        end

        # Test reusing knot interval (ileft)
        @test (i, bs) == @inferred evaluate_all(B, x, op; ileft = i)

        if B isa BSplineBasis
            if op === Derivative(0)
                @test sum(bs) ≈ 1  # partition of unity property
            else
                @test abs(sum(bs)) < 10eps(maximum(bs))  # ≈ 0
            end
        end

        nderiv = _order(op)

        # 1. Compare with evaluation of single B-spline
        if nderiv < k
            for δj ∈ eachindex(bs)
                j = i - δj + 1
                # For recombined bases, the index can fall outside of the domain.
                if B isa RecombinedBSplineBasis && j ∉ 1:N
                    continue
                end
                bj = bs[δj]
                if x == first(ts) && op ∈ first(constraints(B))
                    # In this case all results are expected to be zero.
                    @test abs(bj) < 1e-10
                elseif x == last(ts) && op ∈ last(constraints(B))
                    @test abs(bj) < 1e-10
                else
                    # Results are non-zero.
                    @test bj ≈ B[j](x, op)
                end
            end
        end

        # 2. Compare with full evaluation of a spline
        if nderiv < k
            S′ = op * S  # this is exactly `S` if op == Derivative(0)
            cs = let us = coefficients(S)
                if B isa BSplineBasis
                    ntuple(δ -> us[i + 1 - δ], Val(k))
                else
                    ntuple(Val(k)) do δ
                        j = i + 1 - δ
                        checkbounds(Bool, us, j) ? us[j] : zero(eltype(us))
                    end
                end
            end
            ϵ = 10eps(maximum(abs, coefficients(S′)))
            u, v = S′(x), dot(cs, bs)
            if abs(u) < ϵ
                @test abs(v) < ϵ
            else
                @test u ≈ v
            end
        end

        # 3. Compare to non-generated version (assuming the @generated version
        #    is called)
        if B isa BSplineBasis
            @test evaluate_all(B, x, op) == @inferred BSplines._evaluate_all_alt(
                knots(B), x, BSplineOrder(k), op, eltype(bs),
            )
            @test evaluate_all(B, x, op, Float32) == @inferred BSplines._evaluate_all_alt(
                knots(B), x, BSplineOrder(k), op, Float32,
            )
        end
    end

    nothing
end

rng = MersenneTwister(42)
ξs = sort!(rand(rng, 20))
ξs[begin] = 0; ξs[end] = 1;

@testset "B-splines (k = $k)" for k ∈ (2, 4, 5, 6, 8)
    B = BSplineBasis(BSplineOrder(k), copy(ξs))
    @testset "B-spline basis" begin
        test_bsplines(B)
    end
    ops = (Derivative(0), Derivative(1), Natural())
    @testset "Recombined (op = $op)" for op ∈ ops
        op == Natural() && isodd(k) && continue
        R = RecombinedBSplineBasis(op, B)
        test_bsplines(R)
    end
end

max_stars_repo_name: jipolanco/BasisSplines

max_issues_repo_name: jipolanco/BasisSplines

max_forks_repo_name: jipolanco/BasisSplines


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

using EzXML
import UUIDs
import Dates

function fmi2CreateModelDescription()
    md = fmi2ModelDescription()
    md.guid = UUIDs.uuid1()
    md.generationDateAndTime = Dates.now()
    md.variableNamingConvention = fmi2VariableNamingConventionStructured
    md.numberOfEventIndicators = 0
    md.stringValueReferences = Dict{String, fmi2ValueReference}()

    return md
end

function fmi2ModelDescriptionAddModelExchange(md::fmi2ModelDescription, modelIdentifier::String)
    if md.modelExchange == nothing
        md.modelExchange = fmi2ModelDescriptionModelExchange()
    end
    md.modelExchange.modelIdentifier = modelIdentifier
end

function fmi2ModelDescriptionAddEvent(md::fmi2ModelDescription)
    md.numberOfEventIndicators += 1
end

function fmi2GetIndexOfScalarVariable(md::fmi2ModelDescription, sv::fmi2ScalarVariable)
    for i in 1:length(md.modelVariables)
        if md.modelVariables[i] == sv
            return UInt(i)
        end
    end
    @assert false "fmi2GetIndexOfScalarVariable(...): Scalar variable is not part of the model variables."
end

function fmi2ModelDescriptionAddRealState(md::fmi2ModelDescription, name::String;
    start::Union{Real, Nothing}=nothing,
    kwargs...)

    _Real = fmi2ModelDescriptionReal()
    _Real.start = start
    sv =  fmi2ModelDescriptionAddModelVariable(md, name; _Real=_Real, kwargs...)

    push!(md.stateValueReferences, sv.valueReference)
    push!(md.stringValueReferences, sv.name => sv.valueReference)

    return sv
end

function fmi2ModelDescriptionAddRealDerivative(md::fmi2ModelDescription, name::String;
    start::Union{Real, Nothing}=nothing,
    derivative::Union{UInt, Nothing}=nothing,
    kwargs...)

    _Real = fmi2ModelDescriptionReal()
    _Real.start = start
    _Real.derivative = derivative

    sv = fmi2ModelDescriptionAddModelVariable(md, name; _Real=_Real, kwargs...)
    index = fmi2GetIndexOfScalarVariable(md, sv)

    fmi2ModelDescriptionAddModelStructureDerivatives(md, index)
    fmi2ModelDescriptionAddModelStructureInitialUnknowns(md, index)

    push!(md.derivativeValueReferences, sv.valueReference)
    push!(md.stringValueReferences, sv.name => sv.valueReference)

    return sv
end

function fmi2ModelDescriptionAddRealStateAndDerivative(md::fmi2ModelDescription, stateName::String, derivativeName::String = "der(" * stateName * ")";
    stateDescr::Union{String, Nothing} = nothing,
    derivativeDescr::Union{String, Nothing} = nothing)

    state = fmi2ModelDescriptionAddRealState(md, stateName; description=stateDescr)
    stateIndex = fmi2GetIndexOfScalarVariable(md, state)
    derivative = fmi2ModelDescriptionAddRealDerivative(md, derivativeName; derivative=stateIndex, description=derivativeDescr)

    return state, derivative
end

function fmi2ModelDescriptionAddRealInput(md::fmi2ModelDescription, name::String;
    start::Union{Real, Nothing}=nothing,
    kwargs...)

    _Real = fmi2ModelDescriptionReal()
    _Real.start = start

    sv = fmi2ModelDescriptionAddModelVariable(md, name; _Real=_Real, causality=fmi2CausalityInput, kwargs...)

    push!(md.inputValueReferences, sv.valueReference)
    push!(md.stringValueReferences, sv.name => sv.valueReference)

    return sv
end

function fmi2ModelDescriptionAddRealOutput(md::fmi2ModelDescription, name::String;
    start::Union{Real, Nothing}=nothing,
    kwargs...)

    _Real = fmi2ModelDescriptionReal()
    _Real.start = start

    sv = fmi2ModelDescriptionAddModelVariable(md, name; _Real=_Real, causality=fmi2CausalityOutput, kwargs...)
    index = fmi2GetIndexOfScalarVariable(md, sv)

    fmi2ModelDescriptionAddModelStructureOutputs(md, index)
    push!(md.outputValueReferences, sv.valueReference)
    push!(md.stringValueReferences, sv.name => sv.valueReference)

    return sv
end

function fmi2ModelDescriptionAddRealParameter(md::fmi2ModelDescription, name::String;
    start::Union{Real, Nothing}=nothing,
    kwargs...)

    _Real = fmi2ModelDescriptionReal()
    _Real.start = start

    sv = fmi2ModelDescriptionAddModelVariable(md, name; _Real=_Real, kwargs...)

    push!(md.parameterValueReferences, sv.valueReference)
    push!(md.stringValueReferences, sv.name => sv.valueReference)

    return sv
end

function fmi2ModelDescriptionAddEventIndicator(md::fmi2ModelDescription)
    if md.numberOfEventIndicators == nothing
        md.numberOfEventIndicators = 0
    end
    md.numberOfEventIndicators += 1
end

"""
Nothing = Skip entry
"""
function fmi2ModelDescriptionAddModelVariable(md::fmi2ModelDescription, name::String;
    description::Union{String, Nothing}=nothing,
    valueReference::Union{fmi2ValueReference, Symbol}=:auto,
    causality::Union{fmi2Causality, Nothing}=nothing,
    variability::Union{fmi2Variability, Nothing}=nothing,
    initial::Union{fmi2Initial, Nothing}=nothing,
    canHandleMultipleSetPerTimeInstant::Union{Bool, Nothing}=nothing,
    _Real::Union{fmi2ModelDescriptionReal, Nothing}=nothing,
    _Integer::Union{fmi2ModelDescriptionInteger, Nothing}=nothing,
    _Boolean::Union{fmi2ModelDescriptionBoolean, Nothing}=nothing,
    _String::Union{fmi2ModelDescriptionString, Nothing}=nothing,
    _Enumeration::Union{fmi2ModelDescriptionEnumeration, Nothing}=nothing)

    if valueReference === :auto
        valueReference = fmi2ValueReference(length(md.modelVariables)+1)
    end

    sv = fmi2ScalarVariable(name, valueReference)
    sv.description = description
    sv.causality = causality
    sv.variability = variability
    sv.initial = initial
    sv.canHandleMultipleSetPerTimeInstant = canHandleMultipleSetPerTimeInstant
    sv._Real = _Real
    sv._Integer = _Integer
    sv._Boolean = _Boolean
    sv._String = _String
    sv._Enumeration = _Enumeration

    push!(md.modelVariables, sv)
    return sv
end

"""
Nothing = Skip entry
"""
function fmi2ModelDescriptionAddModelStructureOutputs(md::fmi2ModelDescription, index::UInt;
    dependencies::Union{Array{UInt, 1}, Nothing} = nothing,
    dependenciesKind::Union{Array{fmi2DependencyKind, 1}, Nothing} = nothing)

    sd = fmi2VariableDependency(index)
    sd.dependencies = dependencies
    sd.dependenciesKind = dependenciesKind

    if md.modelStructure.outputs === nothing
        md.modelStructure.outputs = Array{fmi2VariableDependency, 1}()
    end
    push!(md.modelStructure.outputs, sd)
    return sd
end

"""
Nothing = Skip entry
"""
function fmi2ModelDescriptionAddModelStructureDerivatives(md::fmi2ModelDescription, index::UInt;
    dependencies::Union{Array{UInt, 1}, Nothing} = nothing,
    dependenciesKind::Union{Array{fmi2DependencyKind, 1}, Nothing} = nothing)

    sd = fmi2VariableDependency(index)
    sd.dependencies = dependencies
    sd.dependenciesKind = dependenciesKind

    if md.modelStructure.derivatives === nothing
        md.modelStructure.derivatives = Array{fmi2VariableDependency, 1}()
    end
    push!(md.modelStructure.derivatives, sd)
    return sd
end

"""
Nothing = Skip entry
"""
function fmi2ModelDescriptionAddModelStructureInitialUnknowns(md::fmi2ModelDescription, index::UInt;
    dependencies::Union{Array{UInt, 1}, Nothing} = nothing,
    dependenciesKind::Union{Array{fmi2DependencyKind, 1}, Nothing} = nothing)

    sd = fmi2VariableDependency(index)
    sd.dependencies = dependencies
    sd.dependenciesKind = dependenciesKind

    if md.modelStructure.initialUnknowns === nothing
        md.modelStructure.initialUnknowns = Array{fmi2Unknown, 1}()
    end
    push!(md.modelStructure.initialUnknowns, sd)
    return sd
end


text:
using DFTK: interpolate_density
using LinearAlgebra

@testset "Interpolation of density" begin
    lattice = Array{Float64}(I, 3, 3)
    N = 20
    f(n) = cos(2π*(n-1)/N)
    grid_in = (N, N, N)
    grid_out = (N+20, N-5, N+2)
    ρin = [f(i)*f(j)+f(k) for i = 1:N, j = 1:N, k = 1:N]

    # Test interpolation
    ρout = interpolate_density(ρin, grid_in, grid_out, lattice, lattice)
    ρin2 = interpolate_density(ρout, grid_out, grid_in, lattice, lattice)
    @test maximum(abs.(ρin2-ρin)) < .01

    # Test supercell
    ρout = interpolate_density(ρin, grid_in, grid_in, lattice, 2lattice)
    ρout1 = interpolate_density(ρout, grid_in, grid_in, 2lattice, 4lattice)
    ρout2 = interpolate_density(ρin, grid_in, grid_in, lattice, 4lattice)
    @test maximum(abs.(ρout2 - ρout1)) < sqrt(eps())

    ρout = interpolate_density(ρin, grid_in, grid_in, lattice, 2lattice)
    ρout1 = interpolate_density(ρout, grid_in, grid_out, 2lattice, 4lattice)
    ρout2 = interpolate_density(ρin, grid_in, grid_out, lattice, 4lattice)
    @test maximum(abs.(ρout2 - ρout1)) < .01
end


text:
using SerialPorts

@show list_serialports()

s = SerialPort("COM4",9600)
@show isopen(s)
open(s)

txt = """Hello World.
         The world is a big place.
         Yet it is sometimes small."""

@show isreadable(s)
@show iswritable(s)
@show write(s,8)
sleep(1)
@show bytesavailable(s) == 1
@show read(s,1) == "\b"
@show write(s, "Hello World")
sleep(1)
@show readavailable(s)
@show write(s, "Hello World")
sleep(1)
@show flush(s)
@show write(s, txt)
sleep(1)
@show readavailable(s)
@show write(s, Vector{UInt8}("Hello\n")) #22
@show readavailable(s)

close(s)


text:
const MAX_AREA = typemax(Int)

struct Margin
    vertical::Int
    horizontal::Int
end

struct Rect
    x::Int
    y::Int
    width::Int
    height::Int
end

function Rect(x, y, aspect_ratio::Rational)
    h = √(MAX_AREA / aspect_ratio)
    w = h * aspect_ratio
    return Rect(x, y, w, h)
end

Rect() = Rect(1, 1, 1, 1)

function Rect(rect::Rect, margin::Margin)
    if rect.width < 2 * margin.horizontal || rect.height < 2 * margin.vertical
        return Rect()
    else
        return Rect(
            rect.x + margin.horizontal,
            rect.y + margin.vertical,
            rect.width - 2 * margin.horizontal,
            rect.height - 2 * margin.vertical,
        )
    end
end

area(rect::Rect) = rect.width * rect.height

left(rect::Rect) = rect.x

right(rect::Rect) = rect.x + rect.width

top(rect::Rect) = rect.y

bottom(rect::Rect) = rect.y + rect.height

width(rect::Rect) = rect.width

height(rect::Rect) = rect.height

function inner(rect::Rect; padding_x::Int, padding_y::Int)

    x = left(rect) + padding_x
    y = top(rect) + padding_y
    w = width(rect) - padding_x * 2
    h = height(rect) - padding_y * 2

    return Rect(x, y, w, h)
end

intersects(rect1::Rect, rect2::Rect) = rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x && rect1.y < rect2.y + rect2.height && rect1.y + rect1.height > rect2.y

function union(rect1::Rect, rect2::Rect)
    x1 = min(rect1.x, rect2.x)
    y1 = min(rect1.y, rect2.y)
    x2 = max(rect1.x + rect1.width, rect2.x + rect2.width)
    y2 = max(rect1.y + rect1.height, rect2.y + rect2.height)
    return Rect(
        x1,
        y1,
        x2 - x1,
        y2 - y1,
    )
end

function intersection(rect1::Rect, rect2::Rect)
    x1 = max(rect1.x, rect2.x)
    y1 = max(rect1.y, rect2.y)
    x2 = min(rect1.x + rect1.width, rect2.x + rect2.width)
    y2 = min(rect1.y + rect1.height, rect2.y + rect2.height)
    Rect(
        x1,
        y1,
        x2 - x1,
        y2 - y1,
    )
end


text:
using BinaryBuilder

# Collection of sources required to build HDF5
name = "HDF5"
version = v"1.10.5"

sources = [
    # Crib MacOS and Linux binaries from PyPI
    FileSource("https://files.pythonhosted.org/packages/2c/47/e0d58be6f292684a4541d10b1da953542ff679f3ffc6096bee73634832b1/h5py-2.10.0-cp27-cp27m-macosx_10_6_intel.whl", "ecf4d0b56ee394a0984de15bceeb97cbe1fe485f1ac205121293fc44dcf3f31f"),
    FileSource("https://files.pythonhosted.org/packages/3f/b6/23155e343f8719923449ccfebac296c1ab0dda9bdccc28242e1594469f5a/h5py-2.10.0-cp27-cp27m-manylinux1_i686.whl", "86868dc07b9cc8cb7627372a2e6636cdc7a53b7e2854ad020c9e9d8a4d3fd0f5"),
    FileSource("https://files.pythonhosted.org/packages/3a/9b/5b68a27110d459704550cfc0c765a1ae6ee98981cbbbf0ca92983c87046a/h5py-2.10.0-cp27-cp27m-manylinux1_x86_64.whl", "aac4b57097ac29089f179bbc2a6e14102dd210618e94d77ee4831c65f82f17c0"),

    # Take advantage of msys2 mingw builds of HDF5 for Windows
    ArchiveSource("http://repo.msys2.org/mingw/i686/mingw-w64-i686-hdf5-1.10.5-1-any.pkg.tar.xz", "d29a56297219e1981f393e266ee515605237323fc20b0a69a45961c4bfe5e9da"),
    ArchiveSource("http://repo.msys2.org/mingw/i686/mingw-w64-i686-szip-2.1.1-2-any.pkg.tar.xz", "58b5efe1420a2bfd6e92cf94112d29b03ec588f54f4a995a1b26034076f0d369"),
    ArchiveSource("http://repo.msys2.org/mingw/i686/mingw-w64-i686-zlib-1.2.11-7-any.pkg.tar.xz", "addf6c52134027407640f1cbdf4efc5b64430f3a286cb4e4c4f5dbb44ce55a42"),
    ArchiveSource("http://repo.msys2.org/mingw/x86_64/mingw-w64-x86_64-szip-2.1.1-2-any.pkg.tar.xz", "ec8fe26370b0673c4b91f5ccf3404907dc7c24cb9d75c7b8830aa93a7c13ace7"),
    ArchiveSource("http://repo.msys2.org/mingw/x86_64/mingw-w64-x86_64-hdf5-1.10.5-1-any.pkg.tar.xz", "e01196dd53711304aa4026932c153171606efc4d6938dd3c172b6b40d9e7cdd9"),
    ArchiveSource("http://repo.msys2.org/mingw/x86_64/mingw-w64-x86_64-zlib-1.2.11-7-any.pkg.tar.xz", "1decf05b8ae6ab10ddc9035929014837c18dd76da825329023da835aec53cec2"),

     # We need some special compiler support libraries from mingw
    ArchiveSource("http://repo.msys2.org/mingw/i686/mingw-w64-i686-gcc-libs-9.1.0-3-any.pkg.tar.xz", "416819d44528e856fb1f142b41fd3b201615d19ddaed8faa5d71296676d6fa17"),

    # Native build for arm
    ArchiveSource("https://github.com/JuliaPackaging/Yggdrasil/releases/download/HDF5-arm-linux-gnueabihf-v1.10.5/hdf5-arm-linux-gnueabihf-v1.10.5.tar.gz", "12797e8f8b864dd1a5846c09a3efa21439844f76507483b373690b22bc2f09d7"),

    # Conda build (no MPI) for aarch64
    ArchiveSource("https://anaconda.org/conda-forge/hdf5/1.10.5/download/linux-aarch64/hdf5-1.10.5-nompi_h3c11f04_1104.tar.bz2", "46300770bb662aaefc92a9e21c5f78ebfaac5c00d4963844c3f730836400edb2";
                  unpack_target = "hdf5-aarch64-linux-gnu"),
]

# Bash recipe for building across all platforms
script = raw"""
cd ${WORKSPACE}/srcdir/
mkdir -p ${prefix}/lib ${prefix}/bin

# If we're on Windows, extract from msys2 builds.  Otherwise, extract from .whl files
if [[ ${target} == x86_64-*mingw* ]]; then
    mv mingw64/bin/*.dll ${prefix}/bin
elif [[ ${target} == i686-*mingw* ]]; then
    mv mingw32/bin/*.dll ${prefix}/bin
elif [[ "${target}" == arm-linux-gnueabihf ]]; then
    cd hdf5-arm-linux-gnueabihf-*
    # Remove zlib headers that shouldn't be here
    rm include/z*.h
    for dir in bin include lib share; do
        mkdir -p "${prefix}/${dir}"
        cp -r ${dir}/* "${prefix}/${dir}"
    done
    chmod 755 ${bindir}/*
elif [[ "${target}" == aarch64-* ]]; then
    cd hdf5-aarch64-linux-gnu/
    for dir in bin include lib info; do
        mkdir -p "${prefix}/${dir}"
        cp -r ${dir}/* "${prefix}/${dir}"
    done
    chmod 755 ${bindir}/*
else
    if [[ ${target} == x86_64-linux-gnu ]]; then
        WHL_FILE="*-h5py-*manylinux1_x86_64*.whl"
        LIBSDIR=.libs
    elif [[ ${target} == i686-linux-gnu ]]; then
        WHL_FILE="*-h5py-*manylinux1_i686*.whl"
        LIBSDIR=.libs
    elif [[ ${target} == x86_64-apple-darwin* ]]; then
        WHL_FILE="*-h5py-*macosx*.whl"
        LIBSDIR=.dylibs
    else
        echo "ERROR: Unsupported platform ${target}" >&2
        exit 1
    fi

    unzip "${WHL_FILE}"

    mv h5py/${LIBSDIR}/lib{sz,aec,hdf5}* ${prefix}/lib
fi

# We want libhdf5 to use OUR libz, so we force it to:
if [[ ${target} == *86*linux* ]]; then
    # We want libhdf5 to use OUR libz, so we force it to:
    for f in ${prefix}/lib/lib{sz,aec,hdf5}*; do
        patchelf --replace-needed $(basename h5py/${LIBSDIR}/libz*.${dlext}*) libz.${dlext}.1 ${f}
    done
elif [[ ${target} == *apple* ]]; then
    for f in ${prefix}/lib/lib{sz,aec,hdf5}*; do
        install_name_tool -change $(basename h5py/${LIBSDIR}/libz*.${dlext}*) libz.1.${dlext} ${f}
    done
fi

# We need to be able to access `libhdf5` and `libhdf5_hl` directly, so symlink it from the hashed filename from manylinux pypi
if [[ ${target} == *86*linux* ]]; then
    libhdf5name=$(basename ${prefix}/lib/libhdf5-*.${dlext}*)
    base="${libhdf5name%%.*}"
    ext="${libhdf5name#$base}"
    ln -s ${libhdf5name} ${prefix}/lib/libhdf5${ext}

    libhdf5_hlname=$(basename ${prefix}/lib/libhdf5_hl-*.${dlext}*)
    base="${libhdf5_hlname%%.*}"
    ext="${libhdf5_hlname#$base}"
    ln -s ${libhdf5_hlname} ${prefix}/lib/libhdf5_hl${ext}
fi

if [[ "${target}" != arm-linux-gnueabihf ]] && [[ "${target}" != aarch64-linux-gnueabihf ]]; then
    # Install headers
    mkdir -p "${prefix}/include"
    if [[ "${target}" == *-mingw* ]]; then
        # Use MinGW header files, which of course are different
        # from those for the other operating systems.
        cp -r mingw${nbits}/include/* "${prefix}/include"
    else
        # Use headers from the ARM build, with the hope that they'll be fine
        cp ${WORKSPACE}/srcdir/hdf5-arm-linux-gnueabihf-*/include/* "${prefix}/include"
    fi
fi
install_license ${WORKSPACE}/srcdir/hdf5-arm-linux-gnueabihf-*/share/COPYING
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = [
    Linux(:x86_64),
    Linux(:i686),
    Linux(:armv7l, libc=:glibc, call_abi=:eabihf),
    Linux(:aarch64, libc=:glibc),
    MacOS(),
    Windows(:x86_64),
    Windows(:i686),
]

# The products that we will ensure are always built
products = [
    LibraryProduct("libhdf5", :libhdf5),
    LibraryProduct("libhdf5_hl", :libhdf5_hl),
]

# Dependencies that must be installed before this package can be built
dependencies = [
    Dependency("Zlib_jll"),
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)


text:
function Base.show(io::IO, m::GLPK.Prob)
    @printf "%0s \n" "GLPK Model"
    @printf "   %-15s : %10s \n" "sense " GLPK.get_obj_dir(m) == 2 ? "maximize" : "minimize"
    @printf "   %-15s = %10s \n" "variables" GLPK.get_num_cols(m)
    @printf "   %-15s = %10s \n" "constraints" GLPK.get_num_rows(m)
    @printf "   %-15s = %10s \n" "coefficients" GLPK.get_num_nz(m)
end

# status codes
# http://artax.karlin.mff.cuni.cz/r-help/library/glpkAPI/html/glpkConstants.html
# To change settings for GLPK, find the parameter you wish
# to change, uncomment its line, and change the X to the desired
# value.
# Note: You can also, instead of numbers, use fx
#
# setfield!(P, Symbol("msg_lev"), GLPK.MSG_OFF)
# as equivalent to
# setfield!(P, Symbol("msg_lev"),convert(Int32, 1))
#
function settings_glpk()
    P = SimplexParam()
    setfield!(P, Symbol("msg_lev"),convert(Int32, 1))
    #setfield!(P, Symbol("meth"),convert(Int32, X))
    #setfield!(P, Symbol("pricing"),convert(Int32, X))
    #setfield!(P, Symbol("r_test"),convert(Int32, X))
    #setfield!(P, Symbol("tol_bnd"),convert(Float64, X))
    #setfield!(P, Symbol("tol_dj"),convert(Float64, X))
    #setfield!(P, Symbol("tol_piv"),convert(Float64, X))
    #setfield!(P, Symbol("obj_ll"),convert(Float64, X))
    #setfield!(P, Symbol("obj_ul"),convert(Float64, X))
    #setfield!(P, Symbol("it_lim"),convert(Int32, X))
    #setfield!(P, Symbol("tm_lim"),convert(Int32, X))
    #setfield!(P, Symbol("out_frq"),convert(Int32, X))
    #setfield!(P, Symbol("out_dly"),convert(Int32, X))
    #setfield!(P, Symbol("presolve"),convert(Int32, 1))
    return P
end

function change_objective_coef(lp::GLPK.Prob, objective::Number, value::Number = 1.0)
	num_colums = GLPK.get_num_cols(lp)

	new_objective = zeros(num_colums)

	new_objective[objective] = value

	map((x -> GLPK.set_obj_coef(lp, x, new_objective[x])), collect(1:num_colums))
end

function change_objective_coef{T <: Number}(lp::GLPK.Prob, objective::Array{T}, value::Array=[])
	if value == []
		value = ones(Float64, length(objective))
	end
	num_colums = GLPK.get_num_cols(lp)

	new_objective = zeros(num_colums)
	new_objective[objective] = value
	#map((x,y) -> new_objective[x] = y, objective,value)

	map((x -> GLPK.set_obj_coef(lp, x, new_objective[x])), collect(1:num_colums));
end

function get_variable_bounds(lp::GLPK.Prob)
	num_rxns = GLPK.get_num_cols(lp)
	lb = map(x -> GLPK.get_col_lb(lp,x), collect(1:num_rxns))
	lb = vcat(lb...)
	ub = map(x -> GLPK.get_col_ub(lp,x), collect(1:num_rxns))
	ub = vcat(ub...)

	return lb, ub
end

function get_variable_bounds(lp::GLPK.Prob, index::Number)
	lb = GLPK.get_col_lb(lp, index)
	ub = GLPK.get_col_ub(lp, index)
	return lb,ub
end

function get_constraint_bounds(lp::GLPK.Prob)
	num_mets = GLPK.get_num_rows(lp)
	lb = map(x -> GLPK.get_row_lb(lp,x), collect(1:num_mets))
	lb = vcat(lb...)
	ub = map(x -> GLPK.get_row_ub(lp,x), collect(1:num_mets))
	ub = vcat(ub...)

	return lb, ub
end

function get_constraint_matrix(lp::GLPK.Prob)
	num_rxns = GLPK.get_num_cols(lp)
	num_mets = GLPK.get_num_rows(lp)
	num_elements = GLPK.get_num_nz(lp)
	ar = Array(Float64, num_elements)

	ia = map(x -> GLPK.get_mat_col(lp,x)[1], collect(1:num_rxns));
	ia = vcat(ia...)

	ar = map(x -> GLPK.get_mat_col(lp,x)[2], collect(1:num_rxns));
	ar = vcat(ar...)

	ja = map(x -> GLPK.get_mat_row(lp,x)[1], collect(1:num_mets));
	ja = vcat(ja...)
	sort!(ja)

	S = sparse(ia,ja,ar)
end

function get_direction(lp::GLPK.Prob)
	if GLPK.get_obj_dir(lp) == 2
		return "maximize"
	else
		return "minimize"
	end
end

function get_objective_value(lp::GLPK.Prob)
	return GLPK.get_obj_val(lp)
end

function get_reduced_costs(lp::GLPK.Prob)
	num_rxns = GLPK.get_num_cols(lp)
	return map((x -> get_col_dual(lp, x)), collect(1:num_rxns))
end

function get_solution(lp::GLPK.Prob)
	num_colums = GLPK.get_num_cols(lp)
	x = map((x -> get_col_prim(lp, x)), collect(1:num_colums))
end

function get_solution_status(lp::GLPK.Prob)
	code = get_solution_status_code(lp)
	if code == 5
		return "Optimal"
	elseif code == 4
		return "No feasible solution"
	elseif code == 3
		return "Infeasible"
	elseif code == 2
		return "Feasible"
	elseif code == 6
		return "Unbound"
	elseif code == 1
		return "Undefined"
	else
		return warn(string("Unknown status code: ", code))
	end
end

function get_solution_status_code(lp::GLPK.Prob)
	return GLPK.get_status(lp)
end

function get_slack(lp::GLPK.Prob)
	num_mets = GLPK.get_num_rows(lp)
	return map((x -> get_row_dual(lp, x)), collect(1:num_mets))
end

function get_objective(lp::GLPK.Prob)
	num_rxns = GLPK.get_num_cols(lp)
	return map(x -> GLPK.get_obj_coef(lp,x), collect(1:num_rxns))
end

function set_direction(lp::GLPK.Prob, direction::AbstractString)
	if lowercase(direction) == "max"
		GLPK.set_obj_dir(lp, GLPK.MAX);
	else
		GLPK.set_obj_dir(lp, GLPK.MIN);
	end
end

function set_col_bounds(lp::GLPK.Prob, index::Number, lb::Number, ub::Number)
	if lb == ub
		GLPK.set_col_bnds(lp, index, GLPK.FX, lb, ub)
	else
		GLPK.set_col_bnds(lp, index, GLPK.DB, lb, ub)
	end
end

function set_col_bounds(lp::GLPK.Prob, index::Number, fixed_value::Number)
	GLPK.set_col_bnds(lp, index, GLPK.FX, fixed_value, fixed_value)
end

function set_objective(lp::GLPK.Prob, objective::Number, value::Number = 1.0)
	GLPK.set_obj_coef(lp, objective, value)
end

function setup_glpk(model::Model, objective::AbstractString = "max")
	lp = GLPK.Prob()
	GLPK.set_obj_dir(lp, GLPK.MAX)

	if contains(lowercase(objective),"min")
		GLPK.set_obj_dir(lp, GLPK.MIN)
	end

	GLPK.add_cols(lp, length(model.c))
	for i = 1:length(model.c)
		GLPK.set_col_bnds(lp, i, GLPK.DB, model.lb[i],model.ub[i])
		if model.lb[i] == model.ub[i]
			GLPK.set_col_bnds(lp, i, GLPK.FX, model.lb[i],model.ub[i])
		end
		GLPK.set_obj_coef(lp,i,model.c[i])
	end

	GLPK.add_rows(lp, length(model.b))

	for i in model.csense["<="]
		GLPK.set_row_bnds(lp,i,GLPK.UB,model.b[i],model.b[i])
	end
	for i in model.csense[">="]
		GLPK.set_row_bnds(lp,i,GLPK.LO,model.b[i],model.b[i])
	end
	for i in model.csense["="]
		GLPK.set_row_bnds(lp,i,GLPK.FX,model.b[i],model.b[i])
	end

	GLPK.load_matrix(lp, model.S)

	return lp
end

function setup_glpk{T <: Number}(c::Array{T}, lb::Array{T}, ub::Array{T}, b::Array{T},  S::SparseMatrixCSC, objective::AbstractString = "max")
	setup_glpk(c, lb, ub, b, b, S, objective)
end

function setup_glpk{T <: Number}(c::Array{T}, lb::Array{T}, ub::Array{T}, b_lower::Array{T}, b_upper::Array{T}, S::SparseMatrixCSC, objective::AbstractString = "max")
	lp = GLPK.Prob()

	GLPK.set_prob_name(lp, "sample")
	GLPK.term_out(GLPK.ON)

	GLPK.set_obj_dir(lp, GLPK.MAX)

	if contains(lowercase(objective),"min")
		GLPK.set_obj_dir(lp, GLPK.MIN)
	end

	GLPK.add_cols(lp, length(c))
	for i = 1:length(c)
		GLPK.set_col_bnds(lp, i, GLPK.DB, lb[i],ub[i])
		if lb[i] == ub[i]
			GLPK.set_col_bnds(lp, i, GLPK.FX, lb[i],ub[i])
		end
		GLPK.set_obj_coef(lp,i,c[i])
	end

	GLPK.add_rows(lp, length(b_lower))
	for i = 1:length(b_lower)
		if b_lower[i] == b_upper[i]
			GLPK.set_row_bnds(lp,i,GLPK.FX,b_lower[i],b_upper[i])
		else
			GLPK.set_row_bnds(lp,i,GLPK.DB,b_lower[i],b_upper[i])
		end
	end

	GLPK.load_matrix(lp, S)

	return lp
end

function setup_glpk{T <: Number}(c::Array{T}, lb::Array{T}, ub::Array{T}, b::Array{T}, csense::Array{String}, S::SparseMatrixCSC, objective::AbstractString = "max")
    b_lower = deepcopy(b)
    b_upper = deepcopy(b)
    b_lower[find(csense .== "<=")] = -Inf
    b_upper[find(csense .== ">=")] = Inf
    return setup_glpk(c, lb, ub, b_lower, b_upper, S, objective)
end

function setup_glpk{T <: Number}(c::Array{T}, lb::Array{T}, ub::Array{T}, b::Array{T}, csense::Dict, S::SparseMatrixCSC, objective::AbstractString = "max")
    b_lower = deepcopy(b)
    b_upper = deepcopy(b)
    b_lower[get(csense,"<=", [])] = -Inf
    b_upper[get(csense,">=", [])] = Inf
    return setup_glpk(c, lb, ub, b_lower, b_upper, S, objective)
end

function setup_glpk{T <: Number}(c::Array{T}, lb::Array{T}, ub::Array{T}, beq::Array{T}, Seq::SparseMatrixCSC, bineq::Array{T}, Sineq::SparseMatrixCSC, objective::AbstractString = "max")
	lp = GLPK.Prob()

	GLPK.set_prob_name(lp, "sample")
	GLPK.term_out(GLPK.ON)

	GLPK.set_obj_dir(lp, GLPK.MAX)

	if contains(lowercase(objective),"min")
		GLPK.set_obj_dir(lp, GLPK.MIN)
	end

	GLPK.add_cols(lp, length(c))
	for i = 1:length(c)
		GLPK.set_col_bnds(lp, i, GLPK.DB, lb[i],ub[i])
		if lb[i] == ub[i]
			GLPK.set_col_bnds(lp, i, GLPK.FX, lb[i],ub[i])
		end
		GLPK.set_obj_coef(lp,i,c[i])
	end

	GLPK.add_rows(lp, length(beq)+length(bineq))
	for i = 1:length(beq)
		GLPK.set_row_bnds(lp,i,GLPK.FX,beq[i],beq[i])
	end

	#GLPK.add_rows(lp, length(bineq))
	for i = 1:length(bineq)
		GLPK.set_row_bnds(lp,i+length(beq),GLPK.LO,-bineq[i],0.0)
	end
	GLPK.load_matrix(lp, vcat(Seq,Sineq))

	return lp
end

function solve(lp::GLPK.Prob)
	return GLPK.simplex(lp, settings_glpk())
end

function solver_status(lp::GLPK.Prob)

	status_code = get_solution_status_code(lp)

	if status_code == 1
		return "GLP_UNDEF"
	elseif status_code == 2
		return "GLP_FEAS"
	elseif status_code == 3
		return "GLP_INFEAS"
	elseif status_code == 4
		return "GLP_NOFEAS"
	elseif status_code == 5
		return "GLP_OPT"
	elseif status_code == 6
		return "GLP_UNBND"
	end
end

max_stars_repo_name: isebarn/CBM

max_issues_repo_name: isebarn/CBM

max_forks_repo_name: isebarn/CBM


text:
# This file is part of JuliaFMI.
# Licensed under MIT: https://github.com/AnHeuermann/JuliaFMI/blob/master/LICENSE.txt

# This file contains functions to be exported for JuliaFMI package.

module JuliaFMI

include("FMICallbackFunctions.jl")
include("FMI2CTypes.jl")
include("FMI2Types.jl")
include("HelperFunctions.jl")
include("modelDescriptionParsing.jl")
include("FMIWrapper.jl")
include("FMUSimulator.jl")

"""
Main function to simulate a FMU
"""
function simulateFMU(pathToFMU::String)
    main(pathToFMU)
end

export simulateFMU

end # module

max_stars_repo_name: AnHeuermann/JuliaFMU

max_issues_repo_name: AnHeuermann/JuliaFMU

max_forks_repo_name: jwscook/JuliaFMI


text:
@testset "KDTree" begin
    s = [Ball([i,0], 1) for i in 2:4]
    s0 = Ball([0,0], 1)
    s = [s0, s0, s0, s0, s...]
    @test_nowarn KDTree(s)  # must not generate StackOverflowError

    s = Shape{2,4}[Ball([i,0], 1) for i in 0:20]
    kd = KDTree(s)
    @test GeometryPrimitives.depth(kd) == 3
    @test findfirst([10.1,0], kd).c[1] == 10
    @test findfirst([10.1,1], kd) == nothing
    @test checktree(kd, s)

    s = Shape{3,9}[Ball(SVector(randn(rng),randn(rng),randn(rng)), 0.01) for i=1:100]
    @test checktree(KDTree(s), s)
    s = Shape{3,9}[Ball(SVector(randn(rng),randn(rng),randn(rng)), 0.1) for i=1:100]
    @test checktree(KDTree(s), s)
end


text:
struct TriangleInverseAdjoint{P,T,L}  <: AbstractArray{T,4}
    data::NTuple{L,T}
end

#
num_nonzero_in_∂inv(N) = sum(i -> binomial2(i+1) * (N+1-i), 1:N)

function create_inv_tri_adj_tuple(P, Ubase = :U, Lbase = :L)
    outtup = Expr(:tuple,)
    for p ∈ 1:P
        push!(outtup.args, ∂sym(Ubase, p, p, Lbase, p, p))
    end
    ind = P
    for lcol ∈ 1:P
        for lrow ∈ lcol:P
            for ucol ∈ max(2,lrow):P
                for urow ∈ 1:min(P,ucol-1,lcol)
                    push!(outtup.args, ∂sym(Ubase, urow, ucol, Lbase, lrow, lcol))
                end
            end
        end
    end
    outtup
end

# function ∂inv(Lt::LowerTriangularMatrix{P,T,L}) where {P,L,T}
@generated function ∂inv(Lt::AbstractLowerTriangularMatrix{P,T,L}) where {P,L,T}
# @generated function ∂inv(Lt::LowerTriangularMatrix{P,T,L}) where {P,T,L}
    q = quote end
    qa = q.args
    load_packed_L_quote!(qa, P, :Lt, :Lt)
    ∂inv_L_core_quote!(qa, P, :U, :Lt, T)
    uq = store_packed_U_quote!(qa, P, :U, T, L)
    Ladj = num_nonzero_in_∂inv(P)
    quote
        $(Expr(:meta,:inline))
        @fastmath @inbounds begin
            # begin
            $q
            $uq, TriangleInverseAdjoint{$P,$T,$Ladj}($(create_inv_tri_adj_tuple(P, :U, :Lt)))
        end
    end
end
struct ∂Inverse{T}
    x⁻¹::T
end
@inline function ∂inv(x)
    x⁻¹ = Base.FastMath.inv_fast(x)
    x⁻¹, ∂Inverse(x⁻¹)
end
@inline function ReverseDiffExpressionsBase.RESERVED_INCREMENT_SEED_RESERVED!(
    c::ReverseDiffExpressionsBase.AbstractUninitializedReference, ∂::∂Inverse, a
)
    x⁻¹′ = ∂.x⁻¹'
    c[] = @fastmath - x⁻¹′ * a * x⁻¹′
end
@inline function ReverseDiffExpressionsBase.RESERVED_INCREMENT_SEED_RESERVED!(
    c, ∂::∂Inverse, a
)
    x⁻¹′ = ∂.x⁻¹'
    @fastmath c[] -= x⁻¹′ * a * x⁻¹′
end

@generated function ∂inv′(Lt::AbstractLowerTriangularMatrix{P,T,L}) where {P,L,T}
# @generated function ∂inv(Lt::LowerTriangularMatrix{P,T,L}) where {P,T,L}
    q = quote end
    qa = q.args
    load_packed_L_quote!(qa, P, :Lt, :Lt)
    ∂inv_L_core_quote!(qa, P, :U, :Lt, T)
    uq = store_packed_U_quote!(qa, P, :U, T, L)
    Ladj = num_nonzero_in_∂inv(P)
    quote
        # $(Expr(:meta,:inline))
        @fastmath @inbounds begin
            # begin
            $q
            $uq, TriangleInverseAdjoint{$P,$T,$Ladj}($(create_inv_tri_adj_tuple(P, :U, :Lt)))
        end
    end
end
@inline function ∂inv′(x)
    x⁻¹ = Base.FastMath.inv_fast(x)'
    x⁻¹, ∂Inverse(x⁻¹)
end

function partial_inv_quote(P,T,L = binomial2(P+1))
    q = quote end
    qa = q.args
    load_packed_L_quote!(qa, P, :Lt, :Lt)
    ∂inv_L_core_quote!(qa, P, :U, :Lt, T)
    uq = store_packed_U_quote!(qa, P, :U, T, L)
    Ladj = num_nonzero_in_∂inv(P)
    quote
        # $(Expr(:meta,:inline))
        # @fastmath @inbounds begin
            # begin
            $q
            $uq, TriangleInverseAdjoint{$P,$T,$Ladj}($(create_inv_tri_adj_tuple(P, :U, :Lt)))
        # end
    end
end

# extract triangle_transpose

function triangle_adjoint_quote(P,T,L,PL)

    # How to order elements: first P ∂diags
    q = quote end
    loadq = quote end
    storeq = Expr(:tuple,)

    for p ∈ 1:P
        push!(loadq.args, :( $(Symbol(:∂U_,p,:_,p)) = t[$p]))
        push!(q.args, :( $(Symbol(:∂L_,p,:_,p)) = $(Symbol(:∂U_,p,:_,p)) * adj[$p] ))
        push!(storeq.args, Symbol(:∂L_,p,:_,p))
    end
    ind = P
    for ucol ∈ 2:P, urow ∈ 1:ucol-1
        ind += 1
        push!(loadq.args, :( $(Symbol(:∂U_,urow,:_,ucol)) = t[$ind]))
    end

    ind = P
    for lcol ∈ 1:P
        for lrow ∈ lcol:P
            first = lrow == lcol ? false : true
            for ucol ∈ max(2,lrow):P
                for urow ∈ 1:min(P,ucol-1,lcol)
                    ind += 1
                    if first
                        push!(q.args, :( $(Symbol(:∂L_,lrow,:_,lcol)) = $(Symbol(:∂U_,urow,:_,ucol)) * adj[$ind] ))
                        first = false
                    else
                        push!(q.args, :( $(Symbol(:∂L_,lrow,:_,lcol)) += $(Symbol(:∂U_,urow,:_,ucol)) * adj[$ind] ))
                    end
                    # push!(qa, :($(Symbol(:∂U_,urow,:_,ucol,:_∂L_,lrow,:_,lcol)) = $adjsym[$ind] ))
                end
            end
        end
    end

    for lcol ∈ 1:P-1, lrow ∈ lcol+1:P
        push!(storeq.args, Symbol(:∂L_,lrow,:_,lcol))
    end
    outsize = binomial2(P+1)
    for i ∈ outsize+1:PL
        push!(storeq.args, zero(T))
    end

    quote
        $loadq
        $q
    end, storeq
end

@generated function Base.:*(
    t::LinearAlgebra.Adjoint{T,<: PaddedMatrices.AbstractFixedSizeVector{M,T,PL}},
    adj::TriangleInverseAdjoint{P,T,L}
) where {P,T,L,M,PL}
    outsize = binomial2(P+1)
    q, storeq = triangle_adjoint_quote(P,T,L,PL)
    quote
        @fastmath @inbounds begin
            $q
            ConstantFixedSizeVector{$outsize,$T}($storeq)'
        end
    end
end
@generated function Base.:*(
            t::AbstractUpperTriangularMatrix{P,T},
            adj::TriangleInverseAdjoint{P,T,L}
        ) where {P,T,L}
    M = binomial2(P+1)
    Wm1 = VectorizationBase.pick_vector_width(M,T) - 1
    PL = (M + Wm1) & ~Wm1
    q, storeq = triangle_adjoint_quote(P,T,L,PL)
    quote
        @fastmath @inbounds begin
            $q
            LowerTriangularMatrix{$P,$T,$PL}($storeq)
        end
    end
end

function load_inv_tri_adj!(qa, P, adjsym = :triangle_adjoint)
    for p ∈ 1:P
        push!(qa, :($(Symbol(:∂U_,p,:_,p,:_∂L_,p,:_,p)) = $adjsym[$p] ))
    end
    ind = P
    for lcol ∈ 1:P
        for lrow ∈ lcol:P
            for ucol ∈ max(2,lrow):P
                for urow ∈ 1:min(P,ucol-1,lcol)
                    ind += 1
                    push!(qa, :($(Symbol(:∂U_,urow,:_,ucol,:_∂L_,lrow,:_,lcol)) = $adjsym[$ind] ))
                end
            end

        end
    end

    qa

end

@inline function Base.getindex(adj::TriangleInverseAdjoint{P,T,L}, i) where {P,T,L}
    @boundscheck i > L && ThrowBoundsError("i = $i > $L;\nnote TriangleInverseAdjoint matrices are sparse.")
    @inbounds adj.data[i]
end
function Base.getindex(adj::TriangleInverseAdjoint{P,T}, i, j, k, l) where {P,T}
    # for p ∈ 1:P
    #     push!(qa, :($(Symbol(:∂U_,p,:_,p,:_∂L_,p,:_,p)) = $adjsym[$p] ))
    # end
    i == j == k == l && return adj[i]
    ind = P
    for lcol ∈ 1:P
        for lrow ∈ lcol:P
            for ucol ∈ max(2,lrow):P
                for urow ∈ 1:min(P,ucol-1,lcol)
                    ind += 1
                    if urow == i && ucol == j && lrow == k && lcol == l
                        return adj[ind]
                    end
                    # push!(qa, :($(Symbol(:∂U_,urow,:_,ucol,:_∂L_,lrow,:_,lcol)) = $adjsym[$ind] ))
                end
            end

        end
    end
    zero(T)
end
Base.size(::TriangleInverseAdjoint{P}) where {P} = (P,P,P,P)


text:
function perimeter(r)
    oy = moves!(r, Nord)
    ox = moves!(r, Ost)
    for side in [Sud, West, Nord, Ost]
        putmarkers!(r,side)
    end
    moves!(r,Sud, oy)
    moves!(r, West, ox)
end

function moves!(r, side)
    counter = 0
    while !isborder(r, side)
        move!(r, side)
        counter += 1
    end
    return counter
end

function putmarkers!(r, side)
    while !isborder(r, side)
        putmarker!(r)
        move!(r, side)
    end
end

function moves!(r::Robot, side::HorizonSide, num_steps::Int)
    for steps in 1:num_steps
        move!(r, side)
    end
end

max_stars_repo_name: VladislavBukin/mirea-progs

max_issues_repo_name: VladislavBukin/mirea-progs

max_forks_repo_name: VladislavBukin/mirea-progs


text:
### ----------------------------------------------------------------------------
### Conjugate Gradient with Re-Orthogonalizations
### ----------------------------------------------------------------------------
### Algorithm Descriptions:
###     To keep the search directions conjugate, we use Gramschitz Orthogonalizations
###     on all previous conjugate vectors. This struct supports the options of
###     choosing a fixed number of vectors to store by.

mutable struct CGPO{T <: AbstractFloat}
    A::Function             # Linear opeartor
    b::AbstractArray{T}     # RHS vector
    tensor_size::Tuple      # The size of the tensor the linear operator is acting on.

    x::Vector{T}            # current guess, started with initial guess.
    r::Vector{T}            # previous computed residual
    rnew::Vector{T}         # Current residual
    p::Vector{T}            # Conjugate Direction
    Ap::Vector{T}           # for reducing garbage collector time.

    itr::UInt64             # Iteration count.
    P::Vector{Vector{T}}    # Past Conjugate Vectors.
    AP::Vector{Vector{T}}   # Past AP vector.
    R::Vector{Vector{T}}    # past residual vectors.
    storage_limit           # How many P vectors to store.
    orthogonalization_mode::Int64
                            # An options for how to orthogonalized.
                            # 1: Partial orthogonalize according to storage
                            # limit

    function CGPO(
        A::Function,
        b::AbstractArray,
        x0::Union{AbstractArray,Nothing}=nothing
    )
        x0 = x0===nothing ? b .+ 0.1 : x0
        r = reshape(b - A(x0), :)
        this = new{typeof(r[1])}()
        this.r = r
        this.A = A
        this.b = b
        this.tensor_size = size(b)
        this.x = x0
        # this.r = ComputeResidualVec(this, this.x)
        this.rnew = similar(this.r)
        this.p = this.r
        this.Ap = similar(this.r)
        this.x = x0
        this.itr = 0
        this.P = Vector{typeof(r)}()
        this.AP = Vector{typeof(r)}()
        this.R = Vector{typeof(r)}()
        r̂ = this.r/norm(this.r)
        push!(this.P, r̂)
        push!(this.R, r̂)

        # Default settings
        this.storage_limit = length(this.r) - 1       # Maximal limit, if not, we have a problem.
        this.orthogonalization_mode = 1

    return this end

    function CGPO(
        A::AbstractMatrix,
        b::AbstractArray
    )
    return CGPO((x) -> A*x, b) end
end

"""
    Pre-allocates a vector and get the values to the given
    pre-allocated vector.
"""
function ComputeVec(this::CGPO, x::AbstractArray)
    vec = this.A(reshape(x, this.tensor_size))
return reshape(vec, :) end

"""
    Evalute One step of the CGPO, perform conjugation processs according to
    settings.
"""
function (this::CGPO)()
    r = this.r
    if norm(r) == 0
        return 0
    end

    p = this.p
    Ap = this.Ap
    Ap = ComputeVec(this, p)   # <-- introduces error
    a = dot(r, r)/dot(p, Ap)   # Error here

    if a < 0
        warn("reset step size a. ")
        a = 0
    end

    this.x += a*p
    this.rnew .= r - a*Ap      # <--- Here.
    rnew_dotted = dot(this.rnew, this.rnew)
    rnewNorm = sqrt(rnew_dotted)
    b = rnew_dotted/dot(r, r)  # <--- Here too.

    this.p = this.rnew + b*p

    # partial orthogonalizations only errors on r, p is fixed here.
    Ar = ComputeVec(this, this.rnew)
    δp = zeros(size(this.r))
    δr = zeros(size(this.r))
    if this.orthogonalization_mode == 1
        for p̄ in this.P[1: end - 1]
            Ap̄ = ComputeVec(this, p̄)
            δp -= (dot(p̄, Ar)/dot(p̄,Ap̄))*p̄
        end
        this.p += δp
        for r̄ in this.R[1: end - 1]
            δr += dot(r̄, this.rnew)*r̄
        end
        this.rnew -= δr
    end

    this.r = copy(this.rnew)
    UpdatePR!(this, this.p, this.rnew/norm(this.rnew))
    this.itr += 1

return convert(Float64, rnewNorm) end

function GetPMatrix(this::CGPO) return hcat(this.P...) end

"""
    Keep currrent x, and reset everything that is here.
"""
function Reset!(this::CGPO)
    this.r = this.b - ComputeVec(this, this.x)
    this.p = this.r
    empty!(this.P)
return end

function UpdatePR!(this::CGPO, new_p, new_r)
    while length(this.P) > this.storage_limit
        popfirst!(this.P)
        popfirst!(this.R)
    end
    push!(this.P, new_p)
    push!(this.R, new_r)
return end

# Basic Tests ------------------------------------------------------------------

using LinearAlgebra, Plots

function BasicRun()
    N = 128; ϵ = 1e-10
    d = LinRange(0, 1 - ϵ, N)
    A = Diagonal(d.^2 .+ ϵ)
    b = ones(N)
    ẋ = A\b
    cg1 = CGPO(A, b)
    cg1.storage_limit = N/2
    cg3 = CGPO(A, b)
    cg3.orthogonalization_mode = 0
    e0 = ẋ - cg1.x
    P1 = Vector{Vector{Float64}}()
    push!(P1, cg1.p)
    for II in 1:N^2
        cg1()
        push!(P1, cg1.p)
        e = ẋ - cg1.x
        if sqrt(dot(e,A*e))/sqrt(dot(e0, A*e0)) < 1e-1
            println("cg1 Iter: $(II)")
            break
        else
            # println(norm(ẋ - cg1.x, Inf))
        end
    end
    P1 = hcat(P1...)
    D1 = P1'*A*P1
    display(heatmap(D1.|>abs.|>log2))

    P3 = Vector{Vector{Float64}}()
    push!(P3, cg3.p)
    for II in 1:N^2
        cg3()
        e = ẋ - cg3.x
        push!(P3, cg3.p)
        if sqrt(dot(e, A*e))/sqrt(dot(e0, A*e0))  < 1e-1
            println("cg3 Iter: $(II)")
            break
        else
            # println(norm(ẋ - cg3.x, Inf))
        end
    end
    P3 = hcat(P3...)
    D3 = P3'*A*P3
    display(heatmap(D3.|>abs.|>log2))

return end

BasicRun()


text:
using Test
using TypedTables
using SplitApplyCombine

include("Table.jl")
include("FlexTable.jl")


text:
export PackedFluxModelsDistribution

Base.@kwdef mutable struct PackedFluxModelsDistribution <: PackedSamplableBelief
  # standardized _type field
  _type::String
  # shape of the input data
  inputDim::Vector{Int}
  # shape of the output data
  outputDim::Vector{Int}
  # actual Flux models (Base64 encoded binary)
  mimeTypeModel::String
  models::Vector{String}
  # the data used for prediction, must be <: AbstractArray
  mimeTypeData::String
  data::String
  # shuffle model predictions relative to particle index at each sampling
  shuffle::Bool
  # false for default serialization with model info, set true for separate storage of models
  serializeHollow::Bool
    # TODO remove requirement and standardize sampler API
    # specialSampler::Symbol
  # TODO, only use ._type.  Legacy, field name usage to direct the IIF serialization towards JSON method
  PackedSamplableTypeJSON::String
end


text:
import RNG: AbstractRNG

"""
```julia
gen_seed(T[, n])
```

Generate a tuple of `n` truly random numbers in type `T`. If `n` is missing, return only one number.
The "truly" random numbers are provided by the random device of system. See
[`Base.Random.RandomDevice`](https://github.com/JuliaLang/julia/blob/master/base/random.jl#L29).

# Examples
```julia
julia> RNG.gen_seed(UInt64, 2)  # The output should probably be different on different computers.
(0x26aa3fe5e306f725,0x7b9dc3c227d8acc9)

julia> RNG.gen_seed(UInt32)
0x9ba60fdc
```
"""
gen_seed{T<:Number}(::Type{T}) = rand(RandomDevice(), T)
gen_seed{T<:Number}(::Type{T}, n) = tuple(rand(RandomDevice(), T, n)...)

"Get the original output type of a RNG."
@inline output_type{T}(::AbstractRNG{T}) = T

@inline split_uint(x::UInt128) = (x % UInt64, (x >> 64) % UInt64)
@inline split_uint(x::UInt64) = (x % UInt32, (x >> 32) % UInt32)
@inline union_uint(x::NTuple{2, UInt32}) = unsafe_load(Ptr{UInt64}(pointer_from_objref(x)), 1)
@inline union_uint(x::NTuple{2, UInt64}) = unsafe_load(Ptr{UInt128}(pointer_from_objref(x)), 1)
@inline union_uint(x::NTuple{4, UInt32}) = unsafe_load(Ptr{UInt128}(pointer_from_objref(x)), 1)


text:
using JuMP
using Ipopt

function my_recur_model(n)
    m = Model(optimizer_with_attributes(Ipopt.Optimizer,
        "print_level" => 5, "linear_solver" => "mumps"))
    @variable(m, 0 <= x[1:n] <= 1)
    pre_c = Vector{NonlinearExpression}(undef, n)
    pre_c[1] = @NLexpression(m, (x[1] - 0.5)^2)
    for i = 2:n
        pre_c[i] = @NLexpression(m, pre_c[i - 1] + (x[i] - 0.5)^2)
    end
    @NLconstraint(m, [i =1:n], pre_c[i] == 0)
    @NLobjective(m, Max, sum(x[i]^2 for i = 1:n))
    return m
end

function my_recur_model2(n)
    m = Model(optimizer_with_attributes(Ipopt.Optimizer,
        "print_level" => 5, "linear_solver" => "mumps"))
    @variable(m, 0 <= x[1:n] <= 1)
    @NLconstraint(m, [i=1:n], sum((x[j] - 0.5)^2 for j = 1:i) == 0)
    @NLobjective(m, Max, sum(x[i]^2 for i = 1:n))
    return m
end

function my_recur_model3(n)
    m = Model(optimizer_with_attributes(Ipopt.Optimizer,
        "print_level" => 5, "linear_solver" => "mumps"))
    @variable(m, 0 <= x[1:n] <= 1)
    @variable(m, pre_c[1:n])
    @NLconstraint(m, pre_c[1] == (x[1] - 0.5)^2)
    for i = 2:n
        @NLconstraint(m, pre_c[i] == pre_c[i - 1] + (x[i] - 0.5)^2)
    end
    @NLobjective(m, Max, sum(x[i]^2 for i = 1:n))
    @NLconstraint(m, [i =1:n], pre_c[i] == 0)
    return m
end

max_stars_repo_name: mmcordova/Robot-dance

max_issues_repo_name: mmcordova/Robot-dance

max_forks_repo_name: mmcordova/Robot-dance


text:
module Rules

using TermInterface
using Parameters
using AutoHashEquals
using Metatheory.EMatchCompiler
using Metatheory.Patterns
using Metatheory.Patterns: to_expr
using Metatheory: cleanast, binarize, matcher, instantiate

const EMPTY_DICT = Base.ImmutableDict{Int,Any}()

abstract type AbstractRule end
# Must override
Base.isequal(a::AbstractRule, b::AbstractRule) = false

abstract type SymbolicRule <: AbstractRule end

abstract type BidirRule <: SymbolicRule end

struct RuleRewriteError
  rule
  expr
end

getdepth(::Any) = typemax(Int)

showraw(io, t) = Base.show(IOContext(io, :simplify => false), t)
showraw(t) = showraw(stdout, t)

@noinline function Base.showerror(io::IO, err::RuleRewriteError)
  msg = "Failed to apply rule $(err.rule) on expression "
  msg *= sprint(io -> showraw(io, err.expr))
  print(io, msg)
end

"""
Rules defined as `left_hand --> right_hand` are
called *symbolic rewrite* rules. Application of a *rewrite* Rule
is a replacement of the `left_hand` pattern with
the `right_hand` substitution, with the correct instantiation
of pattern variables. Function call symbols are not treated as pattern
variables, all other identifiers are treated as pattern variables.
Literals such as `5, :e, "hello"` are not treated as pattern
variables.

```julia
@rule ~a * ~b --> ~b * ~a
```
"""
@auto_hash_equals struct RewriteRule <: SymbolicRule
  expr # rule pattern stored for pretty printing
  left
  right
  matcher
  patvars::Vector{Symbol}
  ematch_program::Program
end

Base.isequal(a::RewriteRule, b::RewriteRule) = (a.left == b.left) && (a.right == b.right)

function RewriteRule(l, r)
  ex = :($(to_expr(l)) --> $(to_expr(r)))
  RewriteRule(ex, l, r)
end

function RewriteRule(ex, l, r)
  pvars = patvars(l) ∪ patvars(r)
  # sort!(pvars)
  setdebrujin!(l, pvars)
  setdebrujin!(r, pvars)
  RewriteRule(ex, l, r, matcher(l), pvars, compile_pat(l))
end

Base.show(io::IO, r::RewriteRule) = print(io, r.expr)

function (r::RewriteRule)(term)
  # n == 1 means that exactly one term of the input (term,) was matched
  success(bindings, n) = n == 1 ? instantiate(term, r.right, bindings) : nothing

  try
    r.matcher(success, (term,), EMPTY_DICT)
  catch err
    throw(RuleRewriteError(r, term))
  end
end

# ============================================================
# EqualityRule
# ============================================================

"""
An `EqualityRule` can is a symbolic substitution rule that
can be rewritten bidirectional. Therefore, it should only be used
with the EGraphs backend.

```julia
@rule ~a * ~b == ~b * ~a
```
"""
@auto_hash_equals struct EqualityRule <: BidirRule
  expr # rule pattern stored for pretty printing
  left
  right
  patvars::Vector{Symbol}
  ematch_program_l::Program
  ematch_program_r::Program
end

function EqualityRule(ex, l, r)
  pvars = patvars(l) ∪ patvars(r)
  extravars = setdiff(pvars, patvars(l) ∩ patvars(r))
  if !isempty(extravars)
    error("unbound pattern variables $extravars when creating bidirectional rule")
  end
  setdebrujin!(l, pvars)
  setdebrujin!(r, pvars)
  progl = compile_pat(l)
  progr = compile_pat(r)
  EqualityRule(ex, l, r, pvars, progl, progr)
end

function EqualityRule(l, r)
  ex = :($(to_expr(l)) --> $(to_expr(r)))
  EqualityRule(ex, l, r)
end

Base.show(io::IO, r::EqualityRule) = print(io, r.expr)

function (r::EqualityRule)(x)
  throw(RuleRewriteError(r, x))
end

# ============================================================
# UnequalRule
# ============================================================

"""
This type of *anti*-rules is used for checking contradictions in the EGraph
backend. If two terms, corresponding to the left and right hand side of an
*anti-rule* are found in an [`EGraph`], saturation is halted immediately.

```julia
¬a ≠ a
```

"""
@auto_hash_equals struct UnequalRule <: BidirRule
  expr # rule pattern stored for pretty printing
  left
  right
  patvars::Vector{Symbol}
  ematch_program_l::Program
  ematch_program_r::Program
end

function UnequalRule(l, r)
  ex = :($(to_expr(l)) --> $(to_expr(r)))
  UnequalRule(ex, l, r)
end

function UnequalRule(ex, l, r)
  pvars = patvars(l) ∪ patvars(r)
  extravars = setdiff(pvars, patvars(l) ∩ patvars(r))
  if !isempty(extravars)
    error("unbound pattern variables $extravars when creating bidirectional rule")
  end
  # sort!(pvars)
  setdebrujin!(l, pvars)
  setdebrujin!(r, pvars)
  progl = compile_pat(l)
  progr = compile_pat(r)
  UnequalRule(ex, l, r, pvars, progl, progr)
end

Base.show(io::IO, r::UnequalRule) = print(io, r.expr)

# ============================================================
# DynamicRule
# ============================================================
"""
Rules defined as `left_hand => right_hand` are
called `dynamic` rules. Dynamic rules behave like anonymous functions.
Instead of a symbolic substitution, the right hand of
a dynamic `=>` rule is evaluated during rewriting:
matched values are bound to pattern variables as in a
regular function call. This allows for dynamic computation
of right hand sides.

Dynamic rule
```julia
@rule ~a::Number * ~b::Number => ~a*~b
```
"""
@auto_hash_equals struct DynamicRule <: AbstractRule
  expr # rule pattern stored for pretty printing
  left
  rhs_fun::Function
  matcher
  patvars::Vector{Symbol} # useful set of pattern variables
  ematch_program::Program
end

function DynamicRule(l, r)
  ex = :($(to_expr(l)) => $(to_expr(r)))
  DynamicRule(ex, l, r)
end

function DynamicRule(ex, l, r::Function)
  pvars = patvars(l)
  setdebrujin!(l, pvars)

  DynamicRule(ex, l, r, matcher(l), pvars, compile_pat(l))
end

Base.show(io::IO, r::DynamicRule) = print(io, r.expr)

function (r::DynamicRule)(term)
  # n == 1 means that exactly one term of the input (term,) was matched
  success(bindings, n) =
    if n == 1
      bvals = [bindings[i] for i in 1:length(r.patvars)]
      return r.rhs_fun(term, bindings, nothing, bvals...)
    end

  try
    return r.matcher(success, (term,), EMPTY_DICT)
  catch err
    throw(RuleRewriteError(r, term))
  end
end

export SymbolicRule
export RewriteRule
export BidirRule
export EqualityRule
export UnequalRule
export DynamicRule
export AbstractRule

end


text:
# Windows
# =======
#
# Sliding window iterator.
#
# This file is a part of BioJulia.
# License is MIT: https://github.com/BioJulia/Bio.jl/blob/master/LICENSE.md

module Windows

using Bio.Seq

using Compat

export eachwindow,
    EachWindowIterator,
    missed

typealias ArrayOrStringOrSeq Union{AbstractArray, AbstractString, BioSequence}

"""
An iterator which moves across a container, as a sliding window.

Constructor requires the data to move the window across, the width of the
window, and the step of the window.
"""
immutable EachWindowIterator{T <: ArrayOrStringOrSeq}
    "A reference to the collection to iterate over."
    data::T
    "The width of the sliding window."
    width::Int
    "How many positions the sliding window moves along."
    step::Int
    function EachWindowIterator{T}(data::T, width::Int, step::Int = 1)
        @assert width >= 1 "Window width must be ≥ 1."
        @assert step >= 1 "step must be ≥ 1."
        @assert width <= length(data) "The window size cannot be greater than number of data elements."
        return new(data, width, step)
    end
end

"""
Calculate the number of windows that will result from iterating across the container.

Accepts one variable of type EachWindowIterator.
"""
function Base.size(winitr::EachWindowIterator)
    return length(StepRange(winitr.width, winitr.step, length(winitr.data)))
end

Base.length(winitr::EachWindowIterator) = size(winitr)

"""
Calculate the number of elements in the container that are missed during iteration.
Typically because of the width and step size of the window: some elements near the end of the
container are missed if window sizes and step sizes are too large.
"""
function missed(winitr::EachWindowIterator)
    l = length(winitr.data)
    return l - StepRange(winitr.width, winitr.step, l).stop
end

"""
A sliding window iterator is considered equal to another
sliding window iterator if the data is considered equal, and the
width and step of the iterator is also equivalent.
"""
@compat function Base.:(==)(x::EachWindowIterator, y::EachWindowIterator)
    return (x.data == y.data) && (x.width == y.width) && (x.step == y.step)
end

"""
Convienient function for constructing an EachWindowIterator.

Accepts the same arguments as the EachWindowIterator constructor.
"""
function eachwindow{T <: ArrayOrStringOrSeq}(data::T, width::Int, step::Int = 1)
    EachWindowIterator{T}(data, width, step)
end

@inline function Base.start(it::EachWindowIterator)
    return 1
end

@inline function Base.next(it::EachWindowIterator, state::Integer)
    i = state
    window = sub(it.data, i:i + it.width - 1)
    return (i, window), i + it.step
end

# Extra next method to account for fact than strings don't have sub method
# like arrays and Nucleotide sequences do.
# The operation is an indexing operation, rather than a "proper"
# substring or subarray operation.
@inline function Base.next{T <: AbstractString}(it::EachWindowIterator{T}, state::Integer)
    i = state
    window = it.data[i:i + it.width - 1]
    return (i, window), i + it.step
end

@inline function Base.done(it::EachWindowIterator, state::Integer)
    return (state + it.width - 1) > length(it.data)
end

function Base.show(io::IO, it::EachWindowIterator)
    print(io, "Sliding window iterator.\nContainer size: ", length(it.data), " elements.",
    "\nWindow width: ", it.width, "\nStep distance: ", it.step,
    "\nTotal windows: ", size(it), "\nMissed elements: ",
    missed(it))
end

end


text:
using Trello
using Test
using UUIDs

@testset "Trello.jl" begin

    cred = TrelloCred()

    new_board_name = "ZZ_testing_$(uuid1())"

    # Should be able to create boards:
    create_board(cred::TrelloCred, new_board_name; desc="testing")
    boards = get_boards(cred)
    @test haskey(boards, new_board_name)
    @test boards[new_board_name].desc == "testing"
    board_id = boards[new_board_name].id

    # Test labels
    @test isempty(get_labels(cred, board_id))

    # Should be able to create lists
    create_list(cred, board_id, "L1")
    create_list(cred, board_id, "L2")
    create_list(cred, board_id, "L3")

    lists = get_lists(cred, board_id)
    @test collect(keys(lists)) == ["L1", "L2", "L3"]
    list_id = lists["L2"].id

    # Test cards
    create_card(cred, list_id, "C1")
    create_card(cred, list_id, "C2")
    create_card(cred, list_id, "C3")

    cards = get_cards(cred, list_id)
    @test collect(keys(cards)) == ["C1", "C2", "C3"]

    # After deleting board should be gone
    delete_board(cred, board_id)
    @test !haskey(get_boards(cred), new_board_name)
end


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

@doc raw"""ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create.

    IoK8sApimachineryPkgApisMetaV1ObjectMeta(;
        annotations=nothing,
        clusterName=nothing,
        creationTimestamp=nothing,
        deletionGracePeriodSeconds=nothing,
        deletionTimestamp=nothing,
        finalizers=nothing,
        generateName=nothing,
        generation=nothing,
        labels=nothing,
        managedFields=nothing,
        name=nothing,
        namespace=nothing,
        ownerReferences=nothing,
        resourceVersion=nothing,
        selfLink=nothing,
        uid=nothing,
    )

    - annotations::Dict{String, String} : Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations
    - clusterName::String : The name of the cluster which the object belongs to. This is used to distinguish resources with same name and namespace in different clusters. This field is not set anywhere right now and apiserver is going to ignore it if set in create or update request.
    - creationTimestamp::IoK8sApimachineryPkgApisMetaV1Time : CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.  Populated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
    - deletionGracePeriodSeconds::Int64 : Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only.
    - deletionTimestamp::IoK8sApimachineryPkgApisMetaV1Time : DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.  Populated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
    - finalizers::Vector{String} : Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order.  Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list.
    - generateName::String : GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.  If this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header).  Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency
    - generation::Int64 : A sequence number representing a specific generation of the desired state. Populated by the system. Read-only.
    - labels::Dict{String, String} : Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels
    - managedFields::Vector{IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry} : ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like \"ci-cd\". The set of fields is always in the version that the workflow used when modifying the object.
    - name::String : Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names
    - namespace::String : Namespace defines the space within each name must be unique. An empty namespace is equivalent to the \"default\" namespace, but \"default\" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.  Must be a DNS_LABEL. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces
    - ownerReferences::Vector{IoK8sApimachineryPkgApisMetaV1OwnerReference} : List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller.
    - resourceVersion::String : An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.  Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
    - selfLink::String : SelfLink is a URL representing this object. Populated by the system. Read-only.  DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
    - uid::String : UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.  Populated by the system. Read-only. More info: http://kubernetes.io/docs/user-guide/identifiers#uids
"""
mutable struct IoK8sApimachineryPkgApisMetaV1ObjectMeta <: SwaggerModel
    annotations::Any # spec type: Union{ Nothing, Dict{String, String} } # spec name: annotations
    clusterName::Any # spec type: Union{ Nothing, String } # spec name: clusterName
    creationTimestamp::Any # spec type: Union{ Nothing, IoK8sApimachineryPkgApisMetaV1Time } # spec name: creationTimestamp
    deletionGracePeriodSeconds::Any # spec type: Union{ Nothing, Int64 } # spec name: deletionGracePeriodSeconds
    deletionTimestamp::Any # spec type: Union{ Nothing, IoK8sApimachineryPkgApisMetaV1Time } # spec name: deletionTimestamp
    finalizers::Any # spec type: Union{ Nothing, Vector{String} } # spec name: finalizers
    generateName::Any # spec type: Union{ Nothing, String } # spec name: generateName
    generation::Any # spec type: Union{ Nothing, Int64 } # spec name: generation
    labels::Any # spec type: Union{ Nothing, Dict{String, String} } # spec name: labels
    managedFields::Any # spec type: Union{ Nothing, Vector{IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry} } # spec name: managedFields
    name::Any # spec type: Union{ Nothing, String } # spec name: name
    namespace::Any # spec type: Union{ Nothing, String } # spec name: namespace
    ownerReferences::Any # spec type: Union{ Nothing, Vector{IoK8sApimachineryPkgApisMetaV1OwnerReference} } # spec name: ownerReferences
    resourceVersion::Any # spec type: Union{ Nothing, String } # spec name: resourceVersion
    selfLink::Any # spec type: Union{ Nothing, String } # spec name: selfLink
    uid::Any # spec type: Union{ Nothing, String } # spec name: uid

    function IoK8sApimachineryPkgApisMetaV1ObjectMeta(;annotations=nothing, clusterName=nothing, creationTimestamp=nothing, deletionGracePeriodSeconds=nothing, deletionTimestamp=nothing, finalizers=nothing, generateName=nothing, generation=nothing, labels=nothing, managedFields=nothing, name=nothing, namespace=nothing, ownerReferences=nothing, resourceVersion=nothing, selfLink=nothing, uid=nothing)
        o = new()
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("annotations"), annotations)
        setfield!(o, Symbol("annotations"), annotations)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("clusterName"), clusterName)
        setfield!(o, Symbol("clusterName"), clusterName)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("creationTimestamp"), creationTimestamp)
        setfield!(o, Symbol("creationTimestamp"), creationTimestamp)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("deletionGracePeriodSeconds"), deletionGracePeriodSeconds)
        setfield!(o, Symbol("deletionGracePeriodSeconds"), deletionGracePeriodSeconds)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("deletionTimestamp"), deletionTimestamp)
        setfield!(o, Symbol("deletionTimestamp"), deletionTimestamp)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("finalizers"), finalizers)
        setfield!(o, Symbol("finalizers"), finalizers)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("generateName"), generateName)
        setfield!(o, Symbol("generateName"), generateName)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("generation"), generation)
        setfield!(o, Symbol("generation"), generation)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("labels"), labels)
        setfield!(o, Symbol("labels"), labels)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("managedFields"), managedFields)
        setfield!(o, Symbol("managedFields"), managedFields)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("name"), name)
        setfield!(o, Symbol("name"), name)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("namespace"), namespace)
        setfield!(o, Symbol("namespace"), namespace)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("ownerReferences"), ownerReferences)
        setfield!(o, Symbol("ownerReferences"), ownerReferences)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("resourceVersion"), resourceVersion)
        setfield!(o, Symbol("resourceVersion"), resourceVersion)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("selfLink"), selfLink)
        setfield!(o, Symbol("selfLink"), selfLink)
        validate_property(IoK8sApimachineryPkgApisMetaV1ObjectMeta, Symbol("uid"), uid)
        setfield!(o, Symbol("uid"), uid)
        o
    end
end # type IoK8sApimachineryPkgApisMetaV1ObjectMeta

const _property_map_IoK8sApimachineryPkgApisMetaV1ObjectMeta = Dict{Symbol,Symbol}(Symbol("annotations")=>Symbol("annotations"), Symbol("clusterName")=>Symbol("clusterName"), Symbol("creationTimestamp")=>Symbol("creationTimestamp"), Symbol("deletionGracePeriodSeconds")=>Symbol("deletionGracePeriodSeconds"), Symbol("deletionTimestamp")=>Symbol("deletionTimestamp"), Symbol("finalizers")=>Symbol("finalizers"), Symbol("generateName")=>Symbol("generateName"), Symbol("generation")=>Symbol("generation"), Symbol("labels")=>Symbol("labels"), Symbol("managedFields")=>Symbol("managedFields"), Symbol("name")=>Symbol("name"), Symbol("namespace")=>Symbol("namespace"), Symbol("ownerReferences")=>Symbol("ownerReferences"), Symbol("resourceVersion")=>Symbol("resourceVersion"), Symbol("selfLink")=>Symbol("selfLink"), Symbol("uid")=>Symbol("uid"))
const _property_types_IoK8sApimachineryPkgApisMetaV1ObjectMeta = Dict{Symbol,String}(Symbol("annotations")=>"Dict{String, String}", Symbol("clusterName")=>"String", Symbol("creationTimestamp")=>"IoK8sApimachineryPkgApisMetaV1Time", Symbol("deletionGracePeriodSeconds")=>"Int64", Symbol("deletionTimestamp")=>"IoK8sApimachineryPkgApisMetaV1Time", Symbol("finalizers")=>"Vector{String}", Symbol("generateName")=>"String", Symbol("generation")=>"Int64", Symbol("labels")=>"Dict{String, String}", Symbol("managedFields")=>"Vector{IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry}", Symbol("name")=>"String", Symbol("namespace")=>"String", Symbol("ownerReferences")=>"Vector{IoK8sApimachineryPkgApisMetaV1OwnerReference}", Symbol("resourceVersion")=>"String", Symbol("selfLink")=>"String", Symbol("uid")=>"String")
Base.propertynames(::Type{ IoK8sApimachineryPkgApisMetaV1ObjectMeta }) = collect(keys(_property_map_IoK8sApimachineryPkgApisMetaV1ObjectMeta))
Swagger.property_type(::Type{ IoK8sApimachineryPkgApisMetaV1ObjectMeta }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApimachineryPkgApisMetaV1ObjectMeta[name]))}
Swagger.field_name(::Type{ IoK8sApimachineryPkgApisMetaV1ObjectMeta }, property_name::Symbol) =  _property_map_IoK8sApimachineryPkgApisMetaV1ObjectMeta[property_name]

function check_required(o::IoK8sApimachineryPkgApisMetaV1ObjectMeta)
    true
end

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


text:
include("../common/layers.jl")

using Random

mutable struct SimpleSkipGram
    in_layer
    out_layer
    loss_layer1
    loss_layer2
    params
    grads
    word_vecs

    function SimpleSkipGram(vocab_size, hidden_size)
        self = new()
        V, H = vocab_size, hidden_size

        # 重みの初期化
        W_in = 0.01 .* Random.randn(V, H) # Float32の指定は特にしない
        W_out = 0.01 .* Random.randn(H, V) # Float32の指定は特にしない

        # レイヤの生成
        self.in_layer = MatMul(W_in)
        self.out_layer = MatMul(W_out)
        self.loss_layer1 = SoftmaxWithLoss()
        self.loss_layer2 = SoftmaxWithLoss()

        # 全ての重みと勾配を配列にまとめる
        layers = [self.in_layer, self.out_layer]
        self.params, self.grads = [], []
        for layer in layers
            push!(self.params, layer.params)
            push!(self.grads, layer.grads)
        end

        # 構造体の変数に単語の分散表現を設定
        self.word_vecs = W_in
        return self
    end
end

function forward!(self::SimpleSkipGram, contexts, target)
    # contextsの形状は3次元決め打ち
    h = forward!(self.in_layer, target)
    s = forward!(self.out_layer, h)
    l1 = forward!(self.loss_layer1, s, contexts[:, 1, :])
    l2 = forward!(self.loss_layer2, s, contexts[:, 2, :])
    loss = l1 + l2
    return loss
end

function backward!(self::SimpleSkipGram; dout=1)
    dl1 = backward!(self.loss_layer1, dout=dout)
    dl2 = backward!(self.loss_layer2, dout=dout)
    ds = dl1 + dl2
    dh = backward!(self.out_layer, ds)
    backward!(self.in_layer, dh)
end