text:
#"""
#    Fermi.Coupled Cluster.update_energy(T1::Array{T, 2}, T2::Array{T, 4}, f::Array{T,2}, Voovv::Array{T, 4}) where T <: AbstractFloat
#
#Compute CC energy from amplitudes and integrals.
#"""
#function update_energy(T1::Array{T, 2}, T2::Array{T, 4}, f::Array{T,2}, Voovv::Array{T, 4}) where { T <: AbstractFloat }
#
#    @tensoropt (k=>x, l=>x, c=>100x, d=>100x)  begin
#        CC_energy = 2.0*f[k,c]*T1[k,c]
#        B[l,c,k,d] := -1.0*T1[l,c]*T1[k,d]
#        B[l,c,k,d] += -1.0*T2[l,k,c,d]
#        B[l,c,k,d] += 2.0*T2[k,l,c,d]
#        CC_energy += B[l,c,k,d]*Voovv[k,l,c,d]
#        CC_energy += 2.0*T1[l,c]*T1[k,d]*Voovv[l,k,c,d]
#    end
#
#    return CC_energy
#end

"""
    Fermi.CoupledCluster.RCCSD.update_amp(T1::Array{T, 2}, T2::Array{T, 4}, newT1::Array{T,2}, newT2::Array{T,4}, foo::Array{T,2}, fov::Array{T,2}, fvv::Array{T,2}, moint::PhysRestrictedMOIntegrals) where T <: AbstractFloat

Update amplitudes (T1, T2) to newT1 and newT2 using CTF CCSD equations.
"""
function update_amp(T1::Array{T, 2}, T2::Array{T, 4}, newT1::Array{T,2}, newT2::Array{T,4}, foo::Array{T,2}, fov::Array{T,2}, fvv::Array{T,2}, ints::IntegralHelper, alg::A) where { T <: AbstractFloat,
                                                                                A <: CCAlgorithm }

    fill!(newT1, 0.0)
    fill!(newT2, 0.0)

    # Get new amplitudes
    update_T1(T1,T2,newT1,foo,fov,fvv,ints,alg)
    update_T2(T1,T2,newT2,foo,fov,fvv,ints,alg)
end

function RCCSD{Ta}(refwfn::RHF, ints::IntegralHelper, newT1::Array{Tb, 2}, newT2::Array{Tc,4}, alg::A; ecT1 = Array{Float64}(undef,0,0), ecT2 = Array{Float64}(undef,0,0,0,0)) where { Ta <: AbstractFloat,
                                                                                Tb <: AbstractFloat,
                                                                                Tc <: AbstractFloat,
                                       A <: CCAlgorithm }

    # Print intro
    Fermi.CoupledCluster.print_header()
    Fermi.CoupledCluster.print_alg(alg)
    newT1 = convert(Array{Ta},newT1)
    newT2 = convert(Array{Ta},newT2)
    ecT1 = convert(Array{Ta},ecT1)
    ecT2 = convert(Array{Ta},ecT2)

    @output repeat("-",80)*"\n"
    @output "\tBasis: {}\n" ints.bname["primary"]
    @output "\tComputing and Transforming Integrals..."
    tint = @elapsed Fermi.CoupledCluster.compute_integrals(ints,alg)
    delete!(ints.cache,"B") #clear out AO basis integrals for scratch space
    @output " done in {} s\n" tint
    for key in keys(ints.cache)
        ints[key] = convert(Array{Ta},ints[key])
    end

    # Process Fock matrix, important for non HF cases
    foo = convert(Array{Ta},ints["FOO"] - Diagonal(ints["FOO"]))
    fvv = convert(Array{Ta},ints["FVV"] - Diagonal(ints["FVV"]))
    fov = convert(Array{Ta},ints["FOV"])

    d = Ta[i - a for i = diag(ints["FOO"]), a = diag(ints["FVV"])]
    D = Ta[i + j - a - b for i = diag(ints["FOO"]), j = diag(ints["FOO"]), a = diag(ints["FVV"]), b = diag(ints["FVV"])]

    # Compute Guess Energy
    #oovv = convert(Array{Ta},Fermi.CoupledCluster.compute_oovv(ints,alg))
    Ecc = update_energy(newT1, newT2, fov, ints, alg)
    Eguess = Ecc+refwfn.energy

    #@output "Initial Amplitudes Guess: MP2\n"
    @output "\tGuess Energy:   {:15.10f}\n\n" Ecc
    @output "\tGuess Total Energy:   {:15.10f}\n\n" Ecc+refwfn.energy

    # Start CC iterations

    cc_max_iter = Fermi.CurrentOptions["cc_max_iter"]
    cc_e_conv = Fermi.CurrentOptions["cc_e_conv"]
    cc_max_rms = Fermi.CurrentOptions["cc_max_rms"]
    precision_override = Fermi.CurrentOptions["precision_override"]

    preconv_T1 = Fermi.CurrentOptions["preconv_T1"]
    dp = Fermi.CurrentOptions["cc_damp_ratio"]
    do_diis = Fermi.CurrentOptions["cc_diis"]
    ndiis = Fermi.CurrentOptions["cc_ndiis"]
    diis_start = Fermi.CurrentOptions["diis_start"]
    diis_relax = Fermi.CurrentOptions["cc_diis_relax"]
    prec_selector = Dict{String,Any}(
                                     "half" => Float16,
                                     "single" => Float32,
                                     "double" => Float64
                                    )
    diis_prec = prec_selector[Fermi.CurrentOptions["diis_prec"]]
    do_diis ? DM_T1 = Fermi.DIIS.DIISManager{Ta,diis_prec}(size=ndiis) : nothing
    do_diis ? DM_T2 = Fermi.DIIS.DIISManager{Ta,diis_prec}(size=ndiis) : nothing

    @output "\tDropped Occupied Orbitals →  {:3.0f}\n" Int(Fermi.CurrentOptions["drop_occ"])
    @output "\tDropped Virtual Orbitals  →  {:3.0f}\n\n" Int(Fermi.CurrentOptions["drop_vir"])
    @output "\n"*repeat("-",80)*"\n"
    @output "\tOptions:\n"
    @output "\tPrecision? {}\n" Ta
    @output "\tDIIS? {}\n" do_diis
    @output "\tDIIS Vectors? {}\n" (do_diis ? ndiis : 0)
    @output "\tDIIS Precision? {}\n" diis_prec
    @output "\tPreconverge T1 amplitudes? {}\n" preconv_T1
    @output "\tDamping percentage ? {}\n" dp
    @output "\t\tcc_max_iter →  {:3.0d}\n" Int(cc_max_iter)
    @output "\t\tcc_e_conv   →  {:2.0e}\n" cc_e_conv
    @output "\t\tcc_max_rms  →  {:2.0e}\n" cc_max_rms
    if (cc_e_conv < eps(Ta)) && !(precision_override)
        @output "\t⚠ WARNING⚠   cc_e_conv set to less than ϵ ({}) for precision {}\n" eps(Ta) Ta
        @output "\t             CCSD is unlikely to converge to your standards.\n"
        @output "\t             OVERRIDING set convergence criterion.\n"
        @output "\t             Use @set precision_override true to perform the computation as entered.\n"
        cc_e_conv = eps(Ta)
    end
    if (cc_max_rms < eps(Ta)) && !(precision_override)
        @output "\t⚠ WARNING⚠   cc_max_rms set to less than ϵ ({}) for precision {}\n" eps(Ta) Ta
        @output "\t             CCSD is unlikely to converge to your standards.\n"
        @output "\t             OVERRIDING set convergence criterion.\n"
        @output "\t             Use @set precision_override true to perform the computation as entered.\n"
        cc_max_rms = eps(Ta)
    end

    r1 = 1
    r2 = 1
    dE = 1
    rms = 1
    ite = 1
    T1 = deepcopy(newT1)
    T2 = deepcopy(newT2)

    #dfsz,nocc,nvir = size(Bov)

    @output repeat("-",80)*"\n"
    @output "    Starting CC Iterations\n\n"
    preconv_T1 ? T1_time = 0 : nothing
    dummyT2 = zeros(Ta,size(newT2))
    if preconv_T1
        @output "Preconverging T1 amplitudes\n"
        @output "Taking one T2 step\n"
        @output "{:10s}    {: 15s}    {: 12s}    {:12s}    {:10s}\n" "Iteration" "CC Energy" "ΔE" "Max RMS (T1)" "Time (s)"
        t = @elapsed begin
            update_amp(T1, T2, newT1, newT2, foo, fov, fvv, ints, alg)

            #apply external correction
            apply_ec(newT1,dummyT2,ecT1,ecT2)

            # Apply resolvent
            newT1 ./= d
            newT2 ./= D

            # Compute residues
            r1 = sqrt(sum((newT1 .- T1).^2))/length(T1)
            r2 = sqrt(sum((newT2 .- T2).^2))/length(T2)

            if do_diis
                e1 = (newT1 - T1)
                e2 = (newT2 - T2)
                push!(DM_T1,newT1,e1)
                push!(DM_T2,newT2,e2)
            end

            newT1 .= (1-dp)*newT1 .+ dp*T1
            newT2 .= (1-dp)*newT2 .+ dp*T2
        end
        T1_time += t

        rms = max(r1,r2)
        oldE = Ecc
        Ecc = update_energy(newT1, newT2, fov, ints, alg)
        dE = Ecc - oldE
        @output "    {:<5}    {:<15.10f}    {:<12.10f}    {:<12.10f}    {:<10.5f}\n" "pre" Ecc dE rms t

        while abs(dE) > cc_e_conv || rms > cc_max_rms
            if ite > cc_max_iter
                @output "\n⚠  CC Equations did not converge in {:1.0d} iterations.\n" cc_max_iter
                break
            end
            t = @elapsed begin
                T1 .= newT1
                T2 .= newT2
                update_T1(T1,T2,newT1,foo,fov,fvv,ints,alg)
                apply_ec(newT1,dummyT2,ecT1,ecT2)
                newT1 ./= d
                if do_diis
                    e1 = newT1 - T1
                    push!(DM_T1,newT1,e1)
                    newT1 = Fermi.DIIS.extrapolate(DM_T1)
                end

                # Compute residues
                r1 = sqrt(sum((newT1 .- T1).^2))/length(T1)

                newT1 .= (1-dp)*newT1 .+ dp*T1

                rms = r1
                oldE = Ecc
                Ecc = update_energy(newT1, newT2, fov, ints, alg)
                dE = Ecc - oldE
            end
            T1_time += t
            dE > 0 ? sign = "+" : sign = "-"
            @output "    {:<5.0d}    {:<15.10f}    {}{:>12.10f}    {:<12.10f}    {:<10.5f}\n" ite Ecc sign abs(dE) rms t
            ite += 1
        end
        @output "\nT1 pre-convergence took {}s\n" T1_time
    end

    dE = 1
    rms = 1
    ite = 1

    do_diis ? DM_T1 = Fermi.DIIS.DIISManager{Ta,diis_prec}(size=ndiis) : nothing
    do_diis ? DM_T2 = Fermi.DIIS.DIISManager{Ta,diis_prec}(size=ndiis) : nothing
    if preconv_T1
        @output "Including T2 update\n"
    end

    main_time = 0
    @output "{:10s}    {: 15s}    {: 12s}    {:12s}    {:10s}\n" "Iteration" "CC Energy" "ΔE" "Max RMS" "Time (s)"
    relax = 1
            Ecc = update_energy(newT1, newT2, fov, ints, alg)
            @output "{}\n" Ecc

    while (abs(dE) > cc_e_conv || rms > cc_max_rms) || ite < 10
        if ite > cc_max_iter
            @output "\n⚠  CC Equations did not converge in {:1.0d} iterations.\n" cc_max_iter
            break
        end
        t = @elapsed begin

            T1 .= newT1
            T2 .= newT2
            update_amp(T1, T2, newT1, newT2, foo, fov, fvv, ints, alg)

            apply_ec(newT1,newT2,ecT1,ecT2)

            # Apply resolvent
            newT1 ./= d
            newT2 ./= D
            oldE = Ecc
            Ecc = update_energy(newT1, newT2, fov, ints, alg)

            # Compute residues
            r1 = sqrt(sum((newT1 .- T1).^2))/length(T1)
            r2 = sqrt(sum((newT2 .- T2).^2))/length(T2)

            if do_diis && ite > 2
                relax -= 1
                e1 = (newT1 - T1)
                e2 = (newT2 - T2)
                push!(DM_T1,newT1,e1)
                push!(DM_T2,newT2,e2)
                if relax == 0
                    newT2 = Fermi.DIIS.extrapolate(DM_T2;add_res=true)
                    newT1 = Fermi.DIIS.extrapolate(DM_T1;add_res=true)
                    relax = diis_relax
                end
            end

            newT1 .= (1-dp)*newT1 .+ dp*T1
            newT2 .= (1-dp)*newT2 .+ dp*T2
        end
        rms = max(r1,r2)
        Ecc = update_energy(newT1, newT2, fov, ints, alg)
        dE = Ecc - oldE
        main_time += t
        dE > 0 ? sign = "+" : sign = "-"
        @output "    {:<5.0d}    {:<15.10f}    {}{:>12.10f}    {:<12.10f}    {:<10.5f}\n" ite Ecc sign abs(dE) rms t
        ite += 1
    end
    @output "\nMain CCSD iterations done in {}s\n" main_time

    # Converged?
    if abs(dE) < cc_e_conv && rms < cc_max_rms
        @output "\n 🍾 Equations Converged!\n"
    end
    @output "\n⇒ Final CCSD Energy:     {:15.10f}\n" Ecc+refwfn.energy
    @output repeat("-",80)*"\n"

    return RCCSD{Ta}(Eguess, Ecc+refwfn.energy, Fermi.MemTensor(newT1), Fermi.MemTensor(newT2))
