text:
function Ψ_yp!(ˍ₋out, ˍ₋arg1, ˍ₋arg2, ˍ₋arg3; )
    let c = @inbounds(ˍ₋arg1[1]), q = @inbounds(ˍ₋arg1[2]), i = @inbounds(ˍ₋arg1[3]), k = @inbounds(ˍ₋arg2[1]), z = @inbounds(ˍ₋arg2[2]), α = @inbounds(ˍ₋arg3[1]), β = @inbounds(ˍ₋arg3[2]), ρ = @inbounds(ˍ₋arg3[3]), δ = @inbounds(ˍ₋arg3[4]), σ = @inbounds(ˍ₋arg3[5]), Ω_1 = @inbounds(ˍ₋arg3[6])
        @inbounds begin
                nothing
            end
        begin
            @inbounds begin
                    nothing
                end
            begin
                @inbounds begin
                        ((ˍ₋out[1])[1])[1] = (+)((/)((*)(-2, β, (+)(1, (*)(-1, δ), (*)(α, (^)(k, (+)(-1, α)), (exp)(z)))), (^)(c, 4)), (*)(-8, (^)(c, 4), (/)((*)(-1, β, (+)(1, (*)(-1, δ), (*)(α, (^)(k, (+)(-1, α)), (exp)(z)))), (^)(c, 8))))
                        ((ˍ₋out[1])[1])[7] = (*)(-2, c, (/)((*)(α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 4)))
                        ((ˍ₋out[1])[1])[8] = (*)(-2, c, (/)((*)(α, β, (^)(k, (+)(-1, α)), (exp)(z)), (^)(c, 4)))
                        ((ˍ₋out[1])[1])[61] = (*)(-2, c, (/)((*)(α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 4)))
                        ((ˍ₋out[1])[1])[67] = (*)(-1, (/)((*)(-1, α, β, (^)(k, (+)(-3, α)), (+)(-1, α), (+)(-2, α), (exp)(z)), (^)(c, 2)))
                        ((ˍ₋out[1])[1])[68] = (*)(-1, (/)((*)(-1, α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 2)))
                        ((ˍ₋out[1])[1])[71] = (*)(-2, c, (/)((*)(α, β, (^)(k, (+)(-1, α)), (exp)(z)), (^)(c, 4)))
                        ((ˍ₋out[1])[1])[77] = (*)(-1, (/)((*)(-1, α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 2)))
                        ((ˍ₋out[1])[1])[78] = (*)(-1, (/)((*)(-1, α, β, (^)(k, (+)(-1, α)), (exp)(z)), (^)(c, 2)))
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
        end
        begin
            @inbounds begin
                    nothing
                end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
        end
        begin
            @inbounds begin
                    nothing
                end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
        end
    end
end

function Ψ_y!(ˍ₋out, ˍ₋arg1, ˍ₋arg2, ˍ₋arg3; )
    let c = @inbounds(ˍ₋arg1[1]), q = @inbounds(ˍ₋arg1[2]), i = @inbounds(ˍ₋arg1[3]), k = @inbounds(ˍ₋arg2[1]), z = @inbounds(ˍ₋arg2[2]), α = @inbounds(ˍ₋arg3[1]), β = @inbounds(ˍ₋arg3[2]), ρ = @inbounds(ˍ₋arg3[3]), δ = @inbounds(ˍ₋arg3[4]), σ = @inbounds(ˍ₋arg3[5]), Ω_1 = @inbounds(ˍ₋arg3[6])
        @inbounds begin
                nothing
            end
        begin
            @inbounds begin
                    nothing
                end
            begin
                @inbounds begin
                        ((ˍ₋out[1])[1])[34] = (+)((/)(2, (^)(c, 4)), (*)(-8, (^)(c, 4), (/)(1, (^)(c, 8))))
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
        end
        begin
            @inbounds begin
                    nothing
                end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
        end
        begin
            @inbounds begin
                    nothing
                end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
        end
    end
end

function Ψ_xp!(ˍ₋out, ˍ₋arg1, ˍ₋arg2, ˍ₋arg3; )
    let c = @inbounds(ˍ₋arg1[1]), q = @inbounds(ˍ₋arg1[2]), i = @inbounds(ˍ₋arg1[3]), k = @inbounds(ˍ₋arg2[1]), z = @inbounds(ˍ₋arg2[2]), α = @inbounds(ˍ₋arg3[1]), β = @inbounds(ˍ₋arg3[2]), ρ = @inbounds(ˍ₋arg3[3]), δ = @inbounds(ˍ₋arg3[4]), σ = @inbounds(ˍ₋arg3[5]), Ω_1 = @inbounds(ˍ₋arg3[6])
        @inbounds begin
                nothing
            end
        begin
            @inbounds begin
                    nothing
                end
            begin
                @inbounds begin
                        ((ˍ₋out[1])[1])[1] = (/)((*)(-2, c, α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 4))
                        ((ˍ₋out[1])[1])[7] = (/)((*)(α, β, (^)(k, (+)(-3, α)), (+)(-1, α), (+)(-2, α), (exp)(z)), (^)(c, 2))
                        ((ˍ₋out[1])[1])[8] = (/)((*)(α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 2))
                        ((ˍ₋out[1])[1])[61] = (/)((*)(α, β, (^)(k, (+)(-3, α)), (+)(-1, α), (+)(-2, α), (exp)(z)), (^)(c, 2))
                        ((ˍ₋out[1])[1])[67] = (/)((*)(-1, α, β, (^)(k, (+)(-4, α)), (+)(-1, α), (+)(-2, α), (+)(-3, α), (exp)(z)), c)
                        ((ˍ₋out[1])[1])[68] = (/)((*)(-1, α, β, (^)(k, (+)(-3, α)), (+)(-1, α), (+)(-2, α), (exp)(z)), c)
                        ((ˍ₋out[1])[1])[71] = (/)((*)(α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 2))
                        ((ˍ₋out[1])[1])[77] = (/)((*)(-1, α, β, (^)(k, (+)(-3, α)), (+)(-1, α), (+)(-2, α), (exp)(z)), c)
                        ((ˍ₋out[1])[1])[78] = (/)((*)(-1, α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), c)
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
        end
        begin
            @inbounds begin
                    nothing
                end
            begin
                @inbounds begin
                        ((ˍ₋out[2])[1])[1] = (/)((*)(-2, c, α, β, (^)(k, (+)(-1, α)), (exp)(z)), (^)(c, 4))
                        ((ˍ₋out[2])[1])[7] = (/)((*)(α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 2))
                        ((ˍ₋out[2])[1])[8] = (/)((*)(α, β, (^)(k, (+)(-1, α)), (exp)(z)), (^)(c, 2))
                        ((ˍ₋out[2])[1])[61] = (/)((*)(α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 2))
                        ((ˍ₋out[2])[1])[67] = (/)((*)(-1, α, β, (^)(k, (+)(-3, α)), (+)(-1, α), (+)(-2, α), (exp)(z)), c)
                        ((ˍ₋out[2])[1])[68] = (/)((*)(-1, α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), c)
                        ((ˍ₋out[2])[1])[71] = (/)((*)(α, β, (^)(k, (+)(-1, α)), (exp)(z)), (^)(c, 2))
                        ((ˍ₋out[2])[1])[77] = (/)((*)(-1, α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), c)
                        ((ˍ₋out[2])[1])[78] = (/)((*)(-1, α, β, (^)(k, (+)(-1, α)), (exp)(z)), c)
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
        end
    end
end

function Ψ_x!(ˍ₋out, ˍ₋arg1, ˍ₋arg2, ˍ₋arg3; )
    let c = @inbounds(ˍ₋arg1[1]), q = @inbounds(ˍ₋arg1[2]), i = @inbounds(ˍ₋arg1[3]), k = @inbounds(ˍ₋arg2[1]), z = @inbounds(ˍ₋arg2[2]), α = @inbounds(ˍ₋arg3[1]), β = @inbounds(ˍ₋arg3[2]), ρ = @inbounds(ˍ₋arg3[3]), δ = @inbounds(ˍ₋arg3[4]), σ = @inbounds(ˍ₋arg3[5]), Ω_1 = @inbounds(ˍ₋arg3[6])
        @inbounds begin
                nothing
            end
        begin
            @inbounds begin
                    nothing
                end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        ((ˍ₋out[1])[3])[89] = (*)(-1, α, (^)(k, (+)(-3, α)), (+)(-1, α), (+)(-2, α), (exp)(z))
                        ((ˍ₋out[1])[3])[90] = (*)(-1, α, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z))
                        ((ˍ₋out[1])[3])[99] = (*)(-1, α, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z))
                        ((ˍ₋out[1])[3])[100] = (*)(-1, α, (^)(k, (+)(-1, α)), (exp)(z))
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
        end
        begin
            @inbounds begin
                    nothing
                end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        ((ˍ₋out[2])[3])[89] = (*)(-1, α, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z))
                        ((ˍ₋out[2])[3])[90] = (*)(-1, α, (^)(k, (+)(-1, α)), (exp)(z))
                        ((ˍ₋out[2])[3])[99] = (*)(-1, α, (^)(k, (+)(-1, α)), (exp)(z))
                        ((ˍ₋out[2])[3])[100] = (*)(-1, (^)(k, α), (exp)(z))
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
            begin
                @inbounds begin
                        nothing
                    end
            end
        end
    end
end

