text:
using DelimitedFiles
using Serialization
using SparseArrays

function load_lastfm(path="./lastfm-dataset-360K/usersha1-artmbid-artname-plays.tsv")
    function index!(dict, name)
        i = get(dict, name, 0)
        if i == 0
            dict[name] = i = length(dict) + 1
        end
        return i
    end

    data = Array{Int}(undef, countlines(open(path)), 3)
    users = Dict{String, Int}()
    items = Dict{String, Int}()
    for (i, line) in enumerate(eachline(path))
        cells = split(line, '\t')
        data[i, 1] = index!(users, cells[1])
        data[i, 2] = index!(items, cells[2])
        data[i, 3] = parse(Int, cells[4])
    end

    return data
end

lastfm = load_lastfm()
lastfm = sparse(view(lastfm, :, 2),
                view(lastfm, :, 1),
                view(lastfm, :, 3))
serialize("lastfm.jlser", lastfm)

ext: jl

max_stars_repo_name: plafl/julia-cython-comp

max_issues_repo_name: plafl/julia-cython-comp

max_forks_repo_name: plafl/julia-cython-comp


text:
module TestViterbi
    import Base.Test
    include("../src/viterbi.jl")

    create_template(nstates::Integer) = create_template(nstates, 1.0, 0.8, 0.2)
    function create_template(nstates::Integer, a::Real, b::Real, c::Real)
        x = linspace(0,1.5,nstates)
        y = a*sin(2*pi*x).*exp(-(b-x).^2/c)
        return y
    end

    function create_signal(N::Integer, sigma::Number,nspikes::Integer, nstates::Integer)
        T = create_template(nstates)
        return create_signal(N,sigma,nspikes,T)
    end

    function create_signal(N::Integer, sigma::Number, nspikes::Integer, template::Array{Float64,1})
        nstates = length(template)
        S = rand(Normal(0,sigma),N)
        spike_idx = rand(1:N,nspikes)
        for i=1:nspikes
            S[spike_idx[i]:spike_idx[i] + nstates-1] += template
        end
        return S
    end

    function viterbi(N::Integer, sigma::Number, nspikes::Integer, nstates::Integer)
        T = create_template(nstates)
        srand(1234)
        S = create_signal(N, sigma, nspikes, T)
        X = viterbi(S,nspikes/N, T, sigma*sigma)
        Q = T[X] #reconstruction
        return S,Q
    end

    function viterbi()
        S,Q = viterbi(10000,0.1,10,60)
        err = (Q-S)
        err = sum(err.*err)
        Base.Test.@test_approx_eq err 109.70934022342433
        println("Test passed. sse = $err")
    end

    function viterbi2(N::Integer, sigma::Number, nspikes::Integer, nstates::Integer)
        T1 = create_template(nstates)
        T2 = create_template(nstates, 3, 0.6, 0.1)
        srand(1235)
        S1 = create_signal(N, sqrt(2)*sigma, div(nspikes,2), T1)
        S2 = create_signal(N, sqrt(2)*sigma, div(nspikes,2), T2)
        S = S1 + S2
        T = cat(2,T1,T2)
        X = viterbi(S,nspikes/N, T, sigma*sigma)
        Q = T1[X[:,1]+1] + T2[X[:,2]+1] #reconstruction
        return S,Q
    end

    function viterbi2()
        S,Q = viterbi2(10000,0.1,10,60)
        err = S-Q
        err = sum(err.*err)
        Base.Test.@test_approx_eq err 464.267547552014
        println("Test passed. sse = $err")
    end
end


text:
using CommonLH, Random, Test

function check_float_test()
    @testset "Check float" begin
        @test check_float(1.2)
        @test check_float(-1.23; ub = -1.23)
        @test !check_float(1.2; lb = 1.2001)
        @test !check_float(NaN64)
        @test !check_float(-Inf)
    end
end

function check_array_test()
    @testset "Check float array" begin
        rng = MersenneTwister(32);
        dimV = (3,4,5);
        T1 = Float32;
        lb = -1.0;
        ub = Inf;
        m = lb .+ rand(rng, T1, dimV...);
        @test check_float_array(m, lb, ub)
        m[10] = lb - 1e-5;
        @test !check_float_array(m, lb, ub)
	end
end

function monotone_test(N :: Integer)
    rng = MersenneTwister(434);
    @testset "Monotone" begin
        sizeV = 6 : -1 : (7 - N);
        m1 = randn(rng, sizeV[1 : N]...);
        for strict in (true, false)
            for increasing in (true, false)
                for d = 1 : N
                    @test !is_monotone(m1, d; strict, increasing);

                    # Make array that is monotone in dimension d
                    m2 = copy(m1);
                    m3 = copy(m1);
                    increasing  ?  (dx = 0.001)  :  (dx = -0.001);
                    for j = 2 : sizeV[d]
                        selectdim(m2, d, j) .= selectdim(m2, d, j-1) .+ dx;
                        selectdim(m3, d, j) .= selectdim(m3, d, j-1);
                    end
                    @test is_monotone(m2, d; strict, increasing);
                    # Array is constant along dimension d
                    @test is_monotone(m2, d; strict, increasing, atol = 1e-6);
                end
            end
        end

    end
end

@testset "Checks" begin
    check_float_test()
    check_array_test()
    for N = 1 : 3
        monotone_test(N);
    end
end

# ------------


text:
mutable struct Trie{K,V}
    value::V
    children::Dict{K,Trie{K,V}}
    is_key::Bool

    function Trie{K,V}() where {K,V}
        self = new{K,V}()
        self.children = Dict{K,Trie{K,V}}()
        self.is_key = false
        return self
    end

    function Trie{K,V}(ks, vs) where {K,V}
        return Trie{K,V}(zip(ks, vs))
    end

    function Trie{K,V}(kv) where {K,V}
        t = Trie{K,V}()
        for (k,v) in kv
            t[k] = v
        end
        return t
    end
end

Trie() = Trie{Any,Any}()
Trie(ks::AbstractVector{K}, vs::AbstractVector{V}) where {K,V} = Trie{eltype(K),V}(ks, vs)
Trie(kv::AbstractVector{Tuple{K,V}}) where {K,V} = Trie{eltype(K),V}(kv)
Trie(kv::AbstractDict{K,V}) where {K,V} = Trie{eltype(K),V}(kv)
Trie(ks::AbstractVector{K}) where {K} = Trie{eltype(K),Nothing}(ks, similar(ks, Nothing))

function Base.setindex!(t::Trie{K,V}, val, key) where {K,V}
    value = convert(V, val) # we don't want to iterate before finding out it fails
    node = t
    for char in key
        if !haskey(node.children, char)
            node.children[char] = Trie{K,V}()
        end
        node = node.children[char]
    end
    node.is_key = true
    node.value = value
end

function Base.getindex(t::Trie, key)
    node = subtrie(t, key)
    if node != nothing && node.is_key
        return node.value
    end
    throw(KeyError("key not found: $key"))
end

function subtrie(t::Trie, prefix)
    node = t
    for char in prefix
        if !haskey(node.children, char)
            return nothing
        else
            node = node.children[char]
        end
    end
    return node
end

function Base.haskey(t::Trie, key)
    node = subtrie(t, key)
    node != nothing && node.is_key
end

function Base.get(t::Trie, key, notfound)
    node = subtrie(t, key)
    if node != nothing && node.is_key
        return node.value
    end
    return notfound
end

_concat(prefix::String, char::Char) = string(prefix, char)
_concat(prefix::Vector{T}, char::T) where {T} = vcat(prefix, char)

_empty_prefix(::Trie{Char,V}) where {V} = ""
_empty_prefix(::Trie{K,V}) where {K,V} = K[]

function Base.keys(t::Trie{K,V},
                   prefix=_empty_prefix(t),
                   found=Vector{typeof(prefix)}()) where {K,V}
    if t.is_key
        push!(found, prefix)
    end
    for (char,child) in t.children
        keys(child, _concat(prefix, char), found)
    end
    return found
end

function keys_with_prefix(t::Trie, prefix)
    st = subtrie(t, prefix)
    st != nothing ? keys(st,prefix) : []
end

# The state of a TrieIterator is a pair (t::Trie, i::Int),
# where t is the Trie which was the output of the previous iteration
# and i is the index of the current character of the string.
# The indexing is potentially confusing;
# see the comments and implementation below for details.
struct TrieIterator
    t::Trie
    str
end

# At the start, there is no previous iteration,
# so the first element of the state is undefined.
# We use a "dummy value" of it.t to keep the type of the state stable.
# The second element is 0
# since the root of the trie corresponds to a length 0 prefix of str.
function Base.iterate(it::TrieIterator, (t, i) = (it.t, 0))
    if i == 0
        return it.t, (it.t, firstindex(it.str))
    elseif i > lastindex(it.str) || !(it.str[i] in keys(t.children))
        return nothing
    else
        t = t.children[it.str[i]]
        return (t, (t, nextind(it.str, i)))
    end
end

partial_path(t::Trie, str) = TrieIterator(t, str)
Base.IteratorSize(::Type{TrieIterator}) = Base.SizeUnknown()

"""
    find_prefixes(t::Trie, str)

Find all keys from the `Trie` that are prefix of the given string

# Examples
```julia-repl
julia> t = Trie(["A", "ABC", "ABCD", "BCE"])

julia> find_prefixes(t, "ABCDE")
3-element Vector{AbstractString}:
 "A"
 "ABC"
 "ABCD"

julia> t′ = Trie([1:1, 1:3, 1:4, 2:4]);

julia> find_prefixes(t′, 1:5)
3-element Vector{UnitRange{Int64}}:
 1:1
 1:3
 1:4

julia> find_prefixes(t′, [1,2,3,4,5])
3-element Vector{Vector{Int64}}:
 [1]
 [1, 2, 3]
 [1, 2, 3, 4]
```
"""
function find_prefixes(t::Trie, str::T) where {T}
    prefixes = T[]
    it = partial_path(t, str)
    idx = 0
    for t in it
        if t.is_key
            push!(prefixes, str[firstindex(str):idx])
        end
        idx = nextind(str, idx)
    end
    return prefixes
end


text:
####################  Dataless Mask  ####################

struct CausalMask <: AbstractDatalessMask end

Base.@propagate_inbounds Base.getindex(::CausalMask, i, j, _...) = j >= i

struct LocalMask <: AbstractDatalessMask
    width::Int
end

Base.@propagate_inbounds Base.getindex(m::LocalMask, i, j, _...) = j - m.width < i < j + m.width

struct RandomMask <: AbstractDatalessMask
    p::Float64
end

Base.@propagate_inbounds Base.getindex(m::RandomMask, _::Integer...) = rand() > m.p

AxesConstraint(m::RandomMask) = ()

struct BandPartMask <: AbstractDatalessMask
    l::Int
    u::Int
end

Base.@propagate_inbounds Base.getindex(m::BandPartMask, i, j, _...) = (m.l < 0 || i <= j + m.l) && (m.u < 0 || i >= j - m.u)


text:
const parconv = 4.57mol*W^-1*s^-1

"""
    ManualTemperature(airtemperature, soiltemperature)

Environment for simple manual temperature control.

$(FIELDDOCTABLE)
"""
struct ManualTemperature{T}
    airtemperature::T
    soiltemperature::T