end

function apply_ec(T1,T2,ecT1,ecT2)
    s1,s2,s3,s4 = size(ecT2)
    r1 = 1:s1
    r2 = 1:s2
    r3 = 1:s3
    r4 = 1:s4
    T1[r1,r3] .+= ecT1
    T2[r1,r2,r3,r4] .+= ecT2
end


text:
const C2JULIA_NULL_CURSOR = CLCursor(getcursor())

"""
    MetaExpr
Symbols, Exprs, Numbers, Chars, Strings
"""
mutable struct MetaExpr
    expr::Union{Symbol,Expr,Number,AbstractChar,AbstractString}
    leafcursor::CLCursor
    info::String
end
MetaExpr(x, c) = MetaExpr(x, c, "")
MetaExpr(x) = MetaExpr(x, C2JULIA_NULL_CURSOR)

Base.length(x::MetaExpr) = 1
Base.iterate(x::MetaExpr) = (x, nothing)
Base.string(x::MetaExpr) = string(x.expr)
Base.show(io::IO, x::MetaExpr) = show(io, x.expr)

ext: jl


text:
function maximumGap(nums)
    length(nums) < 2 && return 0

    sort!(nums)
    largest = 0;
    last = nums[1]
    for c in nums
        (c - last) > largest && begin largest = (c - last) end
        last = c
    end

    largest
end

using Test
@test maximumGap([3,6,9,1]) == 3
@test maximumGap([10]) == 0

max_stars_repo_name: ccqpein/Arithmetic-Exercises

max_issues_repo_name: ccqpein/Arithmetic-Exercises

max_forks_repo_name: ccqpein/Arithmetic-Exercises


text:
"""
    max_depth(n::Int) -> Function

Create a filter that rejects when the current call depth is greater than `n`.
"""
max_depth(n::Int) = m::Metadata -> current_depth(m) <= n

"""
    min_depth(n::Int) -> Function

Create a filter that rejects when the current call depth is less than `n`.
"""
min_depth(n::Int) = m::Metadata -> current_depth(m) >= n

"""
    excluding(args...) -> Function

Create a filter that rejects when the calling function or module is in `args`.
"""
excluding(args...) = m::Metadata -> !(current_module(m) in args || current_function(m) in args)

"""
    including(args...) -> Function

Create a filter that rejects when the calling function or module is not in `args`.
"""
including(args...) = m::Metadata -> current_module(m) in args || current_function(m) in args


text:
Base.@pure function nondatavaluenamedtuple(::Type{NT}) where {NT <: NamedTuple{names}} where {names}
    TT = Tuple{Any[ DataValueInterfaces.nondatavaluetype(fieldtype(NT, i)) for i = 1:fieldcount(NT) ]...}
    return NamedTuple{names, TT}
end

Base.@pure function datavaluenamedtuple(::Tables.Schema{names, types}) where {names, types}
    TT = Tuple{Any[ DataValueInterfaces.datavaluetype(fieldtype(types, i)) for i = 1:fieldcount(types) ]...}
    return NamedTuple{names, TT}
end

# IteratorWrapper takes an input Row iterators, it will unwrap any DataValue elements as plain Union{T, Missing}
struct IteratorWrapper{S}
    x::S
end

"""
    Tables.nondatavaluerows(x)

Takes any Queryverse-compatible `NamedTuple` iterator source and
converts to a Tables.jl-compatible `AbstractRow` iterator. Will automatically
unwrap any `DataValue`s, replacing `NA` with `missing`.
Useful for translating Query.jl results back to non-`DataValue`-based tables.
"""
nondatavaluerows(x) = IteratorWrapper(IteratorInterfaceExtensions.getiterator(x))
Tables.istable(::Type{<:IteratorWrapper}) = true
Tables.rowaccess(::Type{<:IteratorWrapper}) = true
Tables.rows(x::IteratorWrapper) = x

function Tables.schema(dv::IteratorWrapper{S}) where {S}
    eT = eltype(dv.x)
    (!(eT <: NamedTuple) || eT === Union{}) && return schema(dv.x)
    return Tables.Schema(nondatavaluenamedtuple(eT))
end

Base.IteratorEltype(::Type{IteratorWrapper{S}}) where {S} = Base.IteratorEltype(S)
Base.eltype(x::IteratorWrapper{S}) where {S} = IteratorRow{eltype(x.x)}
Base.eltype(::Type{IteratorWrapper{S}}) where {S} = IteratorRow{eltype(S)}
Base.IteratorSize(::Type{IteratorWrapper{S}}) where {S} = Base.IteratorSize(S)
Base.length(rows::IteratorWrapper) = length(rows.x)
Base.size(rows::IteratorWrapper) = size(rows.x)

@noinline invalidtable(::T, ::S) where {T, S} = throw(ArgumentError("'$T' iterates '$S' values, which doesn't satisfy the Tables.jl `AbstractRow` interface"))

@inline function Base.iterate(rows::IteratorWrapper)
    x = iterate(rows.x)
    x === nothing && return nothing
    row, st = x
    columnnames(row) === () && invalidtable(rows.x, row)
    return IteratorRow(row), st
end

@inline function Base.iterate(rows::IteratorWrapper, st)
    x = iterate(rows.x, st)
    x === nothing && return nothing
    row, st = x
    return IteratorRow(row), st
end

struct IteratorRow{T} <: AbstractRow
    row::T
end

getrow(r::IteratorRow) = getfield(r, :row)

unwrap(::Type{T}, x) where {T} = convert(T, x)
unwrap(::Type{Any}, x) = x.hasvalue ? x.value : missing

nondv(T) = DataValueInterfaces.nondatavaluetype(T)
undatavalue(x::T) where {T} = T == nondv(T) ? x : unwrap(nondv(T), x)

getcolumn(r::IteratorRow, ::Type{T}, col::Int, nm::Symbol) where {T} = undatavalue(getcolumn(getrow(r), T, col, nm))
getcolumn(r::IteratorRow, nm::Symbol) = undatavalue(getcolumn(getrow(r), nm))
getcolumn(r::IteratorRow, i::Int) = undatavalue(getcolumn(getrow(r), i))
columnnames(r::IteratorRow) = columnnames(getrow(r))

# DataValueRowIterator wraps a Row iterator and will wrap `Union{T, Missing}` typed fields in DataValues
struct DataValueRowIterator{NT, sch, S}
    x::S
end

"""
    Tables.datavaluerows(x) => NamedTuple iterator

Takes any table input `x` and returns a `NamedTuple` iterator
that will replace missing values with `DataValue`-wrapped values;
this allows any table type to satisfy the TableTraits.jl
Queryverse integration interface by defining:

```
IteratorInterfaceExtensions.getiterator(x::MyTable) = Tables.datavaluerows(x)
```
"""
function datavaluerows(x)
    r = Tables.rows(x)
    s = Tables.schema(r)
    s === nothing && error("Schemaless sources cannot be passed to datavaluerows.")
    return DataValueRowIterator{datavaluenamedtuple(s), typeof(s), typeof(r)}(r)
end

Base.eltype(rows::DataValueRowIterator{NT}) where {NT} = NT
Base.IteratorSize(::Type{DataValueRowIterator{NT, sch, S}}) where {NT, sch, S} = Base.IteratorSize(S)
Base.length(rows::DataValueRowIterator) = length(rows.x)
Base.size(rows::DataValueRowIterator) = size(rows.x)

function Base.iterate(rows::DataValueRowIterator{NamedTuple{names, dtypes}, Schema{names, rtypes}, S}, st=()) where {names, dtypes, rtypes, S}
    if @generated
        vals = Any[ :(convert($(fieldtype(dtypes, i)), getcolumn(row, $(fieldtype(rtypes, i)), $i, $(Meta.QuoteNode(names[i]))))) for i = 1:length(names) ]
        ret = Expr(:new, :(NamedTuple{names, dtypes}), vals...)
        q = quote
            x = iterate(rows.x, st...)
            x === nothing && return nothing
            row, st = x
            return $ret, (st,)
        end
        # @show q
        return q
    else
        x = iterate(rows.x, st...)
        x === nothing && return nothing
        row, st = x
        return NamedTuple{names, dtypes}(Tuple(convert(fieldtype(dtypes, i), getcolumn(row, fieldtype(rtypes, i), i, names[i])) for i = 1:length(names))), (st,)
    end
end


text:
@testset "Poisson loss" begin
    N = 6
    img = abs.(randn((N, N)))

    @test 0.22741127776021886 ≈ poisson_aux([1.,2.], [3.,4.])

    @test all(0 .≈ Zygote.gradient(poisson_aux, img, img)[1])

    @test all( -1 .≈ Zygote.gradient(poisson_aux, [1.], [2.])[1])
end

@testset "Gaussian Loss" begin
    N = 6
    img = abs.(randn((N, N)))

    gauss = Gauss()
    @test 0 ≈ gauss(img, img)

    @test 0 ≈ gauss_aux(img, img)

    @test all(0 .≈ Zygote.gradient(gauss_aux, img, img)[1])

end

@testset "Scaled Gauss" begin
    N = 6
    img = abs.(randn((N, N)))

    scaled_gauss = ScaledGauss()

    @test 1.7047189562170502 ≈ scaled_gauss([5.], [2.])
    @test 1.7047189562170502 ≈ scaled_gauss_aux([5.], [2.])

    @test all( -1 .≈ Zygote.gradient(scaled_gauss_aux, [1.], [2.])[1])

end


text:
module GUITestRunner
using Tk
using TestRunner

include("Widgets.jl")

import TestRunner: TestStructureNode, FactsCollectionNode, FactNode, children, ContextNode
import Tk:Tk_Frame, Tk_Labelframe

export start_test_runner

source_path =  @__FILE__() |> dirname
hidden_tests_groups_ids = Int[]
get_file_name = ()->""

start_test_runner() = create_main_window()

browse_dir_callback!(file_name_input::Tk_Widget) = set_value(file_name_input, GetOpenFile())

function load_tests_button_callback!(frame)
  try
    tests_structure = get_file_name() |> get_tests_structure |> children
    process_tests_callback!(frame, tests_structure)
  catch
    Messagebox(frame, "Uncorrect file with tests!")
  end
end

function run_tests_button_callback!(frame)
  try
    tests_structure = get_file_name() |> run_all_tests |> children
    process_tests_callback!(frame, tests_structure)
  catch
    Messagebox(frame, "Uncorrect file with tests!")
    return
  end
end

function process_tests_callback!(frame::Tk_Frame, tests_structure::Vector{TestStructureNode})
  clear_current_tests!(frame)
  display_all_tests!(frame, tests_structure)

end

function tests_header_callback!(frame::Tk_Frame, test_node::TestStructureNode, tests_structure::Vector{TestStructureNode})
  global hidden_tests_groups_ids
  if test_node.line in hidden_tests_groups_ids
    hidden_tests_groups_ids = filter(x -> x != line(test_node), hidden_tests_groups_ids)
  else
    push!(hidden_tests_groups_ids, line(test_node))
  end
  clear_all_tests!(frame)
  display_all_tests!(frame, tests_structure)
end

function single_test_callback!(frame::Tk_Frame, test_node::TestStructureNode)
  clear_all_test_details!(frame)
  test_details = details(test_node)
  display_test_details!(frame, test_details)
end

