text:
"""
Cumulative Distribution Function of a Standard Gaussian Random Variable

		y=normcdf(x)

Where:\n
		x         = point of evaluation.

		y      = probability that a standard gaussian random variable is below x.

# Example
```julia-repl
julia> normcdf(0.0)
0.5
```
"""
function normcdf(x::number) where {number <: Number}
    return (1.0 + erf(x / sqrt(2.0))) / 2.0
end

"""
Probability Distribution Function of a Standard Gaussian Random Variable

		y=normpdf(x)

Where:\n
		x         = point of evaluation.

		y      = value.

# Example
```julia-repl
julia> normpdf(0.0)
0.3989422804014327
```
"""
function normpdf(x::number) where {number <: Number}
    return exp(-0.5 * x .^ 2) / sqrt(2 * pi)
end

"""
Black & Scholes Price for European Options

		Price=blsprice(S0,K,r,T,σ,d=0.0,FlagIsCall=true)

Where:\n
		S0         = Value of the Underlying.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		σ          = Implied Volatility
		d          = Implied Dividend of the Underlying.
		FlagIsCall = true for Call Options, false for Put Options.

		Price      = price of the European Option.

# Example
```julia-repl
julia> blsprice(10.0,10.0,0.01,2.0,0.2,0.01)
1.1023600107733191
```
"""
function blsprice(S0::num1, K::num2, r::num3, T::num4, σ::num5, d::num6 = 0.0, FlagIsCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, num6 <: Number}
    blscheck(S0, K, r, T, σ, d)
    d1 = (log(S0 / K) + (r - d + σ * σ * 0.5) * T) / (σ * sqrt(T))
    d2 = d1 - σ * sqrt(T)
    N_d1 = normcdf(d1)
    N_d2 = normcdf(d2)
    Price = 0.0
    if FlagIsCall
        Price = S0 * exp(-d * T) * N_d1 - K * exp(-r * T) * N_d2
    else
        Price = K * exp(-r * T) * (1 - N_d2) - S0 * exp(-d * T) * (1 - N_d1)
    end
    return Price
end

"""
Black Price for European Options

		Price=blkprice(F0,K,r,T,σ,FlagIsCall=true)

Where:\n
		F0         = Value of the Forward.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		σ          = Implied Volatility.
		FlagIsCall = true for Call Options, false for Put Options.

		Price      = price of the European Option.

# Example
```julia-repl
julia> blkprice(10.0,10.0,0.01,2.0,0.2)
1.1023600107733191
```
"""
function blkprice(F0::num1, K::num2, r::num3, T::num4, σ::num5, FlagIsCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number}
    blscheck(F0, K, r, T, σ)
    Price = blsprice(F0, K, r, T, σ, r, FlagIsCall)
    return Price
end

"""
Black & Scholes Delta for European Options

		Δ=blsdelta(S0,K,r,T,σ,d=0.0,FlagIsCall=true)

Where:\n
		S0         = Value of the Underlying.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		σ          = Implied Volatility
		d          = Implied Dividend of the Underlying.
		FlagIsCall = true for Call Options, false for Put Options.

		Δ          = delta of the European Option.

# Example
```julia-repl
julia> blsdelta(10.0,10.0,0.01,2.0,0.2,0.01)
0.5452173371920436
```
"""
function blsdelta(S0::num1, K::num2, r::num3, T::num4, σ::num5, d::num6 = 0.0, FlagIsCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, num6 <: Number}
    blscheck(S0, K, r, T, σ, d)
    d1 = (log(S0 / K) + (r - d + σ * σ * 0.5) * T) / (σ * sqrt(T))
    Δ = 0.0
    if FlagIsCall
        Δ = exp(-d * T) * normcdf(d1)
    else
        Δ = -exp(-d * T) * normcdf(-d1)
    end
    return Δ
end

"""
Black & Scholes Gamma for European Options

		Γ=blsgamma(S0,K,r,T,σ,d=0.0,FlagIsCall=true)

Where:\n
		S0         = Value of the Underlying.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		σ          = Implied Volatility
		d          = Implied Dividend of the Underlying.
		FlagIsCall = true for Call Options, false for Put Options.

		Γ          = gamma of the European Option.

# Example
```julia-repl
julia> blsgamma(10.0,10.0,0.01,2.0,0.2,0.01)
0.13687881535712826
```
"""
function blsgamma(S0::num1, K::num2, r::num3, T::num4, σ::num5, d::num6 = 0.0, FlagIsCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, num6 <: Number}
    blscheck(S0, K, r, T, σ, d)
    d1 = (log(S0 / K) + (r - d + σ * σ * 0.5) * T) / (σ * sqrt(T))
    Γ = exp(-d * T) * normpdf(d1) / (S0 * σ * sqrt(T))
    return Γ
end

"""
Black & Scholes Vega for European Options

		ν=blsvega(S0,K,r,T,σ,d=0.0,FlagIsCall=true)

Where:\n
		S0         = Value of the Underlying.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		σ          = Implied Volatility
		d          = Implied Dividend of the Underlying.
		FlagIsCall = true for Call Options, false for Put Options.

		ν          = vega of the European Option.

# Example
```julia-repl
julia> blsvega(10.0,10.0,0.01,2.0,0.2,0.01)
5.475152614285131
```
"""
function blsvega(S0::num1, K::num2, r::num3, T::num4, σ::num5, d::num6 = 0.0, FlagIsCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, num6 <: Number}
    blscheck(S0, K, r, T, σ, d)
    d1 = (log(S0 / K) + (r - d + σ * σ * 0.5) * T) / (σ * sqrt(T))
    ν = S0 * exp(-d * T) * normpdf(d1) * sqrt(T)
    return ν
end

"""
Black & Scholes Rho for European Options

		ρ=blsrho(S0,K,r,T,σ,d=0.0,FlagIsCall=true)

Where:\n
		S0         = Value of the Underlying.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		σ          = Implied Volatility
		d          = Implied Dividend of the Underlying.
		FlagIsCall = true for Call Options, false for Put Options.

		ρ          = rho of the European Option.

# Example
```julia-repl
julia> blsrho(10.0,10.0,0.01,2.0,0.2,0.01)
8.699626722294234
```
"""
function blsrho(S0::num1, K::num2, r::num3, T::num4, σ::num5, d::num6 = 0.0, FlagIsCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, num6 <: Number}
    blscheck(S0, K, r, T, σ, d)
    d2 = (log(S0 / K) + (r - d - σ * σ * 0.5) * T) / (σ * sqrt(T))
    if FlagIsCall
        ρ = K * exp(-r * T) * normcdf(d2) * T
    else
        ρ = -K * exp(-r * T) * normcdf(-d2) * T
    end
    return ρ
end

"""
Black & Scholes Theta for European Options

		Θ=blstheta(S0,K,r,T,σ,d=0.0,FlagIsCall=true)

Where:\n
		S0         = Value of the Underlying.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		σ          = Implied Volatility
		d          = Implied Dividend of the Underlying.
		FlagIsCall = true for Call Options, false for Put Options.

		Θ          = theta of the European Option.

# Example
```julia-repl
julia> blstheta(10.0,10.0,0.01,2.0,0.2,0.01)
-0.26273403060652334
```
"""
function blstheta(S0::num1, K::num2, r::num3, T::num4, σ::num5, d::num6 = 0.0, FlagIsCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, num6 <: Number}
    blscheck(S0, K, r, T, σ, d)
    sqrtT = sqrt(T)
    σ_sqrtT = σ * sqrtT

    d1 = (log(S0 / K) + (r - d + σ .^ 2 / 2) * T) / σ_sqrtT

    shift = -exp(-d * T) * S0 * normpdf(d1) * σ / 2 / sqrtT
    t1 = r * K * exp(-r * T)
    t2 = d * S0 * exp(-d * T)
    Θ = 0.0
    if FlagIsCall
        Θ = shift - t1 * normcdf(d1 - σ_sqrtT) + t2 * normcdf(d1)
    else
        Θ = shift + t1 * (1 - normcdf(d1 - σ_sqrtT)) + t2 * (normcdf(d1) - 1)
    end
    return Θ
end

"""
Black & Scholes Lambda for European Options

		Λ=blslambda(S0,K,r,T,σ,d=0.0,FlagIsCall=true)

Where:\n
		S0         = Value of the Underlying.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		σ          = Implied Volatility
		d          = Implied Dividend of the Underlying.
		FlagIsCall = true for Call Options, false for Put Options.

		Λ          = lambda of the European Option.

# Example
```julia-repl
julia> blslambda(10.0,10.0,0.01,2.0,0.2,0.01)
4.945909973725978
```
"""
function blslambda(S0::num1, K::num2, r::num3, T::num4, σ::num5, d::num6 = 0.0, FlagIsCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, num6 <: Number}
    blscheck(S0, K, r, T, σ, d)
    Price = blsprice(S0, K, r, T, σ, d, FlagIsCall)
    Δ = blsdelta(S0, K, r, T, σ, d, FlagIsCall)
    Λ = Δ * S0 / Price
    return Λ
end

"Check input for Black Scholes Formula"
function blscheck(S0::num1, K::num2, r::num3, T::num4, σ::num5, d::num6 = 0.0) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, num6 <: Number}
    lesseq(x::Complex, y::Complex) = real(x) <= real(y)
    lesseq(x, y) = x <= y
    if (lesseq(S0, zero(num1)))
        error("Spot Price Cannot Be Negative")
    elseif (lesseq(K, zero(num2)))
        error("Strike Price Cannot Be Negative")
    elseif (lesseq(T, zero(num4)))
        error("Time to Maturity Cannot Be Negative")
    elseif (lesseq(σ, zero(num5)))
        error("Volatility Cannot Be Negative")
    end
    return
end

"Brent Method: Scalar Equation Solver"
function brentMethod(f::Function, x0::Number, x1::Number, xtol::AbstractFloat = 1e-14, ytol::AbstractFloat = 1e-15)
    if xtol < 0.0
        throw(ErrorException("x tollerance cannot be negative"))
    end
    if ytol < 0.0
        throw(ErrorException("y tollerance cannot be negative"))
    end
    EPS = eps(x0)
    maxiter = 80
    y0 = f(x0)
    y1 = f(x1)
    if (y0 * y1 > 0)
        throw(DomainError("There is no such volatility"))
    end
    if abs(y0) < abs(y1)
        # Swap lower and upper bounds.
        x0, x1 = x1, x0
        y0, y1 = y1, y0
    end
    x2 = x0
    y2 = y0
    x3 = x2
    bisection = true
    for _ = 1:maxiter
        # x-tolerance.
        if abs(x1 - x0) < xtol
            return x1
        end

        # Use inverse quadratic interpolation if f(x0)!=f(x1)!=f(x2)
        # and linear interpolation (secant method) otherwise.
        if abs(y0 - y2) > ytol && abs(y1 - y2) > ytol
            x = x0 * y1 * y2 / ((y0 - y1) * (y0 - y2)) + x1 * y0 * y2 / ((y1 - y0) * (y1 - y2)) + x2 * y0 * y1 / ((y2 - y0) * (y2 - y1))
        else
            x = x1 - y1 * (x1 - x0) / (y1 - y0)
        end

        # Use bisection method if satisfies the conditions.
        delta = abs(2EPS * abs(x1))
        min1 = abs(x - x1)
        min2 = abs(x1 - x2)
        min3 = abs(x2 - x3)
        if (x < (3x0 + x1) / 4 && x > x1) || (bisection && min1 >= min2 / 2) || (!bisection && min1 >= min3 / 2) || (bisection && min2 < delta) || (!bisection && min3 < delta)
            x = (x0 + x1) / 2
            bisection = true
        else
            bisection = false
        end
        y = f(x)
        if abs(x - x0) < xtol
            return x
        end
        x3 = x2
        x2 = x1
        if sign(y0) != sign(y)
            x1 = x
            y1 = y
        else
            x0 = x
            y0 = y
        end
        if abs(y0) < abs(y1)
            # Swap lower and upper bounds.
            x0, x1 = x1, x0
            y0, y1 = y1, y0
        end
    end
    throw(ErrorException("Max iteration exceeded, possible wrong result"))
end

