text:
include("setup.jl")

@testset "types are defined" begin
    for (T, s) = (Int256 => 256, Int512 => 512, Int1024 => 1024)
        @test sizeof(T) * 8 == s
        @test T <: Signed
        @test T <: BitIntegers.BitSigned
        @test T <: BitIntegers.BitInteger
        @test T ∈ BitIntegers.BitSigned_types
        @test T ∈ BitIntegers.BitInteger_types
    end
    for (T, s) = (UInt256 => 256, UInt512 => 512, UInt1024 => 1024)
        @test sizeof(T) * 8 == s
        @test T <: Unsigned
        @test T <: BitIntegers.BitUnsigned
        @test T <: BitIntegers.BitInteger
        @test T ∈ BitIntegers.BitUnsigned_types
        @test T ∈ BitIntegers.BitInteger_types
    end
end

@testset "string macros" begin
    @test   int256"1" ===   Int256(1)
    @test  uint256"1" ===  UInt256(1)
    @test   int512"1" ===   Int512(1)
    @test  uint512"1" ===  UInt512(1)
    @test  int1024"1" ===  Int1024(1)
    @test uint1024"1" === UInt1024(1)
end

@testset "typemin, typemax" begin
    for X in XInts
        @test typemin(X) < typemax(X)
        if X <: Unsigned
            @test typemin(X) == 0
            @test count_ones(typemax(X)) == 8 * sizeof(X)
        else
            @test typemin(X) < 0 && typemax(X) > 0
            # @test typemin(X) - 1 == typemax(X)
        end
    end
end

@testset "widen" begin
    M = TestBitIntegers
    @test widen(M.MyInt8)   == Int16
    @test widen(M.MyUInt8)  == UInt16
    @test widen(M.Int24)    == BigInt
    @test widen(M.UInt24)   == BigInt
    @test widen(Int256)   == Int512
    @test widen(UInt256)  == UInt512
    @test widen(Int512)   == Int1024
    @test widen(UInt512)  == UInt1024
    @test widen(Int1024)  == BigInt
    @test widen(UInt1024) == BigInt
end

@testset "conversions" begin
    @testset "between types" begin
        for (X, Y) in TypeCombos
            @test Y(42) === Y(X(42))
            if sizeof(X) * 8 >= 128 > sizeof(Y) * 8
                x = X(UInt128(1) << 126)
                @test_throws InexactError Y(x)
            end
            if X <: Signed && Y <: Unsigned
                x = X(-1)
                @test_throws InexactError Y(x)
            end
        end
    end
    @testset "signedness" begin
        for X in XInts
            XU = Base.uinttype(X)
            @test XU <: Unsigned
            x = X(1)
            @test x isa X
            xu = convert(Unsigned, x)
            xs = convert(Signed, x)
            @test xu isa XU
            @test xu === Unsigned(x) === unsigned(x)
            @test xs === Signed(x) === signed(x)
            if X <: Signed
                @test sizeof(X) == sizeof(XU)
                @test X !== XU
                @test x === xs
            else
                @test X === XU
                @test x === xu
            end
            if X <: Signed
                @test_throws InexactError Unsigned(X(-1))
                @test unsigned(X(-1)) isa XU
            end
        end
    end
end

@testset "promote_rule" begin
    for (X, Y) in TypeCombos
        T = promote_type(X, Y)
        if X.size > Y.size
            @test T === X
        elseif X.size == Y.size
            @test T === (X <: Unsigned ? X : Y)
        else
            @test T == Y
        end
    end
end

@testset "x % T" begin
    i = rand(0:typemax(Int8))
    for (X, Y) in TypeCombos
        x = X(i)
        @test x % Y isa Y
        @test x % Y == x
        @test x % Y % X === x
    end
end

@testset "comparisons" begin
    i, j = sort!(rand(0:typemax(Int8), 2))
    i == j && ((i, j) = (2, 3))
    for (X, Y) in TypeCombos
        x, y = X(i), Y(j)
        @test x < y
        @test x <= y
        @test x != y
        @test y > x
        @test y >= x
        @test x == Y(i)
        @test y == X(j)
    end
end

@testset "bit operations" begin
    i, j = rand(1:Int(typemax(Int8)), 2)
    k, l = rand(Int(typemin(Int8)):-1, 2)
    for X in XInts
        for op in (~, bswap)
            if sizeof(X) % 2 != 0 && op == bswap
                @test_throws ErrorException op(X(i))
                continue
            end
            x = op(X(i))
            @test x isa X
            @test x != X(i) # we assume sizeof(X) > 8
            @test op(x) == X(i)
        end
        for op in (count_ones, leading_zeros, trailing_zeros, leading_ones, trailing_ones)
            r = op(X(i))
            @test r isa Int
            if op ∈ (count_ones, trailing_ones, trailing_zeros, leading_ones)
                @test r === op(i)
            else # leading_zeros
                @test r == op(i) + 8 * (sizeof(X) - sizeof(i))
            end
        end
    end
    for (X, Y) in TypeCombos
        T = promote_type(X, Y)
        for n = (i, k), m = (j, l)
            if n < 0 && X <: Unsigned || m < 0 && Y <: Unsigned
                continue
            end
            x, y = X(n), Y(m)
            for op in (&, |, xor)
                z = op(x, y)
                @test z isa T
                @test signed(z) == op(n, m)
            end
            @test flipsign(x, y) isa X
            if !(n == -128 && X == Int8 && m < 0)
                @test signed(flipsign(x, y)) == flipsign(n, m)
            end
        end
    end
    for (X, Y) in TypeCombos
        x,y = X(i),Y(j)
        @test isodd(x) == isodd(i) == !iseven(x)
        @test isodd(y) == isodd(j) == !iseven(y)
        # Test performance of isodd(x): doesn't allocate.
        @test @allocated(isodd(x) && isodd(y)) == 0
    end
end

@testset "shift operations" begin
    vals = [rand(Int8, 10)..., rand(Int64, 10)..., rand(Int1024, 10)...]
    sh_cts = unique(i + j for i in [0, 32, 64, 128, 200, 256, 1024] for j in -20:20)
    sh_rnd = Integer[rand(1:1024, 20)..., rand(Int256(1):Int256(1024), 20)...]
    shifts = Integer[sh_cts..., -sh_cts..., sh_rnd..., -sh_rnd...]
    for X in XInts
        for val in vals
            mask = big(1) << (8 * sizeof(X)) - 1
            x = val % X
            b = big(x)
            for s in shifts
                @test (x >> s) & mask == (b >> s) & mask
                @test (x << s) & mask == (b << s) & mask
                @test (x >>> s) & mask == ((b & mask) >>> s) & mask
            end
        end
    end
end

@testset "arithmetic operations" begin
    for (X, Y) in TypeCombos
        T = promote_type(X, Y)
        for op = (-, +, *, div, rem, mod)
            TT = op ∈ (-, +, *) ? T :
                 op === mod ?
                   (Y <: Signed   && T <: Unsigned ? typeof(signed(T(0))) :
                    Y <: Unsigned && T <: Signed ?   typeof(unsigned(T(0))) :
                    T) :
                 X <: Signed   && T <: Unsigned ? typeof(signed(T(0))) :
                 X <: Unsigned && T <: Signed ?   typeof(unsigned(T(0))) :
                 T
            @test op(X(5), Y(2)) isa TT
            @test op(X(5), Y(2)) == op(5, 2)
        end
    end
end

@testset "BigInt" begin
    r = -big(2)^2000:big(2)^2000
    b = rand(r)
    for X in XInts
        x = b % X
        @test x isa X
        if typemin(X) <= b <= typemax(X)
            @test x == b
            @test x == X(b)
        else
            @test_throws InexactError X(b)
        end
    end
end

@testset "ndigits0z" begin
    base = rand([-100:-2; 2:200])
    for X in XInts
        x = rand(X)
        if X <: Unsigned && base < 0
            x >>= 1 # ndigits0znb not implemented in this case
        end
        n = big(x)
        @test Base.ndigits0z(x, base) == Base.ndigits0z(n, base)
    end
end

@testset "bitstring" begin
    @test bitstring(UInt256(3)) == bitstring(Int256(3)) == '0'^254 * "11"
    @test bitstring(UInt512(3) << 256) == bitstring(Int512(3) << 256) == '0'^254 * "11" * '0'^256
    let (x, y) = rand(UInt128, 2)
        u = UInt1024(x) << 512 + UInt1024(y)
        v = u + UInt1024(1) << 1023
        @test bitstring(u) == bitstring(Int1024(u)) == '0'^384 * bitstring(x) * '0'^384 * bitstring(y)
        @test bitstring(v) == bitstring(typemin(Int1024) + Int1024(u)) == '1' * '0'^383 * bitstring(x) * '0'^384 * bitstring(y)
    end
end

@testset "floats" begin
    for X in XInts
        x = rand(X)
        n = big(x)
        for F in (Float16, Float32, Float64)
            f = F(n)
            @test F(x) == f
            @test promote_type(X, F) == F
            if !isinf(f)
                @test F(X(f)) == f
            end
            # the argument to X() is ±Inf in many cases:
            @test_throws InexactError X(prevfloat(F(typemin(X))))
            @test_throws InexactError X(nextfloat(F(typemax(X))))
        end
        @test AbstractFloat(x) == Float64(x)
    end
end

@testset "read/write" begin
    function read_write_tests(io, X)
        x, y = rand(X, 2)
        @test write(io, x) == sizeof(x)
        @test write(io, y) == sizeof(y)
        seekstart(io)
        @test read(io, X) == x
        @test read(io, X) == y
        @test_throws EOFError read(io, X)
        seekstart(io)
        serialize(io, x)
        serialize(io, 3)
        serialize(io, y)
        serialize(io, true)
        seekstart(io)
        q = deserialize(io)
        @test q === x
        q = deserialize(io)
        @test q === 3
        q = deserialize(io)
        @test q === y
        q = deserialize(io)
        @test q === true
    end

    @testset "IOBuffer" begin
        for X in XInts
            read_write_tests(IOBuffer(), X)
        end
    end

    @testset "IOStream" begin
        for X in XInts
            open(tempname(), "w+") do iostream
                read_write_tests(iostream, X)
            end
        end
    end
end

@testset "rand" begin
    for X in XInts
        # ranges
        a, k, b = X.(sort!(big.([x >> (sizeof(X)*4) for x in rand(X, 3)]))) # TODO: remove conversions
        k >>= rand(0:ndigits(k, base=2)-1)
        r = k < 0 ? (b:k:a) : (a:k:b)
        @test rand(r) ∈ r

        # scalars
        ispow2(sizeof(X)) || VERSION >= v"1.4" || continue # cf. Issue #29053
        A = rand(X, 3000)
        for a = (ispow2(sizeof(X)) ? [A, bswap.(A)] : [A])
            for f in (leading_zeros, leading_ones, trailing_zeros, trailing_ones)
                @test 0.9 < mean(f.(a)) < 1.1
            end
            @test 8*sizeof(X)÷2 - 1 < mean(count_ones.(a)) < 8*sizeof(X)÷2 + 1
        end
    end