function line_number_button_callback(test_node::TestStructureNode, tests_file_name::AbstractString)
  script_name = @windows ? "/lineNumberButtonOnClick.bat" : "\lineNumberButtonOnClick.sh"
  @async run(`$source_path$script_name $(test_node.line) $tests_file_name`)
end

open_details_button_callback(test_details::AbstractString) =  create_new_window(test_details, 400, 350)

function clear_current_tests!(frame::Tk_Frame)
  global hidden_tests_groups_ids
  empty!(hidden_tests_groups_ids)
  clear_all_tests!(frame)
  clear_all_test_details!(frame)
end

function display_all_tests!(frame::Tk_Frame, tests_structure::Vector{TestStructureNode})
  for node in tests_structure
    display_nodes!(frame, node, tests_structure)
  end
end

function display_nodes!(frame::Tk_Frame, test_node::TestStructureNode, tests_structure::Vector{TestStructureNode}, nesting_level::Int=0)
  nesting_level = draw_node!(frame, tests_structure, test_node, nesting_level)

  global hidden_tests_groups_ids
  line(test_node) in hidden_tests_groups_ids && return
  for child in TestRunner.children(test_node)
    display_nodes!(frame, child, tests_structure, nesting_level)
  end
end

function draw_node!(frame::Tk_Frame, tests_structure::Vector{TestStructureNode}, test_node::TestStructureNode,  nesting_level::Int)
  nesting_level, node_label = get_node_label!(frame, tests_structure, test_node, nesting_level)
  padding = (nesting_level-1)*15
  pack(node_label, fill="x",padx="$padding 0")
  nesting_level
end

function display_test_details!(frame::Tk_Frame, test_details::AbstractString)
  test_details == "" && return
  create_open_details_button!(frame, test_details)
  create_details_textbox!(frame, test_details)
end

get_frame_for_tests(frame::Tk_Frame) = filter(x->isa(x, Tk.Tk_Labelframe), frame.children)[1]

get_frame_for_test_details(frame::Tk_Frame) = filter(x->isa(x, Tk.Tk_Labelframe), frame.children)[2]

clear_all_tests!(frame::Tk_Frame) = clear_all_children!(get_frame_for_tests(frame))

clear_all_test_details!(frame::Tk_Frame) = clear_all_children!(get_frame_for_test_details(frame))

function clear_all_children!(frame::Union{Tk_Frame, Tk_Labelframe, Tk.Tk_Text})
  for child in frame.children
    child |> forget
  end
  empty!(frame.children)
end

end # module


text:
## Element types
struct IIDMLoad <: AbstractNodeLabel
  id::String
  load::Complex128 # MW + im*MVar
end

## 1. Variables creation
function create_vars!(element::T, bus::String, elemid::String, elem_formulation::Symbol, bus_vars::Dict{String, Variable}, scenario::String) where T <: IIDMLoad
  if elem_formulation == :NewVar
    bus_vars[elemid] = Variable(variable_name("Sload", bus, elemid, scenario), Complex)
  end
  return
end

# function create_vars!(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::Dict{String, Variable}) where T <: MyType
#   return
# end

## 2. Power balance
function Snodal(element::T, busid::String, elemid::String, elem_formulation::Symbol, bus_vars::Dict{String, Variable}) where T <: IIDMLoad
  cstrname = "LOAD"
  if elem_formulation == :NbMinVar
    Sload = element.load
    return [cstrname, Polynomial(), -Sload, -Sload]
  elseif elem_formulation == :NewVar
    return [cstrname, Polynomial(bus_vars[elemid]), 0, 0]
  end
  return ["", Polynomial(), 0, 0]
end

# function Sorig(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::Dict{String, Variable}) where T<:MyType
#   return Polynomial()
# end

# function Sdest(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::Dict{String, Variable}) where T<:MyType
#   return Polynomial()
# end

## 3. Constraints creation
function constraint(element::T, busid::String, elemid::String, elem_formulation::Symbol, bus_vars::Dict{String, Variable}) where T <: IIDMLoad
  if elem_formulation == :NewVar
    cstrname = "Cstr_$(busid)_$(elemid)"
    Sload = element.load
    p = Polynomial(bus_vars[elemid])
    return Dict{String, Constraint}(cstrname=> p == Sload)
  end
  return Dict{String, Constraint}()
end

# function constraint(element::T, link::Link, elemid::String, elem_formulation::Symbol, link_vars::Dict{String, Variable}) where T <: MyType
#   return [[], [], [], []]
# end

max_stars_repo_name: Gimaju/GOC

max_issues_repo_name: Gimaju/GOC

max_forks_repo_name: Gimaju/GOC


text:
# module Bukdu.Plug

struct Head <: AbstractPlug
end

function plug(::Type{Head})
    push!(bukdu_env[:prequisite_plugs], function (conn::Conn)
        if conn.request.method == "HEAD"
            conn.method = "GET"
        end
    end)
end

# module Bukdu.Plug


text:
#   Copyright (c) 2020-2022 Velexi Corporation
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

"""
dual.jl defines methods for the dual(x, y) function
"""

# --- Method definitions

# ------ Specializations involving a AbstractBlade instance

# B::AbstractBlade, C::AbstractScalar
# B::AbstractScalar, C::AbstractBlade
dual(B::AbstractBlade, C::AbstractScalar) =
    grade(B) > 0 ? throw(ArgumentError("`B` not contained in `C`")) : B

dual(B::AbstractScalar, C::AbstractBlade) =
    mod(grade(C), 4) < 2 ?
        Blade(C, volume=value(B), copy_basis=false) :
        Blade(C, volume=-value(B), copy_basis=false)

# B::AbstractBlade, C::Real
# B::Real, C::AbstractBlade
dual(B::AbstractBlade, C::Real) =
    grade(B) > 0 ? throw(ArgumentError("`B` not contained in `C`")) : B

dual(B::Real, C::AbstractBlade) =
    mod(grade(C), 4) < 2 ?
        Blade(C, volume=B, copy_basis=false) :
        Blade(C, volume=-B, copy_basis=false)

# ------ Specializations involving a Blade instance

# B::Blade, C::Blade
function dual(B::Blade, C::Blade)
    # --- Check arguments

    # Check that B and C are from the same real vector space
    assert_dim_equal(B, C)

    # Check that B is contained in C
    if grade(B) > grade(C)
        throw(ArgumentError("`B` not contained in `C`"))
    end

    projection_coefficients = transpose(basis(C)) * basis(B)
    if LinearAlgebra.norm(projection_coefficients)^2 ≉ grade(B)
        throw(ArgumentError("`B` not contained in `C`"))
    end

    # --- Handle edge cases

    # Subspaces represented by B and C are the same
    if grade(B) == grade(C)
        dual_sign = mod(grade(B), 4) < 2 ? 1 : -1

        dual_volume = det(projection_coefficients) > 0 ?
            dual_sign * volume(B) : -dual_sign * volume(B)

        return Scalar{typeof(volume(B))}(dual_volume)
    end

    # --- Extend basis(B) to an orthonormal basis for entire subspace
    #     represented by basis(C)

    F = qr(projection_coefficients)

    # --- Compute volume of dual

    # Account for orientation of Q relative to orientation of basis(C)
    dual_volume = volume(B) * sign(det(F.Q))

    # Account for orientation of first grade(B) columns of Q relative to
    # orientation of basis(B)
    if prod(diag(F.R)) < 0
        dual_volume = -dual_volume
    end

    # Account for sign of I_C^{-1} relative to I_C
    if mod(grade(C), 4) >= 2
        dual_volume = -dual_volume
    end

    # Account for reversals required to eliminate B
    if mod(grade(B), 4) >= 2
        dual_volume = -dual_volume
    end

    # --- Construct Blade in embedding space

    Blade{typeof(volume(B))}(dim(B), grade(C) - grade(B),
                             basis(C) * F.Q[:, grade(B) + 1:end], dual_volume,
                             enforce_constraints=false,
                             copy_basis=false)
end

# B::Blade, C::Pseudoscalar
# B::Pseudoscalar, C::Blade
function dual(B::Blade, C::Pseudoscalar)
    assert_dim_equal(B, C)
    dual(B)
end

function dual(B::Pseudoscalar, C::Blade)
    assert_dim_equal(B, C)
    throw(ArgumentError("`B` not contained in `C`"))
end

# B::Blade, C::Vector
# B::Vector, C::Blade
@inline dual(B::Blade, C::Vector) = dual(B, Blade(C))
@inline dual(B::Vector, C::Blade) = dual(Blade(B), C)

# ------ Specializations involving a Pseudoscalar instance

# B::Pseudoscalar, C::Pseudoscalar
function dual(B::Pseudoscalar, C::Pseudoscalar)
    assert_dim_equal(B, C)
    Scalar{typeof(value(B))}(value(B))
end

# B::Pseudoscalar, C::AbstractScalar
# B::AbstractScalar, C::Pseudoscalar
dual(B::Pseudoscalar, C::AbstractScalar) =
    throw(ArgumentError("`B` not contained in `C`"))

dual(B::AbstractScalar, C::Pseudoscalar) =
    mod(grade(C), 4) < 2 ?
        Pseudoscalar(C, value=value(B)) :
        Pseudoscalar(C, value=-value(B))

# B::Pseudoscalar, C::Real
# B::Real, C::Pseudoscalar
dual(B::Pseudoscalar, C::Real) =
    throw(ArgumentError("`B` not contained in `C`"))

dual(B::Real, C::Pseudoscalar) =
    mod(grade(C), 4) < 2 ?
        Pseudoscalar(C, value=B) :
        Pseudoscalar(C, value=-B)

# B::Vector, C::Pseudoscalar
# B::Pseudoscalar, C::Vector
function dual(B::Vector, C::Pseudoscalar)
    assert_dim_equal(B, C)
    dual(Blade(B))
end

function dual(B::Pseudoscalar, C::Vector)
    assert_dim_equal(B, C)

    if dim(B) == 1
        return dual(B, Blade(C))
    end

    throw(ArgumentError("`B` not contained in `C`"))
end

# ------ Specializations involving an AbstractScalar instance

# B::AbstractScalar, C::AbstractScalar
function dual(B::AbstractScalar, C::AbstractScalar)
    if iszero(C)
        dual_relative_to_zero()
    end

    if iszero(B)
        dual_of_zero()
    end

    B
end

# B::AbstractScalar, C::Real
# B::Real, C::AbstractScalar
function dual(B::AbstractScalar, C::Real)
    if iszero(C)
        dual_relative_to_zero()
    end

    if iszero(B)
        dual_of_zero()
    end

    B
end

function dual(B::Real, C::AbstractScalar)
    if iszero(C)
        dual_relative_to_zero()
    end

    if iszero(B)
        dual_of_zero()
    end

    Scalar(B)
end

# B::Vector, C::AbstractScalar
# B::AbstractScalar, C::Vector
dual(B::Vector, C::AbstractScalar) =
    iszero(B) ?
        dual_of_zero() :
        throw(ArgumentError("`B` not contained in `C`"))
dual(B::AbstractScalar, C::Vector) = Blade(C, volume=value(B))

# ------ Specializations involving a Zero instance

# dual(B::Zero, C)
@inline dual_of_zero() = error("The dual of Zero is not well-defined")

dual(B::Zero, C::Blade) = dual_of_zero()
dual(B::Zero, C::Pseudoscalar) = dual_of_zero()
dual(B::Zero, C::Scalar) = dual_of_zero()
dual(B::Zero, C::One) = dual_of_zero()
dual(B::Zero, C::Real) = dual_of_zero()
dual(B::Zero, C::Vector) = dual_of_zero()

# dual(B, C::Zero)
@inline dual_relative_to_zero() =
    error("The dual of anything relative to Zero is not well-defined")

dual(M::Multivector, C::Zero) = dual_relative_to_zero()
dual(B::Blade, C::Zero) = dual_relative_to_zero()
dual(B::Pseudoscalar, C::Zero) = dual_relative_to_zero()
dual(B::Scalar, C::Zero) = dual_relative_to_zero()
dual(B::One, C::Zero) = dual_relative_to_zero()
dual(B::Zero, C::Zero) = dual_relative_to_zero()
dual(B::Real, C::Zero) = dual_relative_to_zero()
dual(B::Vector, C::Zero) = dual_relative_to_zero()


text:
### A Pluto.jl notebook ###
# v0.17.3

using Markdown
using InteractiveUtils

# ╔═╡ 44e51e69-e12b-479f-a630-3f8be3461112
using Pkg; Pkg.activate()

# ╔═╡ 4e322516-2838-11ec-3ceb-c5bfb1e357bc
begin
	using Plots
end

# ╔═╡ f24068a4-992a-434c-b9af-633373f5e67f
md"# Plots.jl Backends"