end

"""
    apply_environment!(organism::Organism, organs::Tuple, u, t)

Apply environmental conditions to an organism.
"""
apply_environment!(organism::AbstractOrganism, organs, u, t) =
    apply_environment!(environment(organism), organism, organs, u, t)

"""
    apply_environment!(organism, env::Nothing, organs, u, t)

No environment included, do nothing. Initial environment variables
will be used for the whole simulation
"""
apply_environment!(env::Nothing, organism, organs, u, t) = nothing

"""
    apply_environment!(plant, env::ManualTemperature, organs, u, t)

Apply an environment to a plant using live user input for variables,
instead of data.
"""
apply_environment!(env::ManualTemperature, plant::Plant, organs, u, t) = begin
    shoot, root = organs
    update_temp!(shoot, env.airtemperature)
    update_temp!(root, env.soiltemperature)
end

"""
    update_temp!(o, temp)

Set the temperature, and update the temperature correction variable.
"""
update_temp!(o, temp) = begin
    set_temp!(o, temp)
    set_tempcorrection!(o, tempcorr(tempcorr_pars(o), temp))
end


text:
julia> [1 2 3 ; 4 5 6]  # a 2x3 matrix
2x3 Array{Int64,2}:
 1  2  3
 4  5  6

julia> [1 2 3 ; 4 5 6]'  # note the quote
3x2 LinearAlgebra.Adjoint{Int64,Array{Int64,2}}:
 1  4
 2  5
 3  6

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
module TestCUDA
using Test
using CUDA
using Adapt
using LinearInterpolations
using LinearInterpolations: Replicate, Reflect, WithPoint, Constant
using StructArrays
using StaticArrays
const LI=LinearInterpolations

@testset "1d" begin
    itp_cpu = Interpolate(sort!(randn(Float32, 10)), randn(Float32, 10), extrapolate=LI.Replicate())
    pts_cpu = randn(Float32, 2)

    result_cpu = itp_cpu.(pts_cpu)
    itp_gpu = adapt(CuArray, itp_cpu)
    pts_gpu = adapt(CuArray, pts_cpu)
    result_gpu = itp_gpu.(pts_gpu)

    @test result_gpu isa CuArray
    @test CuArray(result_cpu) ≈ result_gpu
end

@testset "gpu ≈ cpu" begin
    setups = Any[]
    for extrapolate in [LI.Replicate(), LI.Reflect(), LI.Constant(Float32(42)),
                        #LI.WithPoint(sin∘sum),
                       ]
        for shape_itp in [(10,), (11,12), (11,12,13)]
            axs = Tuple(sort!(randn(Float32, n)) for n in shape_itp)
            vals = randn(Float32, shape_itp...)
            itp = Interpolate(axs, vals, extrapolate=extrapolate)
            dim = length(shape_itp)
            pts = [Tuple(randn(Float32,dim)) for _ in 1:30]
            setup = (;itp, pts, extrapolate, dim)
            push!(setups, setup)
        end
    end
    @testset "$(setup.dim)D $(setup.extrapolate)" for setup in setups
        result_cpu = setup.itp.(setup.pts)
        itp_gpu = adapt(CuArray, setup.itp)
        pts_gpu = adapt(CuArray, setup.pts)
        result_gpu = itp_gpu.(pts_gpu)
        @test result_gpu isa CuArray
        @test Array(result_gpu) ≈ result_cpu

        # TODO: add soa test
        # pts_gpu_soa = StructArray(Tuple(CuArray(map(pt -> pt[i], setup.pts)) for i in 1:setup.dim))
        # pts_gpu_soa = map(SVector{setup.dim}, pts_gpu_soa)
        # @test pts_gpu_soa isa StructArray
        # result_gpu_soa = itp_gpu.(pts_gpu_soa)
        # @test result_gpu_soa isa CuArray
        # @test Array(result_gpu_soa) == Array(result_gpu)
    end
end

end#module


text:
using ArgParse

function parse_commandline()
    s = ArgParseSettings()

    @add_arg_table s begin
        "--gpu", "-g"
            help = "use gpu"
            action = :store_true
        "task"
            help = "task name"
            required = true
            range_tester = x-> x ∈ ["cola", "mnli", "mrpc"]
    end

    return parse_args(ARGS, s)
end

const args = parse_commandline()

enable_gpu(args["gpu"])


text:
include(joinpath(dirname(dirname(@__DIR__)), "docs", "src", "tutorial_lit.jl"))

samples_mh = bat_sample(posterior, MCMCSampling(sampler = MetropolisHastings(), trafo = NoDensityTransform(), nsteps = 10^5)).result

posterior_is, trafo_is = bat_transform(PriorToGaussian(), posterior, PriorSubstitution())
posterior_is2, trafo_is2 = bat_transform(PriorToGaussian(), posterior, FullDensityTransform())

samples_is = bat_sample(posterior_is, MCMCSampling(sampler = HamiltonianMC(), trafo = NoDensityTransform(), nsteps = 10^5)).result
samples_is2 = bat_sample(posterior_is2, MCMCSampling(sampler = HamiltonianMC(), trafo = NoDensityTransform(), nsteps = 10^5)).result

samples = inv(trafo_is).(samples_is)
samples2 = inv(trafo_is2).(samples_is2)

plot(samples)

plot(-4:0.01:4, fit_function, samples)
plot!(
    normalize(hist, mode=:density),
    color=1, linewidth=2, fillalpha=0.0,
    st = :steps, fill=false, label = "Data",
    title = "Data, True Model and Best Fit"
)
plot!(-4:0.01:4, x -> fit_function(true_par_values, x), color=4, label = "Truth")

trafo_us_is = BAT.DistributionTransform(Uniform, trafoof(posterior_is.likelihood).target_dist)
samples_us = trafo_us_is.(samples_is)

bat_eff_sample_size(samples_mh)
bat_eff_sample_size(samples_is)
bat_eff_sample_size(samples_is2)
bat_eff_sample_size(samples)
bat_eff_sample_size(samples_us)

bat_integrate(samples_mh, AHMIntegration()).result
bat_integrate(samples_is, AHMIntegration()).result
bat_integrate(samples_is2, AHMIntegration()).result
bat_integrate(samples, AHMIntegration()).result
bat_integrate(samples_us, AHMIntegration()).result

mode_lbfgs = bat_findmode(posterior, MaxDensityLBFGS(init = ExplicitInit([mode(samples)]))).result

mode_lbfgs_is = bat_findmode(posterior_is, MaxDensityLBFGS(init = ExplicitInit([mode(samples_is)]))).result
mode_lbfgs_fromis = inv(trafo_is)(mode_lbfgs_is)

posterior_is_novc = trafoof(posterior_is.likelihood)(posterior; volcorr = Val(false))
mode_lbfgs_is_novc = bat_findmode(posterior_is_novc, MaxDensityLBFGS(init = ExplicitInit([mode(samples_is)]))).result
mode_lbfgs_fromis_novc = inv(trafo_is)(mode_lbfgs_is_novc)


text:
using Flux, CUDA

d = 10
N = 10
batch_size = 1000
use_cuda = true

if use_cuda && CUDA.functional()
    @info "Training on CUDA GPU"
    CUDA.allowscalar(false)
    device = Flux.gpu
else
    @info "Training on CPU"
    device = Flux.cpu
end

function sde_loop(d,batch_size)
    X0 = zeros(Float32,d)
    y0 = repeat(X0[:],1,batch_size)
    y1 = repeat(X0[:],1,batch_size)
    dt = 0.1
    dWall = sqrt(dt) * randn(d,batch_size,N)
    for i in 1:N
        dW = @view dWall[:,:,i]
        y0 .= y1
        y1 .= y0 .+ 0. * dt .+ 1. .* dW
    end
    return y0, y1
end

function sde_loop_CUDA(d,batch_size)
    X0 = CUDA.zeros(Float32,d)
    y0 = CUDA.repeat(X0[:],1,batch_size)
    y1 = CUDA.repeat(X0[:],1,batch_size)
    dt = 0.1
    dWall = sqrt(dt) * CUDA.randn(d,batch_size,N)
    for i in 1:N
        dW = @view dWall[:,:,i]
        y0 .= y1
        y1 .= y0 .+ 0. * dt .+ 1. .* dW
    end
    return y0, y1
end

using BenchmarkTools

@btime CUDA.randn(1000,1000)
@btime randn(1000,1000)

@btime sde_loop(d,batch_size)
@btime sde_loop_CUDA(d,batch_size)


text:
# Load DataFrame package
require("DataFrames")
using DataFrames

# Set the seed
srand(1)

# DataFrames can also be created with an expression
# Columns are repeated to the longest column
df = DataFrame(quote
    a = shuffle(LETTERS[1:10])
    b = letters[rand(1:5,50)]
    x = randn(50)
end)

# Grouping by column b, find the sum and length of each group
by(df, "b", :( x_sum = sum(x); x_len = length(x)))

# Group by a and b:
by(df, ["a", "b"], :( x_sum = sum(x); x_len = length(x) ))

#
# Digging deeper
#

# by is a shortcut for the following:
based_on(groupby(df, "b"), :( x_sum = sum(x); x_len = length(x) ))

# You can also use the piping operator for the same thing.
df | groupby("b") | :( x_sum = sum(x); x_len = length(x) )

# groupby returns a GroupedDataFrame
gd = groupby(df, "b")

# Iterations or references to a GroupedDataFrame return a
# SubDataFrame, a very useful way to subset a DataFrame without
# copies
gd[1]

# Look at the structure of a GroupedDataFrame
dump(gd)

# Look at the structure and internals of the SubDataFrame for the
# first group
dump(gd[1])
idump(gd[1])

# You can iterate over a GroupedDataFrame or perform other operations
# Here's within:
within(gd, :( x_sum = sum(x) ))


text:
# Practical Machine learning
# Ensemble learning example
# Chapter 13

# Ensemble module.
module Ensemble

# Load source files
include("types.jl")
include("util.jl")
include("transformers.jl")

end # module


text:
using Pkg

Pkg.add("KitBase")
Pkg.add("PyCall")

using KitBase
using PyCall

max_stars_repo_name: vavrines/kineticpy

max_issues_repo_name: vavrines/kineticpy

max_forks_repo_name: vavrines/kineticpy


text:
import Base: show

function _show_indented(io::IO, dep::LibraryDependency, indent, lib)
    print_indented(io,"- Library \"$(dep.name)\"",indent+1)
    if !applicable(dep)
        println(io," (not applicable to this system)")
    else
        println(io)
        if !isempty(lib)
            print_indented(io,"- Satisfied by:\n",indent+4)
            for (k,v) in lib
                print_indented(io,"- $(k[1]) at $v\n",indent+6)
            end
        end
        if length(dep.providers) > 0
            print_indented(io,"- Providers:\n",indent+4)
            for (p,opts) in dep.providers
                show_indented(io,p,indent+6)
                if !can_provide(p,opts,dep)
                    print(io," (can't provide)")
                end
                println(io)
            end
        end
    end
end
show_indented(io::IO, dep::LibraryDependency, indent) = _show_indented(io,dep,indent, applicable(dep) ? _find_library(dep) : nothing)
show(io::IO, dep::LibraryDependency) = show_indented(io, dep, 0)