end

@testset "checked operations" begin
    for X in XInts
        if sizeof(X) != 3 # bug with [U]Int24, cf. Julia issue #34288
            @test Base.sub_with_overflow(typemin(X)+X(3), X(3)) == (typemin(X), false)
            @test Base.sub_with_overflow(typemin(X)+X(2), X(3)) == (typemax(X), true)
            @test Base.add_with_overflow(typemax(X)-X(3), X(3)) == (typemax(X), false)
            @test Base.add_with_overflow(typemax(X)-X(2), X(3)) == (typemin(X), true)
            if X <: Signed # unimplemented otherwise (problem with LLVM)
                @test Base.mul_with_overflow(typemax(X), X(1))  == (typemax(X), false)
                @test Base.mul_with_overflow(typemax(X), X(2))  == (-2 % X,     true)
            end
        end

        @test Base.checked_abs(typemax(X)) == typemax(X)
        if X <: Signed
            @test_throws OverflowError Base.checked_abs(typemin(X))
        else
            @test Base.checked_abs(typemin(X)) == zero(X)
            x = rand(X)
            @test Base.checked_abs(x) == x
        end
    end
end


text:
using MatrixLMnet
using Test

@testset "MatrixLMnet" begin
    # include("l1_helpers.jl")
    include("mlmnetTests.jl")
    include("mlmnetCvTests.jl")
end

ext: jl


text:
module QF939

	include("Data.jl")
	export Data

	include("./initial_point.jl")
	export initial_point

	include("./div_thread.jl")
	include("./initial_linklist.jl")
	include("./rpbc.jl")
	include("./rpbc_quad.jl")
	include("./wrap_cell.jl")
	include("./upair.jl")
	include("./utotal.jl")
	include("./ufpair.jl")
	include("./uftotal.jl")
	export utotal, uftotal

end


text:
# Wrapper type for solutions from Trixi's own time integrators, partially mimicking
# DiffEqBase.ODESolution
struct TimeIntegratorSolution{tType, uType, P}
  t::tType
  u::uType
  prob::P
end

include("methods_2N.jl")
include("methods_3Sstar.jl")


text:
using FFTA, Test
test_nums = [8, 11, 15, 16, 27, 100]
@testset verbose = true " forward" begin
    for N in test_nums
        x = ones(Float64, N)
        y = rfft(x)
        y_ref = 0*y
        y_ref[1] = N
        @test y ≈ y_ref atol=1e-12
    end
end


text:
using Documenter
using TableReader

makedocs(sitename = "TableReader.jl")
deploydocs(repo = "github.com/bicycle1885/TableReader.jl.git")


text:
module TestBasic
using PCloud
using Test

@testset "client creation" begin
    pcloud = PCloudClient()

    res = PCloud.getdigest(pcloud)
    @test res.result == 0
end

@testset "client endpoints" begin
    pcloudapi = "https://api.pcloud.com/"
    pcloud = PCloudClient(set_endpoints = false)

    @test pcloud.apiep == pcloudapi
    @test pcloud.binep == pcloudapi
    @test pcloud.rootep == pcloudapi

    res = PCloud.getapiserver(pcloud)
    update_endpoints!(pcloud)
    @test pcloud.apiep == "https://" * first(res.api) * "/"
    @test pcloud.binep == "https://" * first(res.binapi) * "/"
    @test pcloud.rootep == pcloudapi

    reset_endpoints!(pcloud)
    @test pcloud.apiep == pcloudapi
    @test pcloud.binep == pcloudapi
    @test pcloud.rootep == pcloudapi
end

@testset "client authentication" begin
    @test_throws PCloud.PCloudError PCloudClient(user = "nouser", password = "nopassword")
    pcloud = PCloudClient(auth_token = "notoken")
    @test_throws PCloud.PCloudError PCloud.userinfo(pcloud)
end

end # module


text:
using CuArrays

# TODO: custom kernel for activations on GPU

function sigmoid(x::Float32)::Float32
    return 1 / (1 + CuArrays.exp(-x))
end

function sigmoid_back(x::Float32)::Float32
    sig = sigmoid(x)
    return sig*(1-sig)
end

function relu(x::Float32)::Float32
    if x>0
        return x
    else
        return 0
    end
end

function relu_back(x::Float32)::Float32
    if x>0
        return 1
    else
        return 0
    end
end


text:
using FileIO

function defcolor(c1, c2, c1def, c2def)
    if !isnothing(c1) && isnothing(c2)
        c2 = c1
    else
        c1 = isnothing(c1) ? c1def : c1
        c2 = isnothing(c2) ? c2def : c2
    end
    c1,c2
end

function set_mesh!(vis, model::AbstractModel; kwargs...)
    _set_mesh!(vis["robot"], model; kwargs...)
end

RobotDynamics.RBState(model::AbstractModel, x) =
    RBState(position(model, x), orientation(model, x), zeros(3), zeros(3))

function _set_mesh!(vis, model::RobotZoo.DoubleIntegrator{<:Any,2};
        color=colorant"green", radius=0.1, height=0.05)
    radius = Float32(radius)
    body = Cylinder(Point3f0(0,0,0), Point3f0(0,0,height), radius)
    setobject!(vis["geom"]["body"], body, MeshPhongMaterial(color=color))
end

# Pendulum
function _set_mesh!(vis, model::RobotZoo.Pendulum;
        color=nothing, color2=nothing, length=model.length)
    hinge = Cylinder(Point3f0(0.05,0,0), Point3f0(-0.05,0,0), 0.05f0)
    rod   = Cylinder(Point3f0(0,0,0), Point3f0(0,0,length), 0.01f0)
    mass  = HyperSphere(Point3f0(0,0,length), 0.05f0)
    c1,c2 = defcolor(color, color2, colorant"blue", colorant"red")
    setobject!(vis["geom"]["hinge"], hinge, MeshPhongMaterial(color=colorant"black"))
    setobject!(vis["geom"]["rod"  ], rod,   MeshPhongMaterial(color=c1))
    setobject!(vis["geom"]["mass" ], mass , MeshPhongMaterial(color=c2))
end

# Cartpole
function _set_mesh!(vis, model::RobotZoo.Cartpole;
        color=nothing, color2=nothing)
    dim = Vec(0.1, 0.3, 0.1)
    rod = Cylinder(Point3f0(0,-10,0), Point3f0(0,10,0), 0.01f0)
    cart = Rect3D(-dim/2, dim)
    hinge = Cylinder(Point3f0(-dim[1]/2,0,dim[3]/2), Point3f0(dim[1],0,dim[3]/2), 0.03f0)
    c1,c2 = defcolor(color,color2, colorant"blue", colorant"red")

    pole = Cylinder(Point3f0(0,0,0),Point3f0(0,0,model.l),0.01f0)
    mass = HyperSphere(Point3f0(0,0,model.l), 0.05f0)
    setobject!(vis["rod"], rod, MeshPhongMaterial(color=colorant"grey"))
    setobject!(vis["cart","box"],   cart, MeshPhongMaterial(color=isnothing(color) ? colorant"green" : color))
    setobject!(vis["cart","hinge"], hinge, MeshPhongMaterial(color=colorant"black"))
    setobject!(vis["cart","pole","geom","cyl"], pole, MeshPhongMaterial(color=c1))
    setobject!(vis["cart","pole","geom","mass"], mass, MeshPhongMaterial(color=c2))
    settransform!(vis["cart","pole"], Translation(0.75*dim[1],0,dim[3]/2))
end

function visualize!(vis, model::RobotZoo.Cartpole, x::StaticVector)
    y = x[1]
    θ = x[2]
    q = expm((pi-θ) * @SVector [1,0,0])
    settransform!(vis["robot","cart"], Translation(0,-y,0))
    settransform!(vis["robot","cart","pole","geom"], LinearMap(UnitQuaternion(q)))
end

# Acrobot (doublependulum)
function _set_mesh!(vis, model::RobotZoo.Acrobot; color=colorant"blue", thick=0.05)
    hinge = Cylinder(Point3f0(-0.05,0,0), Point3f0(0.05,0,0), 0.05f0)
    dim1  = Vec(thick, thick, model.l[1])
    link1 = Rect3D(Vec(-thick/2,-thick/2,0),dim1)
    dim2  = Vec(thick, thick, model.l[2])
    link2 = Rect3D(Vec(-thick/2,-thick/2,0),dim2)
    mat1 = MeshPhongMaterial(color=colorant"grey")
    mat2 = MeshPhongMaterial(color=color)
    setobject!(vis["base"], hinge, mat1)
    setobject!(vis["link1"], link1, mat2)
    setobject!(vis["link1","joint"], hinge, mat1)
    setobject!(vis["link1","link2"], link2, mat2)
    settransform!(vis["link1","link2"], Translation(0,0,model.l[1]))
    settransform!(vis["link1","joint"], Translation(0,0,model.l[1]))
end

function visualize!(vis, model::RobotZoo.Acrobot, x::StaticVector)
    e1 = @SVector [1,0,0]
    q1,q2 = expm((x[1]-pi/2)*e1), expm(x[2]*e1)
    settransform!(vis["robot","link1"], LinearMap(UnitQuaternion(q1)))
    settransform!(vis["robot","link1","link2"], compose(Translation(0,0,model.l[1]), LinearMap(UnitQuaternion(q2))))
end

# Dubins Car
function _set_mesh!(vis, model::RobotZoo.DubinsCar;
        color=nothing, color2=nothing, height=0.05, radius=model.radius)
    radius = Float32(radius)
    body = Cylinder(Point3f0(0,0,0), Point3f0(0,0,height), radius)
    face = Rect3D(Vec(3radius/4, -radius/2, 0), Vec(radius/4, radius, height*1.1))
    c1,c2 = defcolor(color, color2, colorant"blue", colorant"yellow")
    setobject!(vis["geom"]["body"], body, MeshPhongMaterial(color=c1))
    setobject!(vis["geom"]["face"], face, MeshPhongMaterial(color=c2))
end

# BicycleModel
function _set_mesh!(vis, model::RobotZoo.BicycleModel)
    L, lr = model.L,  model.lr
    lf = L - lr
    ww = 0.23     # wheel width (m)
    r = 0.3       # wheel radius (m)
    bw = 0.1      # chassis width (m)
    wheel = Cylinder(Point3f0(0,-ww/2,0), Point3f0(0,ww/2,0), Float32(r))
    body = Rect3D(Vec(0,-bw/2,-bw/2), Vec(L,bw,bw))
    setobject!(vis["geom"], Triad())
    setobject!(vis["geom"]["chassis"]["body"], body, MeshPhongMaterial(color=colorant"gray"))
    setobject!(vis["geom"]["chassis"]["wheel"], wheel, MeshPhongMaterial(color=colorant"black"))
    setobject!(vis["geom"]["front"]["wheel"], wheel, MeshPhongMaterial(color=colorant"black"))
    if model.ref == :rear
        settransform!(vis["geom"]["front"], compose(Translation(L,0,0)))
        settransform!(vis["geom"]["chassis"], compose(Translation(0,0,0)))
    elseif model.ref == :front
        settransform!(vis["geom"]["front"], compose(Translation(0,0,0)))
        settransform!(vis["geom"]["chassis"], compose(Translation(-L,0,0)))
    elseif model.ref == :cg
        settransform!(vis["geom"]["front"], compose(Translation(lf,0,0)))
        settransform!(vis["geom"]["chassis"], compose(Translation(-lr,0,0)))
    end
    settransform!(vis["geom"], Translation(0,0,r))