# ╔═╡ f5826703-a88f-4b2b-b3f6-ff5242894251
md"""
> **NB** You need to install the different backends (PlotlyJS, PyPlot, PGFPlotsX, Gaston) separately
"""

# ╔═╡ 0571dd1a-4488-4a2f-932a-155a2e48be92
begin
	gr()
	plot(rand(15), label="Buzz", title="GR")
end

# ╔═╡ df8bc50d-afe1-4b62-9a30-1b7ae1cc3c45
begin
	plotlyjs()
	plot(rand(15), label="Foo", title="PlotlyJS")
end

# ╔═╡ b27088ee-7bab-4f39-8de6-d2b1fe50226d
begin
	pyplot()
	plot(rand(15), label="Bar", title="PyPlot")
end

# ╔═╡ cd2c9a51-06bb-46f2-ab3f-02abab022a8a
begin
	pgfplotsx()
	plot(rand(15), label="Baz", title="PGFPlotsX")
end

# ╔═╡ a5589144-1762-4f63-8020-8ea90965630e
begin
	gaston()
	plot(rand(15), label="Qux", title="Gaston (Gnuplot)")
end

# ╔═╡ Cell order:
# ╟─f24068a4-992a-434c-b9af-633373f5e67f
# ╟─f5826703-a88f-4b2b-b3f6-ff5242894251
# ╠═44e51e69-e12b-479f-a630-3f8be3461112
# ╠═4e322516-2838-11ec-3ceb-c5bfb1e357bc
# ╠═0571dd1a-4488-4a2f-932a-155a2e48be92
# ╠═df8bc50d-afe1-4b62-9a30-1b7ae1cc3c45
# ╠═b27088ee-7bab-4f39-8de6-d2b1fe50226d
# ╠═cd2c9a51-06bb-46f2-ab3f-02abab022a8a
# ╠═a5589144-1762-4f63-8020-8ea90965630e

max_stars_repo_name: csimal/Julia-Unamur

max_issues_repo_name: csimal/Julia-Unamur

max_forks_repo_name: csimal/Julia-Unamur


text:
# ----------------------------------------------------------------------------------- #
# Copyright (c) 2021 Varnerlab
# Robert Frederick School of Chemical and Biomolecular Engineering
# Cornell University, Ithaca NY 14850

# 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.
# ----------------------------------------------------------------------------------- #

mutable struct VLTranslationParameters

    vmax::Float64
    tau_factor::Float64
    KL::Float64

    function VLTranslationParameters()
		this = new()
	end
end

# Create some abstract parent types -
abstract type VLAbstractProblem end
abstract type VLAbstractSolution end

# Concrete subtypes -
mutable struct VLStaticFBAProblem<:VLAbstractProblem

  # initialize -
  flux_bounds_array::Array{Float64,2}
  species_bounds_array::Array{Float64,2}
  stoichiometric_matrix::Array{Float64,2}
  obj_coeff_vector::Array{Float64,1}
  is_minimum_flag::Bool

  function VLStaticFBAProblem()
    this = new()
  end
end

mutable struct VLDynamicFBAProblem<:VLAbstractProblem

  # fields -
  species_bounds_array::Array{Float64,2}
  flux_bounds_arrray::Array{Float64,2}
  # ...

  function VLDynamicFBAProblem()
    this = new()
  end
end

struct VLStaticSolution<:VLAbstractSolution

  objective_value::Float64
  flux::Array{Float64,1}
  exit_flag::Int64
  status_flag::Int64

end

struct VLDynamicSolutionStep<:VLAbstractSolution
end

mutable struct VLDynamicSolution<:VLAbstractSolution

  # initialize -
  solution_object_array::Array{VLDynamicSolutionStep,1}

  function VLDynamicSolution()
    this = new()
  end
end

max_stars_repo_name: varnerlab/CellFreeModelGenerationKit

max_issues_repo_name: varnerlab/CellFreeModelGenerationKit

max_forks_repo_name: varnerlab/CellFreeModelGenerationKit


text:
# see tutorial https://turinglang.github.io/TuringCallbacks.jl/dev/
#turing test

module TuringCLIExample

using Turing, TuringCallbacks, TensorBoardLogger, ArgParse, StatsPlots, CSV, DataFrames

function simulate_and_estimate(;
    num_samples,
    num_adapts,
    target_acceptance_rate,
    s_prior_alpha,
    s_prior_theta,
    kwargs...,
)
    @model function demo(x; s_prior_alpha, s_prior_theta)
        s ~ InverseGamma(s_prior_alpha, s_prior_theta)
        m ~ Normal(0, √s)
        for i in eachindex(x)
            x[i] ~ Normal(m, √s)
        end
    end

    xs = randn(100) .+ 1
    model = demo(xs; s_prior_alpha, s_prior_theta)

    # Sampling
    println("Generating $num_samples samples")
    callback = TensorBoardCallback("tensorboard_logs/run")
    alg = NUTS(num_adapts, target_acceptance_rate)
    chain = sample(model, alg, num_samples; callback)

    println("Generating trace plot")
    trace_plot = plot(chain, seriestype=:traceplot)
    savefig(trace_plot,  joinpath(callback.logger.logdir, "traceplots.png"))

    println("Summarizing the chain")
    sum_stats = describe(chain)
    param_names = sum_stats[1][:,1]
    param_mean = sum_stats[1][:,2]
    param_sd = sum_stats[1][:,3]
    param_ess = sum_stats[1][:,6]
    param_rhat = sum_stats[1][:,7]
    param_ess_per_sec = sum_stats[1][:, 8]

    CSV.write(
        joinpath(callback.logger.logdir, "summary.csv"),
        DataFrame(
            parameter=param_names,
            mean=param_mean,
            sd=param_sd,
            ess=param_ess,
            rhat=param_rhat,
            ess_per_sec= param_ess_per_sec
        )
    )

    # Log the ESS/sec and rhat.  Nice to show as summary results from tensorboard
    for (i, name) = enumerate(param_names)
        TensorBoardLogger.log_value(
            callback.logger,
            "$(name)_ess_per_sec",
            param_ess_per_sec[i],
        )
        TensorBoardLogger.log_value(
            callback.logger,
            "$(name)_rhat",
            param_rhat[i],
        )
    end
end

# Entry for script
function main()
    d = parse_commandline()

    # Generic code to convert the dictionary to
    dictkeys = (collect(Symbol.(keys(d)))...,)
    dictvalues = (collect(values(d))...,)
    args = NamedTuple{dictkeys}(dictvalues)
    # parses converts all arguments to named tuple then splat into solution
    simulate_and_estimate(; args...)
end

function parse_commandline()
    s = ArgParseSettings()

    @add_arg_table! s begin
        "--num_samples"
        help = "samples to draw in chain"
        arg_type = Int64
        default = 10000
        "--num_adapts"
        help = "number of adaptations for NUTS"
        arg_type = Int64
        default = 100
        "--target_acceptance_rate"
        help = "Target acceptance rate for dual averaging."
        arg_type = Float64
        default = 0.65
        "--s_prior_alpha"
        help = "alpha in InverseGamma prior for s"
        arg_type = Float64
        default = 2.0
        "--s_prior_theta"
        help = "theta in InverseGamma prior for s"
        arg_type = Float64
        default = 3.0
    end

    return parse_args(s)
end

# Can experiment later, or can package compiler
# function _precompile_()
#     ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
#     Base.precompile(Tuple{typeof(main)})
# end

# # Only really intended for final versions rather than during interactive use
# # NOTE: Consider commenting out or fix if changing signature of simulate_and_estimte
# if Base.VERSION >= v"1.4.2"
#     precompile(Tuple{typeof(TuringCLIExample.main)})

#     # Is this necessary or does the main() above do it? Comment out if any problem.
#     precompile(Tuple{TuringCLIExample.var"#simulate_and_estimate##kw", NamedTuple{(:num_samples, :num_adapts, :target_acceptance_rate, :s_prior_theta, :s_prior_alpha), Tuple{Int64, Int64, Float64, Float64, Float64}}, typeof(TuringCLIExample.simulate_and_estimate)})

#     _precompile_()
# end
end #module

max_stars_repo_name: essiequoi/TuringCLIExample

max_issues_repo_name: essiequoi/TuringCLIExample

max_forks_repo_name: essiequoi/TuringCLIExample


text:
#multistrip.jl: Convert a multi-strip Plot into a multi-Plot PlotCollection
#-------------------------------------------------------------------------------

#=NOTE:
Useful for plotting backends that do not support multi-strip plots.
=#

#==Helper functions
===============================================================================#

function hasmultistrip(pcoll::PlotCollection)
	for p in pcoll.plotlist
		if length(p.ystriplist) > 1
			return true
		end
	end
	return false
end

#==Main algorithm
===============================================================================#

function _ms2pcoll(src::Plot; title=nooverwrite)
	NoOverwrite(title) && (title = src.title)
	dcoll = PlotCollection(title=title, ncolumns=1)

	for srcy in src.ystriplist
		dplot = Plot(title=srcy.striplabel, legend=src.legend)
		desty = dplot.ystriplist[1]
			desty.scale = srcy.scale
			#desty.striplabel = srcy.striplabel #Use title instead
			desty.axislabel = srcy.axislabel
			desty.ext = deepcopy(srcy.ext)
		dplot.xext=deepcopy(src.xext)
		dplot.xaxis=deepcopy(src.xaxis)
		push!(dcoll, dplot)
	end

	nstrips = length(dcoll.plotlist)
	for srcwfrm in src.wfrmlist
		istrip = clamp(srcwfrm.strip, 1, nstrips)
		dwfrm = copy(srcwfrm); dwfrm.strip = 1
		push!(dcoll.plotlist[istrip], dwfrm)
	end
	dcoll.plotlist[end].xlabel = src.xlabel
	return dcoll
end

#==External interface (for backend implementation)
===============================================================================#

#Conditionally transform multi-strip plots to multi-plot collections:
function condxfrm_multistrip(pcoll::PlotCollection, backendid::String="some code";
	warnconv::Bool=true, warnfail::Bool=true)
	_hasmult = hasmultistrip(pcoll)
	title = pcoll.title
	msghdr ="""
`$backendid` does not natively support multi-strip plots found in:
    PlotCollection(\"$title\")
"""
	if !_hasmult
		return pcoll
	elseif length(pcoll.plotlist) > 1
		if warnconv
			@warn """$msghdr

*EMULATION MODE FAILED*: Can only convert a SINGLE multi-strip plot into multi-plot collection.
                         Output may be difficult to read."""
		end
		return pcoll
	end

	if warnconv
		@info """$msghdr
*EMULATION MODE ENABLED*: Breaking up (single) multi-strip plot into multi-plot collection."""
	end

	return _ms2pcoll(pcoll.plotlist[1], title=pcoll.title)
end

multistrip2plotcoll(src::Plot; kwargs...) = _ms2pcoll(src; kwargs...)

#Last line


text:
module TestCategories
using Test

using Catlab.Theories
using Catlab.CategoricalAlgebra.Sets, Catlab.CategoricalAlgebra.Categories

# Categories from Julia types
#############################

C = TypeCat(FreeCategory.Ob, FreeCategory.Hom)
@test Ob(C) == TypeSet(FreeCategory.Ob)

x, y = Ob(FreeCategory, :x, :y)
f = Hom(:f, x, y)
F = id(C)
@test (dom(F), codom(F)) == (C, C)
@test F(x) == x
@test F(f) == f

α = id(F)
@test (dom(α), codom(α)) == (F, F)

end


text:
module Microbiome

# Samples and Features
export MicrobiomeSample,
       Taxon,
       GeneFunction,
       Metabolite,
       metadata,
       set!,
       unset!,
       insert!,
       delete!,
       name,
       taxrank,
       hasrank,
       taxon,
       hastaxon,
       genefunction,
       commonname,
       masscharge,
       retentiontime

# EcoBase Translations
export abundances,
       nfeatures,
       featurenames,
       getfeature,
       nsamples,
       samplenames,
       getsample,
       AbstractFeature,
       AbstractSample
    #    featureabundances,
    #    sampleabundances

# Profiles
export CommunityProfile,
       featuretype,
       features,
       samples,
       ranks,
       rankfilter,
       profiletype,
       featuretotals,
       sampletotals,
       commjoin,
       metadata

# Abundances
export present,
       prevalence,
       relativeabundance!,
       relativeabundance,
       prevalence_filter
#     filterabund

# Diversity
export ginisimpson,
       shannon,
       ginisimpson!,
       shannon!,
       present,
       prevalence,
       braycurtis,
       jaccard,
       hellinger,
       pcoa