function show(io::IO, deps::LibraryGroup)
    print(io," - Library Group \"$(deps.name)\"")
    all = allf(deps)
    providers = satisfied_providers(deps,all)
    if providers !== nothing && !isempty(providers)
        print(io," (satisfied by ",join(providers,", "),")")
    end
    if !applicable(deps)
        println(io," (not applicable to this system)")
    else
        println(io)
        for dep in deps.deps
            _show_indented(io,dep,4,haskey(all,dep) ? all[dep] : nothing)
        end
    end
end

function debug_context(pkg::AbstractString)
    @info("Reading build script...")
    dir = Pkg.dir(pkg)
    file = joinpath(dir, "deps", "build.jl")
    context = BinDeps.PackageContext(false, dir, pkg, Any[])
    eval_anon_module(context, file)
    context
end

function debug(io,pkg::AbstractString)
    context = debug_context(pkg)
    println(io,"The package declares $(length(context.deps)) dependencies.")

    # We need to `eval()` the rest of this function because `debug_context()` will
    # `eval()` in things like `Homebrew.jl`, which contain new methods for things
    # like `can_provide()`, and we cannot deal with those new methods in our
    # current world age; we need to `eval()` to force ourselves up into a newer
    # world age.
    @eval for dep in $(context.deps)
        show($io,dep)
    end
end
debug(pkg::AbstractString) = debug(stdout,pkg)


text:
# filling

function fills(filler::T, data::AbstractVector{T}) where {T}
    nvals  = axes(data)[1].stop
    return fill(filler, nvals)
end

function fills(filler::T1, data::AbstractVector{T2}) where {T1, T2}
    elemtype = Union{T1,T2}
    nvals  = axes(data)[1].stop
    result = Array{elemtype,1}(undef, nvals)
    result[:] = filler
    return result
end

# number of values to be obtained

function nrolled(seqlength::T, windowspan::T) where {T<:Signed}
    (0 < windowspan <= seqlength) || throw(SpanError(seqlength,windowspan))

    return seqlength - windowspan + 1
end

# number of values to be imputed

function nfilled(windowspan::T) where {T<:Signed}
    windowspan < 1 && throw(SpanError(seqlength,windowspan))

    return windowspan - 1
end

# local exceptions

SpanError(seqlength, windowspan) =
    ErrorException("\n\tBad window span ($windowspan) for length $seqlength.\n" )

WeightsError(nweighting, windowspan) =
    ErrorException("\n\twindowspan ($windowspan) != length(weighting) ($nweighting))).\n" )


text:
const t=10.0

function initial_condition_generator(rng,n,model)
    i = rand(rng,1:2,n)
    X = Vector{Float64}(undef,n)
    for k in 1:n
        x = Inf
        while x>=1
            x = -log(rand(rng))
        end
        X[k]=x
    end
    return (X=X,φ=i)
end

const _first_exit = first_exit_x(0.5*eps(),1.0)
function first_exit_or_t10(model,SFM,SFM0)
    t1 = _first_exit(model,SFM,SFM0)
    i2 = SFM.t>10.0
    return (Ind=(i2||t1.Ind), SFM=t1.SFM)
end

const tau = first_exit_or_t10

const x = range(0,10,length=6_001)


text:
#=
Code taken from IntervalSpecialFunctions.jl which will be added as a dependency
once this has been tagged. Some modifications have been made.

The IntervalSpecialFunctions.jl package is licensed under the MIT "Expat" License:
Copyright (c) 2018: David Sanders.

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.
=#
for f in (:erf, :erfc)

    @eval function($f)(x::BigFloat, r::RoundingMode)
        setrounding(BigFloat, r) do
            ($f)(x)
        end
    end

    @eval ($f)(a::Interval{Float64}) = convert(Interval{Float64}, ($f)(big_val(a)))
end

function erf(a::Interval{T}) where T
    isempty(a) && return a
    @round( erf(a.lo), erf(a.hi) )
end

function erfc(a::Interval{T}) where T
    isempty(a) && return a
    @round( erfc(a.hi), erfc(a.lo) )
end

erfinv(x, r::RoundingMode{:Down}) = _erfinv(x).lo
erfinv(x, r::RoundingMode{:Up}) = _erfinv(x).hi
erfcinv(x, r::RoundingMode{:Down}) = _erfcinv(x).hi
erfcinv(x, r::RoundingMode{:Up}) = _erfcinv(x).lo

function _erfinv(a::T) where T
    domain = Interval{T}(-1, 1)
    a ∉ domain && return DomainError("$a is not in [-1, 1]")
    f = x -> erf(x) - a
    fp = x->2/sqrt(Interval(pi)) * exp(-x^2)
    rts = roots(f, fp, Interval{T}(-Inf, Inf))
    @assert length(rts) == 1 # && rts[1].status == :unique

    rts[1].interval
end

function erfinv(a::Interval{T}) where T
    domain = Interval{T}(-1, 1)
    a = a ∩ domain

    isempty(a) && return a
    @round(erfinv(a.lo), erfinv(a.hi))
end

function _erfcinv(a::T) where T
    domain = Interval{T}(0, 2)
    a ∉ domain && return DomainError("$a is not in [0, 2]")
    f = x -> erfc(x) - a
    fp = x -> -2/sqrt(Interval(pi)) * exp(-x^2)
    rts = roots(f, fp, Interval{T}(-Inf, Inf))
    @assert length(rts) == 1 # && rts[1].status == :unique

    rts[1].interval
end

function erfcinv(a::Interval{T}) where T
    domain = Interval{T}(0, 2)
    a = a ∩ domain

    isempty(a) && return a
    @round(erfcinv(a.hi), erfcinv(a.lo))
end

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
module PokeTypes

greet() = print("Hello World!")

const NO_EFFECT = 0.0
const NOT_VERY_EFFECTIVE = 0.5
const NORMAL_EFFECTIVE = 1.0
const SUPER_EFFECTIVE = 2.0

# Defining our type hierarchy
abstract type PokéType end
struct Normal <: PokéType end
struct Fire     <: PokéType end
struct Water    <: PokéType end
struct Electric <: PokéType end
struct Grass    <: PokéType end
struct Ice      <: PokéType end
struct Fighting <: PokéType end
struct Poison   <: PokéType end
struct Ground   <: PokéType end

# Defining all of the self-to-self attacks
eff(atk::T1, def::T2) where {T1 <: PokéType, T2 <: PokéType} = NORMAL_EFFECTIVE
eff(atk::T, def::T) where {T <: PokéType} = NOT_VERY_EFFECTIVE
eff(atk::Fighting, def::Fighting)         = NORMAL_EFFECTIVE
eff(atk::Ground,   def::Ground)           = NORMAL_EFFECTIVE
eff(atk::Normal,   def::Normal)           = NORMAL_EFFECTIVE

# SUPER_EFFECTIVE Attacks
eff(atk::Fire,     def::Grass)    = SUPER_EFFECTIVE
eff(atk::Fire,     def::Ice)      = SUPER_EFFECTIVE
eff(atk::Water,    def::Fire)     = SUPER_EFFECTIVE
eff(atk::Water,    def::Ground)   = SUPER_EFFECTIVE
eff(atk::Electric, def::Water)    = SUPER_EFFECTIVE
eff(atk::Ground,   def::Poison)   = SUPER_EFFECTIVE
eff(atk::Ground,   def::Fire)     = SUPER_EFFECTIVE
eff(atk::Grass,    def::Water)    = SUPER_EFFECTIVE
eff(atk::Grass,    def::Ground)   = SUPER_EFFECTIVE
eff(atk::Ice,      def::Grass)    = SUPER_EFFECTIVE
eff(atk::Fighting, def::Normal)   = SUPER_EFFECTIVE
eff(atk::Fighting, def::Ice)      = SUPER_EFFECTIVE
eff(atk::Poison,   def::Grass)    = SUPER_EFFECTIVE
eff(atk::Ground,   def::Electric) = SUPER_EFFECTIVE

# NOT_VERY_EFFECTIVE Attacks
eff(atk::Fire,     def::Water)  = NOT_VERY_EFFECTIVE
eff(atk::Water,    def::Grass)  = NOT_VERY_EFFECTIVE
eff(atk::Electric, def::Grass)  = NOT_VERY_EFFECTIVE
eff(atk::Grass,    def::Fire)   = NOT_VERY_EFFECTIVE
eff(atk::Grass,    def::Poison) = NOT_VERY_EFFECTIVE
eff(atk::Ice,      def::Water)  = NOT_VERY_EFFECTIVE
eff(atk::Fighting, def::Poison) = NOT_VERY_EFFECTIVE
eff(atk::Poison,   def::Ground) = NOT_VERY_EFFECTIVE
eff(atk::Ground,   def::Grass)  = NOT_VERY_EFFECTIVE

# NO_EFFECT Attacks
eff(atk::Electric, def::Ground) = NO_EFFECT

# Package Export stuff
export PokéType, Normal, Fire, Water, Electric, Grass, Ice, Fighting, Poison, Ground
export eff, attack

function attack(atk::PokéType, def::PokéType)
    effectiveness = eff(atk, def)
    eff_str = eff_string(effectiveness)
    println("A Pokémon used a $(typeof(atk)) attack against a $(typeof(def)) Pokémon, it was $eff_str")
end

function eff_string(effectiveness)
    if effectiveness == NO_EFFECT
        return "not effective at all!"
    elseif effectiveness == NOT_VERY_EFFECTIVE
        return "not very effective..."
    elseif effectiveness == NORMAL_EFFECTIVE
        return "normally effective."
    elseif effectiveness == SUPER_EFFECTIVE
        return "super effective!!!"
    else
        return "??????"
    end
end

end # module

max_stars_repo_name: QuantumFractal/Julia-Poke-Dispatch


text:
function member_attr(node::Node, attr)
    attr == "name" && haskey(node, "alias") && return node["name"] # special handling for aliases
    val = findfirst(".//$attr", node)
    isnothing(val) && error("Attribute $attr not found in node\n$node")
    val.content
end

function resolve_aliases!(collection::Dict, nodes)
    for node ∈ nodes
        if haskey(node, "alias")
            collection[node["name"]] = collection[node["alias"]]
        end
    end
end

function nested_ntuple(base_type, lengths)
    make_tuple = (x, y) -> :(NTuple{$x,$y})
    foldr(make_tuple, lengths; init = base_type)
end

function extract_type(param)
    base_type = Symbol(findfirst("./type", param).content)

    star_count = count("*", param.content)
    type = star_count == 0 ? base_type : reduce((x, _) -> :(Ptr{$x}), 1:star_count; init = base_type)
    translated_type = translate_c_type(type)
    enum_param = findfirst("./enum", param)
    node_after_name = findfirst("./name", param).nextnode
    bracket_matches = isnothing(node_after_name) ? nothing : collect(eachmatch(r"\[(\d+)\]", node_after_name.content))
    if !isnothing(enum_param) || !isnothing(bracket_matches)
        if !isnothing(enum_param)
            nested_ntuple(translated_type, [Symbol(enum_param.content)])
        elseif !isnothing(bracket_matches)
            nested_ntuple(translated_type, parse.(Int, first.(getproperty.(bracket_matches, :captures))))
        end
    else
        translated_type
    end
end