end

function visualize!(vis, model::RobotZoo.BicycleModel, x::StaticVector)
    θ = x[3]
    δ = x[4]
    settransform!(vis["robot"]["geom"], compose(Translation(x[1], x[2],0), LinearMap(RotZ(θ))))
    settransform!(vis["robot"]["geom"]["front"]["wheel"], LinearMap(RotZ(δ)))
end

# Planar Rocket
function _set_mesh!(vis, model::RobotZoo.PlanarRocket;
        L = model.ℓ,
        rad = L / 15,
        Ltip = L / 5,
        Lcone = L / 10,
    )
    fuselage = Cylinder(Point3(0,0,0.), Point3(0,0,L), rad)
    tip = Cone(Point3(0.,0,L), Point3(0.,0,L+Ltip), rad)
    gimbal = Cone(Point3(0.,0,-Lcone), Point3(0,0,0.), rad/2)
    fins = Pyramid(Point3(0,0,0.), L, 2rad*0.95)
    setobject!(vis["geom"]["fuselage"], fuselage, MeshPhongMaterial(color=colorant"gray"))
    setobject!(vis["geom"]["fins"], fins, MeshPhongMaterial(color=colorant"black"))
    setobject!(vis["geom"]["tip"], tip, MeshPhongMaterial(color=colorant"black"))
    setobject!(vis["geom"]["gimbal"]["cone"], gimbal, MeshPhongMaterial(color=colorant"red"))
    settransform!(vis["geom"]["gimbal"]["cone"], Translation(0,0,Lcone*0.4))
end

function visualize!(vis, model::RobotZoo.PlanarRocket, x::StaticArray)
    settransform!(vis["robot"], compose(Translation(x[1],0,x[2]), LinearMap(RotY(x[3]))))
    settransform!(vis["robot"]["geom"]["gimbal"], LinearMap(RotY(x[4])))
end

# Quadrotor
function _set_mesh!(vis, model::L;
        scaling=1.0, color=colorant"black"
    ) where {L <: Union{RobotZoo.Quadrotor, RobotZoo.PlanarQuadrotor}}
    urdf_folder = joinpath(@__DIR__, "..", "data", "meshes")
    # if scaling != 1.0
    #     quad_scaling = 0.085 * scaling
    obj = joinpath(urdf_folder, "quadrotor_scaled.obj")
    if scaling != 1.0
        error("Scaling not implemented after switching to MeshCat 0.12")
    end
    robot_obj = MeshFileGeometry(obj)
    mat = MeshPhongMaterial(color=color)
    setobject!(vis["geom"], robot_obj, mat)
    if hasfield(L, :ned)
        model.ned && settransform!(vis["geom"], LinearMap(RotX(pi)))
    end
end
function visualize!(vis, model::RobotZoo.Quadrotor, x::StaticVector, addrobot::Bool = true)
    xbar = RBState(model, x)
    if model.ned
        r = position(xbar)
        v = linear_velocity(xbar)
        r = SA[r[1],-r[2],-r[3]]
        v = SA[v[1],-v[2],-v[3]]
        xbar = RBState(r, RotX(pi)*orientation(xbar), v, angular_velocity(xbar))
    end
    visualize!(vis, xbar, addrobot)
end

function visualize!(vis, model::RobotZoo.PlanarQuadrotor, x::StaticVector, addrobot::Bool = true)
    py,pz = x[1], x[2]
    θ = x[3]
    settransform!(vis, compose(Translation(0,py,pz), LinearMap(RotX(θ))))
end

# Yak Plane
function _set_mesh!(vis, ::RobotZoo.YakPlane; color=nothing)
    # meshfile = joinpath(@__DIR__,"..","data","meshes","piper","piper_pa18.obj")
    # meshfile = joinpath(@__DIR__,"..","data","meshes","cirrus","Cirrus.obj")
    meshfile = joinpath(@__DIR__,"..","data","meshes","piper","piper_scaled.obj")
    jpg = joinpath(@__DIR__,"..","data","meshes","piper","piper_diffuse.jpg")
    if isnothing(color)
        img = PngImage(jpg)
        texture = Texture(image=img)
        mat = MeshLambertMaterial(map=texture)
    else
        mat = MeshPhongMaterial(color=color)
    end
    obj = MeshFileGeometry(meshfile)
    # obj.vertices .= obj.vertices .* scaling
    setobject!(vis["geom"], obj, mat)
    settransform!(vis["geom"], compose(Translation(0,0,0.07),LinearMap( RotY(pi/2)*RotZ(-pi/2) )))
end

# _set_mesh!(vis, model::TrajectoryOptimization.InfeasibleModel) = _set_mesh!(vis, model.model)
function _set_mesh!(vis, ::RobotZoo.Satellite; dims=[1,1,2]*0.5, color=colorant"grey70")
    obj = Rect3D(Vec((-dims/2)...), Vec(dims...))
    mat = MeshPhongMaterial(; color=color)
    setobject!(vis["geom"], obj, mat)
end

function _set_mesh!(vis, model::RigidBody; dims=[1,1,2]*0.5, color=colorant"grey70")
    obj = Rect3D(Vec((-dims/2)...), Vec(dims...))
    mat = MeshPhongMaterial(; color=color)
    setobject!(vis["geom"], obj, mat)
end


text:
using Test
using CLIMA.MoistThermodynamics

using CLIMA.PlanetParameters
using LinearAlgebra

@testset "moist thermodynamics" begin
  DT = Float64
  # ideal gas law
  @test air_pressure(DT(1), DT(1), PhasePartition(DT(1))) === DT(R_v)
  @test air_pressure(DT(1), DT(2), PhasePartition(DT(1), DT(0.5), DT(0))) === DT(R_v)
  @test air_pressure(DT(1), DT(1)) === DT(R_d)
  @test air_pressure(DT(1), DT(2)) === 2*DT(R_d)
  @test air_density(DT(1), DT(1)) === 1/DT(R_d)
  @test air_density(DT(1), DT(2)) === 2/DT(R_d)

  # gas constants and heat capacities
  @test gas_constant_air(PhasePartition(DT(0))) === DT(R_d)
  @test gas_constant_air(PhasePartition(DT(1))) === DT(R_v)
  @test gas_constant_air(PhasePartition(DT(0.5), DT(0.5))) ≈ DT(R_d)/2
  @test gas_constant_air() == R_d

  @test cp_m(PhasePartition(DT(0))) === DT(cp_d)
  @test cp_m(PhasePartition(DT(1))) === DT(cp_v)
  @test cp_m(PhasePartition(DT(1), DT(1))) === DT(cp_l)
  @test cp_m(PhasePartition(DT(1), DT(0), DT(1))) === DT(cp_i)
  @test cp_m() == cp_d

  @test cv_m(PhasePartition(DT(0))) === DT(cp_d - R_d)
  @test cv_m(PhasePartition(DT(1))) === DT(cp_v - R_v)
  @test cv_m(PhasePartition(DT(1), DT(1))) === DT(cv_l)
  @test cv_m(PhasePartition(DT(1), DT(0), DT(1))) === DT(cv_i)

  # speed of sound
  @test soundspeed_air(T_0 + 20, PhasePartition(DT(0))) == sqrt(cp_d/cv_d * R_d * (T_0 + 20))
  @test soundspeed_air(T_0 + 100, PhasePartition(DT(1))) == sqrt(cp_v/cv_v * R_v * (T_0 + 100))

  # specific latent heats
  @test latent_heat_vapor(DT(T_0))  ≈ LH_v0
  @test latent_heat_fusion(DT(T_0)) ≈ LH_f0
  @test latent_heat_sublim(DT(T_0)) ≈ LH_s0

  # saturation vapor pressure and specific humidity
  p=DT(1.e5); q_tot=DT(0.23); ρ=DT(1.);
  ρ_v_triple = press_triple / R_v / T_triple;
  @test saturation_vapor_pressure(DT(T_triple), Liquid()) ≈ press_triple
  @test saturation_vapor_pressure(DT(T_triple), Ice()) ≈ press_triple

  @test saturation_shum(DT(T_triple), ρ, PhasePartition(DT(0))) == ρ_v_triple / ρ
  @test saturation_shum(DT(T_triple), ρ, PhasePartition(q_tot,q_tot)) == ρ_v_triple / ρ

  @test saturation_shum_generic(DT(T_triple), ρ; phase=Liquid()) == ρ_v_triple / ρ
  @test saturation_shum_generic(DT(T_triple), ρ; phase=Ice()) == ρ_v_triple / ρ
  @test saturation_shum_generic.(DT(T_triple-20), ρ; phase=Liquid()) >=
        saturation_shum_generic.(DT(T_triple-20), ρ; phase=Ice())

  @test saturation_excess(DT(T_triple), ρ, PhasePartition(q_tot)) ==  q_tot - ρ_v_triple/ρ
  @test saturation_excess(DT(T_triple), ρ, PhasePartition(q_tot/1000)) == 0.0

  # energy functions and inverse (temperature)
  T=DT(300); e_kin=DT(11); e_pot=DT(13);
  @test air_temperature(DT(cv_d*(T-T_0))) === DT(T)
  @test air_temperature(DT(cv_d*(T-T_0)), PhasePartition(DT(0))) === DT(T)

  @test air_temperature(cv_m(PhasePartition(DT(0)))*(T-T_0), PhasePartition(DT(0))) === DT(T)
  @test air_temperature(cv_m(PhasePartition(DT(q_tot)))*(T-T_0) + q_tot*e_int_v0, PhasePartition(q_tot)) ≈ DT(T)

  @test total_energy(DT(e_kin),DT(e_pot), DT(T_0)) === DT(e_kin) + DT(e_pot)
  @test total_energy(DT(e_kin),DT(e_pot), DT(T)) ≈ DT(e_kin) + DT(e_pot) + cv_d*(T-T_0)
  @test total_energy(DT(0),DT(0), DT(T_0), PhasePartition(q_tot)) ≈ q_tot*e_int_v0

  # phase partitioning in equilibrium
  q_liq = DT(0.1);
  T = DT(T_icenuc-10); ρ = DT(1.0); q_tot = DT(0.21)
  @test liquid_fraction_equil(T) === DT(0)
  @test liquid_fraction_equil(T, PhasePartition(q_tot,q_liq,q_liq)) === DT(0.5)
  q = PhasePartition_equil(T, ρ, q_tot)
  @test q.liq ≈ DT(0)
  @test 0 < q.ice <= q_tot

  T = DT(T_freeze+10); ρ = DT(0.1); q_tot = DT(0.60)
  @test liquid_fraction_equil(T) === DT(1)
  @test liquid_fraction_equil(T, PhasePartition(q_tot,q_liq,q_liq/2)) === DT(2/3)
  q = PhasePartition_equil(T, ρ, q_tot)
  @test 0 < q.liq <= q_tot
  @test q.ice ≈ 0

  # saturation adjustment in equilibrium (i.e., given the thermodynamic
  # variables E_int, p, q_tot, compute the temperature and partitioning of the phases
  q_tot = DT(0); ρ = DT(1)
  @test saturation_adjustment(internal_energy_sat(300.0, ρ, q_tot), ρ, q_tot) ≈ 300.0

  q_tot = DT(0.21); ρ = DT(0.1)
  @test saturation_adjustment(internal_energy_sat(200.0, ρ, q_tot), ρ, q_tot) ≈ 200.0
  q = PhasePartition_equil(T, ρ, q_tot)
  @test q.tot - q.liq - q.ice ≈ saturation_shum(T, ρ)

  q_tot = DT(0.78); ρ = DT(1)
  @test saturation_adjustment(internal_energy_sat(300.0, ρ, q_tot), ρ, q_tot) ≈ 300.0
  q = PhasePartition_equil(T, ρ, q_tot)
  @test q.tot - q.liq - q.ice ≈ saturation_shum(T, ρ)

  # potential temperatures
  T = DT(300)
  @test liquid_ice_pottemp(T, DT(MSLP)) === T
  @test liquid_ice_pottemp(T, DT(MSLP)/10) ≈ T * 10^(R_d/cp_d)
  @test liquid_ice_pottemp(T, DT(MSLP)/10, PhasePartition(DT(1))) ≈ T * 10^(R_v/cp_v)

  # dry potential temperatures. FIXME: add correctness tests
  T = DT(300); p=DT(1.e5); q_tot=DT(0.23)
  @test dry_pottemp(T, p, PhasePartition(q_tot)) isa typeof(p)
  @test air_temperature_from_liquid_ice_pottemp(dry_pottemp(T, p, PhasePartition(q_tot)), p, PhasePartition(q_tot)) ≈ T

  # Exner function. FIXME: add correctness tests
  p=DT(1.e5); q_tot=DT(0.23)
  @test exner(p, PhasePartition(q_tot)) isa typeof(p)

  DT = Float32
  ρ = DT(1.0)
  p = DT(1000.0*100)
  e_int = DT(2.0)
  q_tot = DT(0.01)
  q_ice = DT(0.001)
  q_liq = DT(0.001)
  θ_liq_ice = DT(300.0)
  ts_eq = PhaseEquil(e_int, q_tot, ρ)
  ts_neq = PhaseNonEquil(e_int, PhasePartition(q_tot, q_liq, q_ice), ρ)
  ts_θ_liq_ice_eq = LiquidIcePotTempSHumEquil(θ_liq_ice, q_tot, ρ, p)
  for ts in (ts_eq, ts_neq, ts_θ_liq_ice_eq)
    @test soundspeed_air(ts) isa typeof(e_int)
    @test gas_constant_air(ts) isa typeof(e_int)
    @test air_pressure(ts) isa typeof(e_int)
    @test air_density(ts) isa typeof(e_int)
    @test cp_m(ts) isa typeof(e_int)
    @test cv_m(ts) isa typeof(e_int)
    @test eltype(moist_gas_constants(ts)) == typeof(e_int)
    @test air_temperature(ts) isa typeof(e_int)
    @test internal_energy_sat(ts) isa typeof(e_int)
    @test latent_heat_vapor(ts) isa typeof(e_int)
    @test latent_heat_sublim(ts) isa typeof(e_int)
    @test latent_heat_fusion(ts) isa typeof(e_int)
    @test saturation_shum(ts) isa typeof(e_int)
    @test saturation_excess(ts) isa typeof(e_int)
    @test liquid_fraction_equil(ts) isa typeof(e_int)
    @test liquid_fraction_nonequil(ts) isa typeof(e_int)
    @test PhasePartition(ts) isa PhasePartition{typeof(e_int)}
    @test liquid_ice_pottemp(ts) isa typeof(e_int)
    @test dry_pottemp(ts) isa typeof(e_int)
    @test exner(ts) isa typeof(e_int)
    @test liquid_ice_pottemp_sat(ts) isa typeof(e_int)
    @test specific_volume(ts) isa typeof(e_int)
    @test virtual_pottemp(ts) isa typeof(e_int)
  end