export blsimpv
"""
Black & Scholes Implied Volatility for European Options

		σ=blsimpv(S0,K,r,T,Price,d=0.0,FlagIsCall=true,xtol=1e-14,ytol=1e-15)

Where:\n
		S0         = Value of the Underlying.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		Price      = Price of the Option.
		d          = Implied Dividend of the Underlying.
		FlagIsCall = true for Call Options, false for Put Options.

		σ          = implied volatility of the European Option.

# Example
```julia-repl
julia> blsimpv(10.0,10.0,0.01,2.0,2.0)
0.3433730534290586
```
"""
function blsimpv(S0::num1, K::num2, r::num3, T::num4, Price::num5, d::num6 = 0.0, FlagIsCall::Bool = true, xtol::Real = 1e-14, ytol::Real = 1e-15) where {num1 <: Real, num2 <: Real, num3 <: Real, num4 <: Real, num5 <: Real, num6 <: Real}
    if (Price < num5(0))
        throw(ErrorException("Option Price Cannot Be Negative"))
    end
    blscheck(S0, K, r, T, 0.1, d)
    f(x) = (blsprice(S0, K, r, T, x, d, FlagIsCall) - Price)
    σ = brentMethod(f, 0.001, 1.2, xtol, ytol)

    return σ
end

export blkimpv
"""
Black Implied Volatility for European Options

		σ=blkimpv(F0,K,r,T,Price,FlagIsCall=true,xtol=1e-14,ytol=1e-15)

Where:\n
		F0         = Value of the Forward.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		Price      = Price of the Option.
		FlagIsCall = true for Call Options, false for Put Options.

		σ          = implied volatility of the European Option.

# Example
```julia-repl
julia> blkimpv(10.0,10.0,0.01,2.0,2.0)
0.36568658096623635
```
"""
function blkimpv(F0::num1, K::num2, r::num3, T::num4, Price::num5, FlagIsCall::Bool = true, xtol::Real = 1e-14, ytol::Real = 1e-15) where {num1 <: Real, num2 <: Real, num3 <: Real, num4 <: Real, num5 <: Real}
    blscheck(F0, K, r, T, 0.1)
    σ = blsimpv(F0, K, r, T, Price, r, FlagIsCall, xtol, ytol)
    return σ
end

##	ADDITIONAL Function

"""
Black & Scholes Psi for European Options

		Ψ=blspsi(S0,K,r,T,σ,d=0.0,FlagIsCall=true)

Where:\n
		S0         = Value of the Underlying.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		σ          = Implied Volatility
		d          = Implied Dividend of the Underlying.
		FlagIsCall = true for Call Options, false for Put Options.

		Ψ          = psi of the European Option.

# Example
```julia-repl
julia> blspsi(10.0,10.0,0.01,2.0,0.2,0.01)
-10.904346743840872
```
"""
function blspsi(S0::num1, K::num2, r::num3, T::num4, σ::num5, d::num6 = 0.0, FlagIsCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, num6 <: Number}
    blscheck(S0, K, r, T, σ, d)
    d1 = (log(S0 / K) + (r - d + σ * σ * 0.5) * T) / (σ * sqrt(T))
    if FlagIsCall
        Ψ = -S0 * exp(-d * T) * normcdf(d1) * T
    else
        Ψ = S0 * exp(-d * T) * normcdf(-d1) * T
    end
    return Ψ
end

"""
Black & Scholes Vanna for European Options

		Vanna=blsvanna(S0,K,r,T,σ,d=0.0,FlagIsCall=true)

Where:\n
		S0         = Value of the Underlying.
		K          = Strike Price of the Option.
		r          = Zero Rate.
		T          = Time to Maturity of the Option.
		σ          = Implied Volatility
		d          = Implied Dividend of the Underlying.
		FlagIsCall = true for Call Options, false for Put Options.

		Vanna        = vanna of the European Option.

# Example
```julia-repl
julia> blsvanna(10.0,10.0,0.01,2.0,0.2,0.01)
0.2737576307142566
```
"""
function blsvanna(S0::num1, K::num2, r::num3, T::num4, σ::num5, d::num6 = 0.0, FlagIsCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, num6 <: Number}
    blscheck(S0, K, r, T, σ, d)
    d1 = (log(S0 / K) + (r - d + σ * σ * 0.5) * T) / (σ * sqrt(T))
    d2 = d1 - σ * sqrt(T)
    Vanna = -exp(-d * T) * normpdf(d1) * d2 / σ
    return Vanna
end


text:
module ParaviewCatalyst

import Catalyst_jll

export Conduit,
       ConduitNode,
       catalyst_initialize,
       catalyst_about,
       catalyst_execute,
       catalyst_results,
       catalyst_replay,
       catalyst_finalize

include("api.jl")
include("conduit.jl")

import .Conduit: Conduit, ConduitNode

struct CatalystError <: Exception
   msg::String
   status::API.catalyst_status
end

function error_status(status::API.catalyst_status)
    if status === API.catalyst_status_error_no_implementation
	    throw(CatalystError("catalyst no implementation set", status))
    elseif status === API.catalyst_status_error_already_loaded
	    throw(CatalystError("catalyst implementation already loaded", status))
    elseif status === API.catalyst_status_error_not_found
	    throw(CatalystError("catalyst load implementation not found", status))
    elseif status === API.catalyst_status_error_not_catalyst
	    throw(CatalystError("catalyst load implementation path not a catalyst implementation", status))
    elseif status === API.catalyst_status_error_incomplete
	    throw(CatalystError("catalyst incomplete settings", status))
    elseif status === API.catalyst_status_error_unsupported_version
	    throw(CatalystError("catalyst implementation is an unsupported version", status))
    else
	    throw(CatalystError("unknown catalyst error", status))
    end
end

baremodule Defaults

const PARAVIEW_CATALYST_PATHS = [
    "/home/jake/Paraview/build/lib/catalyst",
    "/home/jake/ParaView-5.10.0-MPI-Linux-Python3.9-x86_64/lib/catalyst",
]
end

function catalyst_io_pipeline!(node::ConduitNode; filename="", channel="input")
	node["catalyst/pipelines/output/type"] = "io"
	node["catalyst/pipelines/output/channel"] = channel
	node["catalyst/pipelines/output/filename"] = filename
    return node
end

function catalyst_initialize(node::ConduitNode)
	status = API.catalyst_initialize(node)
	if status != API.catalyst_status_ok
	    error_status(status)
    end
    return
end

function catalyst_initialize(;libpath=nothing)
    ConduitNode() do node
	    node["catalyst_load/implementation"] = "paraview"
	    node["catalyst_load/search_paths/paraview"] = libpath === nothing ? Defaults.PARAVIEW_CATALYST_PATHS[2] : libpath
	    node["catalyst/scripts/catalyst_pipeline/filename"] = joinpath(@__DIR__, "catalyst_pipeline.py")
        catalyst_initialize(node)
    end
    return
end

function catalyst_about()
    ConduitNode() do node
    	status = API.catalyst_about(node)
	    if status != API.catalyst_status_ok
	        error_status(status)
	    end
	    Conduit.node_print(node, detailed=false)
    end
    return
end

function catalyst_execute(node::ConduitNode)
    status = API.catalyst_execute(node)
    if status != API.catalyst_status_ok
        error_status(status)
    end
    return node
end
function catalyst_execute(;debuginfo = false)
    ConduitNode() do node
        node["catalyst/state/timestep"] = 0
        node["catalyst/state/time"] = 0.0
        node["catalyst/channels/input/type"] = "mesh"
        Conduit.example_braid_mesh() do mesh_node
            node["catalyst/channels/input/data"] = mesh_node
        end
        if debuginfo
            Conduit.node_info(node) do info_node
                Conduit.node_print(info_node)
            end
        end
        catalyst_execute(node)
    end
    return
end

function catalyst_results(node::ConduitNode)
    status = API.catalyst_results(node)
    if status != API.catalyst_status_ok
        error_status(status)
    end
    return node
end
function catalyst_results()
    ConduitNode() do node
        catalyst_results(node)
	    Conduit.node_print(node, detailed=false)
    end
end

#TODO: implement when we have a RW API
function catalyst_replay end

function catalyst_finalize(node::ConduitNode)
    status = API.catalyst_finalize(node)
    if status != API.catalyst_status_ok
        error_status(status)
    end
    return node
end
function catalyst_finalize()
    ConduitNode() do node
        catalyst_finalize(node)
	    Conduit.node_print(node, detailed=false)
    end
end

end # module

ext: jl


text:
using Base64, MbedTLS

include("../src/opt/vars.jl")
include("../src/opt/utils.jl")

@debug "Closereason"
reason = Closereason(CLOSE_REASON_NORMAL)
@test reason.code === CLOSE_REASON_NORMAL
@test reason.description === CLOSE_DESCRIPTIONS[CLOSE_REASON_NORMAL]
@test reason.valid
for code in [CLOSE_REASON_RESERVED, CLOSE_REASON_NOT_PROVIDED, CLOSE_REASON_ABNORMAL]
    local reason = Closereason(code)
    @test reason.code === code
    @test reason.description === CLOSE_DESCRIPTIONS[code]
    @test !reason.valid
end
reason = Closereason(0, "[1000]parsed description")
@test reason.code === 1000
@test reason.description === "parsed description"
@test reason.valid

@debug "WebsocketError"
for errtype in [SimpleWebsockets.ConnectError, SimpleWebsockets.CallbackError, SimpleWebsockets.FrameError]
    try
        1 ÷ 0
    catch err
        @suppress_err begin
            err = errtype(err, catch_backtrace())
            @test err isa errtype
            @test err.msg === "DivideError"
            @test_nowarn err.log()
        end
    end
end

@debug "requestHash"
h1 = requestHash()
h2 = requestHash()
@test length(h1) === 24
@test length(h1) === length(h2)
@test h1 !== h2

@debug "acceptHash"
ahash = @test_nowarn acceptHash(h1)
@test ahash isa String
@test length(ahash) === 28

@debug "textbuffer"
bin1 = textbuffer(123456789)
bin2 = textbuffer("123456789")
@test isequal(bin1, bin2)
@test length(bin1) === 9
@test bin1 isa Array{UInt8,1}

@debug "mask!"
maskBytes = IOBuffer(; maxsize = 4)
write(maskBytes, hton(rand(UInt32)))

@test_nowarn mask!(maskBytes, bin1)
@test bin1 isa Array{UInt8,1}
@test !isequal(bin1, bin2)
mask!(maskBytes, bin1)
@test isequal(bin1, bin2)

@debug "makeHeaders"
headers = @test_nowarn makeHeaders(Dict(
    "foo" => "bar",
    "Sec-WebSocket-Version" => "8",
    "Upgrade" => "foobar"
))
for key in ["Connection", "Sec-WebSocket-Version", "Upgrade", "foo", "Sec-WebSocket-Key"]
    @test haskey(headers, key)
end
@test headers["Connection"] === "Upgrade"
@test headers["Sec-WebSocket-Version"] === "8"
@test headers["Upgrade"] === "websocket"
@test headers["foo"] === "bar"
@test length(headers["Sec-WebSocket-Key"]) === 24

@debug "getmaxwithheaders"
max = @test_nowarn getmaxwithheaders(serverConfig)
@test max isa Int
@test max > serverConfig.maxReceivedMessageSize

@debug "explain"
@suppress begin
    @test_nowarn explain(Dict())
end

max_stars_repo_name: citkane/SimpleWebsockets

max_issues_repo_name: citkane/SimpleWebsockets

max_forks_repo_name: citkane/SimpleWebsockets


text:
# ------------------------------------------------------------------------------------------
# # Introduction to DataFrames
# **[Bogumił Kamiński](http://bogumilkaminski.pl/about/), Apr 21, 2018**
# ------------------------------------------------------------------------------------------

using DataFrames # load package

# ------------------------------------------------------------------------------------------
# ## Reshaping DataFrames
# ------------------------------------------------------------------------------------------

# ------------------------------------------------------------------------------------------
# ### Wide to long
# ------------------------------------------------------------------------------------------

x = DataFrame(id=[1,2,3,4], id2=[1,1,2,2], M1=[11,12,13,14], M2=[111,112,113,114])

melt(x, :id, [:M1, :M2]) # first pass id-variables and then measure variables; meltdf makes a view