function extract_identifier(param)
    id = Symbol(findfirst("./name", param).content)
    # Avoid aliasing with Julia built-in identifiers.
    @match id begin
        :module => :_module
        :function => :_function
        _ => id
    end
end
getattr(node::Node, attr; default = nothing, symbol = true) =
    haskey(node, attr) ? (symbol ? Symbol(node[attr]) : node[attr]) : default

function parent_name(node::Node)
    parel = node.parentelement
    parel.name == "command" ? command_name(parel) :
    parel.name == "type" && parel["category"] ∈ ["struct", "union"] ? struct_name(parel) :
    error("Unknown parent element:\n    $parel")
end

function command_name(node::Node)
    isnothing(findfirst("proto", node)) && return command_name(node.parentelement)
    Symbol(findfirst("proto/name", node).content)
end

function struct_name(node::Node)
    (!haskey(node, "category") || node["category"] ∉ ["struct", "union"]) &&
        return Symbol(struct_name(node.parentelement))
    Symbol(node["name"])
end

is_constant(node::Node) = any(split(node.content) .== "const")

name(node::Node) = Symbol(findfirst("./name", node).content)

"""
Semantically translate C types to their Julia counterpart.
Note that since it is a semantic translation, translated types
do not necessarily have the same layout, e.g. VkBool32 => Bool (8 bits).
"""
function translate_c_type(ctype)
    @match ctype begin
        :int => :Int
        x::Symbol && if startswith(string(x), "uint") && endswith(string(x), "_t")
        end => Symbol(replace(string(x)[1:end-2], "uint" => "UInt"))
        x::Symbol && if startswith(string(x), "int") && endswith(string(x), "_t")
        end => Symbol(replace(string(x)[1:end-2], "int" => "Int"))
        :(Ptr{$t}) => @match t begin
            :char => :Cstring
            x => :(Ptr{$(translate_c_type(x))})
        end
        :float => :Float32
        :double => :Float64
        :void => :Cvoid
        :size_t => :UInt
        :char => :Char
        x => x
    end
end

function innermost_type(t)
    @match t begin
        ::Symbol => t
        :($T{$p}) => innermost_type(p)
        _ => error("Cannot take innermost type of $t")
    end
end

is_ptr_to_ptr(ex) = !isnothing(ptrtype(ptrtype(ex)))
is_ptr(ex) = !isnothing(ptr_type(ex))

ptr_type(ex) = @when :(Ptr{$T}) = ex T
ntuple_type(ex) = @when :(NTuple{$N,$T}) = ex T

is_ntuple(ex) = !isnothing(ntuple_type(ex))

max_stars_repo_name: JuliaGPU/VulkanAbstraction

max_issues_repo_name: JuliaGPU/VulkanAbstraction

max_forks_repo_name: JuliaGPU/VulkanAbstraction


text:
module Integration

export AdaptiveSimpsonsIntegration,
        integrate

abstract IntegrationMethod

type AdaptiveSimpsonsIntegration <: IntegrationMethod
	accuracy::Real
	maxIterations::Int
end
AdaptiveSimpsonsIntegration() = AdaptiveSimpsonsIntegration(1e-9, 50)

function integrate(f::Function, si::AdaptiveSimpsonsIntegration, a::Real, b::Real)
	 c = (a + b)/2
	 h = b - a
     fa = f(a)
     fb = f(b)
     fc = f(c)
  	 S = (h/6)*(fa + 4*fc + fb)
  return adaptiveSimpsonsR(f, a, b, si.accuracy, S, fa, fb, fc, si.maxIterations)
end

function adaptiveSimpsonsR(f::Function,  a,  b,  epsilon, S,  fa,  fb,  fc, bottom)
   c = (a + b)/2
   h = b - a
   d = (a + c)/2
   g = (c + b)/2
   fd = f(d)
   fe = f(g)
   Sleft = (h/12)*(fa + 4*fd + fc)
   Sright = (h/12)*(fc + 4*fe + fb)
   S2 = Sleft + Sright
  if (bottom <= 0 || abs(S2 - S) <= 15*epsilon)
    return S2 + (S2 - S)/15
   end
  return adaptiveSimpsonsR(f, a, c, epsilon/2, Sleft,  fa, fc, fd, bottom-1) +
         adaptiveSimpsonsR(f, c, b, epsilon/2, Sright, fc, fb, fe, bottom-1)
end

end #Module


text:
@testset "Differentials" begin
    @testset "Wirtinger" begin
        w = Wirtinger(1+1im, 2+2im)
        @test wirtinger_primal(w) == 1+1im
        @test wirtinger_conjugate(w) == 2+2im
        @test add_wirtinger(w, w) == Wirtinger(2+2im, 4+4im)
        # TODO: other add_wirtinger methods stack overflow
        @test_throws ErrorException mul_wirtinger(w, w)
        @test_throws ErrorException extern(w)
        for x in w
            @test x === w
        end
        @test broadcastable(w) == w
        @test_throws ErrorException conj(w)
    end
    @testset "Zero" begin
        z = Zero()
        @test extern(z) === false
        @test add_zero(z, z) == z
        @test add_zero(z, 1) == 1
        @test add_zero(1, z) == 1
        @test mul_zero(z, z) == z
        @test mul_zero(z, 1) == z
        @test mul_zero(1, z) == z
        for x in z
            @test x === z
        end
        @test broadcastable(z) isa Ref{Zero}
        @test conj(z) == z
    end
    @testset "One" begin
        o = One()
        @test extern(o) === true
        @test add_one(o, o) == 2
        @test add_one(o, 1) == 2
        @test add_one(1, o) == 2
        @test mul_one(o, o) == o
        @test mul_one(o, 1) == 1
        @test mul_one(1, o) == 1
        for x in o
            @test x === o
        end
        @test broadcastable(o) isa Ref{One}
        @test conj(o) == o
    end
end


text:
# quit needs to work or early tests will hang

# Try out queue_draw_area
da = Gtk.@GtkDrawingArea(ccall((:gtk_drawing_area_new, Gtk.libgtk), Ptr{GObject}, ()))
w = @GtkWindow(da, "Test Window")
@test isa(GtkBuilderAid.window(da), GObject)

@test isa(create_similar_surface(da), CairoSurface)

# Can't do much beyond check that it doesn't error out
reveal_area(da, 5, 5, 5, 5)

destroy(w)


text:
using Jive
runtests(@__DIR__)


text:
@testset "Preamble" begin
    @test preamble() == ["\\usepackage{amsmath,amsthm,amssymb}", "\\usepackage{color}"]
    @test add_preamble!("\\usepackage{physics}") == ["\\usepackage{amsmath,amsthm,amssymb}", "\\usepackage{color}", "\\usepackage{physics}"]
    @test reset_preamble!() == ["\\usepackage{amsmath,amsthm,amssymb}", "\\usepackage{color}"]
    @test LatexSVG._assemble_document("testing latex") == """
    \\documentclass[12pt]{article}
    \\usepackage{amsmath,amsthm,amssymb}
    \\usepackage{color}
    \\pagestyle{empty}
    \\begin{document}
    testing latex
    \\end{document}
    """
    @test LatexSVG._assemble_document("testing latex"; standalone=true) == "testing latex"
end


text:
using Flux , Statistics, Plots

NN_ODE = Chain(x -> [x], # Take a scalar as input and transform it into an array
           Dense(1,16,tanh),#input layer
           Dense(16,1), #output layer
           first) # Take first value, i.e. return a scalar

# initial condition u_0 = 1. + all the prior info is HERE
g(t) = 1f0 + t*NN_ODE(t)

# small increment
ϵ = sqrt(eps(Float32))
# g(t+ϵ)-g(t))/ϵ --> difference quotient, derivative definition as a limit
loss() = mean(abs2(((g(t+ϵ)-g(t))/ϵ) - cos(2π*t)) for t in 0:1f-2:1f0)

opt = Flux.ADAM(0.01)
data = Iterators.repeated((),250)
iter = 0

cb = function() #callback function, taking a look at training
    global iter += 1
    if iter % 50 == 0
        display(loss())
    end
end

display(loss())
Flux.train!(loss, Flux.params(NN_ODE), data, opt; cb = cb)

t = 0:1f-2:1f0
plot(t,g.(t),label="NN")
plot!(t, 1f0 .+sin.(2π.*t)/2π, label = "True Solution")

t = 0:1f-2:1.5f0
plot(t,g.(t),label="NN")
plot!(t, 1f0 .+sin.(2π.*t)/2π, label = "True Solution")


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

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

                     @variable(m, -25.420040452488465 <= q <= 21.65452636072683)

                     add_NL_constraint(m, :((-0.9974376164994152 + 0.7314791518637902*(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))*(1 + erf((-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))/sqrt(2)))/2 + 0.4470938857218645*(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))*(1 + erf((0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))/sqrt(2)))/2 + 0.10010754470216687*(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))*(1 + erf((-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))/sqrt(2)))/2 + -0.8594790184444285*(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))*(1 + erf((0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))/sqrt(2)))/2 + -0.4658863904521331*(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))*(1 + erf((0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))/sqrt(2)))/2)*(1 + erf((-0.9974376164994152 + 0.7314791518637902*(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))*(1 + erf((-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))/sqrt(2)))/2 + 0.4470938857218645*(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))*(1 + erf((0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))/sqrt(2)))/2 + 0.10010754470216687*(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))*(1 + erf((-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))/sqrt(2)))/2 + -0.8594790184444285*(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))*(1 + erf((0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))/sqrt(2)))/2 + -0.4658863904521331*(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))*(1 + erf((0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))/sqrt(2)))/2)/sqrt(2)))/2 + (0.15396139316976853 + -0.4228510094486002*(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))*(1 + erf((-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))/sqrt(2)))/2 + -0.8035341866400141*(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))*(1 + erf((0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))/sqrt(2)))/2 + -0.07617073018159282*(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))*(1 + erf((-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))/sqrt(2)))/2 + 0.3940887684836425*(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))*(1 + erf((0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))/sqrt(2)))/2 + 0.6667343490308526*(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))*(1 + erf((0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))/sqrt(2)))/2)*(1 + erf((0.15396139316976853 + -0.4228510094486002*(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))*(1 + erf((-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))/sqrt(2)))/2 + -0.8035341866400141*(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))*(1 + erf((0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))/sqrt(2)))/2 + -0.07617073018159282*(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))*(1 + erf((-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))/sqrt(2)))/2 + 0.3940887684836425*(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))*(1 + erf((0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))/sqrt(2)))/2 + 0.6667343490308526*(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))*(1 + erf((0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))/sqrt(2)))/2)/sqrt(2)))/2 + (0.9665409577623398 + -0.449175249339572*(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))*(1 + erf((-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))/sqrt(2)))/2 + -0.2640107596849468*(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))*(1 + erf((0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))/sqrt(2)))/2 + 0.7284419447850534*(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))*(1 + erf((-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))/sqrt(2)))/2 + 0.5662248826250997*(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))*(1 + erf((0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))/sqrt(2)))/2 + -0.21454884110410477*(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))*(1 + erf((0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))/sqrt(2)))/2)*(1 + erf((0.9665409577623398 + -0.449175249339572*(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))*(1 + erf((-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))/sqrt(2)))/2 + -0.2640107596849468*(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))*(1 + erf((0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))/sqrt(2)))/2 + 0.7284419447850534*(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))*(1 + erf((-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))/sqrt(2)))/2 + 0.5662248826250997*(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))*(1 + erf((0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))/sqrt(2)))/2 + -0.21454884110410477*(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))*(1 + erf((0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))/sqrt(2)))/2)/sqrt(2)))/2 + (-0.1582635851091898 + 0.5103556986884796*(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))*(1 + erf((-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))/sqrt(2)))/2 + -0.6017569427714062*(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))*(1 + erf((0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))/sqrt(2)))/2 + -0.23749573380464106*(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))*(1 + erf((-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))/sqrt(2)))/2 + -0.2344836196764124*(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))*(1 + erf((0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))/sqrt(2)))/2 + 0.07066758651932892*(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))*(1 + erf((0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))/sqrt(2)))/2)*(1 + erf((-0.1582635851091898 + 0.5103556986884796*(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))*(1 + erf((-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))/sqrt(2)))/2 + -0.6017569427714062*(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))*(1 + erf((0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))/sqrt(2)))/2 + -0.23749573380464106*(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))*(1 + erf((-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))/sqrt(2)))/2 + -0.2344836196764124*(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))*(1 + erf((0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))/sqrt(2)))/2 + 0.07066758651932892*(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))*(1 + erf((0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))/sqrt(2)))/2)/sqrt(2)))/2 + (-0.47638200661148833 + 0.9126631115783219*(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))*(1 + erf((-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))/sqrt(2)))/2 + 0.35414400688245484*(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))*(1 + erf((0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))/sqrt(2)))/2 + -0.36037763135774403*(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))*(1 + erf((-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))/sqrt(2)))/2 + -0.18657915153735738*(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))*(1 + erf((0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))/sqrt(2)))/2 + 0.7872605277677782*(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))*(1 + erf((0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))/sqrt(2)))/2)*(1 + erf((-0.47638200661148833 + 0.9126631115783219*(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))*(1 + erf((-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4]))/sqrt(2)))/2 + 0.35414400688245484*(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))*(1 + erf((0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4]))/sqrt(2)))/2 + -0.36037763135774403*(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))*(1 + erf((-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4]))/sqrt(2)))/2 + -0.18657915153735738*(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))*(1 + erf((0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4]))/sqrt(2)))/2 + 0.7872605277677782*(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))*(1 + erf((0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))/sqrt(2)))/2)/sqrt(2)))/2 - $q <= 0.0))

                     @objective(m, Min, q)

                     return m