using Statistics
using SparseArrays
using EcoBase
using Dictionaries
using Tables
using Distances
using MultivariateStats
using ReTest

import Dictionaries: set!, unset!, insert!, delete!
import Base: ==

include("ecobase.jl")
include("samples.jl")
include("features.jl")
include("profiles.jl")
include("diversity.jl")
include("comm_joins.jl")

end  # module Microbiome


text:
####################
#
# Choropleth Plot
#
####################

# Plot choropleth  - given array of shapes and a canvas
function choropleth(shparray::Union{AbstractArray{T, 1}, AbstractArray{Union{Missing, T},1}},
                    canvas::Compose.Context, fill_data, fill_color_map;
                    convertcoords=lonlat_to_webmercator, img_width=12cm,
                    line_width=0.05mm, line_color="black",
                    transform=identity) where {T<:Shapefile.GeoInterface.AbstractGeometry}

    # Check for missings
    try
        shparray = disallowmissing(shparray)
    catch
        error("Error: Shape array contains missing values")
    end

    # This method is only for polygons
    @assert typeof(shparray[1]) <: ShpPolygon

    # Colours
    n_colors = length(fill_color_map)
    minval = transform(minimum(fill_data))
    maxval = transform(maximum(fill_data))
    range = maxval - minval

    # Plot outlines to canvas
    i = 1
    for polygon in shparray
        val = transform(Float64(isnan(fill_data[i]) ? 0.0 : fill_data[i]))  # CHECK CHANGE FROM ISNA TO ISNAN !!!
        i += 1
        normval = (val - minval) / range
        color_idx = round(Int, normval * (n_colors - 1) + 1)
        if length(polygon.parts) == 1
            canvas = compose_single(polygon, canvas, convertcoords, line_width, line_color, fill_color_map[color_idx])
        else
            canvas = compose_multi(polygon, canvas, convertcoords, line_width, line_color, fill_color_map[color_idx])
        end
    end

    # Return canvas
    canvas
end

# Plot choropleth - given array of shapes and an MBR
function choropleth(shparray::Union{AbstractArray{T, 1}, AbstractArray{Union{Missing, T},1}},
                    MBR::Shapefile.Rect,
                    fill_data, fill_color_map;
                    convertcoords=lonlat_to_webmercator, img_width=12cm,
                    options...) where {T<:Shapefile.GeoInterface.AbstractGeometry}

    # Check for missings
    try
        shparray = disallowmissing(shparray)
    catch
        error("Error: Shape array contains missing values")
    end

    # Create canvas
    canvas = create_canvas(MBR, convertcoords, img_width)

    # Plot
    choropleth(shparray, canvas, fill_data, fill_color_map,
               convertcoords=convertcoords, img_width=img_width; options...)
end

# Plot choropleth - given an array of shapes
function choropleth(shparray::Union{AbstractArray{T, 1}, AbstractArray{Union{Missing, T},1}},
                    fill_data, fill_color_map;
                    options...) where {T<:Shapefile.GeoInterface.AbstractGeometry}

    # Check for missings
    try
        shparray = disallowmissing(shparray)
    catch
        error("Error: Shape array contains missing values")
    end

    # Create MBR
    MBR = minBR(shparray)

    # Plot
    choropleth(shparray, MBR, fill_data, fill_color_map; options...)
end


text:
using HartreeFock: Mole, Env, PointCharges, SCF, total_energy, electrostatic_potential, mulliken_charges
using Test