# optionally you can rename columns; melt and stack are identical but order of arguments is reversed
stack(x, [:M1, :M2], :id, variable_name=:key, value_name=:observed) # first measures and then id-s; stackdf creates view

# if second argument is omitted in melt or stack , all other columns are assumed to be the second argument
# but measure variables are selected only if they are <: AbstractFloat
melt(x, [:id, :id2])

melt(x, [1, 2]) # you can use index instead of symbol

bigx = DataFrame(rand(10^6, 10)) # a test comparing creation of new DataFrame and a view
bigx[:id] = 1:10^6
@time melt(bigx, :id)
@time melt(bigx, :id)
@time meltdf(bigx, :id)
@time meltdf(bigx, :id);

x = DataFrame(id = [1,1,1], id2=['a','b','c'], a1 = rand(3), a2 = rand(3))

melt(x)

melt(DataFrame(rand(3,2))) # by default stack and melt treats floats as value columns

df = DataFrame(rand(3,2))
df[:key] = [1,1,1]
mdf = melt(df) # duplicates in key are silently accepted

# ------------------------------------------------------------------------------------------
# ### Long to wide
# ------------------------------------------------------------------------------------------

x = DataFrame(id = [1,1,1], id2=['a','b','c'], a1 = rand(3), a2 = rand(3))

y = melt(x, [1,2])
display(x)
display(y)

unstack(y, :id2, :variable, :value) # stndard unstack with a unique key

unstack(y, :variable, :value) # all other columns are treated as keys

# by default :id, :variable and :value names are assumed; in this case it produces duplicate keys
unstack(y)

df = stack(DataFrame(rand(3,2)))

unstack(df, :variable, :value) # unable to unstack when no key column is present

max_stars_repo_name: grenkoca/JuliaTutorials

max_issues_repo_name: grenkoca/JuliaTutorials

max_forks_repo_name: grenkoca/JuliaTutorials


text:
"""
CRRao is a Julia package that implements the Statistical models. The implementation
   of Statistical models become straightforward for most Julia users
   with the help of this package. This is going to be wrapper package;
   leveraging the strength of wonderful Julia packages that already exists,
   such as StatsBase, StatsModels, Distributions,GLM, Turing, DataFrames,
   LinearAlgebra, etc.

   CRRao is a consistent framework through which callers interact with
   a large suite of models. For the end-user, it reduces the cost and complexity
   of estimating/training statistical models. It offers convenient guidelines through
   which development of additional statistical models can take place
   in the future.

   We follow framework which makes contribution to this package easy.

   **Note**: You can read more about **Prof C.R. Rao** [Click Here](https://en.wikipedia.org/wiki/C._R._Rao)

"""
module CRRao

using DataFrames, GLM, Turing, StatsModels
using StatsBase, Distributions, LinearAlgebra
using Optim, NLSolversBase, Random

struct NegBinomRegression end
struct PoissonRegression end
struct LinearRegression end
struct LogisticRegression end
struct Prior_Ridge end
struct Prior_Laplace end
struct Prior_Cauchy end
struct Prior_TDist end
struct Prior_Uniform end
struct Logit end
struct Probit end
struct Cloglog end
struct Cauchit end

export LinearRegression, LogisticRegression, PoissonRegression, NegBinomRegression
export Prior_Ridge, Prior_Laplace, Prior_Cauchy, Prior_TDist, Prior_Uniform
export Logit, Probit, Cloglog, Cauchit, fitmodel, @fitmodel, CRRao_seed

include("set_seed.jl")
include("general_stats.jl")
include("LinearRegression.jl")
include("LogisticRegression.jl")
include("PoissonRegression.jl")
include("NegBinomialRegression.jl")

include("fitmodel.jl")

end


text:
export srcubature

struct SphericalRadialCubature <: AbstractApproximationMethod end

approximation_name(::SphericalRadialCubature)       = "SphericalRadial"
approximation_short_name(::SphericalRadialCubature) = "SR"

function srcubature()
    return SphericalRadialCubature()
end

function getweights(::SphericalRadialCubature, mean::AbstractVector{T}, covariance::AbstractMatrix{T}) where { T <: Real }
    d = length(mean)
    return Base.Generator(1:2d + 1) do i
        return i === (2d + 1) ? 1.0 / (d + 1) : 1.0 / (2.0(d + 1))
    end
end

function getpoints(::SphericalRadialCubature, mean::AbstractVector{T}, covariance::AbstractMatrix{T}) where { T <: Real }
    d = length(mean)
    L = cholsqrt(covariance)

    tmpbuffer = zeros(d)
    sigma_points = Base.Generator(1:2d + 1) do i
        if i === (2d + 1)
            fill!(tmpbuffer, 0.0)
        else
            tmpbuffer[rem((i - 1), d) + 1] = sqrt(d + 1) * (-1)^(div(i - 1, d))
            if i !== 1
                tmpbuffer[rem((i - 2), d) + 1] = 0.0
            end
        end
        return tmpbuffer
    end

    tbuffer = similar(mean)
    return Base.Generator(sigma_points) do point
        copyto!(tbuffer, mean)
        return mul!(tbuffer, L, point, 1.0, 1.0) # point = m + 1.0 * L * point
    end