text:
function _process_daylight(ts,p,tz)
    dts = Date(ts[1])-Day(1):Date(ts[end])+Day(1)
    rise = sunrise.(dts,p,tz)
    set = sunset.(dts,p,tz)
    rs = DateTime.(collect(Base.Iterators.flatten(zip(rise,set))))

    zs = zeros(length(rs))
    for i in eachindex(zs)
        zs[i] = isodd(i)?1.0:0.0
    end
    rs,zs
end

function tlims(t,x)
    ts = extrema(t)
    a,b = extrema(x)
    ts,a,b
end

@userplot Daylight

@recipe function f(dl::Daylight;loc=Point(0.0,0.0),tz=tz"UTC")
    x = dl.args

    ts,a,b = tlims(x...)

    rs,zs = _process_daylight(ts,loc,tz)

    xlims --> Dates.value.(ts)
    ylims --> (a,b)

    @series begin
        seriestype:= [:steppost :steppre]
        linecolor := :black
        linealpha := 0.0
        fillcolor := [:yellow :grey]
        fillalpha := 0.3
        fillrange := a

        rs, (b-a)*[zs zs]+a
    end

    @series begin
        x
    end
end


text:
#=
In the documents, there are tables of what keyword arguments can be passed
to latexify for different outputs or inputs. This file contains that information
as well as the means to generate tables for the documentation.

This exists so that I do not have to repeat myself and to type the same
information into multiple places (that way lies madness!). With this code, I
can simply filter the information according to some criterion and automatically
have it inserted in the docs.
=#
using Latexify

struct KeywordArgument
    kw::Symbol
    env::Array{Symbol}
    values::String
    default::String
    description::String
    types::Array{Symbol}
end

#     KeywordArgument(:template, [:array], "`Bool`", "`false`", "description", [:Any]),
keyword_arguments = [
    KeywordArgument(:starred, [:align, :array, :arrow, :equation], "`Bool`", "`false`", "Star the environment to prevent equation numbering.", [:Any]),
    KeywordArgument(:separator, [:align], "`String`", "`\" =& \"`", "Specify how to separate the left hand side and the right.", [:Any]),
    KeywordArgument(:transpose, [:array, :tabular, :mdtable], "`Bool`", "`true`", "Flip rows for columns.", [:Any]),
    KeywordArgument(:double_linebreak, [:array, :align, :arrow], "`Bool`", "`false`", "Add an extra `\\\\` to the end of the line.", [:Any]),
    KeywordArgument(:bracket, [:align], "`Bool`", "`false`", "Surround variables with square brackets.", [:ParameterizedFunction, :ReactionNetwork]),
    KeywordArgument(:noise, [:align], "`Bool`", "`false`", "Display the noise function instead of the deterministic one.", [:ReactionNetwork]),
    KeywordArgument(:adjustment, [:tabular, :array], "`:c` for centered, `:l` for left, `:r` for right", "`:c`", "Set the adjustment of text within the table cells.", [:Any]),
    KeywordArgument(:expand, [:arrow, :align], "`Bool`", "`true`", "Expand functions such as `hill(x, v, k, n)` to their mathematical expression.", [:ReactionNetwork]),
    KeywordArgument(:mathjax, [:arrow], "`Bool`", "`true`", "Add `\\require{mhchem}` to tell MathJax to load the required module.", [:ReactionNetwork]),
    KeywordArgument(:latex, [:mdtable, :tabular], "`Bool`", "`true`", "Toggle latexification of the table elements.", [:Any]),
    KeywordArgument(:head, [:mdtable, :tabular], "`Array`", "`[]`", "Add a header to the table. It will error if it is not of the right length (unless empty). ", [:Any]),
    KeywordArgument(:side, [:mdtable, :tabular], "`Array`", "`[]`", "Add a leftmost column to the table. It will error if it is not of the right length (unless empty). ", [:Any]),
    KeywordArgument(:fmt, [:mdtable, :tabular, :align, :array, :raw, :inline], "format string", "`\"\"`", "Format number output in accordence with Printf. Example: \"%.2e\"", [:Any]),
    KeywordArgument(:imaginary_unit, [:mdtable, :tabular, :align, :array, :raw, :inline], "`String`", "`\"\\\\mathit{i}\"`", "The symbol to use to represent the imaginary unit", [:Any]),
    KeywordArgument(:escape_underscores, [:mdtable, :mdtext], "`Bool`", "`false`", "Prevent underscores from being interpreted as formatting.", [:Any]),
    KeywordArgument(:convert_unicode, [:mdtable, :tabular, :align, :array, :raw, :inline], "`Bool`", "`true`", "Convert unicode characters to latex commands, for example `α` to `\\alpha`", [:Any]),
    KeywordArgument(:cdot, [:mdtable, :tabular, :align, :array, :raw, :inline], "`Bool`", "`true`", "Toggle between using `\\cdot` or just a space to represent multiplication.", [:Any]),
    KeywordArgument(:symbolic, [:align], "`Bool`", "`false`", "Use symbolic calculations to clean up the expression.", [:ReactionNetwork]),
    KeywordArgument(:clean, [:align], "`Bool`", "`false`", "Clean out `1*` terms. Only useful for DiffEqBiological versions 3.4 or below.", [:ReactionNetwork]),
    KeywordArgument(:rows, [:align], "Iterable or symol", ":all", "Which rows to include in the output.", [:Any]),
    KeywordArgument(:booktabs, [:tabular], "`Bool`", "`false`", "Add top, mid and bottom booktabs rule", [:Any]),
    KeywordArgument(:index, [:mdtable, :tabular, :align, :array, :raw, :inline], "`Symb`", "`:bracket`", "Represent index specification with `:bracket` (`u[1]`) or `:subscript` (`u_1`). ", [:Any]),
    KeyWordArgument(:snakecase, [:mdtable, :tabular, :align, :array, :raw, :inline], "`Bool`", "`false`", "Treat underscores as literal underscores (if not, treat first underscore as subscript).", [:Any]),
    KeyWordArgument(:safescripts, [:mdtable, :tabular, :align, :array, :raw, :inline], "`Bool`", "`false`", "Put scripts inside brackets (`a{_b}`), sometimes making them uglier, but making alternating scripts possible.", [:Any]),
#     KeywordArgument(:template, [:array], "`Bool`", "`false`", "description", [:Any]),
    ]

#= @latexrecipe function f(list::Array{KeywordArgument}; types=true) =#
#=     isempty(list) && return nothing =#
#=     sort!(list, by=x->x.kw) =#
#=     keys = ["`:$(x.kw)`" for x in list] =#
#=     # values = [join(["$i" for i in x.values], ", ") for x in list] =#
#=     applicable_types = [join(["`$i`" for i in x.types], ", ") for x in list] =#
#=     values = [x.values for x in list] =#
#=     defaults = [x.default for x in list] =#
#=     descriptions = [x.description for x in list] =#

#=     latex --> false =#
#=     env := :mdtable =#

#=     if any(x->x.types != [:Any], list) && types =#
#=         head --> ["Keyword", "Values", "Default", "Applicable types", "Description"] =#
#=         return hcat(keys, values, defaults, applicable_types, descriptions) =#
#=     else =#
#=         head --> ["Keyword", "Values", "Default", "Description"] =#
#=         return hcat(keys, values, defaults, descriptions) =#
#=     end =#
#= end =#

import Latexify: mdtable
function mdtable(list::Array{KeywordArgument}; types=true, kwargs...)
    isempty(list) && return nothing
    sort!(list, by=x->x.kw)
    keys = ["`:$(x.kw)`" for x in list]
    # values = [join(["$i" for i in x.values], ", ") for x in list]
    applicable_types = [join(["`$i`" for i in x.types], ", ") for x in list]
    values = [x.values for x in list]
    defaults = [x.default for x in list]
    descriptions = [x.description for x in list]
    if any(x->x.types != [:Any], list) && types
        mdtable(hcat(keys, values, defaults, applicable_types, descriptions), head=["Keyword", "Values", "Default", "Applicable types", "Description"], latex=false)
    else
        mdtable(hcat(keys, values, defaults, descriptions), head=["Keyword", "Values", "Default", "Description"], latex=false)
    end
end


text:
## Scalar functions on intervals (no directed rounding used)

mag(a::Interval) = max( abs(a.lo), abs(a.hi) )
mag(::EmptyInterval{T}) where T = T(NaN)

function mig(a::Interval{T}) where T
    zero_in(a) && return zero(T)
    r1, r2 = (@round_down(abs(a.lo)), @round_down(abs(a.hi)))
    min( r1, r2 )
end
mig(::EmptyInterval{T}) where T = T(NaN)

# Infimum and supremum of an interval
inf(a::Interval{T}) where T =
    ifelse(iszero(a.lo), -zero(T), a.lo) # IEEE 1788-2015 requires negative sign