end

max_stars_repo_name: christophernhill-dev/CLIMA

max_issues_repo_name: christophernhill-dev/CLIMA

max_forks_repo_name: christophernhill-dev/CLIMA


text:
using PyCall
unshift!(PyVector(pyimport("sys")["path"]), "")
@pyimport Apr_weekend_02_OD_matrix_estimation_GLS

# x = Apr_weekend_02_OD_matrix_estimation_GLS.x; # sample matrix, each column is a link flow vector
# sample; number_of_links * K
# S = Apr_weekend_02_OD_matrix_estimation_GLS.S; # sample covariance matrix
# A = Apr_weekend_02_OD_matrix_estimation_GLS.A; # link_route incidence matrix
P = Apr_weekend_02_OD_matrix_estimation_GLS.P; # route_choice_probability_matrix
# Q = Apr_weekend_02_OD_matrix_estimation_GLS.Q;
L = Apr_weekend_02_OD_matrix_estimation_GLS.L; # dimension of xi
number_of_routes = Apr_weekend_02_OD_matrix_estimation_GLS.number_of_routes;
number_of_links = Apr_weekend_02_OD_matrix_estimation_GLS.number_of_links;

# P

# A = sparse(A);
# P = sparse(P);
# Q = sparse(Q);

# K = size(x, 2)

# inv_S = inv(S)

# A_t = transpose(A)

# b = sum([A_t * inv_S * x[:, k] for k = 1:K])

using JuMP

# model = Model(solver=IpoptSolver())

# @variable(model, xi[1:L] >= 0)

# # Set objective: (K/2) xi' * Q * xi - b' * xi
# obj = 0
# for i = 1:L
#     for j = 1:L
#         obj += (1.0 / 2) * K * xi[i] * Q[i, j] * xi[j]
#     end
# end
# for l = 1:L
#     obj += - b[l] * xi[l]
# end

# @NLobjective(model, Min, obj)

# solve(model)

# xi_list = getvalue(xi)

# xi_list = Apr_weekend_02_OD_matrix_estimation_GLS.xi_list
lam_list = Apr_weekend_02_OD_matrix_estimation_GLS.lam_list

println("The demand vector lam is:")
println(lam_list)

outfile = open("../temp_files/od_demand_vector_simplified_journal_Apr_weekend.json",
"w")

JSON.print(outfile, lam_list)

close(outfile)

#=
for idx = 1:L
    if xi_list[idx] < 1e-1
        xi_list[idx] = 0
    end
end

# for idx = 1:L
#     println(xi_list[idx])
# end

mGLSJulia = Model()

@variable(mGLSJulia, lam[1:size(P,1)] >= 0)

@variable(mGLSJulia, p[1:size(P,1), 1:size(P,2)] >= 0)

for i = 1:size(P,1)
    for j = 1:size(P,2)
        if P[i,j] == 0
            @constraint(mGLSJulia, p[i,j] == 0)
        end
    end
end

for i = 1:size(P,1)
    @NLconstraint(mGLSJulia, sum{p[i,j], j = 1:size(P,2)} == 1)
end

for l = 1:L
    @NLconstraint(mGLSJulia, sum{p[i,l] * lam[i], i = 1:size(P,1)}
    == xi_list[l])
end

# play no actual role, but could not use zero objective
@NLobjective(mGLSJulia, Min, sum{p[1,j], j = 1:size(P,2)})

solve(mGLSJulia)

println("The demand vector lam is:")
println(getvalue(lam))

outfile = open("../temp_files/od_demand_vector_simplified_journal_Apr_weekend.json",
"w")

JSON.print(outfile, getvalue(lam))

close(outfile)

println("The optimal objective function value of (P2) is:")
println(getobjectivevalue(mGLSJulia))
=#

max_stars_repo_name: jingzbu/InverseVITraffic

max_issues_repo_name: jingzbu/InverseVITraffic

max_forks_repo_name: jingzbu/InverseVITraffic


text:
function setSources!(time, source)
    # 3D implementation
    i_src = source.i_src
    j_src = source.j_src
    k_src = source.k_src
    duration = source.duration
    source.externalSource .= 0.0
    if time < duration
        # Set a single source of at the prescribed point
        source.externalSource[i_src, j_src, k_src] = source.discharge
    else
        source.externalSource[i_src, j_src, k_src] = 0.0
    end
end

function setRecharge!(time, recharge)
    # duration = recharge.duration
    # if time < duration
        # Set a single source of at the prescribed point
    recharge.rechargeFlux = recharge.rechargeFactor * recharge.constRecharge
    # else
    #    recharge.recharge_flux = 0.0
    # end
end


text:
using ChainRulesTestUtils
using LinearAlgebra
using Zygote: ZygoteRuleConfig, _pullback

# issue 897

test_rrule(ZygoteRuleConfig(), x->sum(sin, Diagonal(x)), ones(2); rrule_f=rrule_via_ad, check_inferred=false)
test_rrule(ZygoteRuleConfig(), x->sum(sin, Diagonal(x)), rand(3); rrule_f=rrule_via_ad, check_inferred=false)

@testset "adjoints of Iterators.product" begin
    y, back = _pullback(Iterators.product, 1:5, 1:3, 1:2)
    @test back(collect(y)) == (nothing, [6.0, 12.0, 18.0, 24.0, 30.0], [10.0, 20.0, 30.0], [15.0, 30.0])
    @test back([(nothing, j, k) for i in 1:5, j in 1:3, k in 1:2]) == (nothing, nothing, [10.0, 20.0, 30.0], [15.0, 30.0])
    @test back([(i, nothing, k) for i in 1:5, j in 1:3, k in 1:2]) == (nothing, [6.0, 12.0, 18.0, 24.0, 30.0], nothing, [15.0, 30.0])
    @test back([(i, j, nothing) for i in 1:5, j in 1:3, k in 1:2]) == (nothing, [6.0, 12.0, 18.0, 24.0, 30.0], [10.0, 20.0, 30.0], nothing)

    # This was wrong before https://github.com/FluxML/Zygote.jl/pull/1170
    @test gradient(x -> sum([y[2] * y[3] for y in Iterators.product(x, x, x, x)]), [1,2,3,4])[1] ≈ [320, 320, 320, 320]
    @test gradient(x -> sum(y[2] * y[3] for y in Iterators.product(x, x, x, x)), [1,2,3,4])[1] ≈ [320, 320, 320, 320]