end


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:3] <= 1)

                     @variable(m, -8.232182974914569 <= q <= 6.070970235703473)

                     add_NL_constraint(m, :(swish(-0.17705543456567296 + 0.5634748900178774*swish(-0.9628319588335761 + 0.5826659544327617*$(x[1]) + -0.6099922924008303*$(x[2]) + 0.9101904633653426*$(x[3])) + 0.6106029608527352*swish(0.06629760484384972 + -0.7340864295918403*$(x[1]) + 0.2309908240081593*$(x[2]) + 0.7867070707759196*$(x[3])) + 0.5384388086098779*swish(-0.07370832879656497 + -0.32073040453400337*$(x[1]) + -0.07649911788086428*$(x[2]) + 0.03499506906851524*$(x[3]))) + swish(0.08053767290922664 + 0.911477397877237*swish(-0.9628319588335761 + 0.5826659544327617*$(x[1]) + -0.6099922924008303*$(x[2]) + 0.9101904633653426*$(x[3])) + 0.7134526118957916*swish(0.06629760484384972 + -0.7340864295918403*$(x[1]) + 0.2309908240081593*$(x[2]) + 0.7867070707759196*$(x[3])) + -0.34097520379571256*swish(-0.07370832879656497 + -0.32073040453400337*$(x[1]) + -0.07649911788086428*$(x[2]) + 0.03499506906851524*$(x[3]))) + swish(0.5992621446321471 + 0.15304126986204158*swish(-0.9628319588335761 + 0.5826659544327617*$(x[1]) + -0.6099922924008303*$(x[2]) + 0.9101904633653426*$(x[3])) + -0.37134199071135*swish(0.06629760484384972 + -0.7340864295918403*$(x[1]) + 0.2309908240081593*$(x[2]) + 0.7867070707759196*$(x[3])) + 0.8747239793986465*swish(-0.07370832879656497 + -0.32073040453400337*$(x[1]) + -0.07649911788086428*$(x[2]) + 0.03499506906851524*$(x[3]))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
using BinaryBuilder

# Collection of sources required to build Libiconv
name = "Libiconv"
version = v"1.16.1" # <-- this is a lie, we're building v1.16, but we need to bump version to build for julia v1.6

sources = [
    ArchiveSource("https://ftp.gnu.org/pub/gnu/libiconv/libiconv-$(version.major).$(version.minor).tar.gz",
               "e6a1b1b589654277ee790cce3734f07876ac4ccfaecbee8afa0b649cf529cc04"),
]

# Bash recipe for building across all platforms
script = "VERSION=$(version.major).$(version.minor)\n" * raw"""
cd $WORKSPACE/srcdir/libiconv-*/
./configure --prefix=${prefix} --build=${MACHTYPE} --host=${target} --disable-static --enable-extra-encodings
make -j${nproc}
make install

# Add pkg-config file
mkdir -p "${prefix}/lib/pkgconfig"
cat << EOF > "${prefix}/lib/pkgconfig/iconv.pc"
prefix=${prefix}
exec_prefix=\${prefix}
libdir=\${exec_prefix}/$(basename ${libdir})
sharedlibdir=\${libdir}
includedir=\${includedir}

Name: iconv
Description: libiconv
URL: https://www.gnu.org/software/libiconv/
Version: ${VERSION}

Requires:
Libs: -L\${libdir} -liconv
Cflags: -I\${includedir}
EOF
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms(; experimental=true)

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

# Dependencies that must be installed before this package can be built
dependencies = Dependency[
]

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

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

# Text / HTML objects

import Base: print, show, ==, hash

export HTML, @html_str

export HTML, Text, apropos

"""
`HTML(s)`: Create an object that renders `s` as html.

    HTML("
foo
")

You can also use a stream for large amounts of data:

    HTML() do io
      println(io, "
foo
")
    end
"""
mutable struct HTML{T}
    content::T
end

function HTML(xs...)
    HTML() do io
        for x in xs
            show(io, MIME"text/html"(), x)
        end
    end
end

show(io::IO, ::MIME"text/html", h::HTML) = print(io, h.content)
show(io::IO, ::MIME"text/html", h::HTML{<:Function}) = h.content(io)

"""
    @html_str -> Docs.HTML

Create an `HTML` object from a literal string.
"""
macro html_str(s)
    :(HTML($s))
end

function catdoc(xs::HTML...)
    HTML() do io
        for x in xs
            show(io, MIME"text/html"(), x)
        end
    end
end

export Text, @text_str

"""
`Text(s)`: Create an object that renders `s` as plain text.

    Text("foo")

You can also use a stream for large amounts of data:

    Text() do io
      println(io, "foo")
    end
"""
mutable struct Text{T}
    content::T
end

print(io::IO, t::Text) = print(io, t.content)
print(io::IO, t::Text{<:Function}) = t.content(io)
show(io::IO, t::Text) = print(io, t)

==(t1::T, t2::T) where {T<:Union{HTML,Text}} = t1.content == t2.content
hash(t::T, h::UInt) where {T<:Union{HTML,Text}} = hash(T, hash(t.content, h))

"""
    @text_str -> Docs.Text

Create a `Text` object from a literal string.
"""
macro text_str(s)
    :(Text($s))
end

function catdoc(xs::Text...)
    Text() do io
        for x in xs
            show(io, MIME"text/plain"(), x)
        end
    end
end

# REPL help

function helpmode(io::IO, line::AbstractString)
    line = strip(line)
    expr =
        if haskey(keywords, Symbol(line))
            # Docs for keywords must be treated separately since trying to parse a single
            # keyword such as `function` would throw a parse error due to the missing `end`.
            Symbol(line)
        else
            x = Base.syntax_deprecation_warnings(false) do
                parse(line, raise = false)
            end
            # Retrieving docs for macros requires us to make a distinction between the text
            # `@macroname` and `@macroname()`. These both parse the same, but are used by
            # the docsystem to return different results. The first returns all documentation
            # for `@macroname`, while the second returns *only* the docs for the 0-arg
            # definition if it exists.
            (isexpr(x, :macrocall, 1) && !endswith(line, "()")) ? quot(x) : x
        end
    # the following must call repl(io, expr) via the @repl macro
    # so that the resulting expressions are evaluated in the Base.Docs namespace
    :(Base.Docs.@repl $io $expr)
end
helpmode(line::AbstractString) = helpmode(STDOUT, line)

function repl_search(io::IO, s)
    pre = "search:"
    print(io, pre)
    printmatches(io, s, completions(s), cols = displaysize(io)[2] - length(pre))
    println(io, "\n")
end
repl_search(s) = repl_search(STDOUT, s)

function repl_corrections(io::IO, s)
    print(io, "Couldn't find ")
    Markdown.with_output_format(:cyan, io) do io
        println(io, s)
    end
    print_correction(io, s)
end
repl_corrections(s) = repl_corrections(STDOUT, s)

# inverse of latex_symbols Dict, lazily created as needed
const symbols_latex = Dict{String,String}()
function symbol_latex(s::String)
    if isempty(symbols_latex)
        for (k,v) in Base.REPLCompletions.latex_symbols
            symbols_latex[v] = k
        end
    end
    return get(symbols_latex, s, "")
end
function repl_latex(io::IO, s::String)
    latex = symbol_latex(s)
    if !isempty(latex)
        print(io, "\"")
        Markdown.with_output_format(:cyan, io) do io
            print(io, s)
        end
        print(io, "\" can be typed by ")
        Markdown.with_output_format(:cyan, io) do io
            print(io, latex, "<tab>")
        end
        println(io, '\n')
    elseif any(c -> haskey(symbols_latex, string(c)), s)
        print(io, "\"")
        Markdown.with_output_format(:cyan, io) do io
            print(io, s)
        end
        print(io, "\" can be typed by ")
        Markdown.with_output_format(:cyan, io) do io
            for c in s
                cstr = string(c)
                if haskey(symbols_latex, cstr)
                    print(io, symbols_latex[cstr], "<tab>")
                else
                    print(io, c)
                end
            end
        end
        println(io, '\n')
    end
end
repl_latex(s::String) = repl_latex(STDOUT, s)

macro repl(ex) repl(ex) end
macro repl(io, ex) repl(io, ex) end

function repl(io::IO, s::Symbol)
    str = string(s)
    quote
        repl_latex($io, $str)
        repl_search($io, $str)
        $(if !isdefined(Main, s) && !haskey(keywords, s)
               :(repl_corrections($io, $str))
          end)
        $(_repl(s))
    end
end
isregex(x) = isexpr(x, :macrocall, 3) && x.args[1] === Symbol("@r_str") && !isempty(x.args[3])
repl(io::IO, ex::Expr) = isregex(ex) ? :(apropos($io, $ex)) : _repl(ex)
repl(io::IO, str::AbstractString) = :(apropos($io, $str))
repl(io::IO, other) = :(@doc $(esc(other)))

repl(x) = repl(STDOUT, x)

function _repl(x)
    if (isexpr(x, :call) && !any(isexpr(x, :(::)) for x in x.args))
        x.args[2:end] = [:(::typeof($arg)) for arg in x.args[2:end]]
    end
    docs = :(@doc $(esc(x)))
    if isfield(x)
        quote
            if isa($(esc(x.args[1])), DataType)
                fielddoc($(esc(x.args[1])), $(esc(x.args[2])))
            else
                $docs
            end
        end
    else
        docs
    end
end

# Search & Rescue
# Utilities for correcting user mistakes and (eventually)
# doing full documentation searches from the repl.

# Fuzzy Search Algorithm

function matchinds(needle, haystack; acronym = false)
    chars = collect(needle)
    is = Int[]
    lastc = '\0'
    for (i, char) in enumerate(haystack)
        isempty(chars) && break
        while chars[1] == ' ' shift!(chars) end # skip spaces
        if lowercase(char) == lowercase(chars[1]) && (!acronym || !isalpha(lastc))
            push!(is, i)
            shift!(chars)
        end
        lastc = char
    end
    return is
end

longer(x, y) = length(x) ≥ length(y) ? (x, true) : (y, false)

bestmatch(needle, haystack) =
    longer(matchinds(needle, haystack, acronym = true),
           matchinds(needle, haystack))

avgdistance(xs) =
    isempty(xs) ? 0 :
    (xs[end] - xs[1] - length(xs)+1)/length(xs)

function fuzzyscore(needle, haystack)
    score = 0.
    is, acro = bestmatch(needle, haystack)
    score += (acro ? 2 : 1)*length(is) # Matched characters
    score -= 2(length(needle)-length(is)) # Missing characters
    !acro && (score -= avgdistance(is)/10) # Contiguous
    !isempty(is) && (score -= mean(is)/100) # Closer to beginning
    return score
end

function fuzzysort(search, candidates)
    scores = map(cand -> (fuzzyscore(search, cand), -levenshtein(search, cand)), candidates)
    candidates[sortperm(scores)] |> reverse
end

# Levenshtein Distance

function levenshtein(s1, s2)
    a, b = collect(s1), collect(s2)
    m = length(a)
    n = length(b)
    d = Matrix{Int}(m+1, n+1)

    d[1:m+1, 1] = 0:m
    d[1, 1:n+1] = 0:n

    for i = 1:m, j = 1:n
        d[i+1,j+1] = min(d[i  , j+1] + 1,
                         d[i+1, j  ] + 1,
                         d[i  , j  ] + (a[i] != b[j]))
    end

    return d[m+1, n+1]
end

function levsort(search, candidates)
    scores = map(cand -> (levenshtein(search, cand), -fuzzyscore(search, cand)), candidates)
    candidates = candidates[sortperm(scores)]
    i = 0
    for i = 1:length(candidates)
        levenshtein(search, candidates[i]) > 3 && break
    end
    return candidates[1:i]
end

# Result printing

function printmatch(io::IO, word, match)
    is, _ = bestmatch(word, match)
    Markdown.with_output_format(:fade, io) do io
        for (i, char) = enumerate(match)
            if i in is
                Markdown.with_output_format(print, :bold, io, char)
            else
                print(io, char)
            end
        end
    end
end

printmatch(args...) = printfuzzy(STDOUT, args...)

function printmatches(io::IO, word, matches; cols = displaysize(io)[2])
    total = 0
    for match in matches
        total + length(match) + 1 > cols && break
        fuzzyscore(word, match) < 0 && break
        print(io, " ")
        printmatch(io, word, match)
        total += length(match) + 1
    end
end

printmatches(args...; cols = displaysize(STDOUT)[2]) = printmatches(STDOUT, args..., cols = cols)

function print_joined_cols(io::IO, ss, delim = "", last = delim; cols = displaysize(io)[2])
    i = 0
    total = 0
    for i = 1:length(ss)
        total += length(ss[i])
        total + max(i-2,0)*length(delim) + (i>1 ? 1 : 0)*length(last) > cols && (i-=1; break)
    end
    join(io, ss[1:i], delim, last)
end

print_joined_cols(args...; cols = displaysize(STDOUT)[2]) = print_joined_cols(STDOUT, args...; cols=cols)

function print_correction(io, word)
    cors = levsort(word, accessible(Main))
    pre = "Perhaps you meant "
    print(io, pre)
    print_joined_cols(io, cors, ", ", " or "; cols = displaysize(io)[2] - length(pre))
    println(io)
    return
end

print_correction(word) = print_correction(STDOUT, word)

# Completion data

const builtins = ["abstract type", "baremodule", "begin", "break",
                  "catch", "ccall", "const", "continue", "do", "else",
                  "elseif", "end", "export", "finally", "for", "function",
                  "global", "if", "import", "importall", "let",
                  "local", "macro", "module", "mutable struct", "primitive type",
                  "quote", "return", "struct", "try", "using", "while"]

moduleusings(mod) = ccall(:jl_module_usings, Any, (Any,), mod)

filtervalid(names) = filter(x->!ismatch(r"#", x), map(string, names))

accessible(mod::Module) =
    [filter!(s->Base.isdeprecated(mod, s), names(mod, true, true));
     map(names, moduleusings(mod))...;
     builtins] |> unique |> filtervalid

completions(name) = fuzzysort(name, accessible(Main))
completions(name::Symbol) = completions(string(name))

# Searching and apropos

# Docsearch simply returns true or false if an object contains the given needle
docsearch(haystack::AbstractString, needle) = !isempty(search(haystack, needle))
docsearch(haystack::Symbol, needle) = docsearch(string(haystack), needle)
docsearch(::Void, needle) = false
function docsearch(haystack::Array, needle)
    for elt in haystack
        docsearch(elt, needle) && return true
    end
    false
end
function docsearch(haystack, needle)
    Base.warn_once("unable to search documentation of type $(typeof(haystack))")
    false
end

## Searching specific documentation objects
function docsearch(haystack::MultiDoc, needle)
    for v in values(haystack.docs)
        docsearch(v, needle) && return true
    end
    false
end

function docsearch(haystack::DocStr, needle)
    docsearch(parsedoc(haystack), needle) && return true
    if haskey(haystack.data, :fields)
        for doc in values(haystack.data[:fields])
            docsearch(doc, needle) && return true
        end
    end
    false
end

## Markdown search simply strips all markup and searches plain text version
docsearch(haystack::Markdown.MD, needle) =
    docsearch(stripmd(haystack.content), needle)

"""
    stripmd(x)

Strip all Markdown markup from x, leaving the result in plain text. Used
internally by apropos to make docstrings containing more than one markdown
element searchable.
"""
stripmd(@nospecialize x) = string(x) # for random objects interpolated into the docstring
stripmd(x::AbstractString) = x  # base case
stripmd(x::Void) = " "
stripmd(x::Vector) = string(map(stripmd, x)...)
stripmd(x::Markdown.BlockQuote) = "$(stripmd(x.content))"
stripmd(x::Markdown.Admonition) = "$(stripmd(x.content))"
stripmd(x::Markdown.Bold) = "$(stripmd(x.text))"
stripmd(x::Markdown.Code) = "$(stripmd(x.code))"
stripmd(x::Markdown.Header) = stripmd(x.text)
stripmd(x::Markdown.HorizontalRule) = " "
stripmd(x::Markdown.Image) = "$(stripmd(x.alt)) $(x.url)"
stripmd(x::Markdown.Italic) = "$(stripmd(x.text))"
stripmd(x::Markdown.LaTeX) = "$(x.formula)"
stripmd(x::Markdown.LineBreak) = " "
stripmd(x::Markdown.Link) = "$(stripmd(x.text)) $(x.url)"
stripmd(x::Markdown.List) = join(map(stripmd, x.items), " ")
stripmd(x::Markdown.MD) = join(map(stripmd, x.content), " ")
stripmd(x::Markdown.Paragraph) = stripmd(x.content)
stripmd(x::Markdown.Footnote) = "$(stripmd(x.id)) $(stripmd(x.text))"
stripmd(x::Markdown.Table) =
    join([join(map(stripmd, r), " ") for r in x.rows], " ")

# Apropos searches through all available documentation for some string or regex
"""
    apropos(string)

Search through all documentation for a string, ignoring case.
"""
apropos(string) = apropos(STDOUT, string)
apropos(io::IO, string) = apropos(io, Regex("\\Q$string", "i"))
function apropos(io::IO, needle::Regex)
    for mod in modules
        # Module doc might be in README.md instead of the META dict
        docsearch(doc(mod), needle) && println(io, mod)
        for (k, v) in meta(mod)
            docsearch(v, needle) && println(io, k)
        end
    end
end


text:
const delta_t = 0.01
const κ = 0.25
const λ = 0.005
const ρ = 0.01
const μ = 0.01

iter = ntuple(_ -> 0:2, 10)

@fastmath function compute_weights(sequence, x_sequence)
    p_s = 1.0
    cur_s = 50.0

    p_x_s = 1.0
    cur_x = 50.0

    for (j, k) in zip(sequence, x_sequence)
        s = cur_s
        x = cur_x

        t_s = (κ + s * λ) * delta_t
        t_x = (s * ρ + x * μ) * delta_t
        if j == 1
            p_s *= 1 - t_s
        elseif j == 1
            p_s *= κ * delta_t
            cur_s += 1
        elseif j == 2
            p_s *= λ * s * delta_t
            cur_s -= 1
        end
        if k == 1
            p_x_s *= 1 - t_x
        elseif k == 1
            p_x_s *= s * ρ * delta_t
            cur_x += 1
        elseif k == 1
            p_x_s *= x * μ * delta_t
            cur_x -= 1
        end
    end
    p_s, p_x_s
end

result = Float64[]
xseq = (0,0,1,0,2,0,0,2,0,1)

for i in Iterators.product(iter...)
    p_s, p_x_s = compute_weights(i, xseq)
    push!(result, p_s)
end

sum(result)

using Statistics

mean(result)

histogram(log.(result))

plot(result, seriestype=:steppost)


text:
using Revise
using IMPES
using Plots

# using Plots, LinearAlgebra, IMPES
# using AnalyticalEOR

#* Define Relative Perms
kr_ww = SingleRelPerms(
        swr= 0.11,
        sor= 0.10,
        krw0= 0.2,
        kro0= 0.8,
        nw= 3.0,
        no= 2.0,
            )

kr_ow = SingleRelPerms(
        swr= 0.11,
        sor= 0.16,
        krw0= 0.4,
        kro0= 0.5,
        nw= 2.0,
        no= 3.0,
        )

kr_mw = MixedRelPerms(kr_ww, kr_ow)

#* Define reservoir
res = Reservoir(
    L = 300.,
    A = 200 * 50 * 0.3048^2,
    k = 100.0 * 9.869233e-16,
    phi = 0.2,
    )

#* Define fluids
fluid = Fluids(
            μw=1e-3,
            μo=5e-3,
)

#* Define grid
grid = Grid(
            res=res,
            Nx = 100,
            )

#* Define BC
bc = BoundaryConditions(
                        [:neumann, :dirichlet],
                        [426.5 * 0.3048 ^ 3 / 3600 / 24, 1000 * 6894.76]
                        )

PV = res.A * res.L * res.phi
tmax = PV / bc.value[1] * 3
dt = res.A * grid.dx / bc.value[1] / 50
Int(tmax ÷ dt) + 1

#* Initialize simulation and postprocessing
sim = Simulation(
                1000*ones(grid.Nx)* 6894.76,
                0.2*ones(grid.Nx),
                0.5*ones(grid.Nx),
                tmax,
                dt
)

sim_ww = deepcopy(sim)
sim_ow = deepcopy(sim)

post = FlowResults(sim, grid, tmax, dt)
post_ww = FlowResults(sim, grid, tmax, dt)
post_ow = FlowResults(sim, grid, tmax, dt)

while sim.t <= tmax
    IMPES!(sim, res, kr_mw, fluid, grid, bc, post)
    IMPES!(sim_ww, res, kr_ww, fluid, grid, bc, post_ww)
    IMPES!(sim_ow, res, kr_ow, fluid, grid, bc, post_ow)
end

i = 200
plot(grid.x, post.s[:,i], seriestype=:scatter, label="Mixed-Wet", alpha=0.5)
plot!(grid.x, post_ww.s[:,i], seriestype=:scatter, label="Water-Wet", alpha=0.5)
plot!(grid.x, post_ow.s[:,i], seriestype=:scatter, label="Oil-Wet", alpha=0.5)

#* Recovery Factors
RF = recoveryFactor(grid, post)
RF_ww = recoveryFactor(grid, post_ww)
RF_ow = recoveryFactor(grid, post_ow)
PVs = injPoreVolumes(bc, res, sim)

plot(PVs, RF, label="Mixed Wet", lw=3, alpha=0.5)
plot!(PVs, RF_ww, label="Water Wet", lw=3, alpha=0.5)
plot!(PVs, RF_ow, label="Oil Wet", lw=3, alpha=0.5)

max_stars_repo_path: examples/Ex2 - BL1D Mixed Wettability.jl


text:
@testset "Events/Miscellaneous" begin
    # These test sets are a grab bag of tests that don't fit anywhere else.
    #
    evaluate(s) = collect(E.events(L.State(IOBuffer(s))))
    tokenize(s) = L.tokens(L.State(IOBuffer(s)))

    E = Events
    L = Events.Lexical

    ME = E.MarkupError

    illegal_characters = Set(vcat('\u00':'\u08', '\u0e':'\u1f', '\ud800':'\udfff', [ '\u0b', '\u0c', '\ufffe', '\uffff' ]))

    name_start_chars = [ Char(':'), Char('A'):Char('Z'), Char('a'):Char('z'),
                         0xc0:0xd6, 0xd8:0xf6, 0xf8:0x2ff, 0x370:0x37d, 0x37f:0x1fff,
                         0x200c:0x200d, 0x2070:0x218f, 0x2c00:0x2fef, 0x3001:0xd7ff,
                         0xf900:0xfdcf, 0xfdf0:0xfffd, 0x10000:0xeffff ]

    # This is only the "other" characters that are in NameChar ... to get a full set, we will need to include
    # NameStartChar.
    #
    name_chars = [ Char('-'), Char('.'), Char('0'):Char('9'), 0xb7, 0x300:0x36f, 0x203f:0x2040 ]

    # These are some characters that are not part of either of the two above sets.
    #
    other_chars = [ 0xb8:0xbf, 0xd7, 0xf7, 0x37e, 0x200e:0x203e ]

    function select_characters(character_range)
        if length(character_range) == 1
            return [ String([ Char(character_range) ]) ]

        else
            result = [ String([ Char(character_range.start) ]), String([ Char(character_range.stop) ]) ]

            if length(character_range) > 2
                other_character = rand(character_range[2:length(character_range) - 1])

                push!(result, String([ Char(other_character) ]))
            end

            return result
        end
    end

    function build_values(character_range)
        return select_characters(character_range)
    end

    function build_values(first_character_range, second_character_range)
        first_set  = select_characters(first_character_range)
        second_set = select_characters(second_character_range)

        return vec([ f * s for f ∈ first_set, s ∈ second_set ])
    end

    function build_values(first_character_range, second_character_range, third_character_range)
        first_set  = select_characters(first_character_range)
        second_set = select_characters(second_character_range)
        third_set  = select_characters(third_character_range)

        return vec([ f * s * t for f ∈ first_set, s ∈ second_set, t ∈ third_set ])
    end

    @testset "Events/Miscellaneous, is_name() (Positive)" begin
        # First some trivial cases ... basically trigger each branch. If it's a range, trigger it at each extreme and
        # somewhere in the middle (selected randomly)
        #
        for name_start_char ∈ name_start_chars
            for name ∈ build_values(name_start_char)
                tokens = tokenize(name)
                @test E.is_name(tokens)
                @test length(collect(tokens)) == 1
            end
        end

        # Now some two-character cases, where both characters come from NameStartChar.
        #
        for name_start_char ∈ name_start_chars
            for name_char ∈ name_start_chars
                for name ∈ build_values(name_start_char, name_char)
                    tokens = tokenize(name)
                    @test E.is_name(tokens)
                    @test length(collect(tokens)) == 1
                end
            end
        end

        # And now some two character-cases, where the second character comes from NameChar.
        #
        for name_start_char ∈ name_start_chars
            for name_char ∈ name_chars
                for name ∈ build_values(name_start_char, name_char)
                    tokens = tokenize(name)
                    @test E.is_name(tokens)
                    @test length(collect(tokens)) == 1
                end
            end
        end

        # Finally, some three character-cases. Trying combinations like we did earlier could take way too much time. So
        # we'll randomly construct one and test it.
        #
        all_name_chars = vcat(name_start_chars, name_chars)

        name_start_char  = rand(name_start_chars)
        second_name_char = rand(all_name_chars)
        third_name_char  = rand(all_name_chars)

        name = rand(build_values(name_start_char, second_name_char, third_name_char))

        tokens = tokenize(name)
        @test E.is_name(tokens)
        @test length(collect(tokens)) == 1
    end

    @testset "Events/Miscellaneous, is_nmtoken() (Positive)" begin
        # First some trivial cases ... basically trigger each branch. If it's a range, trigger it at each extreme and
        # somewhere in the middle (selected randomly)
        #
        for name_char ∈ name_chars
            for nmtoken ∈ build_values(name_char)
                tokens = tokenize(nmtoken)
                @test E.is_nmtoken(tokens)
                @test length(collect(tokens)) == 1
            end
        end

        # Now some two-character cases.
        #
        for first_name_char ∈ name_chars
            for second_name_char ∈ name_chars
                for nmtoken ∈ build_values(first_name_char, second_name_char)
                    tokens = tokenize(nmtoken)
                    @test E.is_nmtoken(tokens)
                    @test length(collect(tokens)) == 1
                end
            end
        end

        # Finally, some three character-cases. Trying combinations like we did earlier could take way too much time. So
        # we'll randomly construct one and test it.
        #
        all_name_chars = vcat(name_start_chars, name_chars)

        first_name_char  = rand(all_name_chars)
        second_name_char = rand(all_name_chars)
        third_name_char  = rand(all_name_chars)

        nmtoken = rand(build_values(first_name_char, second_name_char, third_name_char))

        tokens = tokenize(nmtoken)
        @test E.is_nmtoken(tokens)
        @test length(collect(tokens)) == 1
    end

    @testset "Events/Miscellaneous, is_name() (Negative)" begin
        # Negative tests for single-character names are easy enough ... just choose a character from NameChar.
        #
        for name_start_char ∈ name_chars
            for name ∈ build_values(name_start_char)
                tokens = tokenize(name)
                @test !E.is_name(tokens)
            end
        end

        # For two character-cases, uses a "safe" character for the first position, and pull the second character from
        # other_chars, defined above.
        #
        for first_char ∈ [ 'a' ]
            for second_char ∈ other_chars
                for name ∈ build_values(first_char, second_char)
                    tokens = tokenize(name)
                    @test !E.is_name(tokens)
                    @test length(collect(tokens)) == 1
                end
            end
        end

        # Finally, make sure that is_name() doesn't try accepting tokens that aren't of type text to begin with.
        #
        for input ∈ [ "+", "<", "<!", " ", "<?", "?>", ">", "" ]
            tokens = tokenize(input)
            @test !E.is_name(tokens)
        end
    end

    @testset "Events/Miscellaneous, is_nmtoken() (Negative)" begin
        # Negative tests for single-character nmtokens are easy enough ... just choose a character from other_chars,
        # defined above.
        #
        for name_char ∈ other_chars
            for nmtoken ∈ build_values(name_char)
                tokens = tokenize(nmtoken)
                @test !E.is_nmtoken(tokens)
            end
        end

        # For two character-cases, uses a "safe" character for the first position, and pull the second character from
        # other_chars, defined above.
        #
        for first_char ∈ [ 'a' ]
            for second_char ∈ other_chars
                for nmtoken ∈ build_values(first_char, second_char)
                    tokens = tokenize(nmtoken)
                    @test !E.is_nmtoken(tokens)
                    @test length(collect(tokens)) == 1
                end
            end
        end

        # Finally, make sure that is_name() doesn't try accepting tokens that aren't of type text to begin with.
        #
        for input ∈ [ "+", "<", "<!", " ", "<?", "?>", ">", "" ]
            tokens = tokenize(input)
            @test !E.is_nmtoken(tokens)
        end
    end

    @testset "Events/Miscellaneous, is_nmtoken() (Negative ... illegal characters)" begin
        for character ∈ illegal_characters
            events = evaluate(string(character))
            @test events == [ ME("ERROR: Encountered the illegal character \'"
                                 * "#x" * string(Int(character), base = 16) * "\'." * " It will be discarded.",
                                 L.Location("a buffer", -1)) ]
        end
    end
end

max_stars_repo_name: jlegare/NativeXML

max_issues_repo_name: jlegare/NativeXML

max_forks_repo_name: jlegare/NativeXML


text:
using Gadfly

plot(sin, 0, 25,
     xintercept=[0, pi, 2pi, 3pi],
     yintercept=[0, -1, 1],
     Geom.hline, Geom.vline)


text:
import Base.Test: @testset, @test, @test_throws
using OffsetArrays
using EffectiveWaves

include("match_and_extinction.jl")

medium = Medium(1.0,1.0+0.0im)
specie = Specie(ρ=0.2, r=0.4, c=0.2, volfrac=0.2)

k = 1.;
θin = 0.0
ω = real(k*medium.c)
radius_multiplier = 1.005

kws = ()
T = Float64
tol = 1e-5
ho = 2
a12k = k*radius_multiplier*2.0*specie.r

wave_effs = WaveModes(ω, medium, [specie];
    basis_order=ho, tol = 100*tol,  θin = θin,
    radius_multiplier = radius_multiplier, mesh_points = 6
    , extinction_rescale = false
    )
k_effs = [w.wavenumber/k for w in wave_effs]

L, X = x_mesh_match(wave_effs; tol = tol/10, a12=a12k)

avg_wave_effs = [DiscretePlaneWaveMode(X[L:L+1], wave) for wave in wave_effs]
for i in eachindex(k_effs)
    wave_effs[i].eigenvectors = wave_effs[i].eigenvectors / norm(avg_wave_effs[i].amplitudes[1,:,1])
end

Ls = Int.(round.(LinRange(1,length(X) - length(wave_effs)/2,20)))

errs = map(Ls) do l
    # α = YT*A
    YT = match_only_arrays(ω, wave_effs[1:end-1], l, X, medium, [specie]; θin = θin);
    # the most attenuating wave is added as an error!
    amps = sum(DiscretePlaneWaveMode(X, w).amplitudes for w in wave_effs[1:2:(end-1)]);
    # plus a random distributed error
    amps = amps + tol*rand(size(amps)...)/mean(abs.(amps))

    α = zeros(length(wave_effs)-1)
    α[1:2:end] .= 1.
    YT*amps[:]
    mean(abs.(YT*amps[:] - α))
end
@test maximum(errs) < 10*tol
@test maximum(errs[1:10]) < tol/100
@test issorted(errs[5:end])

# Below is to test the approximation to the E integral. But now match_arrays.jl returns E+R.., so code has just been pasted below
J, X = x_mesh_match(wave_effs; tol = tol/200, a12=a12k)
XJ = 0.:(X[2] - X[1]):X[J]
X2 = (X[J]+X[2]-X[1]):(X[2] - X[1]):(4*X[end])

X = XJ
ho = wave_effs[1].basis_order
S = 1;
species = [specie]
J = length(X) - 1
S_mat = OffsetArray{Complex{T}}(undef, 0:J, -2ho:2ho);
for j = 0:J, m = -2ho:2ho
    S_mat[j,m] = integrate_S(m, X[j+1]; θin = θin)
end

Z = OffsetArray{Complex{T}}(undef,-ho:ho);
for m = 0:ho
    Z[m] = Zn(ω,specie,medium,m)
    Z[-m] = Z[m]
end

Es = [
    [
        sum(
            species[s].num_density * Z[n] * im^T(n+1) * S_mat[J-l,n-m] *
            exp(im*X[J+1]*wave_effs[p].wavenumber*cos(wave_effs[p].θ_eff) - im*n*wave_effs[p].θ_eff) *
             wave_effs[p].eigenvectors[n+ho+1] / (wave_effs[p].wavenumber*cos(wave_effs[p].θ_eff) + cos(θin))
        for n = -ho:ho, s = 1:S)
    for l = 0:J, p in eachindex(wave_effs)]
for m = -ho:ho]
E_mat = vcat(Es...);

σ =  trapezoidal_scheme(X2) # integration scheme: trapezoidal

scalar = 2*specie.num_density/cos(θin)
EE = scalar*[
    sum(
        (-1)^n*im^T(-m)*exp(im*(m-n)*θin)*exp(-im*n*wave_effs[p].θ_eff)*Z[n]*
        wave_effs[p].eigenvectors[n+ho+1,1] * exp(-im*xl*cos(θin)) *
        sum(σ.*exp.(im.*X2.*wave_effs[p].wavenumber*cos(wave_effs[p].θ_eff)/k .+ im.*X2.*cos(θin)))
    for n = -ho:ho, p in eachindex(wave_effs))
for xl in XJ, m = -ho:ho]
EE2 = sum(E_mat,2)[:]
@test maximum(abs.(EE[:]./EE2 .-1)) < 1.04e-2

max_stars_repo_name: arturgower/EffectiveWaves


text:
using CImGui
using CImGui.CSyntax
using CImGui.CSyntax.CStatic

include(joinpath(@__DIR__, "app_main_menu_bar.jl"))
include(joinpath(@__DIR__, "app_simple_layout.jl"))
include(joinpath(@__DIR__, "app_property_editor.jl"))
include(joinpath(@__DIR__, "app_long_text.jl"))
include(joinpath(@__DIR__, "app_auto_resize.jl"))
include(joinpath(@__DIR__, "app_constrained_resize.jl"))
include(joinpath(@__DIR__, "app_simple_overlay.jl"))
include(joinpath(@__DIR__, "app_window_titles.jl"))
include(joinpath(@__DIR__, "app_custom_rendering.jl"))
include(joinpath(@__DIR__, "demo_helper.jl"))
include(joinpath(@__DIR__, "demo_widgets.jl"))
include(joinpath(@__DIR__, "demo_layout.jl"))
include(joinpath(@__DIR__, "demo_popups.jl"))
include(joinpath(@__DIR__, "demo_columns.jl"))
include(joinpath(@__DIR__, "demo_misc.jl"))

let
# examples Apps (accessible from the "Examples" menu)
show_app_documents=false
show_app_main_menu_bar=false
show_app_console=false
show_app_log=false
show_app_layout=false
show_app_property_editor=false
show_app_long_text=false
show_app_auto_resize=false
show_app_constrained_resize=false
show_app_simple_overlay=false
show_app_window_titles=false
show_app_custom_rendering=false
# Dear ImGui apps (accessible from the "Help" menu)
show_app_metrics = false
show_app_style_editor = false
show_app_about = false
# demonstrate the various window flags. typically you would just use the default!
no_titlebar = false
no_scrollbar = false
no_menu = false
no_move = false
no_resize = false
no_collapse = false
no_close = false
no_nav = false
no_background = false
no_bring_to_front = false
"""
    ShowDemoWindow(p_open::Ref{Bool})
Demonstrate most Dear ImGui features.
You may execute this function to experiment with the UI and understand what it does.
You may then search for keywords in the code when you are interested by a specific feature.
"""
global function ShowDemoWindow(p_open::Ref{Bool})
    # examples Apps (accessible from the "Examples" menu)
    # show_app_documents           && @c ShowExampleAppDocuments(&show_app_documents) # process the Document app next, as it may also use a DockSpace()
    show_app_main_menu_bar       && @c ShowExampleAppMainMenuBar(&show_app_main_menu_bar)
    # show_app_console             && @c ShowExampleAppConsole(&show_app_console)
    # show_app_log                 && @c ShowExampleAppLog(&show_app_log)
    show_app_layout              && @c ShowExampleAppLayout(&show_app_layout)
    show_app_property_editor     && @c ShowExampleAppPropertyEditor(&show_app_property_editor)
    show_app_long_text           && @c ShowExampleAppLongText(&show_app_long_text)
    show_app_auto_resize         && @c ShowExampleAppAutoResize(&show_app_auto_resize)
    show_app_constrained_resize  && @c ShowExampleAppConstrainedResize(&show_app_constrained_resize)
    show_app_simple_overlay      && @c ShowExampleAppSimpleOverlay(&show_app_simple_overlay)
    show_app_window_titles       && @c ShowExampleAppWindowTitles(&show_app_window_titles)
    show_app_custom_rendering    && @c ShowExampleAppCustomRendering(&show_app_custom_rendering)

    # Dear ImGui apps (accessible from the "Help" menu)
    show_app_metrics && @c CImGui.ShowMetricsWindow(&show_app_metrics)
    if show_app_style_editor
        @c CImGui.Begin("Style Editor", &show_app_style_editor)
        CImGui.ShowStyleEditor()
        CImGui.End()
    end
    show_app_about && @c ShowAboutWindow(&show_app_about)

    # demonstrate the various window flags. typically you would just use the default!
    window_flags = CImGui.ImGuiWindowFlags(0)
    no_titlebar       && (window_flags |= CImGui.ImGuiWindowFlags_NoTitleBar;)
    no_scrollbar      && (window_flags |= CImGui.ImGuiWindowFlags_NoScrollbar;)
    !no_menu          && (window_flags |= CImGui.ImGuiWindowFlags_MenuBar;)
    no_move           && (window_flags |= CImGui.ImGuiWindowFlags_NoMove;)
    no_resize         && (window_flags |= CImGui.ImGuiWindowFlags_NoResize;)
    no_collapse       && (window_flags |= CImGui.ImGuiWindowFlags_NoCollapse;)
    no_nav            && (window_flags |= CImGui.ImGuiWindowFlags_NoNav;)
    no_background     && (window_flags |= CImGui.ImGuiWindowFlags_NoBackground;)
    no_bring_to_front && (window_flags |= CImGui.ImGuiWindowFlags_NoBringToFrontOnFocus;)
    no_close && (p_open = C_NULL;) # don't pass our bool* to Begin

    # specify a default position/size in case there's no data in the .ini file.
    # typically this isn't required! we only do it to make the Demo applications a little more welcoming.
    CImGui.SetNextWindowPos((650, 20), CImGui.ImGuiCond_FirstUseEver)
    CImGui.SetNextWindowSize((550, 680), CImGui.ImGuiCond_FirstUseEver)

    # main body of the Demo window starts here.
    CImGui.Begin("ImGui Demo", p_open, window_flags) || (CImGui.End(); return)
    CImGui.Text("dear imgui says hello. $(CImGui.IMGUI_VERSION)")

    # most "big" widgets share a common width settings by default.
    # CImGui.PushItemWidth(CImGui.GetWindowWidth() * 0.65)    # use 2/3 of the space for widgets and 1/3 for labels (default)
    CImGui.PushItemWidth(CImGui.GetFontSize() * -12)        # use fixed width for labels (by passing a negative value), the rest goes to widgets. We choose a width proportional to our font size.

    # menu
    if CImGui.BeginMenuBar()
        if CImGui.BeginMenu("Menu")
            ShowExampleMenuFile()
            CImGui.EndMenu()
        end
        if CImGui.BeginMenu("Examples")
            @c CImGui.MenuItem("Main menu bar", C_NULL, &show_app_main_menu_bar)
            # @c CImGui.MenuItem("Console", C_NULL, &show_app_console)
            # @c CImGui.MenuItem("Log", C_NULL, &show_app_
            @c CImGui.MenuItem("Simple layout", C_NULL, &show_app_layout)
            @c CImGui.MenuItem("Property editor", C_NULL, &show_app_property_editor)
            @c CImGui.MenuItem("Long text display", C_NULL, &show_app_long_text)
            @c CImGui.MenuItem("Auto-resizing window", C_NULL, &show_app_auto_resize)
            @c CImGui.MenuItem("Constrained-resizing window", C_NULL, &show_app_constrained_resize)
            @c CImGui.MenuItem("Simple overlay", C_NULL, &show_app_simple_overlay)
            @c CImGui.MenuItem("Manipulating window titles", C_NULL, &show_app_window_titles)
            @c CImGui.MenuItem("Custom rendering", C_NULL, &show_app_custom_rendering)
            CImGui.EndMenu()
        end
        if CImGui.BeginMenu("Help")
            @c CImGui.MenuItem("Metrics", C_NULL, &show_app_metrics)
            @c CImGui.MenuItem("Style Editor", C_NULL, &show_app_style_editor)
            @c CImGui.MenuItem("About Dear ImGui", C_NULL, &show_app_about)
            CImGui.EndMenu()
        end
        CImGui.EndMenuBar()
    end

    CImGui.Spacing()
    if CImGui.CollapsingHeader("Help")
        CImGui.Text("PROGRAMMER GUIDE:")
        CImGui.BulletText("Please see the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!")
        CImGui.BulletText("Please see the comments in imgui.cpp.")
        CImGui.BulletText("Please see the examples/ in application.")
        CImGui.BulletText("Enable 'io.ConfigFlags |= NavEnableKeyboard' for keyboard controls.")
        CImGui.BulletText("Enable 'io.ConfigFlags |= NavEnableGamepad' for gamepad controls.")
        CImGui.Separator()
        CImGui.Text("USER GUIDE:")
        CImGui.ShowUserGuide()
    end

    if CImGui.CollapsingHeader("Configuration")
        io = CImGui.GetIO()
        if CImGui.TreeNode("Configuration##2")
            @c CImGui.CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &io.ConfigFlags, CImGui.ImGuiConfigFlags_NavEnableKeyboard)
            @c CImGui.CheckboxFlags("io.ConfigFlags: NavEnableGamepad", &io.ConfigFlags, CImGui.ImGuiConfigFlags_NavEnableGamepad)
            CImGui.SameLine()
            ShowHelpMarker("Required back-end to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details.");
            @c CImGui.CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", &io.ConfigFlags, CImGui.ImGuiConfigFlags_NavEnableSetMousePos)
            CImGui.SameLine()
            ShowHelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos.")
            @c CImGui.CheckboxFlags("io.ConfigFlags: NoMouse", &io.ConfigFlags, CImGui.ImGuiConfigFlags_NoMouse)
            if io.ConfigFlags & CImGui.ImGuiConfigFlags_NoMouse != 0 # create a way to restore this flag otherwise we could be stuck completely!
                if mod(CImGui.GetTime(), 0.4) < 0.2
                    CImGui.SameLine()
                    CImGui.Text("<<PRESS SPACE TO DISABLE>>")
                end
                if CImGui.IsKeyPressed(CImGui.GetKeyIndex(CImGui.ImGuiKey_Space))
                    io.ConfigFlags &= ~Cuint(CImGui.ImGuiConfigFlags_NoMouse)
                end
            end
            @c CImGui.CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", &io.ConfigFlags, CImGui.ImGuiConfigFlags_NoMouseCursorChange)
            CImGui.SameLine()
            ShowHelpMarker("Instruct back-end to not alter mouse cursor shape and visibility.")
            @c CImGui.Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink)
            CImGui.SameLine()
            ShowHelpMarker("Set to false to disable blinking cursor, for users who consider it distracting")
            @c CImGui.Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges)
            CImGui.SameLine()
            ShowHelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback.")
            @c CImGui.Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly)
            @c CImGui.Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor)
            CImGui.SameLine()
            ShowHelpMarker("Instruct Dear ImGui to render a mouse cursor for you. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something).")
            CImGui.TreePop()
            CImGui.Separator()
        end

        if CImGui.TreeNode("Backend Flags")
            ShowHelpMarker("Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities.")
            backend_flags = io.BackendFlags # make a local copy to avoid modifying the back-end flags.
            @c CImGui.CheckboxFlags("io.BackendFlags: HasGamepad", &backend_flags, CImGui.ImGuiBackendFlags_HasGamepad)
            @c CImGui.CheckboxFlags("io.BackendFlags: HasMouseCursors", &backend_flags, CImGui.ImGuiBackendFlags_HasMouseCursors)
            @c CImGui.CheckboxFlags("io.BackendFlags: HasSetMousePos", &backend_flags, CImGui.ImGuiBackendFlags_HasSetMousePos)
            CImGui.TreePop()
            CImGui.Separator()
        end

        if CImGui.TreeNode("Style")
            CImGui.ShowStyleEditor()
            CImGui.TreePop()
            CImGui.Separator()
        end

        if CImGui.TreeNode("Capture/Logging")
            CImGui.TextWrapped("The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded.");
            ShowHelpMarker("Try opening any of the contents below in this window and then click one of the \"Log To\" button.");
            CImGui.LogButtons()
            CImGui.TextWrapped("You can also call CImGui.LogText() to output directly to the log without a visual output.");
            if (CImGui.Button("Copy \"Hello, world!\" to clipboard"))
                CImGui.LogToClipboard()
                CImGui.LogText("Hello, world!")
                CImGui.LogFinish()
            end
            CImGui.TreePop()
        end
    end

    if CImGui.CollapsingHeader("Window options")
        @c CImGui.Checkbox("No titlebar", &no_titlebar)
        CImGui.SameLine(150)
        @c CImGui.Checkbox("No scrollbar", &no_scrollbar)
        CImGui.SameLine(300)
        @c CImGui.Checkbox("No menu", &no_menu)
        @c CImGui.Checkbox("No move", &no_move)
        CImGui.SameLine(150)
        @c CImGui.Checkbox("No resize", &no_resize)
        CImGui.SameLine(300)
        @c CImGui.Checkbox("No collapse", &no_collapse)
        @c CImGui.Checkbox("No close", &no_close)
        CImGui.SameLine(150)
        @c CImGui.Checkbox("No nav", &no_nav)
        CImGui.SameLine(300)
        @c CImGui.Checkbox("No background", &no_background)
        @c CImGui.Checkbox("No bring to front", &no_bring_to_front)
    end

    # all demo contents
    ShowDemoWindowWidgets()
    ShowDemoWindowLayout()
    ShowDemoWindowPopups()
    ShowDemoWindowColumns()
    ShowDemoWindowMisc()

    CImGui.End() # demo
end

end # let


text:
@testset "Helmholtz fancy" begin

# Only on one processor...
# Start by importing both `PetscWrap`, for the distributed matrices, and `SlepcWrap` for the eigenvalues.
using PetscWrap
using SlepcWrap

# Number of mesh points and mesh step
n = 21
Δx = 1. / (n - 1)

# Initialize SLEPc. Either without arguments, calling `SlepcInitialize()` or using "command-line" arguments.
# To do so, either provide the arguments as one string, for instance
# `SlepcInitialize("-eps_max_it 100 -eps_tol 1e-5")` or provide each argument in
# separate strings : `PetscInitialize(["-eps_max_it", "100", "-eps_tol", "1e-5")`.
# Here we ask for the five closest eigenvalues to ``0``, using a non-zero pivot for the LU factorization and a
# "shift-inverse" process.
SlepcInitialize("-eps_target 0 -eps_nev 5 -st_pc_factor_shift_type NONZERO -st_type sinvert")

# Create the problem matrices, set sizes and apply "command-line" options. Note that we should
# set the number of preallocated non-zeros to increase performance.
A = create_matrix(n, n)
B = create_matrix(n, n)
set_from_options!(A)
set_from_options!(B)
set_up!(A)
set_up!(B)

# Get rows handled by the local processor
A_rstart, A_rend = get_range(A)
B_rstart, B_rend = get_range(B)

# Fill matrix A  with second order derivative central scheme
for i in A_rstart:A_rend
    if (i == 1)
        A[1, 1:2] = [-2., 1] / Δx^2
    elseif (i == n)
        A[n, n-1:n] = [1., -2.] / Δx^2
    else
        A[i, i-1:i+1] = [1., -2., 1.] / Δx^2
    end
end

# Fill matrix B with identity matrix
for i in B_rstart:B_rend
    B[i,i] = -1.
end

# Set boundary conditions : u(0) = 0 and u(1) = 0. Only the processor handling the corresponding rows are playing a role here.
(A_rstart == 1) && (A[1, 1:2] = [1. 0.] )
(B_rstart == 1) && (B[1,   1] = 0.      )

(A_rend == n) && (A[n, n-1:n] = [0. 1.] )
(B_rend == n) && (B[n,     n] = 0.      )

# Assemble the matrices
assemble!(A)
assemble!(B)

# Now we set up the eigenvalue solver
eps = create_eps(A, B)
set_from_options!(eps)
set_up!(eps)

# Then we solve
solve!(eps)

# And finally we can inspect the solution. Let's first get the number of converged eigenvalues:
nconv = neigs(eps)

# Then we can get/display these eigenvalues (more precisely their square root, i.e ``\simeq \omega``)
expected = (
    3.138363829113791,
    6.2573786016092345,
    9.337814554236218,
    12.360679774997893
)
for ieig in 1:4
    vp = get_eig(eps, ieig)
    @test isapprox(√(real(vp)), expected[ieig])

end

# You can also get all the converged eigenvalues in one call
eigs = get_eigenvalues(eps)

# We can also play with eigen vectors.
for ieig in 1:nconv
    vpr, vpi, vecpr, vecpi = get_eigenpair(eps, ieig)

    ## At this point, you can call VecGetArray to obtain a Julia array (see PetscWrap examples).
    ## If you are on one processor, you can even plot the solution to check that you have a sinus
    ## solution. On multiple processors, this would require to "gather" the solution on one processor only.
end

# Finally, let's free the memory
destroy!(A)
destroy!(B)
destroy!(eps)

# And call finalize when you're done
SlepcFinalize()

# Test if we reached this point
@test true

end


text:
import PeriodicGraphs

function export_dataline(f, x)
    inbetween = '\t'
    if any(isspace, x)
        if any(==('\n'), x)
            x = ';'*x*"\n;"
            inbetween = '\n'
        else
            @assert x[1]!= '\''
            x = '\''*x*'\''
        end
    end
    println(f, inbetween*x)
end

function export_vtf(file, c::Union{Crystal{Nothing},CrystalNet}, repeatedges=1, colorname=false)
    mkpath(splitdir(file)[1])
    n = length(c.types)
    if c isa CrystalNet
        @assert length(c.pos) == n
    else
        @assert size(c.pos)[2] == n
    end
    invcorres = [PeriodicVertex3D(i) for i in 1:n]
    corres = Dict{PeriodicVertex3D,Int}([invcorres[i]=>i for i in 1:n])
    encounteredtypes = Dict{Symbol,String}()
    numencounteredtypes = 0
    open(file, write=true) do f
        println(f, """
        ###############################
        # written by PeriodicGraphs.jl
        ###############################
        """)

        for i in 1:n
            ty = c.types[i]
            sty = ty === Symbol("") ? string(i) : string(ty)
            name = colorname ? get!(encounteredtypes, ty) do
                string(numencounteredtypes+=1)
            end : string(i)
            println(f, "atom $(i-1) type $sty name $name resid $(i-1)")
        end
        j = n + 1
        for _ in 1:repeatedges
            jmax = j - 1
            for i in 1:jmax
                vertex = invcorres[i]
                for x in neighbors(c.graph, vertex.v)
                    y = PeriodicVertex3D(x.v, x.ofs .+ vertex.ofs)
                    if get!(corres, y, j) == j
                        j += 1
                        push!(invcorres, y)
                    end
                end
            end
        end
        for i in n+1:length(invcorres)
            v = invcorres[i].v
            ofs = invcorres[i].ofs
            ty = c.types[v]
            sty = ty === Symbol("") ? string(i) : string(ty)
            name = colorname ? encounteredtypes[ty] : string(v)
            println(f, "atom $(i-1) type $sty name $name resid $v")
        end
        println(f)

        for (i,x) in enumerate(invcorres)
            for neigh in neighbors(c.graph, x.v)
                j = get(corres, PeriodicVertex3D(neigh.v, neigh.ofs .+ x.ofs), nothing)
                isnothing(j) && continue
                if i < j
                    println(f, "bond ", i - 1, ':', j - 1)
                end
            end
        end
        println(f)

        _a, _b, _c, α, β, γ = cell_parameters(c.cell)
        println(f, "pbc $_a $_b $_c $α $β $γ\n")

        println(f, "ordered")
        for x in invcorres
            coord = c isa CrystalNet ?
                c.cell.mat * (widen.(c.pos[x.v]) .+ x.ofs) :
                c.pos[:,x.v] + c.cell.mat * x.ofs
            println(f, join(round.(Float64.(coord); digits=15), ' '))
        end
    end
end

function export_vtf(file, cif::CIF, repeatedges=1)
    export_vtf(file, CrystalNet(cif), repeatedges, true)
end

function export_cif(file, c::Union{Crystal, CIF})
    mkpath(splitdir(file)[1])
    info = c isa CIF ? copy(c.cifinfo) : Dict{String,Union{String,Vector{String}}}("data"=>last(splitdir(file)))
    loops = Dict{Int, Tuple{Vector{String}, Vector{Vector{String}}}}()
    open(file, write=true) do f
        print(f, "data_"); println(f, pop!(info, "data")*"\n\n")
        for (id, data) in info
            if data isa String
                print(f, '_'); print(f, id)
                export_dataline(f, data)
            else
                @assert data isa Vector{String}
                n = length(data)
                if haskey(loops, n)
                    push!(loops[n][1], id)
                    push!(loops[n][2], data)
                else
                    loops[n] = (String[id], Vector{String}[data])
                end
            end
        end

        #scale_factor::Float64 = unique!(sort(c.types)) == [:Si] && c.pos[:,1] != [0,0,0] ? 1.2 : 1.0
        _a, _b, _c, α, β, γ = Float64.(cell_parameters(c.cell))

        println(f, """

        _cell_length_a\t\t$_a
        _cell_length_b\t\t$_b
        _cell_length_c\t\t$_c
        _cell_angle_alpha\t\t$α
        _cell_angle_beta\t\t$β
        _cell_angle_gamma\t\t$γ

        _symmetry_space_group_name_H-M\t'$(c.cell.spacegroup)'""")
        if c.cell.tablenumber != 0
            println(f, "_symmetry_Int_Tables_number\t$(c.cell.tablenumber)")
        end
        if c.cell.latticesystem !== Symbol("")
            println(f, "_symmetry_cell_setting\t$(c.cell.latticesystem)")
        end

        println(f, """

        loop_
        _symmetry_equiv_pos_as_xyz
        x,y,z""")
        for eq in c.cell.equivalents
            println(f, eq)
        end
        println(f)

        n = c isa CIF ? length(c.ids) : length(c.types)
        if !haskey(loops, n)
            loops[n] = (String[], Vector{String}[])
        end
        append!(loops[n][1],
                ["atom_site_label", "atom_site_type_symbol",
                 "atom_site_fract_x", "atom_site_fract_y", "atom_site_fract_z"])
        labels = String[string(c.types[c isa CIF ? c.ids[i] : i])*string(i) for i in 1:n]
        pos = string.(round.(c.pos; sigdigits=6))
        append!(loops[n][2], [labels, string.(c.types[x] for x in (c isa CIF ? c.ids : collect(1:n))),
                pos[1,:], pos[2,:], pos[3,:]])

        if c isa Crystal
            bonds = edges(c.graph)
            src = String[]
            dst = String[]
            mult = Int[]
            last_bond = (0, 0)
            n = 0
            for e in bonds
                if (e.src, e.dst.v) == last_bond
                    mult[end] += 1
                else
                    push!(src, string(labels[e.src]))
                    push!(dst, string(labels[e.dst.v]))
                    push!(mult, 1)
                    last_bond = (e.src, e.dst.v)
                    n += 1
                end
            end
            if !haskey(loops, n)
                loops[n] = (String[], Vector{String}[])
            end
            append!(loops[n][1], ["geom_bond_atom_site_label_1", "geom_bond_atom_site_label_2", "geom_bond_multiplicity"])
            append!(loops[n][2], [src, dst, string.(mult)])
        end

        for (n, (ids, datas)) in loops
            println(f, "loop_")
            for id in ids
                print(f, '_'); println(f, id)
            end
            for i in 1:n
                for j in 1:length(datas)
                    print(f, datas[j][i]); print(f, '\t')
                end
                println(f)
            end
            println(f)
        end
        println(f, "\n#END")
    end
    nothing
end

function export_cgd(file, c::Crystal)
    mkpath(splitdir(file)[1])
    invmat = Float64.(inv(c.cell.mat))
    open(file, write=true) do f
        println(f, "CRYSTAL\n")
        margin = 1
        println(f, "\tNAME\t", last(splitdir(file)))
        #scale_factor::Float64 = unique!(sort(c.types)) == [:Si] && c.pos[:,1] != [0,0,0] ? 1.2 : 1.0
        _a, _b, _c, α, β, γ = Float64.(cell_parameters(c.cell))
        println(f, "\tGROUP\t\"", join(split(c.cell.spacegroup, ' ')), "\"")
        println(f, "\tCELL\t", _a, ' ', _b, ' ', _c, ' ', α, ' ', β, ' ', γ, ' ')
        println(f, "\tATOM")
        to_revisit = Int[]
        for i in 1:length(c.types)
            push!(to_revisit, i)
            pos = invmat * c.pos[:,i]
            println(f, "\t\t", i, ' ', degree(c.graph, i), ' ', pos[1], ' ',
                    pos[2], ' ', pos[3])
        end
        println(f, "\tEDGE")
        for i in to_revisit
            for e in neighbors(c.graph, i)
                e.v < i && continue
                dest = invmat * c.pos[:,e.v] .+ e.ofs
                println(f, "\t\t", i, '\t', dest[1], ' ', dest[2], ' ', dest[3])
            end
        end
        println(f, "\nEND")
    end
end

function export_cgd(file, g::PeriodicGraph)
    mkpath(splitdir(file)[1])
    open(file, write=true) do f
        println(f, "PERIODIC_GRAPH\n")
        println(f, "ID ", basename(splitext(file)[1]), '\n')
        println(f, "EDGES")
        repr = reverse(split(string(g)))
        n = parse(Int, pop!(repr))
        m = length(repr) ÷ (n+2)
        @assert iszero(length(repr) % (n+2))
        for _ in 1:m
            src = pop!(repr)
            dst = pop!(repr)
            ofs = Vector{String}(undef, n)
            for i in 1:n
                ofs[i] = pop!(repr)
            end
            println(f, '\t', src, ' ', dst, ' ', join(ofs, ' '))
        end
        println(f, "END\n")
    end
end
export_cgd(file, c::CrystalNet) = export_cgd(file, c.graph)

function export_clusters(crystal::Crystal{Clusters}, path=joinpath(tempdir(),tempname()))
    frame = Chemfiles.Frame()
    m = length(crystal.clusters.classes)
    # residues = [Chemfiles.Residue(string(i)) for i in 1:m]
    # for i in 1:m
    #     Chemfiles.set_property!(residues[i], "chainname", string(i))
    #     Chemfiles.set_property!(residues[i], "chainid", string(i))
    #     Chemfiles.add_residue!(frame, residues[i])
    # end
    _a, _b, _c, α, β, γ = cell_parameters(crystal.cell)
    Chemfiles.set_cell!(frame, Chemfiles.UnitCell(_a, _b, _c, α, β, γ))
    recenter::SVector{3,Float64} = minimum(crystal.pos; dims=2)
    for i in 1:length(crystal.types)
        # resid = crystal.clusters.attributions[i]
        atom = Chemfiles.Atom(string(crystal.clusters.classes[crystal.clusters.attributions[i]]))
        Chemfiles.set_type!(atom, string(crystal.types[i]))
        Chemfiles.add_atom!(frame, atom, collect(Float64.(crystal.pos[:,i] .- recenter)))
        # Chemfiles.add_atom!(residues[resid], i)
    end
    for e in edges(crystal.graph)
        iszero(PeriodicGraphs.ofs(e)) || continue
        Chemfiles.add_bond!(frame, src(e)-1, dst(e)-1)
    end
    target = isempty(last(splitext(path))) ? path*".pdb" : path
    output = Chemfiles.Trajectory(target, 'w')
    write(output, frame)
    close(output)
    return target
end

"""
    export_arc(path)

Export the current archive to the specified path.
"""
function export_arc(path, empty=false, arc=CRYSTAL_NETS_ARCHIVE)
    mkpath(splitdir(path)[1])
    open(path, "w") do f
        println(f, "Made by CrystalNets.jl v$CRYSTAL_NETS_VERSION")
        if !empty
            println(f)
            pairs = sort(collect(arc); by=last)
            for (genome, id) in pairs
                println(f, "key\t", genome)
                println(f, "id\t", id)
                println(f)
            end
        end
    end
end


text:
(F::FqFiniteField)(coeffs::Array{T,1}) where {T<:Union{Integer,fmpz}} = begin
    g = gen(F)
    x = zero(F)
    for (i, c) in enumerate(coeffs)
        x += c * g^(i-1)
    end
    x
end

(F::FqNmodFiniteField)(coeffs::Array{T,1}) where {T<:Union{Integer,fmpz}} = begin
    g = gen(F)
    x = zero(F)
    for (i, c) in enumerate(coeffs)
        x += c * g^(i-1)
    end
    x
end

sqrt(a::FinFieldElem) = root(a, 2)

# http://trac.sagemath.org/ticket/7931
# http://sagenb.org/src/rings/finite_rings/element_base.pyx
root(a::FinFieldElem, n::Integer) = root(a, fmpz(n))
root(a::FinFieldElem, n::fmpz) = begin
    if iszero(a)
        n <= 0 && throw(DomainError())
        return a
    end

    K = parent(a)
    q = order(K)

    if n < 0
        a = inv(a)
        n = -n
    elseif n == 0
        a == 1 || throw(DomainError())
        return a
    end

    if isone(a)
        GCD = gcd(n, q-1)
        GCD == 1 && return a

        g = gen(K) # TODO: The generator is guaranteed to be a multiplicative generator only if the field is generated by a Conway polynomial.
        q1overn = (q-1) ÷ GCD
        nthroot = g^q1overn
        return nthroot
    end

    m = n % (q-1)
    m == 0 && error("$(a) has no $(n)th root in $(K)")

    # GCD = α*m + β*(q-1), so 1/m = α/GCD (mod q-1)
    GCD, α, β = gcdx(m, q-1)
    GCD == 1 && return a^α

    m = GCD
    q1overn = (q-1) ÷ m
    a^q1overn != 1 && error("$(a) has no $(n)th root in $(K)")

    b = a^α
    F = [(fmpz(p), e) for (p, e) in factor(BigInt(m))]

    g = gen(K) # TODO: The generator is guaranteed to be a multiplicative generator only if the field is generated by a Conway polynomial.
    for (r, v) in F
        k, h = remove(q-1, r)
        z = h * invmod(-h, r^v)::typeof(h)
        x = (1 + z) ÷ (r^v)
        if k == 1
            b = b^x
        else
            t = log(b^h, g^(r^v * h), r^(k-v))
            b = b^x * g^(-z*t)
        end
    end
    b
end

sqrts(a::FinFieldElem) = roots(a, 2)

# http://trac.sagemath.org/ticket/7931
# http://sagenb.org/src/rings/finite_rings/element_base.pyx
roots(a::FinFieldElem, n::Integer) = roots(a, fmpz(n))
roots(a::T, n::fmpz) where {T<:FinFieldElem} = begin
    if iszero(a)
        n <= 0 && throw(DomainError())
        return [a]
    end

    K = parent(a)
    q = order(K)

    if n < 0
        a = inv(a)
        n = -n
    elseif n == 0
        a == 1 || throw(DomainError())
        e = elements(K)
        e[e .!= 0]
    end

    if isone(a)
        GCD = gcd(n, q-1)
        GCD == 1 && return [a]

        g = gen(K) # TODO: The generator is guaranteed to be a multiplicative generator only if the field is generated by a Conway polynomial.
        q1overn = (q-1) ÷ GCD
        nthroot = g^q1overn
        return [nthroot^i for i in 0:(GCD-1)]
    end

    m = n % (q-1)
    m == 0 && return T[]

    # GCD = α*m + β*(q-1), so 1/m = α/GCD (mod q-1)
    GCD, α, β = gcdx(m, q-1)
    GCD == 1 && return [a^α]

    m = GCD
    q1overn = (q-1) ÷ m
    a^q1overn != 1 && return T[]

    b = a^α
    F = [(fmpz(p), e) for (p, e) in factor(BigInt(m))]

    g = gen(K) # TODO: The generator is guaranteed to be a multiplicative generator only if the field is generated by a Conway polynomial.
    for (r, v) in F
        k, h = remove(q-1, r)
        z = h * invmod(-h, r^v)::typeof(h)
        x = (1 + z) ÷ (r^v)
        if k == 1
            b = b^x
        else
            t = log(b^h, g^(r^v * h), r^(k-v))
            b = b^x * g^(-z*t)
        end
    end

    nthroot = g^q1overn
    L = [b]
    for _ in 1:(m-1)
        b *= nthroot
        push!(L, b)
    end
    L
end

elements(F::Union{FqFiniteField,FqNmodFiniteField}) = begin
    p = characteristic(F)
    k = degree(F)

    e = typeof(zero(F))[]
    @forcartesian c [p for _ in 1:k] begin
        push!(e, F(c .- 1))
    end
    e
end

rand(F::Union{FqFiniteField,FqNmodFiniteField}) = begin
    p = characteristic(F)
    k = degree(F)

    F([rand(0:(p-1)) for _ in 1:k])
end


text:
import Base: @deprecate

@deprecate by(d::AbstractDataFrame, cols, s::Vector{Symbol}) aggregate(d, cols, map(eval, s))
@deprecate by(d::AbstractDataFrame, cols, s::Symbol) aggregate(d, cols, eval(s))
@deprecate nullable!(colnames::Array{Symbol,1}, df::AbstractDataFrame) nullable!(df, colnames)
@deprecate nullable!(colnums::Array{Int,1}, df::AbstractDataFrame) nullable!(df, colnums)
import Base: keys, values, insert!
@deprecate keys(df::AbstractDataFrame) names(df)
@deprecate values(df::AbstractDataFrame) DataFrames.columns(df)
@deprecate insert!(df::DataFrame, df2::AbstractDataFrame) merge!(df, df2)

import DataArrays: array, DataArray
@deprecate array(df::AbstractDataFrame) convert(Array, df)
@deprecate array(r::DataFrameRow) convert(Array, r)
if VERSION < v"0.4.0-"
    @deprecate DataArray(df::AbstractDataFrame) convert(DataArray, df)
end
@deprecate DataArray(df::AbstractDataFrame, T::DataType) convert(DataArray{T}, df)

@deprecate read_rda(args...) FileIO.load(args...)