sup(a::Interval{T}) where T =
    ifelse(iszero(a.hi), zero(T), a.hi) # IEEE 1788-2015 requires positive sign

# by convention, empty intervals return values which imply emptiness
inf(a::EmptyInterval{T}) where T = T(Inf)
sup(a::EmptyInterval{T}) where T = T(-Inf)

# mid, diam, radius

#= Fallback in case of overflow: a.hi + a.lo == +Inf or a.hi + a.lo == -Inf.
    This case can not be the default one as it does not pass several
    IEEE1788-2015 tests for small floats.
=#
midpoint_bounded_safe(a::Interval) = 0.5a.lo + 0.5a.hi
midpoint_bounded_accurate(a::Interval{T}) where T = 0.5(a.lo + a.hi) |>
    x -> ifelse(iszero(x), zero(T), x) # ensure positive sign for zero

# NOTE: mid could be renamed to mean? or median?
# Compare pg. 64 of the IEEE 1788-2015 standard:
"""
    mid(a::Interval)

Find the midpoint of interval `a`.

For intervals of the form `[-Inf, x]` or `[x, +Inf]` where `x` is finite, return
respectively `nextfloat(-Inf)` and `prevfloat(+Inf)`. Note that it differs from the
behavior of `mid(a, α=0.5)`.
"""
function mid(a::Interval{T}) where T
    isentire(a) && return zero(T)
    a.lo == -Inf && return nextfloat(a.lo)
    a.hi == +Inf && return prevfloat(a.hi)

    accurate_midpoint = midpoint_bounded_accurate(a)
    if isfinite(accurate_midpoint)
        return accurate_midpoint
    else
        return midpoint_bounded_safe(a)
    end
end

mid(::EmptyInterval{T}) where T = T(NaN)

"""
    diam(a::Interval)

Return the diameter (length) of the `Interval` `a`.
"""
diam(a::Interval{T}) where T = @round_up(a.hi - a.lo) # cf page 64 of IEEE1788
diam(::EmptyInterval{T}) where T = T(NaN)

# Should `radius` this yield diam(a)/2? This affects other functions!
"""
    radius(a::Interval)

Return the radius of the `Interval` `a`, such that
`a ⊆ m ± radius`, where `m = mid(a)` is the midpoint.
"""
function radius(a::Interval{T}) where T
    m = mid(a)
    return max(m - a.lo, a.hi - m)
end
radius(::EmptyInterval{T}) where T = T(NaN)

# midpoint-radius forms
midpoint_radius(a::ValidInterval) = (mid(a), radius(a))


text:
#== # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Description
#
#   Tests related to TLE parser.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ==#

# File: ./src/orbit/tle.jl
# ========================

# Macros tle_str and tlenc_str
# ----------------------------

@testset "Macros tle_str and tlenc_str" begin
    # Read the SCDs TLE from the file.
    tles_file = read_tle("./SCDs.tle")

    # Read the same TLEs from a string.
    tles_str = tle"""
        SCD 1
        1 22490U 93009B   18165.62596833  .00000225  00000-0  11410-4 0  9991
        2 22490  24.9690 231.7852 0042844 200.7311 292.7198 14.44524498338066

        SCD 2
        1 25504U 98060A   18165.15074951  .00000201  00000-0  55356-5 0  9994
        2 25504  24.9961  80.1303 0017060 224.4822 286.6438 14.44043397 37312
        """

    # Read the same TLES from a string with wrong checksums.
    # This should not output any exceptions.
    tles_str_nc = tlenc"""
        SCD 1
        1 22490U 93009B   18165.62596833  .00000225  00000-0  11410-4 0  9990
        2 22490  24.9690 231.7852 0042844 200.7311 292.7198 14.44524498338060

        SCD 2
        1 25504U 98060A   18165.15074951  .00000201  00000-0  55356-5 0  9990
        2 25504  24.9961  80.1303 0017060 224.4822 286.6438 14.44043397 37310
        """

    # Compare the TLEs.
    @test length(tles_file) == length(tles_str)
    @test length(tles_file) == length(tles_str_nc)

    for i = 1:length(tles_file)
        for sym in fieldnames(TLE)
            @test getfield(tles_file[i], sym) == getfield(tles_str[i], sym)

            # Skip the comparison of checksums for `tles_str_nc`.
            ( (sym == :checksum_l1) || (sym == :checksum_l2) ) && continue
            @test getfield(tles_file[i], sym) == getfield(tles_str_nc[i], sym)
        end
    end
end


text:
using Griddly
using Random

image_path = joinpath(@__DIR__,"..","..","Griddly","resources","images");

shader_path = joinpath(@__DIR__,"..","..","Griddly","resources","shaders");

gdy_path = joinpath(@__DIR__,"..","..","Griddly","resources","games");

gdy_reader = Griddly.GDYReader(image_path,shader_path);

grid = Griddly.load!(gdy_reader,joinpath(gdy_path,"RTS/GriddlyRTS.yaml"))

# load a custom string
lvl_str = """ .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  W  .  .  .  .  .  M  M  M
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  M  M
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  M
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  M  W  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  M  W  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  H1 .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  W  M  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  B1 .  .  .  .  .  .  .  M  W  M  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  .  .  .  .  .  .  M  W  .  .  .  .  .  .  .  W  W  W  W  W  .  .  .  .
              .  .  .  .  W  W  W  W  W  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  B2 .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  W  M  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  W  M  .  .  .  .  .  .  .  .  H2 .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              .  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              M  .  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              M  M  .  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
              M  M  M  .  .  .  .  .  W  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .
    """

game = Griddly.create_game(grid,Griddly.SPRITE_2D)

player1 = Griddly.register_player!(game,"Bob", Griddly.BLOCK_2D)
player2 = Griddly.register_player!(game,"Alice", Griddly.BLOCK_2D)

Griddly.init!(game)

Griddly.load_level_string!(grid,lvl_str)

Griddly.reset!(game)

# These are the actions we can use
global actions_map = Griddly.get_player_actions_dict(grid)

multiple_window = MultipleScreen(700,700;nb_scene=3)

for j in 1:1000
     x = rand(1:Griddly.get_width(grid))
     y = rand(1:Griddly.get_height(grid))

     action_choice = rand(1:length(actions_map))
     action_name = collect(keys(actions_map))[action_choice]
     action_id = rand(1:length(actions_map[action_name]))

     # Alternate between player_1 and player_2 actions
     if j % 2 == 0
         player_1_step_result = Griddly.step_player!(player1,action_name, [x, y, action_id])
     else
         player_2_step_result = Griddly.step_player!(player2,action_name, [x, y, action_id])
     end

    # Get all the observations
    player1_tiles = Griddly.get_data(Griddly.observe(player1))
    player2_tiles = Griddly.get_data(Griddly.observe(player2))
    sprites = Griddly.get_data(Griddly.observe(game))

    render_multiple(multiple_window,[player1_tiles,player2_tiles,sprites])
end


text:
######
###### `inv`
######

function frule((_, Δx), ::typeof(inv), x::AbstractArray)
    Ω = inv(x)
    return Ω, -Ω * Δx * Ω
end

function rrule(::typeof(inv), x::AbstractArray)
    Ω = inv(x)
    function inv_pullback(ΔΩ)
        return NO_FIELDS, -Ω' * ΔΩ * Ω'
    end
    return Ω, inv_pullback
end

#####
##### `*`
#####

function rrule(::typeof(*), A::AbstractMatrix{<:Real}, B::AbstractMatrix{<:Real})
    function times_pullback(Ȳ)
        return (NO_FIELDS, @thunk(Ȳ * B'), @thunk(A' * Ȳ))
    end
    return A * B, times_pullback
end

function rrule(::typeof(*), A::Real, B::AbstractArray{<:Real})
    function times_pullback(Ȳ)
        return (NO_FIELDS, @thunk(dot(Ȳ, B)), @thunk(A * Ȳ))
    end
    return A * B, times_pullback
end

function rrule(::typeof(*), B::AbstractArray{<:Real}, A::Real)
    function times_pullback(Ȳ)
        return (NO_FIELDS, @thunk(A * Ȳ), @thunk(dot(Ȳ, B)))
    end
    return A * B, times_pullback
end

#####
##### `/`
#####

function rrule(::typeof(/), A::AbstractVecOrMat{<:Real}, B::AbstractVecOrMat{<:Real})
    Aᵀ, dA_pb = rrule(adjoint, A)
    Bᵀ, dB_pb = rrule(adjoint, B)
    Cᵀ, dS_pb = rrule(\, Bᵀ, Aᵀ)
    C, dC_pb = rrule(adjoint, Cᵀ)
    function slash_pullback(Ȳ)
        # Optimization note: dAᵀ, dBᵀ, dC are calculated no matter which partial you want
        _, dC = dC_pb(Ȳ)
        _, dBᵀ, dAᵀ = dS_pb(unthunk(dC))

        ∂A = last(dA_pb(unthunk(dAᵀ)))
        ∂B = last(dA_pb(unthunk(dBᵀ)))

        (NO_FIELDS, ∂A, ∂B)
    end
    return C, slash_pullback
end

#####
##### `\`
#####

function rrule(::typeof(\), A::AbstractVecOrMat{<:Real}, B::AbstractVecOrMat{<:Real})
    Y = A \ B
    function backslash_pullback(Ȳ)
        ∂A = @thunk begin
            B̄ = A' \ Ȳ
            Ā = -B̄ * Y'
            Ā = add!!(Ā, (B - A * Y) * B̄' / A')
            Ā = add!!(Ā, A' \ Y * (Ȳ' - B̄'A))
            Ā
        end
        ∂B = @thunk A' \ Ȳ
        return NO_FIELDS, ∂A, ∂B
    end
    return Y, backslash_pullback

end

#####
##### `\`, `/` matrix-scalar_rule
#####

function rrule(::typeof(/), A::AbstractArray{<:Real}, b::Real)
    Y = A/b
    function slash_pullback(Ȳ)
        return (NO_FIELDS, @thunk(Ȳ/b), @thunk(-dot(Ȳ, Y)/b))
    end
    return Y, slash_pullback
end

function rrule(::typeof(\), b::Real, A::AbstractArray{<:Real})
    Y = b\A
    function backslash_pullback(Ȳ)
        return (NO_FIELDS, @thunk(-dot(Ȳ, Y)/b), @thunk(Ȳ/b))
    end
    return Y, backslash_pullback
end


text:
using QznbTestPackage
using Documenter

DocMeta.setdocmeta!(QznbTestPackage, :DocTestSetup, :(using QznbTestPackage); recursive=true)

makedocs(;
    modules=[QznbTestPackage],
    authors="qz-michael <michael@quartznotebook.com> and contributors",
    repo="https://github.com/qz-michael/QznbTestPackage.jl/blob/{commit}{path}#{line}",
    sitename="QznbTestPackage.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://qz-michael.github.io/QznbTestPackage.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
    ],
)

deploydocs(;
    devbranch = "main",
    repo="github.com/qz-michael/QznbTestPackage.jl"
)

max_stars_repo_name: qz-michael/QznbTestPackage

max_issues_repo_name: qz-michael/QznbTestPackage

max_forks_repo_name: qz-michael/QznbTestPackage