end


text:
# open up a block to limit scope and lifetime of everything to
# ensure no cross-talk between tests
begin

    N = 500

    A = rand(N)
    a = rand()

    #addition
    @et add_et = a + A + a
    add_native = a + A + a

    @test add_native == add_et

    #subtraction
    @et sub_et = A - a
    sub_native = A - a

    @test sub_native == sub_et

    #multiplication
    @et mult_et = a*A*a
    mult_native = a*A*a

    @test mult_native == mult_et

    #division
    @et div_et = A/a
    div_native = A/a

    @test div_native == div_et

end


text:
#!/usr/bin/env julia

using ArgParse

include("../src/createTsvForHeatmap.jl")

function parse_commandline()
    s = ArgParseSettings("This scrpt creates a TSV file in the format required for creating a heatmap",
                         version = "1.0.1",
                         add_version = true)

    @add_arg_table s begin
        "--verbose", "-v"
            help = "This will cause output to be printed to standard out."
            action = :store_true
        "results-folder"
            help = "This is the directory that the inference results for a run are located."
            required = true
        "pathway-list-file"
            help = "This is the pathway list file provided by Reactome"
            required = true
        "key-outputs-file"
            help = "This file contains the list of keyoutputs for each pathway"
            required = true
    end

    return parse_args(s)
end

function main()
    parsed_args = parse_commandline()

    if parsed_args["verbose"]
        println("Parsed args:")
        for (arg,val) in parsed_args
            println("  $arg  =>  $val")
        end
    end

    CreateTsvForHeatmap.run(parsed_args["results-folder"],
                            parsed_args["pathway-list-file"],
                            parsed_args["key-outputs-file"],
                            parsed_args["verbose"])
end

main()

max_stars_repo_name: OICR/mp-biopath

max_issues_repo_name: OICR/mp-biopath

max_forks_repo_name: OICR/mp-biopath


text:
module Docker

export Container

# stdlib requirements
using Sockets

# package requirements
using HTTP
using JSON

const SRCDIR = @__DIR__
const PKGDIR = dirname(SRCDIR)
const DEPDIR = joinpath(PKGDIR, "deps")

# Extend the "getconnection" function in HTTP to support unix sockets. This allows us to
# directly communicate with the local docker daemon.
function HTTP.ConnectionPool.getconnection(
        ::Type{Sockets.PipeEndpoint},
        host::AbstractString,
        port::AbstractString;
        unix_socket = "",
        kw...
    )::Sockets.PipeEndpoint

    return Sockets.connect(unix_socket)
end

daemon() = "/var/run/docker.sock"

############################################################################################

_query(nt) = Tuple(string(k) => v for (k,v) in pairs(nt))

macro query(ex)
    if ex.head != :tuple
        ex = Expr(:tuple, ex)
    end
    return esc(:(Docker._query($ex)) )
end

# Type for eaily working with containers
mutable struct Container
    id::String
    params::Dict{String,Any}
end

Container(id::String) = Container(id, Dict{String,Any}())
Container(json::Dict) = Container(getid(json), json)

function Base.show(io::IO, c::Container)
    println(io, "Docker Container")
    println(io, "   ID: $(getid(c))")
    # Display some extra information.
    for k in ("Image", "Command", "State")
        if haskey(c.params, k)
            println(io, "   $k: $(c.params[k])")
        end
    end
end

getid(x::String) = x
getid(x::Dict) = x["Id"]
getid(x::Container) = x.id

#default_endpoint() = (host = "localhost", port = _port())
docker_uri(;path = nothing, kw...) = HTTP.URI(;
    scheme = "http",
    path = path,
    host = "localhost",
    kw...
)

docker_headers() = Dict("Content-Type" => "application/json")
parse(data) = JSON.parse(String(data))

test(path) = HTTP.request("GET", docker_uri(path = path), socket_type = Sockets.PipeEndpoint, unix_socket = daemon())

const localkw = (socket_type = Sockets.PipeEndpoint, unix_socket = daemon())

function list_images(;all = false)
    uri = docker_uri(path = "/images/json", query = @query(all=all))
    resp = HTTP.get(uri; localkw...)
    return parse(resp.body)
end

function pull_image(name)
    uri = docker_uri(path = "/images/create", query = @query(fromImage=name))
    resp = HTTP.post(uri; localkw...)
    return resp
end

function remove_image(name; force = false)
    uri = docker_uri(path = "/images/$name", query = @query(force=force))
    resp = HTTP.delete(uri; localkw...)
    return resp
end

function create_container(
        image;
        #endpoint = default_endpoint(),
        cmd          = ``,
        user         = "",
        entryPoint   = "",
        tty          = true,
        attachStdin  = false,
        openStdin    = false,
        attachStdout = true,
        attachStderr = true,
        binds        = [],
        memory       = 0,
        memoryswap   = nothing,
        cpuSets      = "",
        cpuMems      = "",
        volumeDriver = "",
        portBindings = ["",""], # [ContainerPort,HostPort]
        ports        = [],
        pwd          = "",
        env          = [],
        privileged   = false,
        capadd       = [],
    )

    params = Dict(
        "Image" => image,
        "Tty" => tty,
        "Env" => env,
        "AttachStdin"   => attachStdin,
        "OpenStdin"     => openStdin,
        "AttachStdout"  => attachStdout,
        "AttachStderr"  => attachStderr,
        "ExposedPorts"  => Dict([Pair("$(string(p, base=10))/tcp", Dict()) for p in ports]),
        "HostConfig"    => Dict(
            "Memory"       => memory,
            "CpusetCpus"   => cpuSets,
            "CpusetMems"   => cpuMems,
            "VolumeDriver" => volumeDriver,
            "PortBindings" => Dict(
                string(portBindings[1],"/tcp") => [
                    Dict("HostPort" => string(portBindings[2]))
                ]
            ),
            "Binds" => binds,
            "CapAdd" => capadd,
        )
    )

    if privileged
        params["HostConfig"]["SecurityOpt"] = ["seccomp=unconfined"]
    end

    if !isempty(user)
        params["User"] = user
    end

    if !isempty(entryPoint)
        params["Entrypoint"] = entryPoint
    end

    if !isempty(cmd.exec)
        params["Cmd"] = collect(cmd.exec)
    end

    if !isempty(pwd)
        params["WorkingDir"] = pwd
    end

    if memoryswap !== nothing
        params["HostConfig"]["MemorySwap"] = memoryswap
    end

    uri = docker_uri(path = "/containers/create")
    resp =  HTTP.post(uri, docker_headers(), JSON.json(params); localkw...)
    # Create a container out of the response
    return Container(parse(resp.body))
end

macro defcontainerfunc(func, method, endpoint)
    # Check method type. If it is a get, we want to return the parsed response. Otherwise,
    # return the container object support function chaining.
    if method == :GET
        retbody = :(parse(resp.body))
    else
        retbody = :(container)
    end

    return quote
        function $(esc(func))(container::Container)
            id = getid(container)
            uri = docker_uri(path = joinpath("/containers", id, $(string(endpoint))))
            resp = HTTP.request($(string(method)), uri; localkw...)
            return $retbody
        end
    end
end

@defcontainerfunc inspect   GET  json
@defcontainerfunc start     POST start
@defcontainerfunc restart   POST restart
@defcontainerfunc stop      POST stop
@defcontainerfunc pause     POST pause
@defcontainerfunc unpause   POST unpause
@defcontainerfunc Base.kill POST kill
@defcontainerfunc processes GET  top

function remove(container; force = false)
    id = getid(container)
    uri = docker_uri(path = "/containers/$(id)", query = @query(force=force))
    resp = HTTP.delete(uri; localkw...)
end

function list_containers(;all = false, filters = Dict{String,Any}())
    path = "/containers/json"
    query = @query (all=all, filters=json(filters))

    uri = docker_uri(path = path, query = query)

    resp = HTTP.get(uri; localkw...)
    return Container.(parse(resp.body))
end

function log(container; since = 0, tail = "all")
    id = getid(container)
    path = "/containers/$id/logs"
    query = @query (stdout=true, since=since, tail=tail)
    uri = docker_uri(path = path, query = query)
    headers = Dict("Content-Type"=>"plain/text")
    resp = HTTP.get(uri, headers; localkw...)
    return String(resp.body)
end

function stats(container)
    id = getid(container)
    path = "/containers/$id/stats"
    # TODO: right now, we can't support upgrading to a stream, so we must manage
    # streaming behavior on the client side.
    query = @query(stream = false)
    stats = Dict{String,Any}[]
    uri = docker_uri(path = path, query = query)
    resp = HTTP.get(uri; localkw...)
    return parse(resp.body)
end

function attach(container; stdin = stdin, stdout = stdout, stderr = stderr)
    id = getid(container)
    try
        run(`docker attach $id --detach-keys="q"`)
    finally
        print("\n")
        @info "Detached from $id"
        return
    end
end

function cleanse!()
    uri = docker_uri(path = "/containers/json?all=true")
    resp = HTTP.get(uri; localkw...)
    containers = parse(resp.body)
    for container in containers
        @info "Cleaning $(getid(container))"
        remove(container, force = true)
    end
    nothing
end
end # module


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg, Base.BinaryPlatforms

name = "SoapyUHD"
version = v"0.4.1"

# Collection of sources required to complete build
sources = [
    GitSource("https://github.com/pothosware/SoapyUHD.git", "d8aba947a01a530b1d9c2f4a07e4241bbd04d327")
]

dependencies = [
    Dependency("soapysdr_jll"; compat="0.8.0"),
    Dependency("boost_jll"; compat="=1.76.0"), # max gcc7
    Dependency("USRPHardwareDriver_jll"; compat="4.1.0")
]