function Ψ_p!(ˍ₋out, ::Val{:α}, ˍ₋arg2, ˍ₋arg3, ˍ₋arg4; )
    let c = @inbounds(ˍ₋arg2[1]), q = @inbounds(ˍ₋arg2[2]), i = @inbounds(ˍ₋arg2[3]), k = @inbounds(ˍ₋arg3[1]), z = @inbounds(ˍ₋arg3[2]), α = @inbounds(ˍ₋arg4[1]), β = @inbounds(ˍ₋arg4[2]), ρ = @inbounds(ˍ₋arg4[3]), δ = @inbounds(ˍ₋arg4[4]), σ = @inbounds(ˍ₋arg4[5]), Ω_1 = @inbounds(ˍ₋arg4[6])
        @inbounds begin
                nothing
            end
        begin
            @inbounds begin
                    (ˍ₋out[1])[1] = (/)((*)(-2, c, β, (+)((*)((^)(k, (+)(-1, α)), (exp)(z)), (*)(α, (^)(k, (+)(-1, α)), (log)(k), (exp)(z)))), (^)(c, 4))
                    (ˍ₋out[1])[7] = (/)((+)((*)(α, β, (^)(k, (+)(-2, α)), (exp)(z)), (*)(β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (*)(α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (log)(k), (exp)(z))), (^)(c, 2))
                    (ˍ₋out[1])[8] = (/)((+)((*)(β, (^)(k, (+)(-1, α)), (exp)(z)), (*)(α, β, (^)(k, (+)(-1, α)), (log)(k), (exp)(z))), (^)(c, 2))
                    (ˍ₋out[1])[61] = (/)((+)((*)(α, β, (^)(k, (+)(-2, α)), (exp)(z)), (*)(β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (*)(α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (log)(k), (exp)(z))), (^)(c, 2))
                    (ˍ₋out[1])[67] = (/)((+)((*)(-1, α, β, (^)(k, (+)(-3, α)), (+)(-1, α), (exp)(z)), (*)(-1, α, β, (^)(k, (+)(-3, α)), (+)(-2, α), (exp)(z)), (*)(-1, β, (^)(k, (+)(-3, α)), (+)(-1, α), (+)(-2, α), (exp)(z)), (*)(-1, α, β, (^)(k, (+)(-3, α)), (+)(-1, α), (+)(-2, α), (log)(k), (exp)(z))), c)
                    (ˍ₋out[1])[68] = (/)((+)((*)(-1, α, β, (^)(k, (+)(-2, α)), (exp)(z)), (*)(-1, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (*)(-1, α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (log)(k), (exp)(z))), c)
                    (ˍ₋out[1])[71] = (/)((+)((*)(β, (^)(k, (+)(-1, α)), (exp)(z)), (*)(α, β, (^)(k, (+)(-1, α)), (log)(k), (exp)(z))), (^)(c, 2))
                    (ˍ₋out[1])[77] = (/)((+)((*)(-1, α, β, (^)(k, (+)(-2, α)), (exp)(z)), (*)(-1, β, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (*)(-1, α, β, (^)(k, (+)(-2, α)), (+)(-1, α), (log)(k), (exp)(z))), c)
                    (ˍ₋out[1])[78] = (/)((+)((*)(-1, β, (^)(k, (+)(-1, α)), (exp)(z)), (*)(-1, α, β, (^)(k, (+)(-1, α)), (log)(k), (exp)(z))), c)
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    (ˍ₋out[3])[89] = (+)((*)(-1, α, (^)(k, (+)(-2, α)), (exp)(z)), (*)(-1, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (*)(-1, α, (^)(k, (+)(-2, α)), (+)(-1, α), (log)(k), (exp)(z)))
                    (ˍ₋out[3])[90] = (+)((*)(-1, (^)(k, (+)(-1, α)), (exp)(z)), (*)(-1, α, (^)(k, (+)(-1, α)), (log)(k), (exp)(z)))
                    (ˍ₋out[3])[99] = (+)((*)(-1, (^)(k, (+)(-1, α)), (exp)(z)), (*)(-1, α, (^)(k, (+)(-1, α)), (log)(k), (exp)(z)))
                    (ˍ₋out[3])[100] = (*)(-1, (^)(k, α), (log)(k), (exp)(z))
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
    end
end

function Ψ_p!(ˍ₋out, ::Val{:ρ}, ˍ₋arg2, ˍ₋arg3, ˍ₋arg4; )
    let c = @inbounds(ˍ₋arg2[1]), q = @inbounds(ˍ₋arg2[2]), i = @inbounds(ˍ₋arg2[3]), k = @inbounds(ˍ₋arg3[1]), z = @inbounds(ˍ₋arg3[2]), α = @inbounds(ˍ₋arg4[1]), β = @inbounds(ˍ₋arg4[2]), ρ = @inbounds(ˍ₋arg4[3]), δ = @inbounds(ˍ₋arg4[4]), σ = @inbounds(ˍ₋arg4[5]), Ω_1 = @inbounds(ˍ₋arg4[6])
        @inbounds begin
                nothing
            end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
    end
end

function Ψ_p!(ˍ₋out, ::Val{:σ}, ˍ₋arg2, ˍ₋arg3, ˍ₋arg4; )
    let c = @inbounds(ˍ₋arg2[1]), q = @inbounds(ˍ₋arg2[2]), i = @inbounds(ˍ₋arg2[3]), k = @inbounds(ˍ₋arg3[1]), z = @inbounds(ˍ₋arg3[2]), α = @inbounds(ˍ₋arg4[1]), β = @inbounds(ˍ₋arg4[2]), ρ = @inbounds(ˍ₋arg4[3]), δ = @inbounds(ˍ₋arg4[4]), σ = @inbounds(ˍ₋arg4[5]), Ω_1 = @inbounds(ˍ₋arg4[6])
        @inbounds begin
                nothing
            end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
    end
end

function Ψ_p!(ˍ₋out, ::Val{:Ω_1}, ˍ₋arg2, ˍ₋arg3, ˍ₋arg4; )
    let c = @inbounds(ˍ₋arg2[1]), q = @inbounds(ˍ₋arg2[2]), i = @inbounds(ˍ₋arg2[3]), k = @inbounds(ˍ₋arg3[1]), z = @inbounds(ˍ₋arg3[2]), α = @inbounds(ˍ₋arg4[1]), β = @inbounds(ˍ₋arg4[2]), ρ = @inbounds(ˍ₋arg4[3]), δ = @inbounds(ˍ₋arg4[4]), σ = @inbounds(ˍ₋arg4[5]), Ω_1 = @inbounds(ˍ₋arg4[6])
        @inbounds begin
                nothing
            end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
    end
end

function Ψ_p!(ˍ₋out, ::Val{:δ}, ˍ₋arg2, ˍ₋arg3, ˍ₋arg4; )
    let c = @inbounds(ˍ₋arg2[1]), q = @inbounds(ˍ₋arg2[2]), i = @inbounds(ˍ₋arg2[3]), k = @inbounds(ˍ₋arg3[1]), z = @inbounds(ˍ₋arg3[2]), α = @inbounds(ˍ₋arg4[1]), β = @inbounds(ˍ₋arg4[2]), ρ = @inbounds(ˍ₋arg4[3]), δ = @inbounds(ˍ₋arg4[4]), σ = @inbounds(ˍ₋arg4[5]), Ω_1 = @inbounds(ˍ₋arg4[6])
        @inbounds begin
                nothing
            end
        begin
            @inbounds begin
                    (ˍ₋out[1])[1] = (/)((*)(2, c, β), (^)(c, 4))
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
    end
end

function Ψ_p!(ˍ₋out, ::Val{:β}, ˍ₋arg2, ˍ₋arg3, ˍ₋arg4; )
    let c = @inbounds(ˍ₋arg2[1]), q = @inbounds(ˍ₋arg2[2]), i = @inbounds(ˍ₋arg2[3]), k = @inbounds(ˍ₋arg3[1]), z = @inbounds(ˍ₋arg3[2]), α = @inbounds(ˍ₋arg4[1]), β = @inbounds(ˍ₋arg4[2]), ρ = @inbounds(ˍ₋arg4[3]), δ = @inbounds(ˍ₋arg4[4]), σ = @inbounds(ˍ₋arg4[5]), Ω_1 = @inbounds(ˍ₋arg4[6])
        @inbounds begin
                nothing
            end
        begin
            @inbounds begin
                    (ˍ₋out[1])[1] = (/)((*)(2, c, (+)(-1, δ, (*)(-1, α, (^)(k, (+)(-1, α)), (exp)(z)))), (^)(c, 4))
                    (ˍ₋out[1])[7] = (/)((*)(α, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 2))
                    (ˍ₋out[1])[8] = (/)((*)(α, (^)(k, (+)(-1, α)), (exp)(z)), (^)(c, 2))
                    (ˍ₋out[1])[61] = (/)((*)(α, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), (^)(c, 2))
                    (ˍ₋out[1])[67] = (/)((*)(-1, α, (^)(k, (+)(-3, α)), (+)(-1, α), (+)(-2, α), (exp)(z)), c)
                    (ˍ₋out[1])[68] = (/)((*)(-1, α, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), c)
                    (ˍ₋out[1])[71] = (/)((*)(α, (^)(k, (+)(-1, α)), (exp)(z)), (^)(c, 2))
                    (ˍ₋out[1])[77] = (/)((*)(-1, α, (^)(k, (+)(-2, α)), (+)(-1, α), (exp)(z)), c)
                    (ˍ₋out[1])[78] = (/)((*)(-1, α, (^)(k, (+)(-1, α)), (exp)(z)), c)
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
        begin
            @inbounds begin
                    nothing
                end
        end
    end
end

max_stars_repo_name: HighDimensionalEconLab/HMCExamples

max_issues_repo_name: HighDimensionalEconLab/HMCExamples

max_forks_repo_name: HighDimensionalEconLab/HMCExamples


text:
# Edge Animation

using ThreeJS
using NetworkViz
using LightGraphs

main(window) =  begin
    g = Graph(10)
    push!(window.assets,("ThreeJS","threejs"))
    fps1 = fps(1)
    frames = foldp(+, 1, map((x)->1, fps1))
    running = map(x->x<9, frames)
    map(fpswhen(running, 1)) do _
        addEdge(g,frames.value,frames.value+1,1)
    end
end

ext: jl


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

mutable struct IoK8sApiCoreV1NodeSelectorTerm <: SwaggerModel
    matchExpressions::Any # spec type: Union{ Nothing, Vector{IoK8sApiCoreV1NodeSelectorRequirement} } # spec name: matchExpressions
    matchFields::Any # spec type: Union{ Nothing, Vector{IoK8sApiCoreV1NodeSelectorRequirement} } # spec name: matchFields

    function IoK8sApiCoreV1NodeSelectorTerm(;matchExpressions=nothing, matchFields=nothing)
        o = new()
        validate_property(IoK8sApiCoreV1NodeSelectorTerm, Symbol("matchExpressions"), matchExpressions)
        setfield!(o, Symbol("matchExpressions"), matchExpressions)
        validate_property(IoK8sApiCoreV1NodeSelectorTerm, Symbol("matchFields"), matchFields)
        setfield!(o, Symbol("matchFields"), matchFields)
        o
    end
end # type IoK8sApiCoreV1NodeSelectorTerm

const _property_map_IoK8sApiCoreV1NodeSelectorTerm = Dict{Symbol,Symbol}(Symbol("matchExpressions")=>Symbol("matchExpressions"), Symbol("matchFields")=>Symbol("matchFields"))
const _property_types_IoK8sApiCoreV1NodeSelectorTerm = Dict{Symbol,String}(Symbol("matchExpressions")=>"Vector{IoK8sApiCoreV1NodeSelectorRequirement}", Symbol("matchFields")=>"Vector{IoK8sApiCoreV1NodeSelectorRequirement}")
Base.propertynames(::Type{ IoK8sApiCoreV1NodeSelectorTerm }) = collect(keys(_property_map_IoK8sApiCoreV1NodeSelectorTerm))
Swagger.property_type(::Type{ IoK8sApiCoreV1NodeSelectorTerm }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_IoK8sApiCoreV1NodeSelectorTerm[name]))}
Swagger.field_name(::Type{ IoK8sApiCoreV1NodeSelectorTerm }, property_name::Symbol) =  _property_map_IoK8sApiCoreV1NodeSelectorTerm[property_name]

function check_required(o::IoK8sApiCoreV1NodeSelectorTerm)
    true
end

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


text:
const one_over_sqrt2 = 1/sqrt(2)
@inline wiener_randn(rng::AbstractRNG,::Type{T}) where T = randn(rng,T)
@inline function wiener_randn(rng::AbstractRNG,proto::Array{T}) where T
  randn(rng,size(proto))
end
@inline function wiener_randn(rng::AbstractRNG,proto)
  convert(typeof(proto),randn(rng,size(proto)))
end
@inline wiener_randn!(rng::AbstractRNG,rand_vec::Array) = randn!(rng,rand_vec)

# TODO: This needs an overload for GPUs
@inline wiener_randn!(rng::AbstractRNG,rand_vec) = rand_vec .= Base.Broadcast.Broadcasted(randn,())
@inline wiener_randn(y::AbstractRNG,::Type{Complex{T}}) where T = convert(T,one_over_sqrt2)*(randn(y,T)+im*randn(y,T))

@inline function wiener_randn!(y::AbstractRNG,x::AbstractArray{<:Complex{T}}) where T<:Number
  # Remove loop
  @inbounds for i in eachindex(x)
    x[i] = convert(T,one_over_sqrt2)*(randn(y,T)+im*randn(y,T))
  end
end

@inline function WHITE_NOISE_DIST(W,dt,rng)
  if typeof(W.dW) <: AbstractArray && !(typeof(W.dW) <: SArray)
    return @fastmath sqrt(abs(dt))*wiener_randn(rng,W.dW)
  else
    return @fastmath sqrt(abs(dt))*wiener_randn(rng,typeof(W.dW))
  end
end

function WHITE_NOISE_BRIDGE(W,W0,Wh,q,h,rng)
  if typeof(W.dW) <: AbstractArray
    return @fastmath sqrt((1-q)*q*abs(h))*wiener_randn(rng,W.dW)+q*Wh
  else
    return @fastmath sqrt((1-q)*q*abs(h))*wiener_randn(rng,typeof(W.dW))+q*Wh
  end

end
WienerProcess(t0,W0,Z0=nothing;kwargs...) = NoiseProcess{false}(t0,W0,Z0,WHITE_NOISE_DIST,WHITE_NOISE_BRIDGE;kwargs...)

function INPLACE_WHITE_NOISE_DIST(rand_vec,W,dt,rng)
  wiener_randn!(rng,rand_vec)
  sqrtabsdt = @fastmath sqrt(abs(dt))
  @.. rand_vec *= sqrtabsdt
end
function INPLACE_WHITE_NOISE_BRIDGE(rand_vec,W,W0,Wh,q,h,rng)
  wiener_randn!(rng,rand_vec)
  #rand_vec .= sqrt((1.-q).*q.*abs(h)).*rand_vec.+q.*Wh
  sqrtcoeff = @fastmath sqrt((1-q)*q*abs(h))
  @.. rand_vec = sqrtcoeff*rand_vec+q*Wh
end
WienerProcess!(t0,W0,Z0=nothing;kwargs...) = NoiseProcess{true}(t0,W0,Z0,INPLACE_WHITE_NOISE_DIST,INPLACE_WHITE_NOISE_BRIDGE;kwargs...)

#### Real Valued Wiener Process. Ignores complex and the like
function REAL_WHITE_NOISE_DIST(W,dt,rng)
  if typeof(W.dW) <: AbstractArray
    return @fastmath sqrt(abs(dt))*randn(rng,size(W.dW))
  else
    return @fastmath sqrt(abs(dt))*randn(rng)
  end
end
function REAL_WHITE_NOISE_BRIDGE(W,W0,Wh,q,h,rng)
  if typeof(W.dW) <: AbstractArray
    return @fastmath sqrt((1-q)*q*abs(h))*randn(rng,size(W.dW))+q*Wh
  else
    return @fastmath sqrt((1-q)*q*abs(h))*randn(rng)+q*Wh
  end
end
RealWienerProcess(t0,W0,Z0=nothing;kwargs...) = NoiseProcess{false}(t0,W0,Z0,REAL_WHITE_NOISE_DIST,REAL_WHITE_NOISE_BRIDGE;kwargs...)

function REAL_INPLACE_WHITE_NOISE_DIST(rand_vec,W,dt,rng)
  sqabsdt = @fastmath sqrt(abs(dt))
  wiener_randn!(rng,rand_vec)
  sqabsdt = sqrt(abs(dt))
  @.. rand_vec *= sqabsdt
end
function REAL_INPLACE_WHITE_NOISE_BRIDGE(rand_vec,W,W0,Wh,q,h,rng)
  wiener_randn!(rng,rand_vec!)
  @.. rand_vec = @fastmath sqrt((1-q)*q*abs(h))*rand_vec+q*Wh
end
RealWienerProcess!(t0,W0,Z0=nothing;kwargs...) = NoiseProcess{true}(t0,W0,Z0,REAL_INPLACE_WHITE_NOISE_DIST,REAL_INPLACE_WHITE_NOISE_BRIDGE;kwargs...)


text:
############################################################################################
#                                  EXPLICIT METHODS 								       #
############################################################################################

function integrate(::Type{Euler}, model::AbstractModel, x::StaticVector, u::StaticVector, t, dt)
	xdot = dynamics(model, x, u, t)
	return x + xdot * dt
end

function integrate(::Type{RK2}, model::AbstractModel, x::StaticVector, u::StaticVector, t, dt)
	k1 = dynamics(model, x,        u, t       )*dt
	k2 = dynamics(model, x + k1/2, u, t + dt/2)*dt
	x + k2
end

function integrate(::Type{RK3}, model::AbstractModel, x::StaticVector, u::StaticVector,
		t, dt)
    k1 = dynamics(model, x,             u, t       )*dt;
    k2 = dynamics(model, x + k1/2,      u, t + dt/2)*dt;
    k3 = dynamics(model, x - k1 + 2*k2, u, t + dt  )*dt;
    x + (k1 + 4*k2 + k3)/6
end

function integrate(::Type{RK4}, model::AbstractModel, x::StaticVector, u::StaticVector, t, dt)
	k1 = dynamics(model, x,        u, t       )*dt
	k2 = dynamics(model, x + k1/2, u, t + dt/2)*dt
	k3 = dynamics(model, x + k2/2, u, t + dt/2)*dt
	k4 = dynamics(model, x + k3,   u, t + dt  )*dt
	x + (k1 + 2k2 + 2k3 + k4)/6
end


text:
"""
    DiBitVector(n::Integer, v::Integer)

Create a `DiBitVector` with `n` elements preinitialized to a value `v`
from `0` to `3`, inclusive.

A `DiBitVector` is a vector whose elements are two bits wide, allowing
storage of integer values between 0 and 3. This structure is optimized for
performance and memory savings for large numbers of elements.
"""
mutable struct DiBitVector <: AbstractVector{UInt8}
    data::Vector{UInt64}
    len::UInt

    function DiBitVector(n::Integer, v::Integer)
        if Int(n) < 0
            throw(ArgumentError("n ($n) must be greater than or equal to zero"))
        end
        if !(Int(v) in 0:3)
            throw(ArgumentError("v ($v) must be in 0:3"))
        end
        fv = (0x0000000000000000, 0x5555555555555555,
        0xaaaaaaaaaaaaaaaa, 0xffffffffffffffff)[v + 1]
        vec = Vector{UInt64}(undef, cld(n, 32))
        fill!(vec, fv)
        return new(vec, n % UInt64)
    end
end

@inline checkbounds(D::DiBitVector, n::Integer) =  0 < n ≤ length(D.data) << 5 || throw(BoundsError(D, n))

"""
    DiBitVector(n::Integer)

Create a [`DiBitVector`](@ref) with `n` elements set to `0`.
"""
DiBitVector(n::Integer) = DiBitVector(n, 0)
DiBitVector() = DiBitVector(0, 0)

@inline Base.length(x::DiBitVector) = x.len % Int
@inline Base.size(x::DiBitVector) = (length(x),)

@inline index(n::Integer) = ((n-1) >>> 5) + 1
@inline offset(n::Integer) = ((UInt64(n)-1) << 1) & 63

@inline function Base.getindex(x::DiBitVector, i::Int)
    @boundscheck checkbounds(x, i)
    return UInt8((@inbounds x.data[index(i)] >>> offset(i)) & 3)
end

@inline function unsafe_setindex!(x::DiBitVector, v::UInt64, i::Int)
    bits = @inbounds x.data[index(i)]
    bits &= ~(UInt64(3) << offset(i))
    bits |= convert(UInt64, v) << offset(i)
    @inbounds x.data[index(i)] = bits
end

@inline function Base.setindex!(x::DiBitVector, v::Integer, i::Int)
    v & 3 == v || throw(DomainError("Can only contain 0:3 (tried $v)"))
    @boundscheck checkbounds(x, i)
    unsafe_setindex!(x, convert(UInt64, v), i)
end

@inline function Base.push!(x::DiBitVector, v::Integer)
    len = length(x)
    len == UInt64(length(x.data)) << 5 && push!(x.data, zero(UInt64))
    x.len = (len + 1) % UInt64
    x[len+1] = convert(UInt64, v)
    return x
end

@inline function Base.pop!(x::DiBitVector)
    x.len == 0 && throw(ArgumentError("array must be non-empty"))
    v = x[end]
    x.len = (x.len - 1) % UInt64
    x.len == UInt64((length(x.data) -1)) << 5 && pop!(x.data)
    return v
end

@inline zero(x::DiBitVector) = DiBitVector(x.len, 0)


text:
# MIT License

# Copyright (c) 2021 Dr. William A. Pisani

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""
    dihedrals(bonds::Array{Array{Int64,N} where N,1},angles::Array{Tuple{Int64,Int64,Int64},1}) -> Array{NTuple{4,Int64},1}

Determines the dihedrals of a molecule or molecular system given the bonds and angles.
"""
function dihedrals(bonds::Array{Array{Int64,N} where N,1},angles::Array{Tuple{Int64,Int64,Int64},1})
    println("Determining dihedrals...")
    dihedral_set = Set(Tuple{Int64,Int64,Int64,Int64}[])
    count = 1
    for i = 1:length(angles)
        atom1 = angles[i][1]
        atom2 = angles[i][2]
        atom3 = angles[i][3]
        atom123set = Set([atom1,atom2,atom3])
        for j = 1:length(bonds)
            atom4 = bonds[j][1]
            atom5 = bonds[j][2]
            atom45set = Set([atom4,atom5])
            atom1345set = Set([atom1,atom3,atom4,atom5])
            atom12345set = Set([atom1,atom2,atom3,atom4,atom5])
            if length(atom12345set) == 4 && length(atom1345set) == 3
                commonatom = setdiff(atom45set,symdiff(atom123set,atom45set))
                newatom = collect(setdiff(atom45set,commonatom))
                if collect(commonatom)[1] == atom1
                    dihedral = (newatom[1],atom1,atom2,atom3)
                else
                    dihedral = (atom1,atom2,atom3,newatom[1])
                end
                if ∉(dihedral,dihedral_set)
                    dihedral = reverse(dihedral)
                    push!(dihedral_set,dihedral)
                    count += 1
                end
            end
        end
    end
    println("Dihedrals determined!")
    return collect(dihedral_set)
end

max_stars_repo_name: wapisani/CompMatSciTools

max_issues_repo_name: wapisani/CompMatSciTools

max_forks_repo_name: wapisani/CompMatSciTools


text:
"""
Simulation

A simulation composes the observed trace and the backend solve of Algorithm 7.1.
A simulation instance is returned from an `optimize` call.
"""
struct Simulation
    model::Model
    driver::Driver
    trace::BlockOptTrace
    backend::BlockOptBackend

    function Simulation(model::Model, driver::Driver)
        # TODO: Handle ill-formed input
        new(model, driver, BlockOptTrace(model, driver), BlockOptBackend(model, driver))
    end
end

trace(s::Simulation) = getfield(s, :trace)

model(s::Simulation) = model(trace(s))

driver(s::Simulation) = driver(trace(s))

"""
    trs_timer(s::Simulation)

The elapsed time simulation `s` has been in `trs_solve(s)`.
"""
trs_timer(s::Simulation) = trs_timer(trace(s))

"""
    trs_counter(s::Simulation)

The count of trust-region subproblem solves for simulation `s`.
"""
trs_counter(s::Simulation) = trs_counter(trace(s))

"""
    ghs_timer(s::Simulation)

The elapsed time simulation `s` has been in `gHS(s)`.
"""
ghs_timer(s::Simulation) = ghs_timer(trace(s))

"""
    ghs_counter(s::Simulation)

The count of `gHS` evaluations for simulation `s`.
"""
ghs_counter(s::Simulation) = ghs_counter(trace(s))

weave!(s::Simulation, field, val) = weave!(trace(s), field, val)

weave_level(s::Simulation) = weave_level(trace(s))

"""
    f_vals(s::Simulation)

A vector holding objective values ``f(xₖ)`` for each successful iterate ``xₖ``
of simulation `s`.
"""
f_vals(s::Simulation) = f_vals(trace(s))

"""
    ∇f_norms(s::Simulation)

A vector holding normed gradient values ``||∇f(xₖ)||₂`` for each successful iterate ``xₖ``
of simulation `s`.
"""
∇f_norms(s::Simulation) = ∇f_norms(trace(s))

"""
    p_norms(s::Simulation)

A vector holding distance ``||pₖ||₂` of each successful step ``pₖ``
of simulation `s`.
"""
p_norms(s::Simulation) = p_norms(trace(s))

"""
    Δ_vals(s::Simulation)

A vector holding the trust-region radius passed to `trs_small` in TRS.jl
during each successful step of simulation `s`.
"""
Δ_vals(s::Simulation) = Δ_vals(trace(s))

"""
    ρ_vals(s::Simulation)

A vector storing the ratio of actual reduction to model reduction of
each successful step of simulation `s`.
"""
ρ_vals(s::Simulation) = ρ_vals(trace(s))

"""
    weave(args::Simulation...)

Generates a Weave.jl report of the simulation args.
"""
function weave(args::Simulation...)
    println(pwd())
    Weave.weave(
        joinpath(dirname(pathof(BlockOpt)), "lib/trace.jmd");
        args = args,
        out_path = mkpath(
            joinpath(directory(model(first(args))), "trace_$(trunc(now(), Minute))"),
        ),
    )
end

io(s::Simulation) = io(trace(s))

log_level(s::Simulation) = log_level(trace(s))

info!(s::Simulation, args...) = info!(trace(s), args...)

debug!(s::Simulation, args...) = debug!(trace(s), args...)

warn!(s::Simulation, args...) = warn!(trace(s), args...)

error!(s::Simulation, args...) = error!(trace(s), args...)

backend(s::Simulation) = getfield(s, :backend)

fₖ(s::Simulation) = fₖ(backend(s))

∇fₖ_norm(s::Simulation) = ∇fₖ_norm(backend(s))

pₖ_norm(s::Simulation) = pₖ_norm(backend(s))

Δₖ(s::Simulation) = Δₖ(backend(s))

ρ(s::Simulation) = ρ(backend(s))

Base.getproperty(s::Simulation, sym::Symbol) = @restrict Simulation

Base.propertynames(s::Simulation) = ()

"""
    initialize(s::Simulation)

Performs each step up to the preliminary update
to obtain ``H₀``. Lines 1-6 of `Algorithm 7.1`.
"""
function initialize(s::Simulation)

    initialize(backend(s))

    increment!(ghs_counter(s))

    weave!(s, f_vals, fₖ(s))

    weave!(s, ∇f_norms, ∇fₖ_norm(s))

    weave!(s, Δ_vals, Δₖ(s))

    info!(s, "Simulating:", s)

    nothing
end

"""
    terminal(s::Simulation)

True if the state of `s` is terminal.
"""
function terminal(s::Simulation)
    if terminal(backend(s), evaluations(trs_counter(s)))
        return true
    end

    return false
end

"""
    build_trs(s::Simulation)

Build arguments for the trs_small call to TRS.jl.
"""
function build_trs(s::Simulation)

    build_trs(backend(s))

    nothing
end

"""
    solve_trs(s::Simulation)

Solve ``aₖ`` in Equation (5.5).
"""
function solve_trs(s::Simulation)

    on!(trs_timer(s))

    solve_trs(backend(s))

    off!(trs_timer(s))

    increment!(trs_counter(s))

    nothing
end

"""
    build_trial(s::Simulation)

Build trial iterate, evaluate the objective at the trial location, and compute ``ρ``.
"""
function build_trial(s::Simulation)

    build_trial(backend(s))

    nothing
end

"""
    update_Δₖ(s::Simulation)

Updates the radius Δₖ after each trust-region subproblem solve.
"""
function update_Δₖ(s::Simulation)

    update_Δₖ(backend(s))

    nothing
end

"""
    accept_trial(s::Simulation)

Observe the value of ``ρ``, accept positive values, and then update ``xₖ, fₖ``.
"""
function accept_trial(s::Simulation)

    if accept_trial(backend(s))

        weave!(s, f_vals, fₖ(s))

        weave!(s, Δ_vals, Δₖ(s))

        weave!(s, p_norms, pₖ_norm(s))

        weave!(s, ρ_vals, ρ(s))

        return true
    end

    return false
end

"""
    pflag(s::Simulation)

The preliminary secant update flag of the Driver of `s` the default value is false.
"""
function pflag(s::Simulation)
    return pflag(backend(s))
end

"""
    secantQN(s::Simulation)

Performs the standard secant update for `s`'s inverse Hessian approximation ``Hₖ``.

The QN formula used is given by the Driver of `s`.
"""
function secantQN(s::Simulation)

    secantQN(backend(s))

    nothing
end

"""
    update_Sₖ(s::Simulation)

Updates the ``2w-1`` sample directions of simulation `s`.

See: `S_update_a`, `S_update_b`, `S_update_c`, `S_update_d`, `S_update_e`, `S_update_f`.
"""
function update_Sₖ(s::Simulation)

    update_Sₖ(backend(s))

    nothing
end

"""
    gHS(s::Simulation)

See Algorithm ``3.1``
"""
function gHS(s::Simulation)

    on!(ghs_timer(s))

    gHS(backend(s))

    off!(ghs_timer(s))

    increment!(ghs_counter(s))

    weave!(s, ∇f_norms, ∇fₖ_norm(s))

    nothing
end

"""
    blockQN(s::Simulation)

Performs a block update for `s`'s inverse Hessian approximation ``Hₖ``.

The QN formula used is given by the Driver of `s`.
"""
function blockQN(s::Simulation)

    blockQN(backend(s))

    nothing
end

function optimize!(simulation::Simulation)

    initialize(simulation)

    build_trs(simulation)

    while !terminal(simulation)

        solve_trs(simulation)

        build_trial(simulation)

        if accept_trial(simulation)

            if pflag(simulation)
                secantQN(simulation)
            end

            update_Sₖ(simulation)

            gHS(simulation)

            blockQN(simulation)

            build_trs(simulation)
        end

        update_Δₖ(simulation)
    end

    info!(simulation, "Terminating:", trace(simulation))

    return simulation
end


text:
# This is code for computing a transit model and derivatives integrated over
# a time step, giving the fluence in units of time (since
# flux is normalized to unity).

using Cubature

include("transit_poly_struct.jl")

# Now the version with derivatives:
function integrate_timestep_gradient!(param::Array{T,1},trans::Transit_Struct{T},t1::T,t2::T,tol::T,maxdepth::Int64) where {T <: Real}

  function fill_flux!(tmid::T,fmid0::T,trans_mid::Transit_Struct{T}) where {T <: Real}
  fmid = Array{T}(6+trans_mid.n)
  fmid[1] = fmid0   # flux
  fmid[2] = trans_mid.dfdrb[1]  # r derivative
  fmid[3] = trans_mid.dfdrb[2]/trans_mid.b*param[2]^2*(param[1]-tmid)  # t0 derivative
  fmid[4] = trans_mid.dfdrb[2]*param[2]/trans_mid.b*(tmid-param[1])^2  # v derivative
  fmid[5] = trans_mid.dfdrb[2]*param[3]/trans_mid.b  # b0 derivative
  @inbounds for i=1:trans_mid.n+1
    fmid[5+i] = trans_mid.dfdg[i]  # d_i derivatives
  end
  return fmid
  end

  function solver(time::T) where {T <: Real}
  # This predicts the impact parameter as a function of time in
  # terms of the transit_struct.
  # For now, transit is approximated as a straight line, where params are given as:
  # param[1] = t0 (mid-transit time; units of days/JD)
  # param[2] = v/R_* (sky velocity in terms of radius of the star - units are day^{-1}
  # param[3] = b (impact parameter at time t0)
  return sqrt(param[3]^2+(param[2]*(time-param[1]))^2)
  end

  # Function to define the vector integration in cubature:
  function transit_flux_derivative(tmid::T,fmid::Array{T,1}) where {T <: Real}
  trans.b = solver(tmid)
  fmid0 = transit_poly_d!(trans)
  fmid .= fill_flux!(tmid,fmid0,trans)
#  println("b: ",trans.b," f/df: ",fmid)
  return
  end

  fint,ferr = hquadrature(trans.n+6,transit_flux_derivative,t1,t2,abstol=tol)
return fint
end


text:
module Prerequisites

using Reexport: @reexport
using Formatting: FormatSpec, fmt

export atol, rtol, Float
export decimaltostr, ordinal, delta, concatenate

"Absolute tolerance for float numbers."
const atol = 5 * 10^-14

"Relative tolerance for float numbers."
const rtol = √atol

"Default float type."
const Float = Float64

"""
    decimaltostr(number, ::Int=5)
    decimaltostr(number::Integer, n::Int=5)
    decimaltostr(number::Rational, n::Int=5)
    decimaltostr(number::AbstractFloat, n::Int=5)
    decimaltostr(number::Complex, n::Int=5)

Convert a number to a string with at most `n` decimal places.
"""
@inline decimaltostr(number, ::Int=5) = repr(number)
@inline decimaltostr(number::Integer, ::Int=5) = string(number)
@inline decimaltostr(number::Rational, ::Int=5) = string(number)
function decimaltostr(number::AbstractFloat, n::Int=5)
    if number == 0.0
        result = "0.0"
    elseif 10^-5 < abs(number) < 10^6
        result = rstrip(fmt(FormatSpec(".$(n)f"), number), '0')
        (result[end] == '.') && (result = result * '0')
    else
        result = fmt(FormatSpec(".$(n)e"), number)
        epos = findfirst(isequal('e'), result)
        temp = rstrip(result[1:epos-1], '0')
        result = (temp[end] == '.') ? (temp * "0" * result[epos:end]) : (temp * result[epos:end])
    end
    result
end
function decimaltostr(number::Complex, n::Int=5)
    sreal = (real(number) == 0) ? "0" : decimaltostr(real(number), n)
    simag = (imag(number) == 0) ? "0" : decimaltostr(imag(number), n)
    result = ""
    (sreal == "0") || (result = result * sreal)
    (simag == "0") || (result = ((simag[1] == '-') ? (result * simag) : (length(result) == 0) ? simag : (result * "+" * simag)) * "im")
    (length(result) == 0) && (result = "0.0")
    return result
end

"""
    ordinal(number::Integer)

Convert a positive number to its corresponding ordinal.
"""
@inline function ordinal(number::Integer)
    @assert number > 0 "ordinal error: input number must be positive."
    (number == 1) ? "1st" : (number == 2) ? "2nd" : (number == 3) ? "3rd" : "$(number)th"
end

"""
    delta(i, j) -> Int

Kronecker delta function.
"""
@inline delta(i, j) = (i == j) ? 1 : 0

"""
    concatenate(ts::Tuple...) -> Tuple

Concatenate tuples.
"""
@inline @generated concatenate(ts::Tuple...) = Expr(:tuple, map(i->:(ts[$i]...), 1:length(ts))...)

"""
    searchsortedfirst(table, basis; compare=<) -> Int

Use the binary search method to find the position of a basis in a sorted table so that the order is preserved if the basis in inserted in that position.
"""
function Base.searchsortedfirst(table, basis; compare=<)
    lo, hi = 0, length(table)+1
    @inbounds while lo < hi-1
        m = (lo+hi) >>> 1
        if compare(table[m], basis)
            lo = m
        else
            hi = m
        end
    end
    return hi
end

include("Combinatorics.jl")
include("Traits.jl")
include("CompositeStructures.jl")
include("SimpleTrees.jl")
include("NamedVectors.jl")
include("VectorSpaces.jl")

@reexport using .Combinatorics
@reexport using .Traits
@reexport using .CompositeStructures
@reexport using .SimpleTrees
@reexport using .NamedVectors
@reexport using .VectorSpaces

end # module


text:
# ThomasFermi.jl
#  - Thomas Fermi Density Functional Theory

# Marder is: "Condensed Mattery Physics", Michael Marder, 2000.

# Also very useful is Andrei Postnikov's first DFT lecture, on the Thomas-Fermi method
# http://www.home.uni-osnabrueck.de/apostnik/Lectures/DFT-1.pdf

"""
ThomasFermi_T(n)

Thomas Fermi kinetic energy (T).
 Following eqn. 9.69 Marder p/ 217
"""
function ThomasFermi_T(n)
    T= (hbar^2)/(2*me) * 3/5 * (3*pi^2)^(2/3) * n^(5/3)
    T
end

"
ThomasFermi_T_fnderiv(n)

Thomas Fermi kinetic energy (T) as a functional derivative.
 Following eqn. 9.76 Marder p/ 217
"
function ThomasFermi_T_fnderiv(n)
#    @printf("ThomasFermi_T_fnderiv(%g,%g)\n",n,V) # to locate NaN error
    T= (hbar^2)/(2*me) * 3/5 * (3*pi^2)^(2/3) * n^(2/3)
    T
end

"
 ThomasFermi_Exc(n)

 Thomas Fermi exchange and correlation energy; takes electron density, returns energy.
 Following eqn. 9.73 Marder p/ 217
"
function ThomasFermi_Exc(n)
    Exc= - 3/4 * (3/pi)^(1/3) * q^2 * n^(5/3)
    Exc
end

"
UAtomic(Z,r)

Potential due to Atomic charge; simple bare Coulomb form.
"
function UAtomic(Z,r)
    U = -k_e * Z * q^2/r
end

function ThomasFermi_CoulombPotential(density,i,gridspacing,N)
    # Coulomb integral.
    # Nb: as spherical atom, probably need some horrible weighting parameters for the area of the spherical shell in the range [i] or [j]
    # i.e. currently it's some 1D pipe full of electrons with a nuclear charge at the end
    Potential=0.0
    for j in 1:N
        if j==i
            continue
        end
        Potential+= k_e * q^2*density[j]/(gridspacing*(i-j))
    end
    Potential
end

"
 AtomicTest(Z,N=100)
 Evaluate Thomas Fermi energy for a spherical atom, atomic charge Z.
 N: number of grid points in 1D density repr.

 c.f. Marder, p.219, Eqn (9.76):
 'The energy of an atomic of nuclear charge Z is approximately -1.5375 Z^(7/3) Ry'
"
function AtomicTest(Z; N=10,verbose::Bool=false)
    println("AtomicTest, atomic charge: ",Z)

    const radius=25Å

    density=zeros(N).+Z/N # I know, a bit dirty... Fills density with flat electron density as initial guess.
    gridspacing=N/radius

    # Do some DFT here...
    V = 4/3*pi*radius^3 # Volume of total sphere of charge density considered.
    # Nb: Not sure if corect; Kinetic energy T is proport. to V. Defo volume and not potential?

    sumE=0.0
    for n in 1:10
        if verbose; @printf("SCF Loop: %d\n",n); end;
        sumE=0.0
        # Central equation as (9.76) in Marder, dropping Dirac term
        for i in 1:N

            # mu being the chemical potential; this pulls together (9.76)
            # Mu is the Lagrange multiplier to enforce the constraint that the density is conserved;
            # helpfully this is also identical to the chemical potential
            mu=ThomasFermi_T_fnderiv(density[i]) + UAtomic(Z,i*gridspacing) + ThomasFermi_CoulombPotential(density,i,gridspacing,N)
            # So I gues we could use the fact that the chem potential is constant, to start moving electron density around?

            # From Postnikov 1.2; mu drops to zero at r=infinity, therefore mu is zero everywhere

            # TODO: Insert self-consistency here...

            if verbose
                @printf("\t i: %d density: %g T: %g \n\t\tmu %g = T_fnderiv %g + UAtomic: %g + Coulomb %g\n",
                i,density[i],
                ThomasFermi_T(density[i]),
                mu,ThomasFermi_T_fnderiv(density[i]),UAtomic(Z,i*gridspacing),ThomasFermi_CoulombPotential(density,i,gridspacing,N))
            end

            # OK; calculate total energy
            E=ThomasFermi_T(density[i]) + density[i]*UAtomic(Z,i*gridspacing) + density[i]*ThomasFermi_CoulombPotential(density,i,gridspacing,N)
            if verbose
                @printf("\t\tE %g = T %g + U %g + Coulomb %g\nTotal E: %g J = %g eV\n",
                E,ThomasFermi_T(density[i]), density[i]*UAtomic(Z,i*gridspacing), density[i]*ThomasFermi_CoulombPotential(density,i,gridspacing,N),
                sumE,sumE/q)
            end
            sumE+=E

            # Nb: horrid hack :^)
            density[i]-=mu*10E35 # vary density based on how much chemical potential mu exceeds 0
            if density[i]<0.0; density[i]=0.0; end
        end
        # Impose constraint sum. density = Z
        if verbose
            @printf("Sum of density pre normalisation: %f\n",sum(density))
        end
        density=density.*Z/sum(density)

    end

    # TODO: calculate total Thomas-Fermi energy here, from density...

    println("Density: ",density)
    @printf("Total E: %g J = %g Ry = %g eV\n",sumE,sumE/Ry,sumE/q)
    println("Marder analytic reference: E ~= -1.5375.Z^(7/3) = ",-1.5375*Z^(7/3), " Ry") # Nb: do some unit conversions
end


text:
module LatticeBoltzmann

import Base: range

using LinearAlgebra
using Plots

δ(α, β) = α == β ? 1 : 0

include("quadratures.jl")

# Equilibria
include("hermite_polynomials.jl")

# Velocity Distribution Function related methods
include("velocity_distribution_function/moments.jl")
include("velocity_distribution_function/maxwell_boltzmann_equilibrium.jl")
include("velocity_distribution_function/hermite.jl")
include("velocity_distribution_function/quadratures.jl")

include("boundary_conditions.jl")
include("problems/problems.jl")
include("initial_conditions.jl")
include("stream.jl")
include("collision_models.jl")
include("processing_methods.jl")
include("lattice_boltzmann_model.jl")

include("interop/plots.jl")

export CollisionModel, SRT, TRT, MRT
export Quadrature, D2Q4, D2Q5, D2Q9, D2Q13, D2Q17, D2Q21, D2Q37, opposite

export analayze_convergence
# Problems
export DecayingShearFlow
export LidDrivenCavityFlow
export TaylorGreenVortex
export CouetteFlow
export GenericFluidFlowProblem
export LinearizedThermalDiffusion, LinearizedTransverseShearWave
export PoiseuilleFlow

export process!,
    apply_boundary_conditions!,
    density,
    velocity,
    pressure,
    temperature,
    decay,
    force,
    FluidFlowProblem,
    viscosity,
    delta_t
export Lattice,
    initialize,
    AnalyticalEquilibriumAndOffEquilibrium,
    AnalyticalEquilibrium,
    AnalyticalVelocity,
    IterativeInitialization,
    density,
    momentum,
    pressure,
    total_energy,
    kinetic_energy,
    internal_energy,
    temperature,
    dimension,
    equilibrium,
    equilibrium!,
    hermite_equilibrium,
    hermite_first_nonequilibrium,
    hermite,
    stream!,
    collide!,
    simulate

end


text:
struct PutativeParticle{P,O,S,C}
    ancestor::P
    obs::O
    state::S
    updated_comp::C
    weight::Float64
end

instantiate(p::PutativeParticle{P}) where P =
    error("Don't know how to instantiate a putative $P")

weight(p::PutativeParticle) = p.weight

abstract type AbstractParticle end

Base.broadcastable(p::AbstractParticle) = Ref(p)

weight(p::AbstractParticle) = p.weight
Distributions.components(p::AbstractParticle) = p.components

nobs(p::AbstractParticle) = sum(nobs(c) for c in components(p))
Base.isempty(p::AbstractParticle) = all(nobs(c) == 0 for c in components(p))

function assignments(p::AbstractParticle)
    asgns = Int[]
    while !isempty(p)
        push!(asgns, p.assignment)
        p = p.ancestor
    end
    reverse!(asgns)
end

"""
An InfiniteParticle holds a potentially infinite number of components,
potentially expanding every time it generates putatives.
"""
mutable struct InfiniteParticle{P,S,T} <: AbstractParticle
    components::Vector{Component{P,S}}
    ancestor::Union{Nothing,InfiniteParticle}
    assignment::Int
    weight::Float64
    prior::Component{P,S}
    stateprior::T
end

function Base.show(io::IO, p::InfiniteParticle)
    if get(io, :compact, false)
        print(io, "$(length(p.components))+ Particle")
    else
        println(io, "Particle with $(length(p.components))+ components:")
        for c in p.components
            println(io, "  $c")
        end
        println(io, "  (prior: $(p.prior))")
    end
end

InfiniteParticle(prior::Component, α::Float64) =
    InfiniteParticle(prior, ChineseRestaurantProcess(α))
InfiniteParticle(prior::Component, stateprior::T) where T<:StatePrior =
    InfiniteParticle(typeof(prior)[], nothing, 0, 1.0, prior, stateprior)
InfiniteParticle(prior, stateprior) = InfiniteParticle(Component(prior), stateprior)

weight(p::InfiniteParticle, w::Float64) =
    InfiniteParticle(p.components, p.ancestor, p.assignment, w, p.prior, p.stateprior)

putatives(p::InfiniteParticle, y) =
    (PutativeParticle(p, y, j) for j in candidates(p.stateprior))

"""
    PutativeParticle(p::InfiniteParticle, y, x)

Lazily compute the consequences of adding observation `y` to cluster `x` of
particle `p` weight without actually updating the suff stats etc, which requires
(potentially expensive) copying

The weight update term is the ratio of the previous and updated marginal
posterior:
```math
\\frac{p((z_{1:n}, x) | y_{1:n+1} )}{p(z_{1:n} | y_{1:n} )} ∝
\\frac{p(y_{1:n+1} | (z_{1:n}, x)) p((z_{1:n}, x))}{p(y_{1:n} | z_{1:n}) p(z_{1:n})}
```

The prior ratio can be reduced using the conditional distribution: ``p(z_{1:n},
x)/p(z_{1:n}) = p(x | z_{1:n})``.  Under a Chinese Restaurant Process prior, this
is ``N_x / ∑_j N_j + α`` if ``x`` corresponds to an existing component and
``α / ∑_j N_j + α`` if it's new.  Because the total count ``∑_j
N_j`` is the same across particles, the net change is proportional to ``N_x`` or
``α``.

The likelihood ratio also depends on whether ``y`` is being assigned to a new
component or not.  If it is being assigned to a new component, then its marginal
likelihood is independent of all other points and the entire adjustment is
proportional to the marginal likelihood of ``y`` under the prior.  When ``x``
corresponds to an existing component, the adjustment is proportional to the
ratio of the marginal likelihood of that component before and after
incorporating ``y``: ``\\frac{p(y_{x_i=x}, y_{n+1})}{p(y_{x_i=x})}``.
"""
function PutativeParticle(p::InfiniteParticle, obs::O, state::S) where {O,S}
    logweight = log(p.weight)
    logweight += log_prior(p.stateprior, state)
    comp_i = state_to_index(p.stateprior, state)
    if comp_i ≤ length(p.components)
        # likelihood adjustment for old observations
        comp = p.components[comp_i]
        logweight -= marginal_log_lhood(comp)
    else
        comp = p.prior
    end
    updated_comp = add(comp, obs)
    logweight += marginal_log_lhood(add(comp, obs))

    return PutativeParticle(p, obs, state, updated_comp, exp(logweight))

end

"""
    instantiate(p::PutativeParticle)

Do all the bookkeeping necessary to convert a `PutativeParticle` into a real one:

* update the state prior
* update the vector of components

Both of these require copying vectors (of counts for most of the state priors,
and of components) to make minor updates, and are only necessary if a particle
is accepted, hence separating the creation of the putative particle and
instantiating/accepting it.
"""
instantiate(putative::PutativeParticle{<:InfiniteParticle}) =
    instantiate(putative, putative.weight)

function instantiate(putative::PutativeParticle{<:InfiniteParticle}, weight)
    p = putative.ancestor
    stateprior, comp_i = add(p.stateprior, putative.state)
    0 < comp_i ≤ length(p.components)+1 ||
        throw(ArgumentError("can't fit component $comp_i: must be between 0 and " *
                            "$(length(p.components)+1)"))

    components = copy(p.components)
    if comp_i > length(components)
        push!(components, putative.updated_comp)
    else
        components[comp_i] = putative.updated_comp
    end

    return InfiniteParticle(components, p, comp_i, weight, p.prior, stateprior)
end

instantiate(p::AbstractParticle) = p
instantiate(p::AbstractParticle, w::Float64) = weight(p, w)

fit(p::InfiniteParticle, y, x) = instantiate(PutativeParticle(p, y, x))

Distributions.components(p::InfiniteParticle) = [p.components..., p.prior]
Distributions.ncomponents(p::InfiniteParticle, includeprior::Bool=false) =
    length(p.components) + includeprior

weights(p::InfiniteParticle) = exp.(log_prior(p.stateprior))

state_entropy(p::InfiniteParticle) = entropy(p.stateprior)

"""
    posterior_predictive(p::P) where P<:AbstractParticle

Get the posterior predictive distribution for a particle, which is a mixture of
the posterior predictives for each component (including the prior, for an
`InfiniteParticle`).
"""
posterior_predictive(p::P) where P<:AbstractParticle =
    MixtureModel(posterior_predictive.(components(p)), weights(p))

"""
    marginal_posterior(p::AbstractParticle)

The (unnormalized) posterior probability of the parameters in `p` given the data
`fit!` by it thus far.
"""
marginal_posterior(p::AbstractParticle) = exp(marginal_log_posterior(p))

marginal_log_posterior(p::InfiniteParticle) =
    sum(marginal_log_lhood(c) for c in components(p)) + marginal_log_prior(p.stateprior)

# TODO: normalize clusters (sort based on mean, and re-write assignments, or
# provide a view...


text:
function plot_walls!(bt::Billiard{T}) where {T<:AbstractFloat}
    for wall in bt
        xs = [wall.sp[1], wall.ep[1]]
        ys = [wall.sp[2], wall.ep[2]]
        if typeof(wall) <: VirtualGate
            color = wall.color
            alpha = 0.3
            lw = 5.0
        else
            color = :black
            alpha = 1.0
            lw = 2.0
        end
        plot!(xs, ys,
            linealpha = alpha,
            linewidth = lw,
            linecolor = color)
    end
end

function plot_agent!(agent::Agent{T}) where {T<:AbstractFloat}
    xs = [agent.p.pos[1]]
    ys = [agent.p.pos[2]]
    scatter!(xs, ys,
        marker = (6,0.1,:brown,stroke(1.0)))
end

function plot_map(agt::Vector, bt::Billiard{T}) where {T<:AbstractFloat}
    plot()
    plot_walls!(bt)
    # Plot particle
    for i = 1:length(agt)
        plot_agent!(agt[i])
    end
    plot!(aspect_ratio=:equal, grid=:false, axis=:false, legend=:false)
end

max_stars_repo_name: gbarsih/Representations-in-Robotics

max_issues_repo_name: gbarsih/Representations-in-Robotics

max_forks_repo_name: gbarsih/Representations-in-Robotics


text:
type RectangleShape <: Drawable
    ptr::Ptr{Void}
    _texture::Texture

    function RectangleShape(ptr::Ptr{Void})
        r = new(ptr)
        finalizer(r, destroy)
        r
    end
end

function RectangleShape()
    RectangleShape(ccall((:sfRectangleShape_create, libcsfml_graphics), Ptr{Void}, ()))
end

function copy(shape::RectangleShape)
    return RectangleShape(ccall((:sfRectangleShape_copy, libcsfml_graphics), Ptr{Void}, (Ptr{Void},), shape.ptr))
end

function destroy(shape::RectangleShape)
    ccall((:sfRectangleShape_destroy, libcsfml_graphics), Void, (Ptr{Void},), shape.ptr)
end

function set_position(shape::RectangleShape, position::Vector2f)
    ccall((:sfRectangleShape_setPosition, libcsfml_graphics), Void, (Ptr{Void}, Vector2f,), shape.ptr, position)
end

function set_rotation(shape::RectangleShape, angle::Real)
    ccall((:sfRectangleShape_setRotation, libcsfml_graphics), Void, (Ptr{Void}, Cfloat), shape.ptr, angle)
end

function set_scale(shape::RectangleShape, scale::Vector2f)
    ccall((:sfRectangleShape_setScale, libcsfml_graphics), Void, (Ptr{Void}, Vector2f,), shape.ptr, scale)
end

function set_origin(shape::RectangleShape, origin::Vector2f)
    ccall((:sfRectangleShape_setOrigin, libcsfml_graphics), Void, (Ptr{Void}, Vector2f,), shape.ptr, origin)
end

function set_size(shape::RectangleShape, size::Vector2f)
    ccall((:sfRectangleShape_setSize, libcsfml_graphics), Void, (Ptr{Void}, Vector2f,), shape.ptr, size)
end

function set_fillcolor(shape::RectangleShape, color::Color)
    ccall((:sfRectangleShape_setFillColor, libcsfml_graphics), Void, (Ptr{Void}, Color,), shape.ptr, color)
end

function set_texture(shape::RectangleShape, texture::Texture)
    ccall((:sfRectangleShape_setTexture, libcsfml_graphics), Void, (Ptr{Void}, Ptr{Void}, Int32,), shape.ptr, texture.ptr, false)
    shape._texture = texture
end

function set_texture_rect(shape::RectangleShape, rect::IntRect)
    ccall((:sfRectangleShape_setTextureRect, libcsfml_graphics), Void, (Ptr{Void}, IntRect,), shape.ptr, rect)
end

function set_outlinecolor(shape::RectangleShape, color::Color)
    ccall((:sfRectangleShape_setOutlineColor, libcsfml_graphics), Void, (Ptr{Void}, Color,), shape.ptr, color)
end

function set_outline_thickness(shape::RectangleShape, thickness::Real)
    ccall((:sfRectangleShape_setOutlineThickness, libcsfml_graphics), Void, (Ptr{Void}, Cfloat,), shape.ptr, thickness)
end

function get_position(shape::RectangleShape)
    return ccall((:sfRectangleShape_getPosition, libcsfml_graphics), Vector2f, (Ptr{Void},), shape.ptr)
end

function get_origin(shape::RectangleShape)
    ccall((:sfRectangleShape_getOrigin, libcsfml_graphics), Vector2f, (Ptr{Void},), shape.ptr)
end

function get_rotation(shape::RectangleShape)
    ccall((:sfRectangleShape_getRotation, libcsfml_graphics), Cfloat, (Ptr{Void},), shape.ptr)
end

function get_scale(shape::RectangleShape)
    ccall((:sfRectangleShape_getScale, libcsfml_graphics), Vector2f, (Ptr{Void},), shape.ptr)
end

function get_size(shape::RectangleShape)
    ccall((:sfRectangleShape_getSize, libcsfml_graphics), Vector2f, (Ptr{Void},), shape.ptr)
end

function get_fillcolor(shape::RectangleShape)
    ccall((:sfRectangleShape_getFillColor, libcsfml_graphics), Color, (Ptr{Void},), shape.ptr)
end

function get_outlinecolor(shape::RectangleShape)
    ccall((:sfRectangleShape_getOutlineColor, libcsfml_graphics), Color, (Ptr{Void},), shape.ptr)
end

function get_outline_thickness(shape::RectangleShape)
    ccall((:sfRectangleShape_getOutlineThickness, libcsfml_graphics), Cfloat, (Ptr{Void},), shape.ptr)
end

function move(shape::RectangleShape, offset::Vector2f)
    ccall((:sfRectangleShape_move, libcsfml_graphics), Void, (Ptr{Void}, Vector2f,), shape.ptr, offset)
end

function rotate(shape::RectangleShape, angle::Real)
    ccall((:sfRectangleShape_rotate, libcsfml_graphics), Void, (Ptr{Void}, Cfloat,), shape.ptr, angle)
end

function scale(shape::RectangleShape, factors::Vector2f)
    ccall((:sfRectangleShape_scale, libcsfml_graphics), Void, (Ptr{Void}, Vector2f,), shape.ptr, factors)
end

function get_texture(shape::RectangleShape)
    Texture(ccall((:sfRectangleShape_getTexture, libcsfml_graphics), Ptr{Void}, (Ptr{Void},), shape.ptr))
end

function get_texture_rect(shape::RectangleShape)
    ccall((:sfRectangleShape_getTextureRect, libcsfml_graphics), IntRect, (Ptr{Void},), shape.ptr)
end

function get_localbounds(shape::RectangleShape)
    ccall((:sfRectangleShape_getLocalBounds, libcsfml_graphics), FloatRect, (Ptr{Void},), shape.ptr)
end

function get_globalbounds(shape::RectangleShape)
    ccall((:sfRectangleShape_getGlobalBounds, libcsfml_graphics), FloatRect, (Ptr{Void},), shape.ptr)
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"""Node affinity is a group of node affinity scheduling rules.

    IoK8sApiCoreV1NodeAffinity(;
        preferredDuringSchedulingIgnoredDuringExecution=nothing,
        requiredDuringSchedulingIgnoredDuringExecution=nothing,
    )

    - preferredDuringSchedulingIgnoredDuringExecution::Vector{IoK8sApiCoreV1PreferredSchedulingTerm} : The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most preferred.
    - requiredDuringSchedulingIgnoredDuringExecution::IoK8sApiCoreV1NodeSelector : If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node.
"""
mutable struct IoK8sApiCoreV1NodeAffinity <: SwaggerModel
    preferredDuringSchedulingIgnoredDuringExecution::Any # spec type: Union{ Nothing, Vector{IoK8sApiCoreV1PreferredSchedulingTerm} } # spec name: preferredDuringSchedulingIgnoredDuringExecution
    requiredDuringSchedulingIgnoredDuringExecution::Any # spec type: Union{ Nothing, IoK8sApiCoreV1NodeSelector } # spec name: requiredDuringSchedulingIgnoredDuringExecution

    function IoK8sApiCoreV1NodeAffinity(;preferredDuringSchedulingIgnoredDuringExecution=nothing, requiredDuringSchedulingIgnoredDuringExecution=nothing)
        o = new()
        validate_property(IoK8sApiCoreV1NodeAffinity, Symbol("preferredDuringSchedulingIgnoredDuringExecution"), preferredDuringSchedulingIgnoredDuringExecution)
        setfield!(o, Symbol("preferredDuringSchedulingIgnoredDuringExecution"), preferredDuringSchedulingIgnoredDuringExecution)
        validate_property(IoK8sApiCoreV1NodeAffinity, Symbol("requiredDuringSchedulingIgnoredDuringExecution"), requiredDuringSchedulingIgnoredDuringExecution)
        setfield!(o, Symbol("requiredDuringSchedulingIgnoredDuringExecution"), requiredDuringSchedulingIgnoredDuringExecution)
        o
    end
end # type IoK8sApiCoreV1NodeAffinity

const _property_map_IoK8sApiCoreV1NodeAffinity = Dict{Symbol,Symbol}(Symbol("preferredDuringSchedulingIgnoredDuringExecution")=>Symbol("preferredDuringSchedulingIgnoredDuringExecution"), Symbol("requiredDuringSchedulingIgnoredDuringExecution")=>Symbol("requiredDuringSchedulingIgnoredDuringExecution"))
const _property_types_IoK8sApiCoreV1NodeAffinity = Dict{Symbol,String}(Symbol("preferredDuringSchedulingIgnoredDuringExecution")=>"Vector{IoK8sApiCoreV1PreferredSchedulingTerm}", Symbol("requiredDuringSchedulingIgnoredDuringExecution")=>"IoK8sApiCoreV1NodeSelector")
Base.propertynames(::Type{ IoK8sApiCoreV1NodeAffinity }) = collect(keys(_property_map_IoK8sApiCoreV1NodeAffinity))
Swagger.property_type(::Type{ IoK8sApiCoreV1NodeAffinity }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiCoreV1NodeAffinity[name]))}
Swagger.field_name(::Type{ IoK8sApiCoreV1NodeAffinity }, property_name::Symbol) =  _property_map_IoK8sApiCoreV1NodeAffinity[property_name]

function check_required(o::IoK8sApiCoreV1NodeAffinity)
    true
end

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


text:
# Autogenerated wrapper script for PROJ_jll for aarch64-linux-musl-cxx03
export cct, ch, cs2cs, geod, gie, gl27, itrf2000, itrf2008, itrf2014, libproj, nad27, nad83, nad_lst, other_extra, proj, proj_db, proj_ini, projinfo, projsync, world

using SQLite_jll
using Libtiff_jll
using Zlib_jll
using LibCURL_jll
using LibSSH2_jll
using MbedTLS_jll
using nghttp2_jll
JLLWrappers.@generate_wrapper_header("PROJ")
JLLWrappers.@declare_executable_product(cct)
JLLWrappers.@declare_file_product(ch)
JLLWrappers.@declare_executable_product(cs2cs)
JLLWrappers.@declare_executable_product(geod)
JLLWrappers.@declare_executable_product(gie)
JLLWrappers.@declare_file_product(gl27)
JLLWrappers.@declare_file_product(itrf2000)
JLLWrappers.@declare_file_product(itrf2008)
JLLWrappers.@declare_file_product(itrf2014)
JLLWrappers.@declare_library_product(libproj, "libproj.so.19")
JLLWrappers.@declare_file_product(nad27)
JLLWrappers.@declare_file_product(nad83)
JLLWrappers.@declare_file_product(nad_lst)
JLLWrappers.@declare_file_product(other_extra)
JLLWrappers.@declare_executable_product(proj)
JLLWrappers.@declare_file_product(proj_db)
JLLWrappers.@declare_file_product(proj_ini)
JLLWrappers.@declare_executable_product(projinfo)
JLLWrappers.@declare_executable_product(projsync)
JLLWrappers.@declare_file_product(world)
function __init__()
    JLLWrappers.@generate_init_header(SQLite_jll, Libtiff_jll, Zlib_jll, LibCURL_jll, LibSSH2_jll, MbedTLS_jll, nghttp2_jll)
    JLLWrappers.@init_executable_product(
        cct,
        "bin/cct",
    )

    JLLWrappers.@init_file_product(
        ch,
        "share/proj/CH",
    )

    JLLWrappers.@init_executable_product(
        cs2cs,
        "bin/cs2cs",
    )

    JLLWrappers.@init_executable_product(
        geod,
        "bin/geod",
    )

    JLLWrappers.@init_executable_product(
        gie,
        "bin/gie",
    )

    JLLWrappers.@init_file_product(
        gl27,
        "share/proj/GL27",
    )

    JLLWrappers.@init_file_product(
        itrf2000,
        "share/proj/ITRF2000",
    )

    JLLWrappers.@init_file_product(
        itrf2008,
        "share/proj/ITRF2008",
    )

    JLLWrappers.@init_file_product(
        itrf2014,
        "share/proj/ITRF2014",
    )

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

    JLLWrappers.@init_file_product(
        nad27,
        "share/proj/nad27",
    )

    JLLWrappers.@init_file_product(
        nad83,
        "share/proj/nad83",
    )

    JLLWrappers.@init_file_product(
        nad_lst,
        "share/proj/nad.lst",
    )

    JLLWrappers.@init_file_product(
        other_extra,
        "share/proj/other.extra",
    )

    JLLWrappers.@init_executable_product(
        proj,
        "bin/proj",
    )

    JLLWrappers.@init_file_product(
        proj_db,
        "share/proj/proj.db",
    )

    JLLWrappers.@init_file_product(
        proj_ini,
        "share/proj/proj.ini",
    )

    JLLWrappers.@init_executable_product(
        projinfo,
        "bin/projinfo",
    )

    JLLWrappers.@init_executable_product(
        projsync,
        "bin/projsync",
    )

    JLLWrappers.@init_file_product(
        world,
        "share/proj/world",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
@testset "Domain2MILP: $(fct_type), dimension $(dim), $(n_values) values, $(T)" for fct_type in ["single variable", "scalar affine function"], dim in [2, 3], n_values in [2, 3], T in [Int, Float64]
    mock = MOIU.MockOptimizer(MILPModel{T}())
    model = COIB.Domain2MILP{T}(mock)

    if T == Int
        @test MOI.supports_constraint(model, MOI.VariableIndex, MOI.Integer)
    end
    @test MOI.supports_constraint(model, MOI.VariableIndex, MOI.ZeroOne)
    @test MOI.supports_constraint(
        model,
        MOI.ScalarAffineFunction{T},
        MOI.EqualTo{T},
    )
    @test MOIB.supports_bridging_constraint(
        model,
        MOI.ScalarAffineFunction{T},
        CP.Domain{T},
    )
    @test MOIB.supports_bridging_constraint(
        model,
        MOI.VariableIndex,
        CP.Domain{T},
    )

    if T == Int
        x, _ = MOI.add_constrained_variable(model, MOI.Integer())
    elseif T == Float64
        x = MOI.add_variable(model)
    end
    x_values = Set(
        T(i)
        for i in 1:n_values
    )
    x_vector = collect(x_values) # Use collect() to get the same order as in the bridge.

    fct = if fct_type == "single variable"
        x
    elseif fct_type == "scalar affine function"
        one(T) * x
    else
        @assert false
    end
    c = MOI.add_constraint(model, fct, CP.Domain(x_values))

    @test MOI.is_valid(model, x)
    @test MOI.is_valid(model, c)

    bridge = first(MOIBC.bridges(model))[2]

    @testset "Bridge properties" begin
        @test MOIBC.concrete_bridge_type(typeof(bridge), MOI.VariableIndex, CP.Domain{T}) == typeof(bridge)
        @test MOIB.added_constrained_variable_types(typeof(bridge)) == [(MOI.ZeroOne,)]
        @test MOIB.added_constraint_types(typeof(bridge)) == [
            (MOI.ScalarAffineFunction{T}, MOI.EqualTo{T}),
        ]

        @test MOI.get(bridge, MOI.NumberOfVariables()) == n_values
        @test MOI.get(bridge, MOI.NumberOfConstraints{MOI.VariableIndex, MOI.ZeroOne}()) == n_values
        @test MOI.get(bridge, MOI.NumberOfConstraints{MOI.ScalarAffineFunction{T}, MOI.EqualTo{T}}()) == 2

        @test MOI.get(bridge, MOI.ListOfVariableIndices()) == bridge.vars
        @test MOI.get(bridge, MOI.ListOfConstraintIndices{MOI.VariableIndex, MOI.ZeroOne}()) == bridge.vars_bin
        @test MOI.get(bridge, MOI.ListOfConstraintIndices{MOI.ScalarAffineFunction{T}, MOI.EqualTo{T}}()) == [bridge.con_choose_one, bridge.con_value]
    end

    @testset "New variables" begin
        @test length(bridge.vars) == n_values
        @test length(bridge.vars_bin) == n_values

        for i in 1:n_values
            @test MOI.is_valid(model, bridge.vars[i])
            @test MOI.is_valid(model, bridge.vars_bin[i])
            @test MOI.get(model, MOI.ConstraintFunction(), bridge.vars_bin[i]) == bridge.vars[i]
            @test MOI.get(model, MOI.ConstraintSet(), bridge.vars_bin[i]) == MOI.ZeroOne()
        end
    end

    @testset "Choose one" begin
        @test MOI.is_valid(model, bridge.con_choose_one)
        @test MOI.get(model, MOI.ConstraintSet(), bridge.con_choose_one) == MOI.EqualTo(one(T))

        f = MOI.get(model, MOI.ConstraintFunction(), bridge.con_choose_one)
        @test length(f.terms) == n_values
        @test f.constant === zero(T)

        for i in 1:n_values
            t = f.terms[i]
            @test t.coefficient === one(T)
            @test t.variable == bridge.vars[i]
        end
    end

    @testset "Value" begin
        @test MOI.is_valid(model, bridge.con_value)
        @test MOI.get(model, MOI.ConstraintSet(), bridge.con_value) == MOI.EqualTo(zero(T))

        f = MOI.get(model, MOI.ConstraintFunction(), bridge.con_value)
        @test length(f.terms) == 1 + n_values
        @test f.constant === zero(T)

        t1 = f.terms[1]
        @test t1.coefficient === one(T)
        @test t1.variable == x

        for j in 1:n_values
            t = f.terms[1 + j]
            @test t.coefficient === -x_vector[j]
            @test t.variable == bridge.vars[j]
        end
    end
end


text:
## read the soundings
using PyPlot, Revise, transD_GP
soundings = transD_GP.TEMPEST1DInversion.read_survey_files(
	fname_dat= "91010901.asc",
	fname_specs_halt="electronics_halt.jl",
	frame_height = 20,
	frame_dz = 32,
	frame_dx = 30,
	frame_dy = 31,
	Hxs = [37, 51],
	Hzs = [76, 90],
	Hxp = 70,
	Hzp = 109,
	units = 1e-15,
	yaw_rx = 35,
	pitch_rx = 33,
	roll_rx = 34,
	yaw_tx = 23,
	pitch_tx = 21,
	roll_tx = 22,
	X = 12,
	Y = 13,
	Z = 18,
	fid = 3,
	startfrom = 1,
	skipevery = 2,
	linenum = 1,
	makesounding=true)


text:
module TestGemv
using ParallelAccelerator

@acc gemv_t(A,y) = A*y
@acc gemv_t2(A,y) = A'*y

function test()
    A = [1. 2. 3.; 4. 5. 6.]
    y = [1.,2.,3.]
    y2 = [1.,2.]
    z = gemv_t(A,y)
    return z
end

function test2()
    A = [1. 2. 3.; 4. 5. 6.]
    y = [1.,2.]
    z = gemv_t2(A,y)
    return z
end

end

using Base.Test
println("testing gemv...")
@test_approx_eq TestGemv.test() [14.0,32.0]
@test_approx_eq TestGemv.test2() [9.0,12.0,15.0]
println("Done testing gemv.")


text:
using DataFrames, DataFramesMeta, Statistics
using PyPlot, CSV

# Top-level functions to process dataframe files (outputs of simulations)
# in order to create the csv data for the plots

# ------------------------------------------------------------------------------
# For Figure 5
function run_process_M(;
                        filepath = "/path/to/jldfiles_FINAL_MULTI/",
                        stochasticities = [5., 2., 1., 0.25, 0.14, 0.1, 0.01],
                        changeprobabilities = [0.1, 0.05, 0.01, 0.005, 0.001, 0.0001]
                        )

    dfall = df_loadseparately(filepath = filepath)
    settings = collect(Iterators.product(stochasticities, changeprobabilities))
    for setting in settings
        process_M_csv(dfall, setting[1], setting[2])
    end
end
function process_M_csv(dfall, stochvalue, changeprobabilityvalue;
                    savepath = homedir())
   dfresults = DataFrame()
   for i in 1:length(dfall)
       dftrimmed = df_trim(dfall[i], stochvalue, changeprobabilityvalue)
       learnername, learnerparam = df_getlearnerinfo(dftrimmed)
       learnerparam = formatparamlist(learnerparam)
       merrswitches, stderrswitches, stderrorrerrswitches = df_meanerrorsafterswitches(dftrimmed)
       if i==1
           dfresults[:x] = collect(1:length(merrswitches))
       end
       dfresults[Symbol(learnername*"_mean")] = merrswitches
       dfresults[Symbol(learnername*"_std")] = stderrswitches
       dfresults[Symbol(learnername*"_se")] = stderrorrerrswitches
    end
    CSV.write(joinpath(savepath, "multi_s"* string(stochvalue) * "_Pc" *string(changeprobabilityvalue)*".csv"),
        dfresults, delim = " ")
end
# ------------------------------------------------------------------------------
# For Figure 2
function run_process_G(;
                        filepath = "/path/to/jldfiles_FINAL_GAUSSIAN/",
                        sigmas = [5., 2., 1., 0.5, 0.1],
                        changeprobabilities = [0.1, 0.05, 0.01, 0.005, 0.001, 0.0001]
                        )
    dfall = df_loadseparately(filepath = filepath)
    settings = collect(Iterators.product(sigmas, changeprobabilities))
    for setting in settings
        process_G_csv(dfall, setting[1], setting[2])
    end
end
function process_G_csv(dfall, stochvalue, changeprobabilityvalue;
                    savepath = homedir())
   dfresults = DataFrame()
   for i in 1:length(dfall)
       dftrimmed = df_trim(dfall[i], stochvalue, changeprobabilityvalue)
       learnername, learnerparam = df_getlearnerinfo(dftrimmed)
       learnerparam = formatparamlist(learnerparam)
       merrswitches, stderrswitches, stderrorrerrswitches = df_meanerrorsafterswitches(dftrimmed)
       if i==1
           dfresults[:x] = collect(1:length(merrswitches))
       end
       dfresults[Symbol(learnername*"_mean")] = merrswitches
       dfresults[Symbol(learnername*"_std")] = stderrswitches
       dfresults[Symbol(learnername*"_se")] = stderrorrerrswitches
    end
    CSV.write(joinpath(savepath, "gaussian_s"* string(stochvalue) * "_Pc" *string(changeprobabilityvalue)*".csv"), dfresults,
        delim = " ")
end
# ------------------------------------------------------------------------------
# For Figure 6 and Figure 7
function process_heatmap_M(;savepath = homedir(),
                        filepath = "/path/to/jldfiles_FINAL_MULTI/",
                        )
    dfall = df_loadcat(filepath = filepath)
    #runmakeheatmap_csv(dfall, savepath, prefix = "multi_")
    #runmakeheatmap_diff(dfall, savepath)
    # runmakeheatmap_diff_csv(dfall, savepath, prefix = "multi_")
    runmakeheatmap_diff_stats_nonindependent_csv(dfall, savepath, prefix = "multi_")
end
# ------------------------------------------------------------------------------
# For Figure 3 and Figure 4
function process_heatmap_G(;savepath = homedir(),
                        filepath = "/path/to/jldfiles_FINAL_GAUSSIAN/",
                        )
    dfall = df_loadcat(filepath = filepath)
    #runmakeheatmap_csv(dfall, savepath, prefix = "gaussian_")
    #runmakeheatmap_diff(dfall, savepath)
    # runmakeheatmap_diff_csv(dfall, savepath, prefix = "gaussian_")
    runmakeheatmap_diff_stats_nonindependent_csv(dfall, savepath, prefix = "gaussian_")
end

# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# --------- Not used eventually for the paper, only for inspection -------------
function process_M_fig(dfall, stochvalue, changeprobabilityvalue;
                    savepath = homedir())
   # clist = [cmap(i) for i in range(0., 1., length = length(jldfiles)+1)]
   clist = clisthardcodedM()
   fig = figure(); ax = gca()
   for i in 1:length(dfall)
       dftrimmed = df_trim(dfall[i], stochvalue, changeprobabilityvalue)
       learnername, learnerparam = df_getlearnerinfo(dftrimmed)
       learnerparam = formatparamlist(learnerparam)
       merrswitches, stderrswitches, stderrorrerrswitches = df_meanerrorsafterswitches(dftrimmed)
       plot_shadedline_core(merrswitches, stderrorrerrswitches,
                    learnername*"_"*string(learnerparam), clist[i], ax)
   end
   ax.legend(); ax.set_yscale("log")
   title("Mean error after switch - " * "stoch: " * string(stochvalue)
        * " , Pc: " * string(changeprobabilityvalue))
    PyPlot.savefig(joinpath(savepath,
            "multi_s"* string(stochvalue) * "_Pc" *string(changeprobabilityvalue)*".png"))
    PyPlot.close()
end
function process_G_fig(dfall, sigmavalue, changeprobabilityvalue;
                    savepath = homedir())
   clist = clisthardcodedG()
   fig = figure(); ax = gca()
   for i in 1:length(dfall)
       dftrimmed = df_trim(dfall[i], sigmavalue, changeprobabilityvalue)
       learnername, learnerparam = df_getlearnerinfo(dftrimmed)
       learnerparam = formatparamlist(learnerparam)
       merrswitches, stderrswitches, stderrorrerrswitches = df_meanerrorsafterswitches(dftrimmed)
       plot_shadedline_core(merrswitches, stderrorrerrswitches,
                    learnername*"_"*string(learnerparam), clist[i], ax)
   end
   ax.legend(); ax.set_yscale("log")
   title("Mean error after switch - " * "sigma: " * string(sigmavalue)
        * " , Pc: " * string(changeprobabilityvalue))
    PyPlot.savefig(joinpath(savepath,
            "gauss_s"* string(sigmavalue) * "_Pc" *string(changeprobabilityvalue)*".png"))
    PyPlot.close()
end


text:
using PackageCompiler
using MKL_jll

# if no environment variable ENV["USE_BLAS64"] is set install.jl
# tries to change USE_BLAS64 = false
const USEBLAS64 = parse(Bool,get(ENV, "USE_BLAS64","false"))

include("../src/install.jl")
enable_mkl_startup()


text:
function uri2filepath(uri::AbstractString)
    uri_path = normpath(URIParser.unescape(URIParser.URI(uri).path))

    if Sys.iswindows()
        if uri_path[1] == '\\' || uri_path[1] == '/'
            uri_path = uri_path[2:end]
        end
    end
    return uri_path
end

function filepath2uri(file::String)
    if Sys.iswindows()
        file = normpath(file)
        file = replace(file, "\\" => "/")
        file = URIParser.escape(file)
        file = replace(file, "%2F" => "/")
        return string("file:///", file)
    else
        file = normpath(file)
        file = URIParser.escape(file)
        file = replace(file, "%2F" => "/")
        return string("file://", file)
    end
end

function should_file_be_linted(uri, server)
    !server.runlinter && return false

    uri_path = uri2filepath(uri)

    if length(server.workspaceFolders)==0
        return false
    else
        return any(i->startswith(uri_path, i), server.workspaceFolders)
    end
end

# CompletionItemKind(t) = t in [:String, :AbstractString] ? 1 :
#                                 t == :Function ? 3 :
#                                 t == :DataType ? 7 :
#                                 t == :Module ? 9 : 6

# SymbolKind(t) = t in [:String, :AbstractString] ? 15 :
#                         t == :Function ? 12 :
#                         t == :DataType ? 5 :
#                         t == :Module ? 2 :
#                         t == :Bool ? 17 : 13

# Find location of default datatype constructor
const DefaultTypeConstructorLoc= let def = first(methods(Int))
    Base.find_source_file(string(def.file)), def.line
end

function is_ignored(uri, server)
    fpath = uri2filepath(uri)
    fpath in server.ignorelist && return true
    for ig in server.ignorelist
        if !endswith(ig, ".jl")
            if startswith(fpath, ig)
                return true
            end
        end
    end
    return false
end

is_ignored(uri::URI2, server) = is_ignored(uri._uri, server)

# TODO I believe this will also remove files from documents that were added
# not because they are part of the workspace, but by either StaticLint or
# the include follow logic.
function remove_workspace_files(root, server)
    for (uri, doc) in getdocuments_pair(server)
        fpath = uri2filepath(uri._uri)
        get_open_in_editor(doc) && continue
        for folder in server.workspaceFolders
            if startswith(fpath, folder)
                continue
            end
            deletedocument!(server, uri)
        end
    end
end

function Base.getindex(server::LanguageServerInstance, r::Regex)
    out = []
    for (uri,doc) in getdocuments_pair(server)
        occursin(r, uri._uri) && push!(out, doc)
    end
    return out
end

function _offset_unitrange(r::UnitRange{Int}, first = true)
    return r.start-1:r.stop
end

function get_toks(doc, offset)
    ts = CSTParser.Tokenize.tokenize(get_text(doc))
    ppt = CSTParser.Tokens.RawToken(CSTParser.Tokens.ERROR, (0,0), (0,0), 1, 0, CSTParser.Tokens.NO_ERR, false, false)
    pt = CSTParser.Tokens.RawToken(CSTParser.Tokens.ERROR, (0,0), (0,0), 1, 0, CSTParser.Tokens.NO_ERR, false, false)
    t = CSTParser.Tokenize.Lexers.next_token(ts)

    while t.kind != CSTParser.Tokenize.Tokens.ENDMARKER
        if t.startbyte < offset <= t.endbyte + 1
            break
        end
        ppt = pt
        pt = t
        t = CSTParser.Tokenize.Lexers.next_token(ts)
    end
    return ppt, pt, t
end

function isvalidjlfile(path)
    hasreadperm(path) &&
    isfile(path) &&
    endswith(path, ".jl") &&
    validchars(path)
end

function validchars(path)
    io = open(path)
    while !eof(io)
        c = read(io, Char)
        Base.ismalformed(c) && return false
    end
    close(io)
    return true
end

function get_expr(x, offset, pos = 0, ignorewhitespace = false)
    if pos > offset
        return nothing
    end
    if x.args !== nothing && typof(x) !== CSTParser.NONSTDIDENTIFIER
        for a in x.args
            if pos < offset <= (pos + a.fullspan)
                return get_expr(a, offset, pos, ignorewhitespace)
            end
            pos += a.fullspan
        end
    elseif pos == 0
        return x
    elseif (pos < offset <= (pos + x.fullspan))
        ignorewhitespace && pos + x.span < offset && return nothing
        return x
    end
end

function get_expr(x, offset::UnitRange{Int}, pos = 0, ignorewhitespace = false)
    if all(pos .> offset)
        return nothing
    end
    if x.args !== nothing && typof(x) !== CSTParser.NONSTDIDENTIFIER
        for a in x.args
            if all(pos .< offset .<= (pos + a.fullspan))
                return get_expr(a, offset, pos, ignorewhitespace)
            end
            pos += a.fullspan
        end
    elseif pos == 0
        return x
    elseif all(pos .< offset .<= (pos + x.fullspan))
        ignorewhitespace && all(pos + x.span .< offset) && return nothing
        return x
    end
    pos -= x.fullspan
    if all(pos .< offset .<= (pos + x.fullspan))
        ignorewhitespace && all(pos + x.span .< offset) && return nothing
        return x
    end
end

function get_expr1(x, offset, pos = 0)
    if x.args === nothing || isempty(x.args) || typof(x) === CSTParser.NONSTDIDENTIFIER
        if pos <= offset <= pos + x.span
            return x
        else
            return nothing
        end
    else
        for i = 1:length(x.args)
            arg = x.args[i]
            if pos < offset < (pos + arg.span) # def within span
                return get_expr1(arg, offset, pos)
            elseif arg.span == arg.fullspan
                if offset == pos
                    if i == 1
                        return get_expr1(arg, offset, pos)
                    elseif CSTParser.typof(x.args[i-1]) === CSTParser.IDENTIFIER
                        return get_expr1(x.args[i-1], offset, pos)
                    else
                        return get_expr1(arg, offset, pos)
                    end
                elseif i == length(x.args) # offset == pos + arg.fullspan
                    return get_expr1(arg, offset, pos)
                end
            else
                if offset == pos
                    if i == 1
                        return get_expr1(arg, offset, pos)
                    elseif CSTParser.typof(x.args[i-1]) === CSTParser.IDENTIFIER
                        return get_expr1(x.args[i-1], offset, pos)
                    else
                        return get_expr1(arg, offset, pos)
                    end
                elseif offset == pos + arg.span
                    return get_expr1(arg, offset, pos)
                elseif offset == pos + arg.fullspan
                elseif pos+arg.span < offset < pos + arg.fullspan
                    return nothing
                end
            end
            pos += arg.fullspan
        end
        return nothing
    end
end

function get_identifier(x, offset, pos = 0)
    if pos > offset
        return nothing
    end
    if x.args !== nothing
        for a in x.args
            if pos <= offset <= (pos + a.span)
                return get_identifier(a, offset, pos)
            end
            pos += a.fullspan
        end
    elseif typof(x) === CSTParser.IDENTIFIER && (pos <= offset <= (pos + x.span)) || pos == 0
        return x
    end
end

@static if Sys.iswindows() && VERSION < v"1.3"
    function _splitdir_nodrive(a::String, b::String)
        m = match(r"^(.*?)([/\\]+)([^/\\]*)$",b)
        m === nothing && return (a,b)
        a = string(a, isempty(m.captures[1]) ? m.captures[2][1] : m.captures[1])
        a, String(m.captures[3])
    end
    function _dirname(path::String)
        m = match(r"^([^\\]+:|\\\\[^\\]+\\[^\\]+|\\\\\?\\UNC\\[^\\]+\\[^\\]+|\\\\\?\\[^\\]+:|)(.*)$"s, path)
        a, b = String(m.captures[1]), String(m.captures[2])
        _splitdir_nodrive(a,b)[1]
    end
else
    _dirname = dirname
end

function valid_id(s::String)
    !isempty(s) && all(i == 1 ? Base.is_id_start_char(c) : Base.is_id_char(c) for (i,c) in enumerate(s))
end

function sanitize_docstring(doc::String)
    doc = replace(doc, "```jldoctest"=>"```julia")
    doc = replace(doc,"\n#"=>"\n###")
    return doc
end