text:
OTLP_VERSION = v"0.10.0"

using Downloads
using CodecZlib
using Tar
using gRPCClient

download_url = "https://github.com/open-telemetry/opentelemetry-proto/archive/refs/tags/v$OTLP_VERSION.tar.gz"

open(Downloads.download(download_url)) do tar_gz
    tar = GzipDecompressorStream(tar_gz)
    dir = Tar.extract(tar)
    proto_dir = joinpath(dir, "opentelemetry-proto-$OTLP_VERSION")
    trace_proto_file = joinpath(
        proto_dir,
        "opentelemetry",
        "proto",
        "collector",
        "trace",
        "v1",
        "trace_service.proto",
    )
    gRPCClient.generate(
        trace_proto_file;
        outdir = joinpath(@__DIR__, "..", "src", "generated"),
        includes = [proto_dir],
    )
end


text:
#=
A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.

Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?
=#
function calc()
  maxsum = 1
  for a in 1:100
    for b in 1:100
      x = a^BigInt(b)
      s = sum(digits(x))
      maxsum = max(maxsum, s)
    end
  end
  maxsum
end
@time println(calc())

max_stars_repo_name: daniel-beard/JuliaProjectEuler

max_issues_repo_name: daniel-beard/JuliaProjectEuler

max_forks_repo_name: daniel-beard/JuliaProjectEuler


text:
module PipeLayout

include("instances.jl")
# --> deserialization.jl
# --> random.jl
include("types.jl")

include("util.jl")
include("gasphysics.jl")
include("pwl.jl")
include("diameter.jl")

# graph methods and topologies
include("topology/util.jl")
include("topology/geosteiner.jl")
include("topology/grid.jl")
include("topology/mst.jl")
include("topology/isomorph.jl")

include("flow.jl") # needs topology

# optimization models and approaches
module PipeDim
using ..PipeLayout
include("models/pipedimensioning.jl")
end

module JuncLoc
using ..PipeLayout
include("models/junctionlocation/main.jl")
end

module GndStr
using ..PipeLayout
include("models/gndstruct_discdiam/main.jl")
end

# visualization via Plots recipes
include("plot_recipes.jl")

end


text:
__precompile__()

module CurrencyAPI

using HTTP
using JSON
using TimeSeries
using DataFrames
using Dates

export
    cconvert,
    get_symbols

include("cconvert.jl")
include("get_symbols.jl")

end


text:
# utility/z-test.jl

using Test

@test downsample(:test)


text:
module Grisu
export print_shortest
export @grisu_ccall, NEG, DIGITS, BUFLEN, LEN, POINT

import Base.show, Base.print, Base.showcompact

const NEG    = Array(Bool)
const DIGITS = Array(Uint8,309+17)
const BUFLEN = int32(length(DIGITS)+1)
const LEN    = Array(Int32)
const POINT  = Array(Int32)

macro grisu_ccall(value, mode, ndigits)
    quote
        ccall((:grisu, :libgrisu), Void,
              (Float64, Int32, Int32, Ptr{Uint8}, Int32,
               Ptr{Bool}, Ptr{Int32}, Ptr{Int32}),
              $(esc(value)), $(esc(mode)), $(esc(ndigits)),
              DIGITS, BUFLEN, NEG, LEN, POINT)
    end
end

const SHORTEST        = int32(0) # shortest exact representation for doubles
const SHORTEST_SINGLE = int32(1) # shortest exact representation for singles
const FIXED           = int32(2) # fixed number of trailing decimal points
const PRECISION       = int32(3) # fixed precision regardless of magnitude

# wrapper for the core grisu function, primarily for debugging
function grisu(x::Float64, mode::Integer, ndigits::Integer)
    if !isfinite(x); error("non-finite value: $x"); end
    if ndigits < 0; error("negative digits requested"); end
    @grisu_ccall x mode ndigits
    NEG[1], DIGITS[1:LEN[1]], int(POINT[1])
end

grisu(x::Float64) = grisu(x, SHORTEST, int32(0))
grisu(x::Float32) = grisu(float64(x), SHORTEST_SINGLE, int32(0))
grisu(x::Real) = grisu(float(x))

function grisu_fix(x::Real, n::Integer)
    if n > 17; n = 17; end
    grisu(float64(x), FIXED, int32(n))
end
function grisu_sig(x::Real, n::Integer)
    if n > 309; n = 309; end
    grisu(float64(x), PRECISION, int32(n))
end

_show(io::IO, x::FloatingPoint, mode::Int32, n::Int, t) =
    _show(io, x, mode, n, t, "NaN", "Inf")
_show(io::IO, x::Float32, mode::Int32, n::Int, t) =
    _show(io, x, mode, n, t, "NaN32", "Inf32")
_show(io::IO, x::Float16, mode::Int32, n::Int, t) =
    _show(io, x, mode, n, t, "NaN16", "Inf16")

function _show(io::IO, x::FloatingPoint, mode::Int32, n::Int, typed, nanstr, infstr)
    if isnan(x) return write(io, typed ? nanstr : "NaN"); end
    if isinf(x)
        if x < 0 write(io,'-') end
        write(io, typed ? infstr : "Inf")
        return
    end
    if typed && isa(x,Float16) write(io, "float16("); end
    @grisu_ccall x mode n
    pdigits = pointer(DIGITS)
    neg = NEG[1]
    len = int(LEN[1])
    pt  = int(POINT[1])
    if mode == PRECISION
        while len > 1 && DIGITS[len] == '0'
            len -= 1
        end
    end
    if neg write(io,'-') end
    if pt <= -4 || pt > 6 # .00001 to 100000.
        # => #.#######e###
        write(io, pdigits, 1)
        write(io, '.')
        if len > 1
            write(io, pdigits+1, len-1)
        else
            write(io, '0')
        end
        write(io, typed && isa(x,Float32) ? 'f' : 'e')
        write(io, dec(pt-1))
        if typed && isa(x,Float16) write(io, ")"); end
        return
    elseif pt <= 0
        # => 0.00########
        write(io, "0.")
        while pt < 0
            write(io, '0')
            pt += 1
        end
        write(io, pdigits, len)
    elseif pt >= len
        # => ########00.0
        write(io, pdigits, len)
        while pt > len
            write(io, '0')
            len += 1
        end
        write(io, ".0")
    else # => ####.####
        write(io, pdigits, pt)
        write(io, '.')
        write(io, pdigits+pt, len-pt)
    end
    if typed && isa(x,Float32) write(io, "f0") end
    if typed && isa(x,Float16) write(io, ")"); end
    nothing
end

show(io::IO, x::Float64) = _show(io, x, SHORTEST, 0, true)
show(io::IO, x::Float32) = _show(io, x, SHORTEST_SINGLE, 0, true)
show(io::IO, x::Float16) = _show(io, x, PRECISION, 5, true)

print(io::IO, x::Float32) = _show(io, x, SHORTEST_SINGLE, 0, false)
print(io::IO, x::Float16) = _show(io, x, PRECISION, 5, false)

showcompact(io::IO, x::Float64) = _show(io, x, PRECISION, 6, false)
showcompact(io::IO, x::Float32) = _show(io, x, PRECISION, 6, false)
showcompact(io::IO, x::Float16) = _show(io, x, PRECISION, 5, false)

# normal:
#   0 < pt < len        ####.####           len+1
#   pt <= 0             .000########        len-pt+1
#   len <= pt (dot)     ########000.        pt+1
#   len <= pt (no dot)  ########000         pt
# exponential:
#   pt <= 0             ########e-###       len+k+2
#   0 < pt              ########e###        len+k+1

function _print_shortest(io::IO, x::FloatingPoint, dot::Bool, mode::Int32, n::Int)
    if isnan(x); return write(io, "NaN"); end
    if x < 0 write(io,'-') end
    if isinf(x); return write(io, "Inf"); end
    @grisu_ccall x mode n
    pdigits = pointer(DIGITS)
    len = int(LEN[1])
    pt  = int(POINT[1])
    e = pt-len
    k = -9<=e<=9 ? 1 : 2
    if -pt > k+1 || e+dot > k+1
        # => ########e###
        write(io, pdigits+0, len)
        write(io, 'e')
        write(io, dec(e))
        return
    elseif pt <= 0
        # => .000########
        write(io, '.')
        while pt < 0
            write(io, '0')
            pt += 1
        end
        write(io, pdigits+0, len)
    elseif e >= dot
        # => ########000.
        write(io, pdigits+0, len)
        while e > 0
            write(io, '0')
            e -= 1
        end
        if dot
            write(io, '.')
        end
    else # => ####.####
        write(io, pdigits+0, pt)
        write(io, '.')
        write(io, pdigits+pt, len-pt)
    end
    nothing
end

print_shortest(io::IO, x::Float64, dot::Bool) = _print_shortest(io, x, dot, SHORTEST, 0)
print_shortest(io::IO, x::Float32, dot::Bool) = _print_shortest(io, x, dot, SHORTEST_SINGLE, 0)
print_shortest(io::IO, x::Float16, dot::Bool=false) = _print_shortest(io, x, dot, PRECISION, 5)
print_shortest(io::IO, x::Union(FloatingPoint,Integer)) = print_shortest(io, float(x), false)

end # module

max_stars_repo_name: jakebolewski/julia

max_issues_repo_name: jakebolewski/julia

max_forks_repo_name: jakebolewski/julia


text:
module joHelpers_etc

    using JOLI

    const elmOnType{D,R} = Union{joAbstractLinearOperator{D,R},joAbstractFosterLinearOperator{D,R}} where {D,R}
    function elements_helper(A::elmOnType{DDT,RDT}) where {DDT,RDT}
        (M,N)=size(A)
        x=zeros(DDT,N)
        eA=zeros(RDT,M,N)
        for n=1:N
            x[n] = one(DDT)
            eA[:,n] = A*x
            x[n] = zero(DDT)
        end
        return eA
    end

    function elements_column_helper(A::elmOnType{DDT,RDT},r::UnitRange{URT}) where {DDT,RDT,URT<:Integer}
        (M,N)=size(A)
        n=length(r)
        eA=zeros(RDT,M,n)
        for i in r
            eA[:,i-r.start+1] = elements_column_helper(A,i)
        end
        return eA
    end

    function elements_column_helper(A::elmOnType{DDT,RDT},n::Integer) where {DDT,RDT}
        (M,N)=size(A)
        @assert (n>=1&&n<=N) "column index $n out of range <1,$N> for $(A.name)"
        x=zeros(DDT,N)
        x[n] = one(DDT)
        cA = A*x
        return cA
    end

end
using .joHelpers_etc


text:
struct AliasTable{S} <: Sampleable{Univariate,Discrete}
    accept::Vector{Float64}
    alias::Vector{Int}
    isampler::S
end
ncategories(s::AliasTable) = length(s.accept)

function AliasTable(probs::AbstractVector{T}) where T<:Real
    n = length(probs)
    n > 0 || throw(ArgumentError("The input probability vector is empty."))
    accp = Vector{Float64}(undef, n)
    alias = Vector{Int}(undef, n)
    StatsBase.make_alias_table!(probs, 1.0, accp, alias)
    AliasTable(accp, alias, Random.RangeGenerator(1:n))
end