# Bash recipe for building across all platforms
script = raw"""
cd SoapyUHD
mkdir _build
cd _build

cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
      -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
      -DCMAKE_BUILD_TYPE=Release \
      ..
make -j${nproc}
make install
if [[ "${target}" == *-apple-* ]]; then
    mv ${libdir}/SoapySDR/modules0.8/libuhdSupport.so  ${libdir}/SoapySDR/modules0.8/libuhdSupport.dylib
fi
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = filter!(p -> !Sys.iswindows(p) && !in(arch(p),("armv7l","armv6l")), supported_platforms(;experimental=true))
platforms = expand_cxxstring_abis(platforms)

# The products that we will ensure are always built
products = Product[
    LibraryProduct("libuhdSupport", :libuhdSupport, ["lib/SoapySDR/modules0.8/"])
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat="1.6", preferred_gcc_version=v"7")

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
using Test, SimpleGraphs, SimplePlanarGraphs
@test count_cross(Icosahedron())==0
G = Cube(3)
embed(G,:combined)
@test count_cross(G) == 2

G = RandomTriangulation(17)
@test count_cross(G) == 0
@test euler_char(G) == 2
H = dual(G)
embed(H,:tutte)
@test count_cross(H) == 0
@test euler_char(H) == 2


text:
using Knet,MAT,Images
using ImageView,TestImages
mview(x)=ImageView.view(x)
#isdefined(:vgg) || (vgg = loadmodel())
#a = load(joinpath("/mnt/ai/home/dyuret/.gnome2/cheese/media/2016-11-08-135940.jpg"))
# some images with multiple objects
# /mnt/ai/data/ImageNet/ILSVRC2015/Data/CLS-LOC/val/ILSVRC2012_val_00026677.JPEG
#img = load("/mnt/ai/data/img/ImageNet/ILSVRC2015/Data/CLS-LOC/val/ILSVRC2012_val_00010447.JPEG")

immutable Model; weights; average; description; end
const op = [1,2,1,2,1,1,2,1,1,2,1,1,2,3,3,4]
convx(w,x)=conv4(w,x;padding=1,mode=1)

function test1(path="/mnt/ai/data/img/ImageNet/ILSVRC2015/Data/CLS-LOC/val/ILSVRC2012_val_00010447.JPEG")
    global vgg
    isdefined(:vgg) || (vgg=loadmodel())
    global img=load(path)
    mview(img)
    global out, coor
    (out,coor) = multipred(vgg,img)
end

function test2()
    global vgg
    isdefined(:vgg) || (vgg=loadmodel())
    global img=rndimg()
    mview(img)
    global out, coor
    (out,coor) = multipred(vgg,img)
end

# minibatch multiple regions of the image and find the ones with lowest entropy
function multipred(model, img; n=100)
    data = Array(Float32,224,224,3,n)
    coor = Any[]
    for i=1:n
        r = rand(1:div(min(size(img)...),3))
        x = rand(r+1:size(img,1)-r)
        y = rand(r+1:size(img,2)-r)
        a = img[x-r:x+r,y-r:y+r]
        b = normalize(a, model.average)
        Base.unsafe_copy!(data, 1+(i-1)*length(b), b, 1, length(b))
        push!(coor, (x,y,r))
    end
    out = process(model.weights, data)
    lp = logp(out,1)
    en = sum(-lp.*exp(lp),1)
    sp = sortperm(vec(en))
    pr = falses(size(out,1))
    for i in sp
        c = indmax(vec(out[:,i]))
        pr[c] && continue
        pr[c] = true
        println((exp(lp[c,i]), coor[i], model.description[c]))
    end
    (out, coor)
end

# predict a given image: focus on a region by predict(vgg,a[75:700,500:1200]);
function predict(model, img; top=5)
    x = normalize(img, model.average)
    w = model.weights
    y0 = process(w,x)
    printclasses(y0, model, top)
    return y0
end

function printclasses(y0, model, top; msg="")
    y1 = vec(Array(y0))
    s1 = sortperm(y1,rev=true)
    s2 = s1[1:top]
    p1 = exp(logp(y1))
    Base.display(hcat(p1[s2], model.description[s2]))
    println(msg)
end

function process(w, x)
    x = KnetArray(x)
    for k=1:div(length(w),2)
        if op[k] == 1
            x = relu(convx(w[2k-1],x) .+ w[2k])
        elseif op[k] == 2
            x = pool(relu(convx(w[2k-1],x) .+ w[2k]))
        elseif op[k] == 3
            x = relu(w[2k-1]*mat(x) .+ w[2k])
        else
            x = w[2k-1]*mat(x) .+ w[2k]
        end
    end
    return Array(x)
end

# normalize a given image
function normalize(img, averageImage)
    new_size = ntuple(i->div(size(img,i)*224,minimum(size(img))),2)
    a1 = Images.imresize(img, new_size)
    i1 = div(size(a1,1)-224,2)
    j1 = div(size(a1,2)-224,2)
    b1 = a1[i1+1:i1+224,j1+1:j1+224]
    c1 = separate(b1)
    d1 = convert(Array{Float32}, c1)
    e1 = reshape(d1[:,:,1:3], (224,224,3,1))
    f1 = (255 * e1 .- averageImage)
    g1 = permutedims(f1, [2,1,3,4])
end

function loadmodel(path=Knet.dir("data","imagenet-vgg-verydeep-16.mat"))
    m = matread(path)
    w = Any[]
    for l in m["layers"]
        haskey(l,"weights") && !isempty(l["weights"]) && push!(w, l["weights"]...)
    end
    for i in 2:2:26             # reshape bias layers to 1,1,n,1
        w[i] = reshape(w[i], (1,1,length(w[i]),1))
    end
    for i in 27:2:32            # reshape fully connected layers to m,n
        w[i] = mat(w[i])'
    end
    w = map(KnetArray,w)
    a = convert(Array{Float32},m["meta"]["normalization"]["averageImage"])
    d = m["meta"]["classes"]["description"]
    Model(w,a,d)
end

# pick a random image from ImageNet validation set
function rndimg(path="/mnt/ai/data/img/ImageNet/ILSVRC2015/Data/CLS-LOC/val")
    a = readdir(path)
    i = rand(1:length(a))
    println(a[i])
    load(joinpath(path,a[i]))
end

max_stars_repo_name: JuliaTagBot/play

max_issues_repo_name: JuliaTagBot/play

max_forks_repo_name: JuliaTagBot/play


text:
module BalancePlot

export load_ing_config_from_file, load_ing_transactions_from_file, convert_ing_transactions, plot_transactions

import Dates.Date
import Dates
import Base.<
using Plots

include("Transaction.jl")
include("INGConfig.jl")
include("INGSource.jl")

struct DateMonth
    year::Int
    month::Int
end

function date_to_datemonth(date::Date)
    return DateMonth(Dates.year(date), Dates.month(date))
end

function datemonth_to_date(datemonth::DateMonth, day::Int=15)
    return Date(datemonth.year, datemonth.month, day)
end

function inc_month(datemonth::DateMonth)
    if datemonth.month > 11
        return DateMonth(datemonth.year + 1, 1)
    else
        return DateMonth(datemonth.year, datemonth.month + 1)
    end
end

Base.:<(a::DateMonth, b::DateMonth) =
    if a.year == b.year
        a.month < b.month
    else
        a.year < b.year
    end
Base.isless(a::DateMonth, b::DateMonth) = a < b

function inbetween_months_from_dates(dates::Array{Date})::Array{DateMonth}
    minDate = Date(2050)
    maxDate = Date(1970)
    for date in dates
        if date < minDate
            minDate = date
        end
        if date > maxDate
            maxDate = date
        end
    end
    months = [date_to_datemonth(minDate)]
    if minDate != maxDate
        while last(months) < date_to_datemonth(maxDate)
            push!(months, inc_month(last(months)))
        end
    end
    return months
end

function inbetween_value_from_values(values::Array{Float64}, increment::Float64)::Array{Float64}
    minValue = minimum(values)
    maxValue = maximum(values)
    minValueRounded = minValue - minValue % increment
    maxValueRounded = maxValue - maxValue % increment
    return minValueRounded:increment:maxValueRounded
end

function get_category_sum_per_month(transactions::Array{Transaction})::Dict{String, Dict{DateMonth, Float64}}
    accountnames = map(account -> account.name, collect(keys(first(transactions).balance)))
    categories::Array{String} = []
    for transaction in transactions
        if !(transaction.category in categories) && !(transaction.category in accountnames)
            push!(categories, transaction.category)
        end
    end
    months = inbetween_months_from_dates(map(tr -> tr.date, transactions))
    result::Dict{String, Dict{DateMonth, Float64}} = Dict()
    for category in categories
        result[category] = Dict()
        for month in months
            result[category][month] = 0
        end
    end

    for transaction in transactions
        if !(transaction.category in accountnames)
            datemonth = date_to_datemonth(transaction.date)
            result[transaction.category][datemonth] += transaction.change[account_main]
        end
    end

    return result
end

function plot_transactions(transactions::Array{Transaction})
    accounts = collect(keys(first(transactions).balance))
    category_sums_per_month = get_category_sum_per_month(transactions)
    dates = map(transaction -> transaction.date, transactions)
    balances_dates = repeat([dates], length(accounts))
    balances = map(account ->
        map(transaction -> transaction.balance[account], transactions)
    , accounts)
    labels = map(account -> account.name, accounts)

    for category in keys(category_sums_per_month)
        sums::Array{Pair{DateMonth, Float64}} = []
        for month in sort(collect(keys(category_sums_per_month[category])))
            push!(sums, Pair(month, category_sums_per_month[category][month]))
        end

        push!(balances_dates, map(pair -> datemonth_to_date(pair.first), sums))
        push!(balances, map(pair -> pair.second, sums))
        push!(labels, category)
    end

    xlabel = "Date"
    ylabel = "Amount (€)"
    xticks = map(month -> Dates.value.(datemonth_to_date(month, 1)),
                 inbetween_months_from_dates(map(tr -> tr.date, transactions)))
    yticks = inbetween_value_from_values(collect(Iterators.flatten(balances)), 250.0)

    plotly()
    plot(xlabel=xlabel, ylabel=ylabel, xticks=xticks, yticks=yticks, window_title="BalancePlot.jl", size=[1800, 1000])
    map(function(data)
            plot!(data[2], data[1], label=data[3])
        end,
        zip(balances, balances_dates, labels))
    gui()
end

end

max_stars_repo_name: CrazedProgrammer/BalancePlot

max_issues_repo_name: CrazedProgrammer/BalancePlot

max_forks_repo_name: CrazedProgrammer/BalancePlot


text:
using GlobalDiffEq, OrdinaryDiffEq, LinearAlgebra, Random
using GlobalDiffEq: vec_expt_full, orth_vec
using Test

Random.seed!(123)

@testset "GlobalDiffEq Tests" begin

@testset "Vector Expectation" begin

  @testset "Vector Expectation Full" begin
    @test vec_expt_full(2) ≈ 2/π
  end;

  @testset "Random Orthogonal Vectors" begin
    function compute_vec_series(k, n)
      for _ ∈ 1:k
        z₁, z₂ = orth_vec(n)
        @test norm(z₁) ≈ 1
        @test norm(z₂) ≈ 1
        @test dot(z₁, z₂) ≈ 0 atol=1e-10
      end
    end
    k = 100 # number of random iters
    n = 10 # dimension of the vector
    compute_vec_series(k, n)
  end;
end;

@testset "Global Pendulum" begin
  l = 1.0                             # length [m]
  m = 1.0                             # mass[m]
  g = 9.81                            # gravitational acceleration [m/s²]

  function pendulum!(du,u,p,t)
      du[1] = u[2]                    # θ'(t) = ω(t)
      du[2] = -3g/(2l)*sin(u[1]) + 3/(m*l^2)*p(t) # ω'(t) = -3g/(2l) sin θ(t) + 3/(ml^2)M(t)
  end

  θ₀ = 0.01                           # initial angular deflection [rad]
  ω₀ = 0.0                            # initial angular velocity [rad/s]
  u₀ = [θ₀, ω₀]                       # initial state vector
  tspan = (0.0,10.0)                  # time interval

  M = t->0.1sin(t)                    # external torque [Nm]

  prob = ODEProblem(pendulum!,u₀,tspan,M)

  v0 = solve(prob, Tsit5(), dt=0.1, reltol=1e-12, abstol=0).(1:10)

  @testset "Global Pendulum Richardson" begin
    ve = solve(prob, GlobalRichardson(SSPRK33()), dt=0.2, reltol=1e-12, abstol=0).(1:10)
    @test norm(ve - v0) / norm(v0) < 1e-10
  end;

  @testset "Global Pendulum Adjoint" begin
    # The adjoint tests with pendulum! fail because the parameters are a function rather than a constant term
    sol_adjoint = solve(prob, GlobalAdjoint(SSPRK33()), dt=0.2, reltol=1e-4, abstol=1e-4)
    ve_adjoint = sol_adjoint.(1:10)
    @test norm(ve_adjoint - v0) / norm(v0) < 1e-4
  end;
end;

@testset "Global Lotka Volterra" begin
  function Lotka_Volterra!(du,u,p,t)
    du[1] = p[1]*u[1] - p[2]*u[1]*u[2]
    du[2] = -p[3]*u[2] + u[1]*u[2]
  end

  u₀_LV = [1.0;1.0]
  p_LV = [1.5,1.0,3.0]
  tspan_LV = (0.0,10.0)
  prob_LV = ODEProblem(Lotka_Volterra!,u₀_LV,tspan_LV,p_LV)

  v0_LV = solve(prob_LV, Tsit5(), dt=0.1, reltol=1e-12, abstol=0).(1:10)

  @testset "Global Lotka Volterra Richardson" begin
    sol_LV_Richardson = solve(prob_LV, GlobalRichardson(SSPRK33()), dt=0.2, reltol=1e-12, abstol=0)
    ve_LV_Richardson = sol_LV_Richardson.(1:10)
    @test norm(ve_LV_Richardson - v0_LV) / norm(v0_LV) < 1e-10
  end;

  @testset "Global Lotka Volterra Adjoint" begin
    sol_LV_adjoint = solve(prob_LV, GlobalAdjoint(Tsit5()), dt=0.2, reltol=1e-10, abstol=1e-10)
    ve_LV_adjoint = sol_LV_adjoint.(1:10)
    @test norm(ve_LV_adjoint - v0_LV) / norm(v0_LV) < 1e-10
  end;
end;

end;


text:
function grab_tag(string, tag)
    tag = match(Regex("\"$tag\":.*?(.*?),"), string)
    return tag.captures[1]
end

in_path = ARGS[1]
out_path = ARGS[2]

file_out = open(out_path, "w")

#data_dir = "data/mqtt"
data_dir = in_path
data_files = readdir(data_dir)

write(file_out, "latitude, longitude, distance, timestamp\n")

for file_name = data_files
    file_path = data_dir*"/"*file_name
    file = open(file_path, "r")
    file_content = read(file, String)
    lat = grab_tag(file_content, "latitude")
    lon = grab_tag(file_content, "longitude")
    lev = grab_tag(file_content, "distance")
    timestamp = grab_tag(file_content, "timestamp")
    write(file_out, "$lat, $lon, $lev, $timestamp\n")
end
close(file_out)

max_stars_repo_name: smart-facility/smart-faware

max_issues_repo_name: smart-facility/smart-faware

max_forks_repo_name: smart-facility/smart-faware


text:
module BenchPartitionLengthMaximum

using BenchmarkTools
using Transducers

const SUITE = BenchmarkGroup()

f(xs, ex) = Transducers.fold(
    max,
    xs |> ReducePartitionBy(identity, Map(_ -> 1)'(+), 0),
    ex;
    init = typemin(Int),
)

let s = SUITE["rand"] = BenchmarkGroup()
    xs = rand(Bool, 2^25)
    s["foldl"] = @benchmarkable f($xs, SequentialEx())
    s["reduce"] = @benchmarkable f($xs, ThreadedEx())
end

end  # module
BenchPartitionLengthMaximum.SUITE


text:
module polyBindingModel

using NLsolve
using LinearAlgebra

function rootSolve(f!, Rtot)
    local solve_res
    try
        solve_res = nlsolve(f!, Rtot, method = :newton, autodiff = :forward, xtol = 1e-9, iterations = 10_000)
        @assert converged(solve_res) == true
        @assert all(solve_res.zero .<= Rtot .+ eps())
        @assert all(-eps() .<= solve_res.zero)
    catch e
        println("Req solving failed:")
        println(solve_res)
        rethrow(e)
    end

    return solve_res.zero
end

include("randomBinding.jl")
include("complexBinding.jl")

export polyfc, polyc, polycm, polyfcm, polyc_Req

end # module


text:
using MIDI

const N_OCTAVES = 8
const RANGE_MIN = name_to_pitch("C0")
const NOTE_RANGE = [Note(RANGE_MIN+i, 127, 0, 0) for i in 0:N_OCTAVES*12]
const RANGE_MAX = NOTE_RANGE[end]
const MIDDLE_C = Note(name_to_pitch("C4"), 127, 0, 0)
const NOTE_LETTERS = 'A', 'B', 'C', 'D', 'E', 'F', 'G'
const SHARP = '♯'


text: println("Is this interactive? $(isinteractive())")


text:
@inline remove_column(table::TypedTables.Table, colname::Symbol) =
    TypedTables.Table(Base.structdiff(TypedTables.columns(table), NamedTuple{(colname,),Tuple{Int}}(0)))

@inline add_column(table::TypedTables.Table, nt::NamedTuple) =
    TypedTables.Table(merge(nt, TypedTables.columns(table)))
@inline add_column(table::TypedTables.Table, newname::Symbol, col::CT) where {CT} =
    add_column(table, NamedTuple{(newname,), Tuple{CT}}((col,)) )

@inline _rename_fields_impl(nt::NamedTuple{names}, from::Val{a}, to::Val{b}) where {names, a, b} =
    NamedTuple{map(x -> x == a ? b : x, names)}(values(nt))

@inline rename_fields(nt::NamedTuple, pattern::Pair{Symbol,Symbol}) =
    _rename_fields_impl(nt, Val(pattern.first), Val(pattern.second))

@inline rename_cols(table::Any, pattern::Pair{Symbol,Symbol}) =
    TypedTables.Tables.materializer(table)(rename_fields(TypedTables.Tables.columns(table), pattern))

function common_length(x, y)
    a = length(x); b = length(y)
    if a == b || b == 1
        a
    elseif a == 1
        b
    else
        throw(ArgumentError("Lengths are not compatible"))
    end
end
common_length(x, y, z...) = common_length(common_length(x, y), z...)

nested_col(x::AbstractVector, n::AbstractVector{<:Integer}) = VectorOfVectors(Fill.(x, n))

function nested_col(x::AbstractVector{<:AbstractVector}, n::AbstractVector{<:Integer})
    @assert length.(x) == n
    x
end

function blow_up_to_commen_length(table::TypedTables.Table)
    n = common_length.(values(TypedTables.columns(table))...)
    return TypedTables.Table(map(c -> nested_col(c, n), TypedTables.columns(table)))
end

function split_table_by_each_charge_deposition(table::TypedTables.Table)
    row_lengths = length.(values(table[1]))
    all_vectors = all(t -> t <: AbstractVector, typeof.(values(table[1])))
    if all(isequal(row_lengths[1]), row_lengths) && all_vectors
        TypedTables.Table( map(flatview, TypedTables.columns(table)) )
    else
        split_table_by_each_charge_deposition(blow_up_to_commen_length(table))
    end
end

function sort_by_time(table::TypedTables.Table)
    @assert length(table.thit[1]) == 1 "Split the table first: split_table_by_each_charge_deposition"
    sorted_inds = sortperm(table.thit)
    TypedTables.Table(map( c -> c[sorted_inds], TypedTables.columns(table)))
end

function cluster_by_time(table::TypedTables.Table, Δt = 1u"ns")
    @assert length(table.thit[1]) == 1 "Split the table first: split_table_by_each_charge_deposition"
    if Δt == 0u"s" return table end
    times_sorted = !issorted(table.thit) ? sort_by_time(table).thit : table.thit
    n_charge_depos = length(times_sorted)
    t0 = times_sorted[1]
    t_last = t0
    inds = Int[]
    for i in 2:n_charge_depos
        t = times_sorted[i]
        dt = t - t_last
        if dt > Δt
            push!(inds, i - 1)
            t_last = t
        end
    end
    if length(inds) > 0
        ranges = vcat( [1:inds[1]], broadcast(:, inds[1:end-1].+1, inds[2:end]),
                        n_charge_depos > inds[end] ? [inds[end]+1:n_charge_depos] : [] )
        TypedTables.Table(map(c -> VectorOfVectors(map(r -> c[r], ranges)), TypedTables.columns(table)))
    else
        TypedTables.Table(map(c -> VectorOfVectors(map(r -> c[r], [1:n_charge_depos])), TypedTables.columns(table)))
    end
end

function add_physics_event_numbers(table::TypedTables.Table)
    n_events = length(TypedTables.columns(table)[1])
    add_column(table, :phyevtno, flatview(collect(Int32, 1:n_events)))
end

function groub_by_evt_number(table::TypedTables.Table, colname::Symbol = :mcevtno)
    sorting_idxs = sortperm(getproperty(table, colname))
    sorted = table[sorting_idxs]
    return TypedTables.Table(consgroupedview((getproperty(table, colname), Tables.columns(sorted))))
end

function translate_event_positions(table::TypedTables.Table, tv::AbstractVector{<:Unitful.Quantity{<:Real, Unitful.𝐋}})
    @assert length(tv) == 3 "translation vector must be of length 3"
    TP = eltype(eltype(eltype(table.pos)))
    u = unit(TP)
    @assert all(e -> dimension(e) == Unitful.𝐋, tv) "All elements of translation vector muss be of dimension Unitful.𝐋"
    trans = uconvert.(u, tv)
    newpos = (pos = VectorOfVectors(map(poss -> map(pos -> pos + trans, poss), table.pos)),)
    TypedTables.Table(merge( TypedTables.columns(table), newpos ))
end

function rotate_event_positions(table, rot::Rotations.Rotation{3})
    newpos = (pos = VectorOfVectors(map(poss -> map(pos -> rot * pos, poss), table.pos)),)
    TypedTables.Table(merge( TypedTables.columns(table), newpos ))
end

function chunked_ranges(n, chunksize)
    if n < chunksize return [1:n] end
    ranges = map( s -> s:s+chunksize-1, 1:chunksize:n)
    if last(ranges[end]) > n ranges[end] = first(ranges[end]):n end
    return ranges
end


text:
# Propagators.jl
# Define functions to propagate the sites using the classical equation of motion
# and the wavefunctions using the time dependent Schrodinger equation

"""
Function to calculate the forces produced by the potential energy surface
-----------
pes = potential energy surface to be differentiated
-----------
f = force from potential energy surface as a function of site position
"""
function force(pes::Function)
    f = function (R) return -derivative(r->pes(r),R) end
    return f
end

"""
Define ordinary differential equation to be solved for classical equation of motion
-------------
du = [velocity, acceleration]
u = [position,velocity]
p = coefficient
t = time
F = force
-------------
ODE problem to be used in OrdinaryDiffEq Solver
"""
function acceleration(du::Array,u::Array,p,t,F::Function, M::Float64, K::Float64, R_0::Float64, ExtField::Float64)
    x = u[1]
    dx = u[2]
    du[1] = dx
    du[2] = 1.6e8/1.66*(-K*(x-R_0)+real(F(x))-ExtField)/M #1eV/(a.m.u*A) = 1.6e8/1.66 A/(0.1ns)^2
end

"""
Function to classically propagate nuclei
---------------
T = total time
x_0 = initial position
v_0 = initial velocity
dt = time step
F = function of force
---------------
x = array of positions
v = array of velocities
"""
function classical_propagation(T::Float64, x_0::Float64, R_0::Float64, v_0::Float64, dt::Float64, F::Function, M::Float64, K::Float64, ExtField::Float64)
    tspan = (0.0,T)
    myacceleration(du,u,p,t)=acceleration(du,u,p,t,F,M,K,R_0,ExtField)

    EoM = ODEProblem(myacceleration,[x_0,v_0],tspan)
    sol = solve(EoM, Euler(), dt = dt)
    x = sol[1,:]
    v = sol[2,:]
    return x,v
end

"""
Function to solve the time dependent Schrodinger equation to propagate the
adiabatic coefficients.
--------------------
a_ig = initial lower adiabatic state coeffient
a_ie = initial upper adiabatic state coeffient
d_ge = Non-adiabatic coupling vector from lower to upper adiabatic states
d_eg = Non-adiabatic coupling vector from upper to lower adiabatic states
d_gg = Non-adiabatic coupling vector from lower to lower adiabatic states
d_ee = Non-adiabatic coupling vector from upper to upper adiabatic states
R_e = Location of the electronic state on the nuclear coordinates
--------------------
a_fg = final lower adiabatic state coeffient
a_fe = final upper adiabatic state coeffient
"""
function new_a_mn(a_ig::Complex{Float64}, a_ie::Complex{Float64}, apg::Function, ape::Function, d_ge::Float64, d_eg::Float64, d_gg::Float64, d_ee::Float64, R_e::Float64, dt)
    Matrix = [-im*apg(R_e)/6.56e-26 -d_ge ; -d_eg -im*ape(R_e)/6.56e-26]

    lambdas = eigvals(Matrix)
    one = eigvecs(Matrix)[:,1]; two = eigvecs(Matrix)[:,2]
    C = (a_ig*two[2] - a_ie*two[1])/(one[1]*two[2] - one[2]*two[1])
    D = -(a_ig*one[2] - a_ie*one[1])/(one[1]*two[2] - one[2]*two[1])

    a_fg = C*one[1]*exp(lambdas[1]*dt) + D*two[1]*exp(lambdas[2]*dt)
    a_fe = C*one[2]*exp(lambdas[1]*dt) + D*two[2]*exp(lambdas[2]*dt)
    return a_fg, a_fe
end


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

using Base.Test

using Mortar3D: approx_in,
                is_vertex_inside_polygon,
                calculate_polygon_clip

@testset "approx in" begin
    P = Vector[[1.0, 1.0], [2.0, 2.0]]
    q1 = [1.0, 1.0] + eps(Float64)
    q2 = [1.0, 1.0] + 0.1
    @test approx_in(q1, P)
    @test !approx_in(q2, P)
end

@testset "vertex inside polygon" begin
    P = Vector[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    q1 = [ 0.1, 0.1, 0.0]
    q2 = [-0.1, 0.1, 0.0]
    @test is_vertex_inside_polygon(q1, P) == true
    @test is_vertex_inside_polygon(q2, P) == false
end

@testset "calculate polygon clip general case" begin
    xs = Vector[[0, 0, 0], [1, 0, 0], [0, 1, 0]]
    xm = Vector[[-1/4, 1/2, 0], [1/2, -1/4, 0], [3/4, 3/4, 0]]
    n = [0, 0, 1]
    P = calculate_polygon_clip(xs, xm, n)
    @test isapprox(P[6], [7/20, 13/20, 0])
    @test isapprox(P[5], [0, 9/16, 0])
    @test isapprox(P[4], [0, 1/4, 0])
    @test isapprox(P[3], [1/4, 0, 0])
    @test isapprox(P[2], [9/16, 0, 0])
    @test isapprox(P[1], [13/20, 7/20, 0])
end

@testset "calculate polygon clip, master node inside slave" begin
    xs = Vector[[0.0,0.0,0.0], [1.0,0.0,0.0], [0.0,1.0,0.0]]
    xm = Vector[[0.0,-0.9,0.0], [0.5,0.1,0.0], [1.0,-0.9,0.0]]
    n = [0.0, 0.0, 1.0]
    P = calculate_polygon_clip(xs, xm, n)
    @test length(P) == 3
end

@testset "calculate polygon clip, slave node inside master" begin
    xm = Vector[[0.0,0.0,0.0], [1.0,0.0,0.0], [0.0,1.0,0.0]]
    xs = Vector[[0.0,-0.9,0.0], [0.5,0.1,0.0], [1.0,-0.9,0.0]]
    n = [0.0, 0.0, 1.0]
    P = calculate_polygon_clip(xs, xm, n)
    @test length(P) == 3
end


text:
using Plots

x = 1:10; y = rand(10) # These are the plotting data
plot(x,y)

x = 1:10; y = rand(10,2) # 2 columns means two lines
#plot!(x,y)
plot!(twinx(),y)

gui()


text:
using SafeTestsets, Test

@safetestset "Model" begin include("model.jl") end
@safetestset "DictModel" begin include("dict_model.jl") end
@safetestset "JuMP" begin include("jump.jl") end
@testset "MMA" begin
    @safetestset "Approximation" begin include("approximation.jl") end
    @safetestset "Algorithm" begin include("mma.jl") end
end
@safetestset "AugLag/Percival" begin include("percival.jl") end
@safetestset "AugLag2" begin include("auglag.jl") end
@safetestset "Ipopt" begin include("ipopt.jl") end
@safetestset "NLopt" begin include("nlopt.jl") end
@safetestset "Juniper" begin include("juniper.jl") end
@safetestset "Pavito" begin include("pavito.jl") end
@safetestset "Hyperopt" begin include("hyperopt.jl") end
@safetestset "Bayesian optimization" begin include("bayesian.jl") end
@safetestset "Deflation" begin include("deflation.jl") end


text:
#MAIN ENTRY POINT
#final columns for the decompressed file
prepcrsp(;refreshcrsp=true)::DataFrame = loadcrspdata(refreshcrsp=refreshcrsp)

function loadcrspdata(crspname=CRSP_NAME; datapath=DATA_PATH, refreshcrsp=true,
  incsvstream::Function = IN_CSV_STREAM,
  injlsstream::Function = IN_JLS_STREAM, outjlsstream::Function = OUT_JLS_STREAM)::DataFrame
  local p::String = "$datapath\\$crspname"
  local crsp::DataFrame

  #makes a serialization object so we don't have to keep parsing the CSV
  if refreshcrsp || (!isfile("$p.jls.lz4"))
    crsp = incsvstream("$p.csv.lz4") |> CSV.read |> DataFrame

    println(describe(crsp))

    #preprocesscrsp!(crsp)

    crsp = preprocesscrsp(crsp)

    outjlsstream("$p.jls.lz4") do s
      serialize(s, crsp)
    end

  else
    injlsstream("$p.jls.lz4") do s
      crsp = deserialize(s)
    end

  end
  #println(describe(crsp))

  println("hello15")

  return crsp
end

function preprocesscrsp(crsp::DataFrame;
  crspdateformat::DateFormat = CRSP_DATE_FORMAT,
  crspcolumns::Vector{Symbol} = CRSP_COLUMNS)::DataFrame

  #rename columns to lower case

  names!(crsp, (s::Symbol->Symbol(lowercase(string(s)))).(names(crsp)))

  #parse some columns
  crsp.ret = (s::MString->parsecrsp(Float64, s)).(crsp.ret)
  crsp.dlret= (s::MString->parsecrsp(Float64, s)).(crsp.dlret)
  crsp.siccd = (s::MString->parsecrsp(Int, s)).(crsp.siccd)

  rename!(crsp, :ret=>:retlisted)
  #make sure we capture delisting returns
  crsp.ret = ((retlisted,dlret)->
    ismissing(retlisted) && ismissing(dlret) ? missing :
      ismissing(retlisted) ? dlret :
      ismissing(dlret) ? retlisted :
      (1+retlisted)*(1+dlret) - 1.
    ).(crsp.retlisted,crsp.dlret)

  #drop rows with missing data
  #below stopped working
  #deleterows!(crsp, (!).(completecases(crsp[:,[:ret, :SHRCD, :EXCHCD, :SICCD]])))
  crsp = crsp[completecases(crsp[:,[:ret, :shrcd, :exchcd, :siccd]]),:]

  #NOTE: SHRCD==10,11 : US Common Shares
  #NOTE:  :EXCHCD ∈ [1,2,3] : NYSE, Amex, NASDAQ
  #NOTE: r[:SICCD] ∉ 6000:6999 : No financial companies
  crsp[(r::DataFrameRow->
    (r[:shrcd] ∈ (10,11)) &&
    (r[:exchcd] ∈ (1,2,3)) &&
    (r[:siccd] ∉ 6000:6999)).(eachrow(crsp)),:]

  #println(describe(crsp))
  crsp.date = (s->parsecrsp(Date, s)).(crsp.date)
  select!(crsp, Not(setdiff(names(crsp), crspcolumns)))

  #get log returns
  crsp.lret = (log).(1.0 .+ crsp.ret)

  return crsp
end

#make tryparse handle missing values
#Base.tryparse(::Type{<:Any}, v::Missing)::Nothing = nothing

#parse a value where the type is known: Generic case
function parsecrsp(::Type{T}, s::String;
    parsedmissings = CRSP_PARSED_MISSINGS) where T

  #if it doesn't parse to the right type, set to missing
  v::Union{T,Missing} = something(tryparse(T, s), missing)

  #check against the list of missing codes
  (!ismissing(v)) && (v ∈ parsedmissings) && (v=missing)

  return v
end

#the date case
parsecrsp(::Type{Date}, s::String;
    crspdateformat::DateFormat = CRSP_DATE_FORMAT) = Dates.Date(s, crspdateformat)

#helper methods and special cases
parsecrsp(::Type{<:Any}, v::Missing) = missing
parsecrsp(::Type{Date}, i::Int) = parsecrsp(Date, "$i")

max_stars_repo_name: clintonTE/CCA

max_issues_repo_name: clintonTE/CCA

max_forks_repo_name: clintonTE/CCA