H2 = Mole("
H   0.000000  0.000000  0.000000
H   0.740848  0.000000  0.000000
", "STO-3G")
E = total_energy(H2)
@test E ≈ -1.116714325 atol=1e-7

H2O = Mole(joinpath(@__DIR__, "data/water.xyz"), "STO-3G")
E = total_energy(H2O)
@test E ≈ -74.962927947 atol=1e-7

pointcharges = PointCharges("
-0.834    0.00000  0.00000 -5.00000
 0.417    0.00000  0.00000 -4.04280
 0.417   -0.92663  0.00000 -5.23999
")
env = Env(pointcharges)
scf = SCF(H2O, env)

E = total_energy(scf)
@test E ≈ -74.964115862

V = electrostatic_potential(scf, pointcharges.positions)
@test all(isapprox.(V, [-0.73578734E-02, -0.11128084E-01, -0.64441894E-02], atol=1e-7))

Q = mulliken_charges(scf)
@test all(isapprox.(Q, [-0.369266, 0.184633, 0.184633], atol=1e-6))


text:
export Surf
module Surf

using MLStyle
using MLFS.TypedIO: @typedIO

abstract type TyExpr end
abstract type Decl end
abstract type Expr end

@data TyExpr begin
    TForall(Vector{Symbol}, TyExpr)
    TApp(TyExpr, TyExpr)
    TArrow(TyExpr, TyExpr)
    TTuple(Vector{TyExpr})
    TImplicit(TyExpr)
    TVar(Symbol)
    TSym(Symbol)
    TNew(Symbol)
    TQuery(String, TyExpr)
end

@typedIO TyExpr = begin
    TForall(Vector{Symbol}, TyExpr)
    TApp(TyExpr, TyExpr)
    TArrow(TyExpr, TyExpr)
    TTuple(Vector{TyExpr})
    TImplicit(TyExpr)
    TVar(Symbol)
    TSym(Symbol)
    TNew(Symbol)
    TQuery(String, TyExpr)
end

@data Decl begin
    DAnn(Symbol, TyExpr)
    DOpen(Expr)
    DLoc(LineNumberNode)
    DBind(Symbol, Expr)
    DQuery(String, Symbol)
end

@typedIO Decl = begin
    DAnn(Symbol, TyExpr)
    DOpen(Expr)
    DLoc(LineNumberNode)
    DBind(Symbol, Expr)
    DQuery(String, Symbol)
end

@data Expr begin
    ELoc(LineNumberNode, Expr)
    EVar(Symbol)
    EVal(Union{String, Char, Bool, Integer, AbstractFloat})
    ELet(Vector{Decl}, Expr)
    EITE(Expr, Expr, Expr)
    EFun(Symbol, Expr)
    EApp(Expr, Expr)
    EField(Expr, Symbol)
    ETup(Vector{Expr})
    EExt(Any)
    EQuery(String, Expr)
end

@typedIO Expr = begin
    ELoc(LineNumberNode, Expr)
    EVar(Symbol)
    EVal(Union{String, Char, Bool, Integer, AbstractFloat})
    ELet(Vector{Decl}, Expr)
    EITE(Expr, Expr, Expr)
    EFun(Symbol, Expr)
    EApp(Expr, Expr)
    EField(Expr, Symbol)
    ETup(Vector{Expr})
    EExt(Any)
    EQuery(String, Expr)
end

@as_record struct ModuleRecord
    name :: Symbol
    imports :: Vector{Pair{Symbol, Symbol}}
    decls :: Vector{Decl}
end

@typedIO ModuleRecord(Symbol, Vector{Pair{Symbol, Symbol}}, Vector{Decl})

end # module


text:
println("Hello world!")

# something on main branch
# changed back on main branch

# something...

# something again something added on the temp branch

max_stars_repo_name: sylvaticus/testGit

max_issues_repo_name: sylvaticus/testGit

max_forks_repo_name: sylvaticus/testGit


text:
import NPZ: npzread
using Flux
import Flux: stack, unstack, Data.DataLoader

get_2d_dl(T::DataType=Float32; seq_len=32, batchsize=16, normalise=true) = get_dl(T; seq_len, batchsize, normalise, stacked=false)
get_3d_dl(T::DataType=Float32; seq_len=32, batchsize=16, normalise=true) = get_dl(T; seq_len, batchsize, normalise, stacked=true)
get_3d_ct_dl(T::DataType=Float32; seq_len=32, batchsize=16, normalise=true, ct=true) = get_dl(T; seq_len, batchsize, normalise, stacked=true, ct=true)

function get_dl(T::DataType=Float32; seq_len=32, batchsize=16, stacked=true, normalise=true, ct=false)
    filepath = joinpath(@__DIR__, "data")
    data_dir = filepath

    obs_size = size(npzread("$(data_dir)/trace_0000.npy"),2) # 17

    all_files = readdir(data_dir)
    all_files = ["$(data_dir)/$(f)" for f in all_files]
    valid_files = all_files[1:5]
    test_files = all_files[6:15]
    train_files = all_files[16:16]

    train_x, train_y, train_seq = _load_files(T, train_files, seq_len)
    test_x, test_y, test_seq = _load_files(T, test_files, seq_len)
    valid_x, valid_y, valid_seq = _load_files(T, valid_files, seq_len)

    # (970×32×17)
    train_x = permutedims(train_x,(3,1,2))
    train_y = permutedims(train_y,(3,1,2))
    test_x = permutedims(test_x,(3,1,2))
    test_y = permutedims(test_y,(3,1,2))
    valid_x = permutedims(valid_x,(3,1,2))
    valid_y = permutedims(valid_y,(3,1,2))

    # (17x970x32)
    if normalise
      train_x = Flux.normalise(train_x)
      train_y = Flux.normalise(train_y)
    end

    train_x_new = train_y_new = stacked ? Vector{Array{T,3}}() : Vector{Vector{Matrix{T}}}()
    test_x_new = test_y_new = stacked ? Vector{Array{T,3}}() : Vector{Vector{Matrix{T}}}()
    valid_x_new = valid_y_new = stacked ? Vector{Array{T,3}}() : Vector{Vector{Matrix{T}}}()

    if ct
      train_x_new = train_y_new = Vector{Tuple{Array{T,3},Tuple{T,T}}}()
      test_x_new = test_y_new = Vector{Tuple{Array{T,3},Tuple{T,T}}}()
      valid_x_new = valid_y_new = Vector{Tuple{Array{T,3},Tuple{T,T}}}()
    end
    # train_x_new = train_y_new = []
    # test_x_new = test_y_new = []
    # valid_x_new = valid_y_new = []
    for i in 1:batchsize:size(train_x,2)-batchsize-1
        tmp_x = unstack(train_x[:,i:i+batchsize-1,:],3)
        tmp_y = unstack(train_y[:,i+1:i+batchsize,:],3)
        tmp_x, tmp_y = stacked ? (stack(tmp_x,2),stack(tmp_y,2)) : (tmp_x,tmp_y)

        if ct
          tspan_x = (T(i-1),T(i-1+size(tmp_x,2)))
          tspan_y = (T(i),T(i+size(tmp_y,2)))
          tmp_x, tmp_y = (tmp_x, tspan_x), (tmp_y, tspan_y)
        end
        push!(train_x_new, tmp_x)
        push!(train_y_new, tmp_y)
        # push!(train_x_new, train_x[:,i:i+batchsize-1,:])
        # push!(train_y_new, train_y[:,i+1:i+batchsize,:])
    end
    for i in 1:batchsize:size(test_x,2)-batchsize-1
        tmp_x = unstack(test_x[:,i:i+batchsize-1,:],3)
        tmp_y = unstack(test_y[:,i+1:i+batchsize,:],3)
        tmp_x, tmp_y = stacked ? (stack(tmp_x,2),stack(tmp_y,2)) : (tmp_x,tmp_y)
        if ct
          tspan_x = (T(i-1),T(i-1+size(tmp_x,2)))
          tspan_y = (T(i),T(i+size(tmp_y,2)))
          tmp_x, tmp_y = (tmp_x, tspan_x), (tmp_y, tspan_y)
        end
        push!(test_x_new, tmp_x)
        push!(test_y_new, tmp_y)
    end
    for i in 1:batchsize:size(valid_x,2)-batchsize-1
        tmp_x = unstack(valid_x[:,i:i+batchsize-1,:],3)
        tmp_y = unstack(valid_y[:,i+1:i+batchsize,:],3)
        tmp_x, tmp_y = stacked ? (stack(tmp_x,2),stack(tmp_y,2)) : (tmp_x,tmp_y)
        if ct
          tspan_x = (T(i-1),T(i-1+size(tmp_x,2)))
          tspan_y = (T(i),T(i+size(tmp_y,2)))
          tmp_x, tmp_y = (tmp_x, tspan_x), (tmp_y, tspan_y)
        end
        push!(valid_x_new, tmp_x)
        push!(valid_y_new, tmp_y)
    end

    # train_x_new = Flux.stack(train_x_new,4)
    # train_y_new = Flux.stack(train_y_new,4)
    # test_x_new = Flux.stack(test_x_new,4)
    # test_y_new = Flux.stack(test_y_new,4)
    # valid_x_new = Flux.stack(valid_x_new,4)
    # valid_y_new = Flux.stack(valid_y_new,4)

    #train_x = Flux.unstack(train_x,3)

    # train_dl = Flux.Data.DataLoader((train_x,train_y),batchsize=1)
    # test_dl = Flux.Data.DataLoader((test_x,test_y),batchsize=batchsize)
    # valid_dl = Flux.Data.DataLoader((valid_x,valid_y),batchsize=batchsize)
    # train_dl = Flux.Data.DataLoader((train_x_new,train_y_new),batchsize=1)
    # test_dl = Flux.Data.DataLoader((test_x_new,test_y_new),batchsize=1)
    # valid_dl = Flux.Data.DataLoader((valid_x_new,valid_y_new),batchsize=1)

    # @show size(train_x_new)
    # @show size(train_x_new[1])
    # @show size(train_x_new[1][1])
    #
    # @show size(train_x_new[2])
    # @show size(train_x_new[2][1])

    train_dl = zip(train_x_new, train_y_new) #|> f32
    test_dl = zip(test_x_new, test_y_new) #|> f32
    valid_dl = zip(valid_x_new, valid_y_new) #|> f32

    return train_dl, test_dl, valid_dl, train_x_new

    @show summary(train_x_new)
    @show summary(train_x_new[1])
    @show summary(train_x_new[1][1])

    #train_dl = DataLoader((train_x_new, train_y_new), batchsize=1, shuffle=false)
    # i = 0
    # for (tx,ty) in train_dl
    #   @show tx[1][2]
    #   i += 1
    #   if i == 3
    #     break
    #   end
    # end

    # train_dl = (train_x_new, test_y_new)
    # test_dl = (test_x_new, test_y_new)
    # valid_dl = (valid_x_new, valid_y_new)

    return train_dl, test_dl, valid_dl, train_seq
end

function _load_files(T, files, seq_len)
    all_x = []
    all_y = []
    sequences = []
    for f in files
        arr = T.(npzread(f))
        push!(sequences, permutedims(arr, (2,1)))
        x, y = _cut_in_sequences(arr, seq_len, 10)
        push!(all_x, x...)
        push!(all_y, y...)
    end

    return stack(all_x,1), stack(all_y,1), sequences
    #return all_x, all_y
end

function _cut_in_sequences(x, seq_len, inc=1)
    seq_x = []
    seq_y = []
    for s in 1:inc:size(x,1)-seq_len-1
        i_s = s
        i_e = i_s + seq_len - 1
        push!(seq_x, x[i_s:i_e,:])
        push!(seq_y, x[i_s+1:i_e+1,:])
    end
    return seq_x, seq_y
end

# train_dl = get_dl()[1][1]
# x = train_dl[1]

function mycb(p,l,ŷ,y;doplot=true)
  #display(l)
  if doplot
    y = ndims(y) < 3 ? stack(y,2) : y
    ŷ = ndims(ŷ) < 3 ? stack(ŷ,2) : ŷ

    if size(y,1) > 3
      hy = heatmap(1:size(y,2),1:size(y,1),(@view y[:,:,1]),title="data")
      hŷ = heatmap(1:size(ŷ,2),1:size(ŷ,1),(@view ŷ[:,:,1]),title="prediction")
      he = heatmap(1:size(y,2),1:size(y,1),(@view y[:,:,1]).-(@view ŷ[:,:,1]),title="error", c=:curl)
      p = plot((@view y[1,:,1]), label="y[1,:,1]")
      plot!(p, (@view ŷ[1,:,1]), label="ŷ[1,:,1]")
      fig = plot(hy,he,hŷ,p)
      display(fig)
    else
      p = plot((@view y[1,:,1]), label="y1")
      plot!(p, (@view ŷ[1,:,1]), label="ŷ1")
      for i in 2:size(y,1)
        plot!(p, (@view y[i,:,1]), label="y$(i)")
        plot!(p, (@view ŷ[i,:,1]), label="ŷ$(i)")
      end
      display(p)

      if size(y,3) > 1
        p = plot((@view y[1,:,2]), label="y1")
        plot!(p, (@view ŷ[1,:,2]), label="ŷ1")
        for i in 2:size(y,1)
          plot!(p, (@view y[i,:,2]), label="y$(i)")
          plot!(p, (@view ŷ[i,:,2]), label="ŷ$(i)")
        end
        display(p)
      end
    end

    # fig = plot(y[1,:,1], label="y1")
    # size(y,1) > 1 && plot!(fig, y[2,:,1], label="y2")
    # plot!(fig, ŷ[1,:,1], label="ŷ1")
    # size(y,1) > 1 && plot!(fig, ŷ[2,:,1], label="ŷ2")
    # display(fig)
    #
    # fig = plot(y[end-1,:,1], label="ye1")
    # size(y,1) > 1 && plot!(fig, y[end,:,1], label="ye2")
    # plot!(fig, ŷ[end-1,:,1], label="ŷe1")
    # size(y,1) > 1 && plot!(fig, ŷ[end,:,1], label="ŷe2")
    # display(fig)
  end
  return false
end


text:
using Documenter, AzStorage, Serialization

makedocs(sitename="AzStorage", modules=[AzStorage])

deploydocs(
    repo = "github.com/ChevronETC/AzStorage.jl.git",
)


text:
module TestLevels
    using Base.Test
    using CategoricalArrays
    using CategoricalArrays: DefaultRefType

    pool = CategoricalPool([2, 1, 3])

    @test isa(levels(pool), Vector{Int})
    @test length(levels(pool)) === 3
    @test levels(pool) == pool.index == [2, 1, 3]
    @test pool.invindex == Dict(1=>2, 2=>1, 3=>3)
    @test pool.order == [1, 2, 3]
    @test pool.valindex == [CategoricalValue(i, pool) for i in 1:3]

    for rep in 1:3
        push!(pool, 4)

        @test isa(pool.index, Vector{Int})
        @test length(pool) === 4
        @test pool.index == [2, 1, 3, 4]
        @test pool.invindex == Dict(1=>2, 2=>1, 3=>3, 4=>4)
        @test pool.order == [1, 2, 3, 4]
        @test pool.levels == [2, 1, 3, 4]
        @test get(pool, 4) === DefaultRefType(4)
        @test pool[4] === CategoricalValue(4, pool)
        @test pool.valindex == [CategoricalValue(i, pool) for i in 1:4]
    end

    for rep in 1:3
        push!(pool, 0)

        @test isa(pool.index, Vector{Int})
        @test length(pool) === 5
        @test levels(pool) == pool.index == [2, 1, 3, 4, 0]
        @test pool.invindex == Dict(1=>2, 2=>1, 3=>3, 4=>4, 0=>5)
        @test pool.order == [1, 2, 3, 4, 5]
        @test pool.levels == [2, 1, 3, 4, 0]
        @test get(pool, 0) === DefaultRefType(5)
        @test pool[5] === CategoricalValue(5, pool)
        @test pool.valindex == [CategoricalValue(i, pool) for i in 1:5]
    end

    for rep in 1:3
        push!(pool, 10, 11)

        @test isa(pool.index, Vector{Int})
        @test length(pool) === 7
        @test levels(pool) == pool.index == [2, 1, 3, 4, 0, 10, 11]
        @test pool.invindex == Dict(1=>2, 2=>1, 3=>3, 4=>4, 0=>5, 10=>6, 11=>7)
        @test pool.order == [1, 2, 3, 4, 5, 6, 7]
        @test pool.levels == [2, 1, 3, 4, 0, 10, 11]
        @test get(pool, 10) === DefaultRefType(6)
        @test get(pool, 11) === DefaultRefType(7)
        @test pool[6] === CategoricalValue(6, pool)
        @test pool[7] === CategoricalValue(7, pool)
        @test pool.valindex == [CategoricalValue(i, pool) for i in 1:7]
    end

    for rep in 1:3
        push!(pool, 12, 13)

        @test isa(pool.index, Vector{Int})
        @test length(pool) === 9
        @test levels(pool) == pool.index == [2, 1, 3, 4, 0, 10, 11, 12, 13]
        @test pool.invindex == Dict(1=>2, 2=>1, 3=>3, 4=>4, 0=>5, 10=>6, 11=>7, 12=>8, 13=>9)
        @test pool.order == [1, 2, 3, 4, 5, 6, 7, 8, 9]
        @test pool.levels == [2, 1, 3, 4, 0, 10, 11, 12, 13]
        @test get(pool, 12) === DefaultRefType(8)
        @test get(pool, 13) === DefaultRefType(9)
        @test pool[8] === CategoricalValue(8, pool)
        @test pool[9] === CategoricalValue(9, pool)
        @test pool.valindex == [CategoricalValue(i, pool) for i in 1:9]
    end

    for rep in 1:3
        delete!(pool, 13)

        @test isa(pool.index, Vector{Int})
        @test length(pool) == 8
        @test levels(pool) == pool.index == [2, 1, 3, 4, 0, 10, 11, 12]
        @test pool.invindex == Dict(1=>2, 2=>1, 3=>3, 4=>4, 0=>5, 10=>6, 11=>7, 12=>8)
        @test pool.order == [1, 2, 3, 4, 5, 6, 7, 8]
        @test pool.levels == [2, 1, 3, 4, 0, 10, 11, 12]
        @test_throws KeyError get(pool, 13)
        @test pool.valindex == [CategoricalValue(i, pool) for i in 1:8]
    end

    for rep in 1:3
        delete!(pool, 12, 11)

        @test isa(pool.index, Vector{Int})
        @test length(pool) == 6
        @test levels(pool) == pool.index == [2, 1, 3, 4, 0, 10]
        @test pool.invindex == Dict(1=>2, 2=>1, 3=>3, 4=>4, 0=>5, 10=>6)
        @test pool.order == [1, 2, 3, 4, 5, 6]
        @test pool.levels == [2, 1, 3, 4, 0, 10]
        @test_throws KeyError get(pool, 11)
        @test_throws KeyError get(pool, 12)
        @test pool.valindex == [CategoricalValue(i, pool) for i in 1:6]
    end

    for rep in 1:3
        delete!(pool, 4)

        @test isa(pool.index, Vector{Int})
        @test length(pool) == 5
        @test levels(pool) == pool.index == [2, 1, 3, 0, 10]
        @test pool.invindex == Dict(1=>2, 2=>1, 3=>3, 0=>4, 10=>5)
        @test pool.order == [1, 2, 3, 4, 5]
        @test pool.levels == [2, 1, 3, 0, 10]
        @test_throws KeyError get(pool, 4)
        @test pool.valindex == [CategoricalValue(i, pool) for i in 1:5]
    end

    @test levels!(pool, [1, 2, 3]) === pool
    @test levels(pool) == [1, 2, 3]

    @test isa(pool.index, Vector{Int})
    @test length(pool) == 3
    @test length(pool.valindex) == 3
    @test levels(pool) == pool.index == [1, 2, 3]
    @test pool.invindex == Dict(1=>1, 2=>2, 3=>3)
    @test pool.order == [1, 2, 3]
    @test pool.levels == [1, 2, 3]
    @test get(pool, 1) === DefaultRefType(1)
    @test_throws KeyError get(pool, 0)
    @test_throws KeyError get(pool, 10)
    @test pool.valindex == [CategoricalValue(i, pool) for i in 1:3]

    @test levels!(pool, [1, 2, 4]) === pool
    @test levels(pool) == [1, 2, 4]

    @test isa(pool.index, Vector{Int})
    @test length(pool) == 3
    @test length(pool.valindex) == 3
    @test levels(pool) == pool.index == [1, 2, 4]
    @test pool.invindex == Dict(1=>1, 2=>2, 4=>3)
    @test pool.order == [1, 2, 3]
    @test pool.levels == [1, 2, 4]
    @test get(pool, 1) === DefaultRefType(1)
    @test_throws KeyError get(pool, 3)
    @test pool.valindex == [CategoricalValue(i, pool) for i in 1:3]

    @test levels!(pool, [6, 5, 4]) === pool
    @test levels(pool) == [6, 5, 4]

    @test isa(pool.index, Vector{Int})
    @test length(pool) == 3
    @test length(pool.valindex) == 3
    @test levels(pool) == pool.index == [6, 5, 4]
    @test pool.invindex == Dict(6=>1, 5=>2, 4=>3)
    @test pool.order == [1, 2, 3]
    @test pool.levels == [6, 5, 4]
    @test get(pool, 5) === DefaultRefType(2)
    @test_throws KeyError get(pool, 3)
    @test pool.valindex == [CategoricalValue(i, pool) for i in 1:3]

    # Changing order while preserving existing levels
    @test levels!(pool, [5, 6, 4]) === pool
    @test levels(pool) == [5, 6, 4]

    @test isa(pool.index, Vector{Int})
    @test length(pool) == 3
    @test length(pool.valindex) == 3
    @test levels(pool) == [5, 6, 4]
    @test pool.index == [6, 5, 4]
    @test pool.invindex == Dict(6=>1, 5=>2, 4=>3)
    @test pool.order == [2, 1, 3]
    @test pool.levels == [5, 6, 4]
    @test get(pool, 5) === DefaultRefType(2)
    @test pool.valindex == [CategoricalValue(i, pool) for i in 1:3]

    # Adding levels while preserving existing ones
    @test levels!(pool, [5, 2, 3, 6, 4]) === pool
    @test levels(pool) == [5, 2, 3, 6, 4]

    @test isa(pool.index, Vector{Int})
    @test length(pool) == 5
    @test length(pool.valindex) == 5
    @test levels(pool) == [5, 2, 3, 6, 4]
    @test pool.index == [6, 5, 4, 2, 3]
    @test pool.invindex == Dict(6=>1, 5=>2, 4=>3, 2=>4, 3=>5)
    @test pool.order == [4, 1, 5, 2, 3]
    @test pool.levels == [5, 2, 3, 6, 4]
    @test get(pool, 2) === DefaultRefType(4)
    @test get(pool, 3) === DefaultRefType(5)
    @test pool.valindex == [CategoricalValue(i, pool) for i in 1:5]

    for rep in 1:3
        delete!(pool, 6)

        @test isa(pool.index, Vector{Int})
        @test length(pool) == 4
        @test length(pool.valindex) == 4
        @test levels(pool) == [5, 2, 3, 4]
        @test pool.index == [5, 4, 2, 3]
        @test pool.invindex == Dict(5=>1, 4=>2, 2=>3, 3=>4)
        @test pool.order == [1, 4, 2, 3]
        @test pool.levels == [5, 2, 3, 4]
        @test get(pool, 4) === DefaultRefType(2)
        @test_throws KeyError get(pool, 6)
        @test pool.valindex == [CategoricalValue(i, pool) for i in 1:4]
    end

    # Test that overflow of reftype is detected and doesn't corrupt levels

    res = @test_throws LevelsException{Int, UInt8} CategoricalPool{Int, UInt8}(collect(256:-1:1))
    @test res.value.levels == [1]
    @test sprint(showerror, res.value) == "cannot store level(s) 1 since reference type UInt8 can only hold 255 levels. Use the decompress function to make room for more levels."

    pool = CategoricalPool(collect(30:288))
    res = @test_throws LevelsException{Int, UInt8} convert(CategoricalPool{Int, UInt8}, pool)
    @test res.value.levels == collect(285:288)
    @test sprint(showerror, res.value) == "cannot store level(s) 285, 286, 287 and 288 since reference type UInt8 can only hold 255 levels. Use the decompress function to make room for more levels."

    pool = CategoricalPool{String, UInt8}(string.(318:-1:65))
    res = @test_throws LevelsException{String, UInt8} levels!(pool, vcat("az", levels(pool), "bz", "cz"))
    @test res.value.levels == ["bz", "cz"]
    @test sprint(showerror, res.value) == "cannot store level(s) \"bz\" and \"cz\" since reference type UInt8 can only hold 255 levels. Use the decompress function to make room for more levels."
    lev = copy(levels(pool))
    levels!(pool, vcat(lev, "az"))
    @test levels(pool) == vcat(lev, "az")
end


text:
"""
The module `PDB` defines types and methods to work with protein structures inside Julia.
It is useful to link structural and sequential information, and
needed for measure the predictive performance at protein contact prediction of mutual information scores.

**Features**

- Read and parse PDF and PDBML files
- Calculate distance and contacts between atoms or residues
- Determine interaction between residues

```julia

using MIToS.PDB
```
"""
module PDB

using LightXML
using AutoHashEquals
using DataStructures
using Formatting
using MIToS.Utils
using PairwiseListMatrices
using FixedSizeArrays
using RecipesBase           # Plots for PDBResidue

import Base: ==, hash, length, size, -, +, ./, norm, dot, angle, cross, vec, any, print, show, parse
import MIToS.Utils: findobjects, isobject

export covalentradius, vanderwaalsradius, check_atoms_for_interactions,

PDBResidueIdentifier, Coordinates, PDBAtom, PDBResidue,
distance, contact, findheavy, findatoms, findCB, selectbestoccupancy, bestoccupancy,
angle, proximitymean,

ishydrophobic, isaromatic, iscationic, isanionic,
ishbonddonor, ishbondacceptor, hydrogenbond,
vanderwaals, vanderwaalsclash, covalent, disulphide,
aromaticsulphur, pication, aromatic, ionic, hydrophobic,
stridehydrogenbond, chimerahydrogenbond,

PDBFile, PDBML, downloadpdb, getpdbdescription,

kabsch, center!, rmsd,
getCA, CAmatrix, coordinatesmatrix, change_coordinates,
centeredcoordinates, centeredresidues,
superimpose,
mean_coordinates, rmsf,

# Mitos.Utils
isobject, findobjects, Is, Not, In, collectobjects, collectcaptures,

@residues, residues, @atoms, atoms, @residuesdict, residuesdict

include("PDBResidues.jl")
include("AtomsData.jl")
include("Interaction.jl")
include("PDBMLParser.jl")
include("PDBParser.jl")
include("Kabsch.jl")
include("Plots.jl")

@deprecate bestoccupancy! bestoccupancy

end


text:
isquotenode(x) = false
isquotenode(x::QuoteNode) = true

quotenode(x) = QuoteNode(x)

iswidgettuple(x) = false
iswidgettuple(x::Expr) = x.head == :tuple && all(isquotenode, x.args) && length(x.args) > 0

parse_layout_call(d, x, func, args...) = parse_layout_call!(OrderedDict(), d, x, func, args...)

function parse_layout_call!(syms, d, x::Expr, func, args...)
    if x.head == :. && length(x.args) == 2 && isquotenode(x.args[2])
        Expr(x.head, parse_layout_call!(syms, d, x.args[1], func, args...), x.args[2])
    elseif x.head == :call && length(x.args) == 2 && x.args[1] == :^
        x.args[2]
    elseif iswidgettuple(x)
        return parse_layout_call!(syms, d, x.args[1], func, x.args[2:end]..., args...)
    else
        Expr(x.head, (parse_layout_call!(syms, d, arg, func, args...) for arg in x.args)...)
    end
end

function parse_layout_call!(syms, d, x, func, args...)
    if isquotenode(x)
        func(d, x, args...)
    elseif x == :(_)
        func(d, args...)
    else
        x
    end
end

extract_name(s) = s
extract_name(s::QuoteNode) = s.value
function extract_name(expr::Expr)
    isquotenode(expr) && return extract_name(expr.args[1])
    expr.head == :macrocall && return extract_name(expr.args[1])
    expr.head == :. || return nothing
    extract_name(expr.args[2])
end

isparameters(::Any) = false
isparameters(x::Expr) = x.head == :parameters

"""
`@nodeps(expr)`

`@nodeps` is deprecated. Simply use e.g. `Widgets.dropdown(x)` instead of `Widgets.@nodeps dropdown(x)`.

Macro to remove need to depend on package X that defines a recipe to use it in one's own recipe.
For example, InteractBase defines `dropwdown` recipe. To use `dropdown` in a recipe in a package,
without depending on InteractBase, wrap the `dropdown` call in the `@nodeps` macro:

```julia
function myrecipe(i)
    label = "My recipe"
    wdg = Widgets.@nodeps dropdown(i)
    Widget(["label" => label, "dropdown" => wdg])
end
```
"""
macro nodeps(expr)
    @warn "`@nodeps` is deprecated. Simply use e.g. `Widgets.dropdown(x)` instead of `Widgets.@nodeps dropdown(x)`."
    @assert expr isa Expr
    @assert expr.head == :call
    shortname = extract_name(expr.args[1])
    qn = quotenode(shortname)
    args = expr.args[2:end]
    if length(args) > 0 && isparameters(args[1])
        esc(Expr(:call, :(Widgets.widget), args[1], Expr(:call, :Val, qn), args[2:end]...))
    else
        esc(Expr(:call, :(Widgets.widget), Expr(:call, :Val, qn), args...))
    end
end

name2string(x::Symbol) = Expr(:call, :string, Expr(:quote, x))
name2string(x::QuoteNode) = Expr(:call, :string, x)
name2string(x::Expr) = name2string(x.args[end])

isijulia() = isdefined(Main, :IJulia) && Main.IJulia.inited

to_abstractobservable(s::AbstractObservable) = s
to_abstractobservable(s) = Observable(s)


text:
"""
    shuffleobs(data, [obsdim])

Return a "subset" of `data` that spans all observations, but
has the order of the observations shuffled.

The values of `data` itself are not copied. Instead only the
indices are shuffled. This function calls [`datasubset`](@ref) to
accomplish that, which means that the return value is likely of a
different type than `data`.

```julia
# For Arrays the subset will be of type SubArray
@assert typeof(shuffleobs(rand(4,10))) <: SubArray

# Iterate through all observations in random order
for (x) in eachobs(shuffleobs(X))
    ...
end
```

The optional (keyword) parameter `obsdim` allows one to specify
which dimension denotes the observations. see `LearnBase.ObsDim`
for more detail.

For this function to work, the type of `data` must implement
[`nobs`](@ref) and [`getobs`](@ref). See [`DataSubset`](@ref)
for more information.
"""
shuffleobs(data; obsdim = default_obsdim(data)) =
    shuffleobs(data, convert(LearnBase.ObsDimension,obsdim))

function shuffleobs(data, obsdim)
    allowcontainer(shuffleobs, data) || throw(MethodError(shuffleobs, (data,obsdim)))
    datasubset(data, randperm(nobs(data, obsdim)), obsdim)
end


text:
module DotEnv

import Base: getindex, get, isempty

struct EnvDict
    dict::Dict{String, String}
end

getindex(ed::EnvDict, key) = get(ed.dict, key, ENV[key])
get(ed::EnvDict, key, default) = get(ed.dict, key, get(ENV, key, default))
isempty(ed::EnvDict) = isempty(ed.dict)

"""
`DotEnv.parse` accepts a String or an IOBuffer (Any value that
 can be converted into String), and it will return a Dict with
 the parsed keys and values.
"""
function parse( src )
    res = Dict{String,String}()
    src = IOBuffer(src)
    for line in eachline(src)
        m = match(r"^\s*([\w.-]+)\s*=\s*(.*)?\s*$", line)
        if m !== nothing
            key = m.captures[1]
            value = string(m.captures[2])

            if (length(value) > 0 && value[1] === '"' && value[end] === '"')
                value = replace(value, r"\\n"m => "\n")
            end

            value = replace(value, r"(^['\u0022]|['\u0022]$)" => "")

            value = strip(value)

            push!(res, Pair(key, value) )
        end
    end
    res
end

"""
`config` reads your .env file, parse the content, stores it to `ENV`,
and finally return a Dict with the content.
"""
function config( path, override = false)
    if (isfile(path))
        parsed = parse(read(path, String))

        for (k, v) in parsed
            if( !haskey( ENV, k ) || override )
                ENV[k] = v
            end
        end

        return EnvDict(parsed)
    else
        return EnvDict(Dict{String, String}())
    end
end

config( ;path=".env", override = false ) = config(path, override)

load(opts...; kwargs...) = config(opts...; kwargs...)

end


text:
module Mancala
  export Game, Board
  include("game.jl")
  module Training
    using AlphaZero
    include("params.jl")
  end
end


text:
x = randn()

LHS = sin(x)
RHS = cos(x-pi/2)

@test isnumericallyclose(LHS, RHS)

println("LHS = ", LHS)
println("RHS = ", RHS)

max_stars_repo_name: RoyCCWang/RWJuliaUtilities

max_issues_repo_name: RoyCCWang/RWJuliaUtilities

max_forks_repo_name: RoyCCWang/RWJuliaUtilities


text:
testf(b,k) = k[1] - b[1]

@assert inner_eval(testf, b*(k*b)*k) == inner_eval(testf, (b*k)*(b*k))

immutable SomeInner <: AbstractInner end
QuDirac.inner_rule(::SomeInner, b, k) = b[1]*k[1]
s = (e^(bra(SomeInner(),1) * ket(SomeInner(),2)) + (bra(SomeInner(),3)*ket(SomeInner(),4))im)^4
@assert s == (e^2 + 12im)^4


text:
export RImage

import ComradeBase: Pulse, κ, ω, κflux

@doc raw"""
    $(TYPEDEF)
An image model given by a set of coefficients and a kernel response or basis function.
This corresponds to a continous image defined by a finite set of points. The defined
intensity is given by
```math
    I(x,y) = \sum_{ij} c_{ij}κ(x-x_i)κ(y-y_i).
```
An important thing to note is that the ``c_{ij}`` do not represent pixel intensities, i.e.
the κ doesn't have to be an interpolating kernel.

## Example
```julia
samples = rand(10,10)
model = RImage(samples, BSplineKernel{3})
```

## Notes

This is defined in terms of pixel response, so the image size is 1μas. To resize the image
use the scale function like with other models.

## Fields

$(FIELDS)

"""
struct RImage{S,B<:Pulse,M<:AbstractMatrix{S}} <: AbstractModel
    """ Image coefficients cᵢⱼ in expansion """
    coeff::M
    """ Image kernel/basis κ that defined the delta image response """
    kernel::B
    # pixel size in 1/pixels
    psizex::S
    # pixel size in 1/pixels
    psizey::S
    function RImage(coeff::M, basis::B) where {S,M<:AbstractMatrix{S},B}
        ny, nx = size(coeff)
        psizex = one(S)/max(nx-1, 1)
        psizey = one(S)/max(ny-1, 1)
        new{S,B,M}(coeff, basis, psizex, psizey)
    end
end
@inline visanalytic(::Type{<:RImage}) = IsAnalytic()
@inline isprimitive(::Type{<:RImage}) = IsPrimitive()
@inline radialextent(m::RImage{S}) where {S} = max(radialextent(m.kernel), 0.75)
#=
struct FourierCache{C} <: ObservationCache
    cache::C
end

function FourierCache(rimage::I, obs::Observation) where {S,I<:AbstractRadioImage{S}}
    cache = zeros(Complex{S}, size(rimage)..., nsamples(obs))
    ny,nx = size(rimage)
    u = getdata(obs, :u)
    v = getdata(obs, :v)
    dx = 1/max(nx-1,1)
    dy = 1/max(ny-1,1)
    startx = -0.5
    starty = -0.5
    x = range(startx, length=nx, step=dx)
    y = range(starty, length=ny, step=dy)
    for i in eachindex(u,v)
        cache[:,:,i] .= exp.(2im*π*(u[i].*x' .+ v[i].*y))
    end
    FourierCache(cache)
end
=#

@inline function flux(model::RImage{S,B,M}) where {S,B,M}
    sum = zero(S)
    @turbo for i in eachindex(model.coeff)
        sum += model.coeff[i]
    end
    # Divide by pixel number to convert properly
    ny,nx = size(model.coeff)
    dx = 1/max(nx-1,1)
    dy = 1/max(ny-1,1)
    return sum*κflux(model.kernel)
end

"""
    $(SIGNATURES)
return the size of the coefficient matrix for `model`.
"""
@inline Base.size(model::RImage) = size(model.coeff)

@inline function intensity_point(model::RImage{S,M,B}, x, y, args...) where {S,M,B}
    sum = zero(S)
    ny,nx = size(model)
    dx = 1/(max(nx-1,1))
    dy = 1/(max(ny-1,1))
    #The kernel is written in terms of pixel number so we convert x to it
    @inbounds @fastmath for I in CartesianIndices(model.coeff)
        iy,ix = Tuple(I)
        xx = x - (-0.5 + dx*(ix-1))
        yy = y - (-0.5 + dy*(iy-1))
        sum += model.coeff[I]* κ(model.kernel, xx/dx)*κ(model.kernel, yy/dy)/(dx*dy)
    end
    # Note this will be intensity per uas
    return sum
end

@inline function visibility_point(model::RImage{S,M,B}, u, v, args...) where {S,M,B}
    sum = zero(Complex{S})
    ny,nx = size(model)
    dx = 1/max(nx-1,1)
    dy = 1/max(ny-1,1)
    startx = -0.5
    starty = -0.5
    upx = u*dx
    vpx = v*dy
    phasecenter = exp(2im*π*(u*startx + v*starty))
    @inbounds @fastmath for i in axes(model.coeff,2), j in axes(model.coeff,1)
        sum += model.coeff[j,i]*exp(2im*π*(upx*(i-1) + vpx*(j-1)))
    end
    return sum*ω(model.kernel, u*dx)*ω(model.kernel, v*dy)*phasecenter
end


text:
@defstruct InnerProductLayer Layer (
  (name :: AbstractString = "", !isempty(name)),
  param_key :: AbstractString = "",
  (tops :: Vector{Symbol} = Symbol[], length(tops) >= 1),
  (bottoms :: Vector{Symbol} = Symbol[], length(bottoms) == length(tops)),
  (output_dim :: Int = 0, output_dim > 0),
  weight_init :: Initializer = XavierInitializer(),
  bias_init :: Initializer = ConstantInitializer(0),
  weight_regu :: Regularizer = L2Regu(1),
  bias_regu :: Regularizer = NoRegu(),
  weight_cons :: Constraint = NoCons(),
  bias_cons :: Constraint = NoCons(),
  weight_lr :: AbstractFloat = 1.0,
  bias_lr :: AbstractFloat = 2.0,
  neuron :: ActivationFunction = Neurons.Identity()
)
@characterize_layer(InnerProductLayer,
  can_do_bp  => true,
  has_param  => true,
  has_neuron => true
)

type InnerProductLayerState <: LayerState
  layer      :: InnerProductLayer
  blobs      :: Vector{Blob}
  blobs_diff :: Vector{Blob}

  parameters :: Vector{Parameter}

  W  :: Blob
  ∇W :: Blob
  b  :: Blob
  ∇b :: Blob

  # a all-1 vector used in gemm to help bias calculation
  bias_multipliers :: Vector{Blob}

  frozen :: Bool

  InnerProductLayerState(backend::Backend, layer::InnerProductLayer, shared_params, inputs::Vector{Blob}) = begin
    fea_size = get_fea_size(inputs[1])
    data_type = eltype(inputs[1])
    out_dim = layer.output_dim

    # make sure all blobs has the same feature dimension (batch_size could be different)
    for i = 2:length(inputs)
      @assert get_fea_size(inputs[i]) == fea_size
      @assert eltype(inputs[i]) == data_type
    end

    blobs = Array{Blob}(length(inputs))
    blobs_diff = Array{Blob}(length(inputs))
    bias_multipliers = Array{Blob}(length(inputs))

    for i = 1:length(inputs)
      nums = get_num(inputs[i])
      blobs[i] = make_blob(backend, data_type, out_dim, nums)
      blobs_diff[i] = make_blob(backend, data_type, out_dim, nums)
      bias_multipliers[i] = make_blob(backend, ones(data_type, 1, nums))
    end

    state = new(layer, blobs, blobs_diff)
    state.bias_multipliers = bias_multipliers

    if shared_params != nothing
      @assert length(shared_params) == 2
      @assert shared_params[1].name == "weight" && shared_params[2].name == "bias"
      @assert size(shared_params[1].blob) == (fea_size, out_dim)
      @assert eltype(shared_params[1].blob) == data_type
      @assert size(shared_params[2].blob) == (out_dim, 1)
      m_debug("InnerProductLayer($(layer.name)): sharing weights and bias")

      param_weight, param_bias = [share_parameter(backend, param) for param in shared_params]
    else
      param_weight = make_parameter(backend, "weight", data_type, (fea_size,out_dim),
          layer.weight_init, layer.weight_regu, layer.weight_cons, layer.weight_lr)
      param_bias   = make_parameter(backend, "bias", data_type, (out_dim,1),
          layer.bias_init, layer.bias_regu, layer.bias_cons, layer.bias_lr)
    end

    state.W  = param_weight.blob
    state.∇W = param_weight.gradient
    state.b  = param_bias.blob
    state.∇b = param_bias.gradient
    state.parameters = [param_weight, param_bias]
    state.frozen = false

    return state
  end
end

function freeze!(state::InnerProductLayerState)
  state.frozen = true
end
function unfreeze!(state::InnerProductLayerState)
  state.frozen = false
end
function is_frozen(state::InnerProductLayerState)
  state.frozen
end

function setup(backend::Backend, layer::InnerProductLayer, shared_state, inputs::Vector{Blob}, diffs::Vector{Blob})
  state = InnerProductLayerState(backend, layer, shared_state, inputs)
  return state
end
function setup(backend::Backend, layer::InnerProductLayer, inputs::Vector{Blob}, diffs::Vector{Blob})
  setup(backend, layer, nothing, inputs, diffs)
end
function shutdown(backend::Backend, state::InnerProductLayerState)
  map(destroy, state.blobs)
  map(destroy, state.blobs_diff)
  map(destroy, state.bias_multipliers)
  map(destroy, state.parameters)
end

function forward(backend::CPUBackend, state::InnerProductLayerState, inputs::Vector{Blob})
  M = size(state.W, 2)   # target dim
  K = size(state.W, 1)   # source dim
  dtype = eltype(state.W)
  for i = 1:length(inputs)
    input = inputs[i]
    N = get_num(input)   # batch size
    output = state.blobs[i]
    # output = W^T * X
    BLAS.gemm!('T', 'N', one(dtype), state.W.data,
                reshape(input.data, (K,N)), zero(dtype), output.data)
    # output += bias
    BLAS.gemm!('N', 'N', one(dtype), state.b.data,
                state.bias_multipliers[i].data, one(dtype), output.data)
  end
end

function backward(backend::CPUBackend, state::InnerProductLayerState, inputs::Vector{Blob}, diffs::Vector{Blob})
  target_dim = size(state.W, 2)
  source_dim = size(state.W, 1)
  data_type  = eltype(state.W)

  # used in BLAS, at first it is zero, indicating overwriting the data
  # then it becomes one, indicating adding to the data
  zero_and_then_one = zero(data_type)

  for i = 1:length(inputs)
    # ∂f/∂W = input * [∂f/∂o]^T
    input = inputs[i]
    batch_size = get_num(input)
    ∂f_∂o = state.blobs_diff[i]

    if !state.frozen
      BLAS.gemm!('N', 'T', one(data_type), reshape(input.data, (source_dim, batch_size)),
                 ∂f_∂o.data, zero_and_then_one, state.∇W.data)

      # ∂f/∂b = sum(∂f/∂o, 2)
      BLAS.gemm!('N', 'N', one(data_type), ∂f_∂o.data,
                 reshape(state.bias_multipliers[i].data, (batch_size, 1)),
                 zero_and_then_one, state.∇b.data)
    end

    zero_and_then_one = one(data_type)

    # if back propagate down
    if isa(diffs[i], CPUBlob)
      # ∂f/∂x = W * [∂f/∂o]
      BLAS.gemm!('N', 'N', one(data_type), state.W.data,
                 ∂f_∂o.data, zero(data_type),
                 reshape(diffs[i].data, (source_dim, batch_size)))
    end
  end
end


text:
using MeetBot
using Test

@testset "MeetBot.jl" begin
    # Write your tests here.
end


text:
### A Pluto.jl notebook ###
# v0.12.7

using Markdown
using InteractiveUtils

# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49
using Pkg, DrWatson

# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72
begin
	@quickactivate "StatisticsWithJuliaPlutoNotebooks"
	using Distributions, Random, StatsBase, DataFrames, Plots
	Random.seed!(1)
end;

# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549
md"## Listing 3.16"

# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b
function rouletteSpins(p)
    x = 0
    while true
        x += 1
        if rand() < p
            return x
        end
    end
end

# ╔═╡ beee83e0-2162-11eb-10f1-7f63ce3708d2
begin
	p, xGrid, N = 18/37, 1:7, 10^6
	mcEstimate = counts([rouletteSpins(p) for _ in 1:N],xGrid)/N

	gDist = Geometric(p)
	gPmf = [pdf(gDist,x-1) for x in xGrid]
end;

# ╔═╡ beeeb36a-2162-11eb-0698-5fc29070f3ee
begin
	plot(xGrid, mcEstimate, line=:stem, marker=:circle,
		c=:blue, ms=10, msw=0, lw=4, label="MC estimate")
	plot!( xGrid, gPmf, line=:stem, marker=:xcross,
		c=:red, ms=6, msw=0, lw=2, label="PMF",
		ylims=(0,0.5), xlabel="x", ylabel="Probability")
end

# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3
md"## End of listing 3.16"

# ╔═╡ Cell order:
# ╠═ed174bc4-1ea0-11eb-1e2f-a32874cec549
# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49
# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72
# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b
# ╠═beee83e0-2162-11eb-10f1-7f63ce3708d2
# ╠═beeeb36a-2162-11eb-0698-5fc29070f3ee
# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3