function rand(rng::AbstractRNG, s::AliasTable)
    i = rand(rng, s.isampler) % Int
    u = rand(rng)
    @inbounds r = u < s.accept[i] ? i : s.alias[i]
    r
end

show(io::IO, s::AliasTable) = @printf(io, "AliasTable with %d entries", ncategories(s))


text:
condf(ω, x, y) = Bool(y(ω)) ? x(ω) : error("Condition unsatisfied")

"""$(SIGNATURES)
Condition RandVar `x` with random predicate `y` whose `elemtype`
is an `AbstractBool`

```julia
x = normal(0.0, 1.0)
x_ = cond(x, x > 0)
```
"""
cond(x::RandVar, y::RandVar) = URandVar(ω -> condf(ω, x, y))

"""
$(SIGNATURES)

Convenience function to condition with a predicate

`cond(x, p(x))`

```jldoctest
cond(poisson(0.5), iseven)
```

"""
cond(x::RandVar, p) = cond(x, lift(p)(x))

"""$(SIGNATURES)

Condition intermediate values from within the functional definition of a `RandVar`

```
function x_(ω)
  x = 0.0
  xs = Float64[]
  while bernoulli(ω, 0.8, Bool)
    x += uniform(ω, -5.0, 5.0)
    cond(ω, x <=ₛ 1.0)
    cond(ω, x >=ₛ -1.0)
    push!(xs, x)
  end
  xs
end

x = ciid(x_)
samples = rand(x, 100; alg = SSMH)
```
"""
cond(ω::Ω, bool) = nothing


text:
using ReinforcementLearning
using StableRNGs
using Flux
using Flux.Losses
using Nature
# using Serialization
using TensorBoardLogger, Logging
using Infiltrator
using Dates
using Serialization

MAX_STEPS=1_000_000

N_STARTING_PLAYERS = 36
UPDATE_FREQ = 128
WORLD_SIZE = (64, 64)
CLIP = 0.1f0

trial_id = ""

timestamp = Dates.format(now(),"yyyy-mm-dd HH:MM:SS")

function RL.Experiment(
    ::Val{:JuliaRL},
    ::Val{:PPO},
    ::Val{:Nature},
    ::Nothing;
    save_dir = nothing,
    seed = 123,
)

    rng = StableRNG(seed)
    env = NatureEnv(num_starting_players=N_STARTING_PLAYERS,
                    world_size=WORLD_SIZE,
                    episode_len=500,
                    window=3,
                    vocab_size=5,
                    food_generators=[
                        FoodGen([15,15],[60,60]),
                        FoodGen([45,45],[60,60]),
                       ])
    RLBase.reset!(env)

    global trial_id = "$timestamp clip=$CLIP uf=$UPDATE_FREQ maxsteps=$MAX_STEPS ws=$(WORLD_SIZE[1:2]) nf=$(length(env.food_generators))"

    runs = readdir("tensorboard_logs/")
    for (i, run) in enumerate(runs)
        println(i, ". ", run)
    end
    println("n. (NEW RUN)")
    print("Select a run: ")
    trial = readline()
    if trial == "n"
        println("Default name: $trial_id")
        print(  "Enter new name (empty for default) ")
        name = readline()
        if name != ""
            global trial_id = name
        end
        agents = false
        println("Creating new run: $trial_id")
    else
        global trial_id = runs[parse(Int, trial)]
        println("Resuming run: $trial_id")
        agents = deserialize("checkpoints/$trial_id.jls")
    end

    print("Enable TensorBoard Logging? y/n: ")
    if readline() == "y"
        disable_logging(Logging.Debug)
        lg=TBLogger("tensorboard_logs/$trial_id", tb_append)
        global_logger(lg)
    else
        disable_logging(Logging.Info)
        global_logger(ConsoleLogger())
    end

    # We don't build agents at agents = false because
    # we don't want to compile between user inputs
    if agents == false
        agents = build_MultiPPOManager(env, N_STARTING_PLAYERS, UPDATE_FREQ, CLIP)
    end

    stop_condition = StopAfterStep(MAX_STEPS, is_show_progress=!haskey(ENV, "CI"))
    hook = NatureHook(env, trial_id, MAX_STEPS)

    Experiment(agents, env, stop_condition, hook, "# PPO with Nature")
end

ex = E`JuliaRL_PPO_Nature`
run(ex)
serialize("checkpoints/$trial_id.jls", ex.policy)
# step_through_env(ex.env, policy)


text:
#using DataFrames, CSV, Pipe, QuantEcon, StatsModels, LinearAlgebra, MixedModels, Random, Plots
# removed QuantEcon from requirements
using DataFrames,CSV,StatsModels,LinearAlgebra,MixedModels,Random

#include("test/expandgrid.jl")

#include("test/exponentialCorrelation.jl")
#include("test/Circulant.jl")
#include("test/fitsignal.jl")
include("test/sim_utilities.jl")

n_part = 20 # participants
n_item = 30 # items
n_t = 400

Σ = circulant(exponentialCorrelation([0:1:(n_t-1);],nu=1))
Ut =  LinearAlgebra.cholesky(Σ).U'

df_item = DataFrame(id_item = 1:n_item)
df_part = DataFrame(id_part = 1:n_part)
#df1 = df_part
#df2 = df_item

transform!(df_part, :id_part=> (x->ifelse.(x .< (n_part/2),"Fp1","Fp2")) => :f_part)
transform!(df_item, :id_item=> (x->ifelse.(x .< (n_item/2),"Fi1","Fi2")) => :f_item)

df = expandgrid(df_part,df_item)

### add random intercept participant
df.rep = map(x -> randn(Random.MersenneTwister(x + 1000),Float64,(1,n_t))*Ut',df.id_part)

### add random slope participant / different per item-category
df.repf = map((x,y) -> randn(Random.MersenneTwister(x + 100*y+ 10000),Float64,(1,n_t))*Ut',df.id_part,df.f_item.=="Fi1")

### add random intercept item
df.rei = map(x -> randn(Random.MersenneTwister(x + 20000),Float64,(1,n_t))*Ut',df.id_item)

### add random slope item ( different per subject-category)
df.reif = map((x,y) -> randn(Random.MersenneTwister(x + 100*y+ 30000),Float64,(1,n_t))*Ut',df.id_item,df.f_part.=="Fp1")

### add error
df.err = map(x -> randn(Random.MersenneTwister(x +40000),Float64,(1,n_t))*Ut',[1:1:nrow(df);])

df.y = df.rep + df.repf + df.rei + df.reif + df.err
df.part = categorical(df.id_part)
df.item = categorical(df.id_item)
df = select(df,[:part, :f_part, :item, :f_item, :y])

sign = vcat(df.y...)

### models
co = Dict(:f_part => EffectsCoding(), :f_item => EffectsCoding())
form = @formula(yi ~ f_part*f_item + (1|part)+ (1|part&f_item)+ (1|item) + (1|item&f_part))

lmods = fitsignal(form,df,sign,co)

ff = @formula(0~f_part*f_item)
mm = ModelMatrix(ModelFrame(ff, df, contrasts = co))


text:
#
#--------------------------------------#
export grad
#--------------------------------------#
"""
 Compute gradient of u∈H¹(Ω).

 Continuity isn't enforced across
 element boundaries for gradients

 [Dx] * u = [rx sx] * [Dr] * u
 [Dy]     = [ry sy]   [Ds]

"""
function grad(u  ::Array
             ,msh::Mesh)

    @unpack Dr,Ds,rx,ry,sx,sy = msh

    ux,uy = grad(u,Dr,Ds,rx,ry,sx,sy)

    return ux,uy
end
#--------------------------------------#
function grad(u,Dr,Ds,rx,ry,sx,sy)

  ur = ABu([],Dr,u)
  us = ABu(Ds,[],u)

  ux = @. rx * ur + sx * us
  uy = @. ry * ur + sy * us

  return ux,uy
end
#--------------------------------------#
export gradᵀ
#--------------------------------------#
"""
 Gradient transpose operator

 [Dx' Dy'] = [Dr' Ds'] [rx ry]
                       [sx sy]
"""
function gradᵀ(u  ::Array
              ,msh::Mesh)

    @unpack Dr,Ds,rx,ry,sx,sy = msh

    ux,uy = gradᵀ(u,Dr,Ds,rx,ry,sx,sy)

    return ux,uy
end
#--------------------------------------#
function gradᵀ(u,Dr,Ds,rx,ry,sx,sy)

  ux = ABu(Dr',[] ,rx .* u) +
       ABu([] ,Ds',sx .* u)

  uy = ABu(Dr',[] ,ry .* u) +
       ABu([] ,Ds',sy .* u)

  return ux,uy
end
#--------------------------------------#


text:
"""
    partitions_recursive(n)

Finds partitions of an integer using recursion.

A partition of a positive integer n, also called an integer partition,
is a way of writing n as a sum of positive integers.

There are 7 partitions of 5:
5
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1

Partitions of n is equal to the sum of partitions of n with k parts.

``P \\left ( n \\right ) = \\sum_{k=1}^{n} P_{k} \\left ( n \\right )``

Partitions of n with k parts is the sum of
partitions of n-1 with k-1 parts and,
partitions of n-k with k parts.

``P_{k}\\left ( n \\right ) =
P_{k-1}\\left ( n - 1 \\right ) + P_{k}\\left ( n - k \\right )``

# Example
```julia
partitions_recursive(0)      # returns 1
partitions_recursive(1)      # returns 1
partitions_recursive(10)     # returns 42
partitions_recursive(-1)     # returns DomainError
```
# References
- Partitions of a positive integer -- https://en.wikipedia.org/wiki/Partition_function_(number_theory)
- Partitions of a positive integer -- https://www.whitman.edu/mathematics/cgt_online/book/section03.03.html

# Contributor
- [Vaishakh C R](https://github.com/Whiteshark-314)
"""
function partitions_recursive(n::N)::BigInt where {N<:Integer}
    n < 0 && throw(
        DomainError(
            "partitions_recursive() only accepts positive integral values",
        ),
    )
    if n == 0
        return one(BigInt)
    end
    k = collect(1:n)
    return sum(partitions_k_parts.(n, k))
end

function partitions_k_parts(n, k)
    n < 0 ||
        k < 0 && throw(
            DomainError(
                "partitions_k_parts() only accepts positive integral values",
            ),
        )
    if (n == 0 && k == 0) || (n > 0 && k == 1) || n == k
        return one(BigInt)
    elseif k == 0 || k > n
        return zero(BigInt)
    end
    return partitions_k_parts(n - 1, k - 1) + partitions_k_parts(n - k, k)
end

max_stars_repo_name: Nikola-Mircic/Julia

max_issues_repo_name: Nikola-Mircic/Julia

max_forks_repo_name: Nikola-Mircic/Julia


text:
using LockPatternComplexity

directory = "plots"
create_plots(2, "results/2x2_sat.txt", directory; limit=5)
create_plots(3, "results/3x3_sat.txt", directory; limit=22)
create_plots(4, "results/4x4_opt.txt", directory; limit=61)
create_plots(4, "results/4x4_opt2.txt", directory; limit=61)
create_plots(5, "results/5x5_opt.txt", directory; limit=119)
create_plots(6, "results/6x6_opt.txt", directory; limit=207)
create_plots(7, "results/7x7_opt.txt", directory; limit=313)