text:
export CompositeMod

struct CompositeMod{M} <: ArrayModifier
    modifiers   ::  M
end

const EmptyCompositeMod = CompositeMod{Tuple{}}

# Convenience constructor that packs arguments into a tuple
CompositeMod(mods::ArrayModifier...) = CompositeMod(mods)

modifiers(m::CompositeMod) = m.modifiers
modifiers(m::ArrayModifier) = (m,)

first(m::CompositeMod) = first(m.modifiers)
tail(m::CompositeMod) = CompositeMod(tail(m.modifiers))
tail(m::EmptyCompositeMod) = CompositeMod()

"Combine two modifiers into a single modifier, or a composite modifier."
compose(mod1::ArrayModifier, mod2::ArrayModifier) =
    CompositeMod(modifiers(mod2)..., modifiers(mod1)...)

# Provide additional  constructors for a ModifiedArray

modify(A, mods::ArrayModifier...) = modify(A, CompositeMod(mods))
modify(A::ModifiedArray, mod::ArrayModifier) =
    modify(parent(A), compose(modifier(A), mod))
modify(A::ModifiedArray, mods::ArrayModifier...) =
    modify(parent(A), compose(modifier(A), CompositeMod(mods)))

struct CompositeStyle <: ModStyle end

ModStyle(::CompositeMod, ::Interface) = CompositeStyle()

mod_eltype(::CompositeStyle, mod::CompositeMod, A) =
    mod_eltype_composite(first(mod), tail(mod), A)
mod_eltype_composite(mod::ArrayModifier, mods::EmptyCompositeMod, A) =
    mod_eltype(mod, A)
mod_eltype_composite(mod::ArrayModifier, mods, A) =
    mod_eltype_composite(ModStyle(mod, IF_eltype()), mod, mods, A)
mod_eltype_composite(::ModNothing, mod, mods, A) =
    mod_eltype_composite(first(mods), tail(mods), A)
mod_eltype_composite(::ModFinal, mod, mods, A) =
    mod_eltype_final(mod)
function mod_eltype_composite(::ModRecursive, mod, mods, A)
    Z = mod_eltype_composite(first(mods), tail(mods), A)
    mod_eltype_post(mod, Z)
end

mod_ndims(::CompositeStyle, mod::CompositeMod, A) =
    mod_ndims_composite(first(mod), tail(mod), A)
mod_ndims_composite(mod::ArrayModifier, mods::EmptyCompositeMod, A) =
    mod_ndims(mod, A)
mod_ndims_composite(mod::ArrayModifier, mods, A) =
    mod_ndims_composite(ModStyle(mod, IF_ndims()), mod, mods, A)
mod_ndims_composite(::ModNothing, mod, mods, A) =
    mod_ndims_composite(first(mods), tail(mods), A)
mod_ndims_composite(::ModFinal, mod, mods, A) =
    mod_ndims_final(mod)
function mod_ndims_composite(::ModRecursive, mod, mods, A)
    Z = mod_ndims_composite(first(mods), tail(mods), A)
    mod_ndims_post(mod, Z)
end

mod_size(::CompositeStyle, mod::CompositeMod, A) =
    mod_size_composite(first(mod), tail(mod), A)
mod_size_composite(mod::ArrayModifier, mods::EmptyCompositeMod, A) =
    mod_size(mod, A)
mod_size_composite(mod::ArrayModifier, mods, A) =
    mod_size_composite(ModStyle(mod, IF_size()), mod, mods, A)
mod_size_composite(::ModNothing, mod, mods, A) =
    mod_size_composite(first(mods), tail(mods), A)
mod_size_composite(::ModFinal, mod, mods, A) =
    mod_size_final(mod)
function mod_size_composite(::ModRecursive, mod, mods, A)
    Z = mod_size_composite(first(mods), tail(mods), A)
    mod_size_post(mod, Z)
end

@propagate_inbounds mod_getindex(::CompositeStyle, mod::CompositeMod, A, I...) =
    mod_getindex_composite(first(mod), tail(mod), A, I...)
@propagate_inbounds mod_getindex_composite(mod::ArrayModifier, mods::EmptyCompositeMod, A, I...) =
    mod_getindex(mod, A, I...)
@propagate_inbounds mod_getindex_composite(mod::ArrayModifier, mods::CompositeMod, A, I...) =
    mod_getindex_composite(ModStyle(mod, IF_getindex()), mod, mods, A, I...)

@propagate_inbounds mod_getindex_composite(::ModNothing, mod, mods, A, I...) =
    mod_getindex_composite(first(mods), tail(mods), A, I...)
@propagate_inbounds mod_getindex_composite(::ModFinal, mod, mods, A, I...) =
    mod_getindex_final(mod, I...)
@propagate_inbounds function mod_getindex_composite(::ModRecursive, mod, mods, A, I...)
    J = mod_getindex_pre(mod, I...)
    Z = mod_getindex_composite(first(mods), tail(mods), A, J...)
    @inbounds mod_getindex_post(mod, Z, I...)
end

@propagate_inbounds mod_setindex!(::CompositeStyle, mod::CompositeMod, A, val, I...) =
    mod_setindex!_composite(first(mod), tail(mod), A, val, I...)
@propagate_inbounds mod_setindex!_composite(mod::ArrayModifier, mods::EmptyCompositeMod, A, val, I...) =
    mod_setindex!(mod, A, val, I...)
@propagate_inbounds mod_setindex!_composite(mod::ArrayModifier, mods::CompositeMod, A, val, I...) =
    mod_setindex!_composite(ModStyle(mod, IF_setindex!()), mod, mods, A, val, I...)

@propagate_inbounds mod_setindex!_composite(::ModNothing, mod, mods, A, val, I...) =
    mod_setindex!_composite(first(mods), tail(mods), A, val, I...)
@propagate_inbounds mod_setindex!_composite(::ModFinal, mod, mods, A, val, I...) =
    mod_setindex!_final(mod, val, I...)
@propagate_inbounds function mod_setindex!_composite(::ModRecursive, mod, mods, A, val, I...)
    J = mod_setindex!_pre(mod, val, I...)
    @inbounds mod_setindex!_composite(first(mods), tail(mods), A, J...)
end

mod_axes(::CompositeStyle, mod::CompositeMod, A) =
    mod_axes_composite(first(mod), tail(mod), A)
mod_axes_composite(mod::ArrayModifier, mods::EmptyCompositeMod, A) =
    mod_axes(mod, A)
mod_axes_composite(mod::ArrayModifier, mods, A) =
    mod_axes_composite(ModStyle(mod, IF_axes()), mod, mods, A)
mod_axes_composite(::ModNothing, mod, mods, A) =
    mod_axes_composite(first(mods), tail(mods), A)
mod_axes_composite(::ModFinal, mod, mods, A) =
    mod_axes_final(mod)
function mod_axes_composite(::ModRecursive, mod, mods, A)
    Z = mod_axes_composite(first(mods), tail(mods), A)
    mod_axes_post(mod, Z)
end

ModStyle(::Type{<:CompositeMod}, ::IF_IndexStyle) = CompositeStyle()

Base.first(::Type{CompositeMod{Tuple{}}}) = EmptyCompositeMod
Base.first(::Type{CompositeMod{Tuple{A}}}) where {A} = A
Base.first(::Type{CompositeMod{Tuple{A,B}}}) where {A,B} = A
Base.first(::Type{CompositeMod{Tuple{A,B,C}}}) where {A,B,C} = A

Base.tail(::Type{CompositeMod{Tuple{}}}) = EmptyCompositeMod
Base.tail(::Type{CompositeMod{Tuple{A}}}) where {A} = EmptyCompositeMod
Base.tail(::Type{CompositeMod{Tuple{A,B}}}) where {A,B} = CompositeMod{Tuple{B}}
Base.tail(::Type{CompositeMod{Tuple{A,B,C}}}) where {A,B,C} = CompositeMod{Tuple{B,C}}

mod_IndexStyle(::CompositeStyle, Mod, AA) = mod_IndexStyle_composite(first(Mod), tail(Mod), AA)

mod_IndexStyle_composite(Mod::Type{<:ArrayModifier}, Mods::Type{EmptyCompositeMod}, AA) =
    mod_IndexStyle(Mod, AA)
mod_IndexStyle_composite(Mod::Type{<:ArrayModifier}, Mods::Type{<:CompositeMod}, AA) =
    mod_IndexStyle_composite(ModStyle(Mod, IF_IndexStyle()), Mod, Mods, AA)

mod_IndexStyle_composite(::ModNothing, Mod, Mods, AA) =
    mod_IndexStyle_composite(first(Mods), tail(Mods), AA)
mod_IndexStyle_composite(::ModFinal, Mod, Mods, AA) =
    mod_IndexStyle_final(Mod)
function mod_IndexStyle_composite(::ModRecursive, Mod, Mods, AA)
    Z = mod_IndexStyle_composite(first(Mods), tail(Mods), AA)
    mod_IndexStyle_post(Mod, Z)
end


text:
module FrostHelperAnxietyTriggerModule

using ..Ahorn, Maple

@mapdef Trigger "FrostHelper/AnxietyTrigger" FrostHelperAnxietyTriggerPlacement(x::Integer, y::Integer, width::Integer=16, height::Integer=16, multiplyer::Number=1.0)

const placements = Ahorn.PlacementDict(
	"Anxiety (Frost Helper)" => Ahorn.EntityPlacement(
		FrostHelperAnxietyTriggerPlacement,
		"rectangle"
	)
)

end

ext: jl

max_stars_repo_name: JaThePlayer/FrostHelper

max_issues_repo_name: JaThePlayer/FrostHelper

max_forks_repo_name: JaThePlayer/FrostHelper


text:
def (fib n)
  if (n == 0)
    then 0
  else if (n == 1)
    then 1
  else
    ((fib (n-1)) +
     (fib (n-2)))

def (fact n)
  if (n == 0)
    then 1
  else
    ((fact (n-1)) * n)

def ns [1,2,3,4,5]

def main
  ((print (fib 19)) >>
   (print (ns >>= (return . fact))))


text:
# Fair warning: This program lets you execute arbitrary code on your computer.

module Eval

using Discord

# Set this environment variable or replace with your own user ID.
const USER = parse(Discord.Snowflake, get(ENV, "DISCORD_USER_ID", 1234567890))
const CODE_BLOCK = r"```(?:julia)?\n(.*)\n```"s

module Sandbox end

function codeblock(val)
    io = IOBuffer()
    print(io, val === nothing ? "nothing" : val)
    return "```julia\n" * String(take!(io)) * "\n```"
end

function eval_codeblock(c::Client, msg::Discord.Message)
    if msg.author.id != USER
        reply(c, msg, "Only user $USER can run this command.")
        return
    end

    m = match(CODE_BLOCK, msg.content)

    m = if m === nothing
        reply(c, msg, "That's not a code block.")
        return
    else
        first(m.captures)
    end

    code = replace(m, '\n' => ';')
    ex = try
        Meta.parse(code)
    catch e  # Parsing error.
        reply(c, msg, codeblock(sprint(showerror, e)))
        return
    end

    result = try
        @eval Sandbox $ex
    catch e  # Runtime error.
        sprint(showerror, e)
    end

    reply(c, msg, codeblock(result))
end

function main()
    c = Client(ENV["DISCORD_TOKEN"])
    add_command!(c, "!eval", eval_codeblock)
    open(c)
    return c
end

end

if abspath(PROGRAM_FILE) == @__FILE__
    c = Eval.main()
    wait(c)
end


text:
function merge_sort!(arr::Vector{T},l::Int=1,r::Int=length(arr),temp::Vector{T}=Vector{T}(undef,r-l+1))where T
    if l>=r
        return
    end
    # split
    mid=(l+r)>>1
    merge_sort!(arr,l,mid)
    merge_sort!(arr,mid+1,r)
    # merge
    l_pos=l # pos of the left part
    r_pos=mid+1 # pos of the right part
    for t_pos in 1:r-l+1
        if l_pos<=mid && (r_pos>r || arr[l_pos]<arr[r_pos])
            temp[t_pos]=arr[l_pos]
            l_pos+=1
        else
            temp[t_pos]=arr[r_pos]
            r_pos+=1
        end
    end
    for i in l:r
        arr[i]=temp[i-l+1]
    end
end

max_stars_repo_name: frankschmitt/Julia

max_issues_repo_name: frankschmitt/Julia

max_forks_repo_name: frankschmitt/Julia


text:
function readspecies!( isp::Int64, filename,
    atsp_vars::AtomicSpeciesVars,
    mtr_vars::MuffinTinRadialVars,
    apwlo_vars::APWLOVars;
    verbose=false
)
    f = open(filename, "r")

    # species symbol
    line = readline(f)
    atsp_vars.spsymb[isp] = replace(split(line)[1], "'" => "")
    verbose && println("spsymb = ", atsp_vars.spsymb[isp])

    # species name
    line = readline(f)
    atsp_vars.spname[isp] = replace(split(line)[1], "'" => "")
    verbose && println("spname = ", atsp_vars.spname[isp])

    # atomic number
    line = readline(f)
    atsp_vars.spzn[isp] = parse(Float64, split(line)[1])
    verbose && println("spzn   = ", atsp_vars.spzn[isp])

    # mass
    line = readline(f)
    atsp_vars.spmass[isp] = parse(Float64, split(line)[1])
    verbose && println("spmass = ", atsp_vars.spmass[isp])

    # Radial mesh
    line = readline(f)
    ll = split(line)

    atsp_vars.rminsp[isp] = parse(Float64, ll[1])

    mtr_vars.rmt[isp] = parse(Float64, ll[2])  # muffin tin

    atsp_vars.rmaxsp[isp] = parse(Float64, ll[3])

    mtr_vars.nrmt[isp] = parse(Int64, ll[4])

    verbose && println("rminsp = ", atsp_vars.rminsp[isp])
    verbose && println("rmt    = ", mtr_vars.rmt[isp])
    verbose && println("rmaxsp = ", atsp_vars.rmaxsp[isp])
    verbose && println("nrmt   = ", mtr_vars.nrmt[isp])

    # Atomic states
    line = readline(f)
    atsp_vars.nstsp[isp] = parse(Int64, split(line)[1])
    #
    for ist in 1:atsp_vars.nstsp[isp]
        #
        line = readline(f)
        ll = split(line)
        #
        atsp_vars.nsp[ist,isp] = parse(Int64, ll[1])
        atsp_vars.lsp[ist,isp] = parse(Int64, ll[2])
        atsp_vars.ksp[ist,isp] = parse(Int64, ll[3]) # whats this?
        atsp_vars.occsp[ist,isp] = parse(Float64, ll[4])
        if ll[5] == "T"
            atsp_vars.spcore[ist,isp] = true
        elseif ll[5] == "F"
            atsp_vars.spcore[ist,isp] = false
        else
            error("Unable to parse spcore")
        end
    end

    # apword
    line = readline(f)
    apwlo_vars.apword[1,isp] = parse(Int64, split(line)[1])
    # set the APW orders for > 0
    lmaxapw = mtr_vars.lmaxapw
    apwlo_vars.apword[2:lmaxapw+1,isp] .= apwlo_vars.apword[1,isp]

    # apwe0, apwdm, apwve
    for iorb in apwlo_vars.apword[1,isp]
        line = readline(f)
        ll = split(line)
        apwlo_vars.apwe0[iorb,1,isp] = parse(Float64,ll[1])
        apwlo_vars.apwdm[iorb,1,isp] = parse(Int64, ll[2])
        if ll[3] == "T"
            apwlo_vars.apwve[iorb,1,isp] = true
        elseif ll[3] == "F"
            apwlo_vars.apwve[iorb,1,isp] = false
        else
            error("Unable to parse apwve")
        end
        #
        # set the APW linearisation energies, derivative orders and variability for l > 0
        apwlo_vars.apwe0[iorb,2:lmaxapw+1,isp] .= apwlo_vars.apwe0[iorb,1,isp]
        apwlo_vars.apwdm[iorb,2:lmaxapw+1,isp] .= apwlo_vars.apwdm[iorb,1,isp]
        apwlo_vars.apwve[iorb,2:lmaxapw+1,isp] .= apwlo_vars.apwve[iorb,1,isp]
        #
        apwlo_vars.e0min = min( apwlo_vars.e0min, apwlo_vars.apwe0[iorb,1,isp] )
    end

    # nlx (skipped?) XXX
    line = readline(f)
    nlx = parse(Int64, split(line)[1])
    if nlx > 0
        error("Unsupported value of nlx")
    end

    # nlorb
    line = readline(f)
    nlorb = parse(Int64, split(line)[1])
    for iorb in 1:nlorb
        # lorbl, lorbord
        line = readline(f); ll = split(line)
        apwlo_vars.lorbl[iorb,isp] = parse(Int64, ll[1])
        apwlo_vars.lorbord[iorb,isp] = parse(Int64, ll[2])
        #
        for i in 1:apwlo_vars.lorbord[iorb,isp]
            # lorbe0, lorbdm, lorbve
            line = readline(f); ll = split(line)
            apwlo_vars.lorbe0[i,iorb,isp] = parse(Float64, ll[1])
            apwlo_vars.lorbdm[i,iorb,isp] = parse(Float64, ll[2])
            if ll[3] == "T"
                apwlo_vars.lorbve[i,iorb,isp] = true
            elseif ll[3] == "F"
                apwlo_vars.lorbve[i,iorb,isp] = false
            else
                error("Unable to parse lorbve")
            end
        end
    end

    close(f)

end


text:
function main(::Robot)
  a = []
  summa = 0
  side = Ost
  while !isborder(r, Nord)
  movess!(r, side, a)
    if side == Ost
      side = West
    else
      side = Ost
    end
  end
  movess!(r, side, a)
  k = length(a)
  while length(a) > 0
    summa += pop!(a)
  end
  println(summa/k)

end

function movess!(::Robot, side, a)
  while !isborder(r, side)
    if ismarker(r)
      push!(a, temperature(r))
    end
    move!(r,side)
  end
  if !isborder(r, Nord)
    move!(r, Nord)
  end
end


text:
using DataDeps

register(DataDep(
  "flags",
  "http://archive.ics.uci.edu/ml/datasets/Flags",
  "http://archive.ics.uci.edu/ml/machine-learning-databases/flags/flag.data",
  "ff7061c0838b2916906040057a2fb6505b5ed43c7f4a231a2c59d0e37bdac3fb",
  post_fetch_method=(path -> begin
    UCIData.process_dataset(path,
        target_index=7,
        feature_indices=[2:6; 8:30],
        id_indices=1,
        categoric_indices=[2:3; 6; 18; 29:30],
    )
  end),
))

max_stars_repo_name: JackDunnNZ/uci-data

max_issues_repo_name: JackDunnNZ/uci-data

max_forks_repo_name: JackDunnNZ/uci-data


text:
module MCMCUtil

using LinearAlgebra
using Distributions

updateMean(t::Int, Xt::Float64, m0::Float64) = (Xt + m0*(t-1)) / t
updateMean(t::Int, Xt::Array{Float64,1}, m0::Array{Float64,1}) = @. (Xt + m0*(t-1)) / t

function updateVar(t::Int, Xt::Float64, mt::Float64, m0::Float64, V0::Float64)
    return V0*(t-2)/(t-1) + t*(mt-m0)^2
end

function updateVar(t::Int, Xt::Array{Float64,1}, mt::Array{Float64,1},
                   m0::Array{Float64,1}, V0::Array{Float64,2}, eps::Matrix{Float64})
    return V0.*(t-2)/(t-1) + 1/(t-1).*((t-1).*(m0 * transpose(m0)) .- t.* (mt * transpose(mt)) .+ (Xt * transpose(Xt)) + eps)
end

function MH_single(target_log::Function, init, prop)
    r = target_log(prop) - target_log(init)

    if log(rand()) < r
        return prop, 1
    else
        return init, 0
    end
end

function MH_single(target_log::Function, init::T, proposal::Function, init_loglik::T) where T <: Real
    prop = proposal(init)
    tlp = target_log(prop)
    tli = target_log(init, init_loglik)

    if log(rand()) < (tlp[1] - tli[1])
        return prop, 1, tlp[2]
    else
        return init, 0, tlp[2]
    end
end

## single adaptive Metropolis step
function AM_RR_single(target_log::Function, init::Vector{T}, V::Matrix{T},
                      t::Int, t0::Int=2*length(init),
                      s::T=(2.38)^2/length(init), beta::T=0.05) where T <: Real

    d = length(init)
    proposal = zeros(T, d)

    if (t <= t0) || (rand() < beta)
        proposal = rand(MvNormal(init, (0.1)^2*diagm(0 => ones(eltype(init), d))/d))
    else
        proposal = rand(MvNormal(init, s*V))
    end

    if log(rand()) < (target_log(proposal) - target_log(init))
        return proposal, 1
    else
        return init, 0
    end
end

function AM_RR_single(target_log::Function, init::Float64, V::Float64,
                      t::Int, t0::Int=2, s::Float64=2.38, beta::Float64=0.05)

    proposal::Float64 = 0

    if (t <= t0) | (rand(1)[1] < beta)
        proposal = rand(Normal(init, 0.1))
    else
        if(s*V == 0)
            proposal = init
        else
            proposal = rand(Normal(init, s*sqrt(V)))
        end
    end

    r = target_log(proposal) - target_log(init)

    if log(rand()) < r ##min(1.0, r[1])
        return proposal, 1
    else
        return init, 0
    end
end

end


text:
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Fill Matrix
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
export addto!
function addto!(M::AbstractMatrix, opt::Operator)
    for j = 1:length(opt.B)
        colmn!(view(M, :, j), opt, j)
    end
    M
end
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Cnvert to dense array
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function Array(opt::Operator)
    M = zeros(eltype(opt), size(opt))
    addto!(M, opt)
end

#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Multiplication
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function mul!(target::AbstractVector, opt::Operator, v::AbstractVector)
    for j = 1:length(v)
        colmn!(target, opt, j, v[j])
    end
    target
end
function mul!(target::AbstractMatrix, opt::Operator, m::AbstractMatrix)
    for j = 1:size(m, 1)
        colmn!(target, opt, j, view(m, j, :))
    end
    target
end
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function *(opt::Operator, vom::AbstractVecOrMat)
    ctype = promote_type(eltype(opt), eltype(vom))
    M = zeros(ctype, size(vom))
    mul!(M, opt, vom)
end

#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Helper Functions
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function colmn!(target::AbstractVector, M::SparseMatrixCSC, I::Vector{Int}, b::AbstractBasis, coeff::Real=1)
    rows, vals = rowvals(M), nonzeros(M)
    j = index(b.dgt, I, base=b.B)
    change = false
    for i in nzrange(M, j)
        row, val = rows[i], vals[i]
        change!(b.dgt, I, row, base=b.B)
        C, pos = index(b)
        target[pos] += C * val * coeff
        change = true
    end
    change ? change!(b.dgt, I, j, base=b.B) : nothing
end
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function colmn!(target::AbstractVector, opt::Operator, j::Integer, coeff::Real=1)
    b, M, I = opt.B, opt.M, opt.I
    N = change!(b, j) * coeff
    for i = 1:length(M)
        colmn!(target, M[i], I[i], b, N)
    end
end
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function colmn!(target::AbstractMatrix, M::SparseMatrixCSC, I::Vector{Int}, b::AbstractBasis, coeff::AbstractVector{<:Number})
    rows, vals = rowvals(M), nonzeros(M)
    j = index(b.dgt, I, base=b.B)
    change = false
    for i in nzrange(M, j)
        row, val = rows[i], vals[i]
        change!(b.dgt, I, row, base=b.B)
        C, pos = index(b)
        target[pos, :] .+= (C * val) .* coeff
        change = true
    end
    change ? change!(b.dgt, I, j, base=b.B) : nothing
end
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function colmn!(target::AbstractMatrix, opt::Operator, j::Integer, coeff::AbstractVector{<:Number})
    b, M, I = opt.B, opt.M, opt.I
    N = change!(b, j) .* coeff
    for i = 1:length(M)
        colmn!(target, M[i], I[i], b, N)
    end
end


text:
module ClozeTest
using DataDeps

using ..Datasets: Dataset, maybegoogle_download
import ..Datasets: testfile, trainfile, get_labels

export StoryCloze

function __init__()
    storycloze_init()
end

include("./storycloze.jl")

end


text:
function SimpleRegression()
    return SimpleRegression(())
end

function SimpleRegression(arg0::jboolean)
    return SimpleRegression((jboolean,), arg0)
end

function add_data(obj::SimpleRegression, arg0::Vector{Vector{jdouble}})
    return jcall(obj, "addData", void, (Vector{Vector{jdouble}},), arg0)
end

function add_data(obj::SimpleRegression, arg0::jdouble, arg1::jdouble)
    return jcall(obj, "addData", void, (jdouble, jdouble), arg0, arg1)
end

function add_observation(obj::SimpleRegression, arg0::Vector{jdouble}, arg1::jdouble)
    return jcall(obj, "addObservation", void, (Vector{jdouble}, jdouble), arg0, arg1)
end

function add_observations(obj::SimpleRegression, arg0::Vector{Vector{jdouble}}, arg1::Vector{jdouble})
    return jcall(obj, "addObservations", void, (Vector{Vector{jdouble}}, Vector{jdouble}), arg0, arg1)
end

function append(obj::SimpleRegression, arg0::SimpleRegression)
    return jcall(obj, "append", void, (SimpleRegression,), arg0)
end

function clear(obj::SimpleRegression)
    return jcall(obj, "clear", void, ())
end

function get_intercept(obj::SimpleRegression)
    return jcall(obj, "getIntercept", jdouble, ())
end

function get_intercept_std_err(obj::SimpleRegression)
    return jcall(obj, "getInterceptStdErr", jdouble, ())
end

function get_mean_square_error(obj::SimpleRegression)
    return jcall(obj, "getMeanSquareError", jdouble, ())
end

function get_n(obj::SimpleRegression)
    return jcall(obj, "getN", jlong, ())
end

function get_r(obj::SimpleRegression)
    return jcall(obj, "getR", jdouble, ())
end

function get_r_square(obj::SimpleRegression)
    return jcall(obj, "getRSquare", jdouble, ())
end

function get_regression_sum_squares(obj::SimpleRegression)
    return jcall(obj, "getRegressionSumSquares", jdouble, ())
end

function get_significance(obj::SimpleRegression)
    return jcall(obj, "getSignificance", jdouble, ())
end

function get_slope(obj::SimpleRegression)
    return jcall(obj, "getSlope", jdouble, ())
end

function get_slope_confidence_interval(obj::SimpleRegression)
    return jcall(obj, "getSlopeConfidenceInterval", jdouble, ())
end

function get_slope_confidence_interval(obj::SimpleRegression, arg0::jdouble)
    return jcall(obj, "getSlopeConfidenceInterval", jdouble, (jdouble,), arg0)
end

function get_slope_std_err(obj::SimpleRegression)
    return jcall(obj, "getSlopeStdErr", jdouble, ())
end

function get_sum_of_cross_products(obj::SimpleRegression)
    return jcall(obj, "getSumOfCrossProducts", jdouble, ())
end

function get_sum_squared_errors(obj::SimpleRegression)
    return jcall(obj, "getSumSquaredErrors", jdouble, ())
end

function get_total_sum_squares(obj::SimpleRegression)
    return jcall(obj, "getTotalSumSquares", jdouble, ())
end

function get_x_sum_squares(obj::SimpleRegression)
    return jcall(obj, "getXSumSquares", jdouble, ())
end

function has_intercept(obj::SimpleRegression)
    return jcall(obj, "hasIntercept", jboolean, ())
end

function predict(obj::SimpleRegression, arg0::jdouble)
    return jcall(obj, "predict", jdouble, (jdouble,), arg0)
end

function regress(obj::SimpleRegression)
    return jcall(obj, "regress", RegressionResults, ())
end

function regress(obj::SimpleRegression, arg0::Vector{jint})
    return jcall(obj, "regress", RegressionResults, (Vector{jint},), arg0)
end

function remove_data(obj::SimpleRegression, arg0::Vector{Vector{jdouble}})
    return jcall(obj, "removeData", void, (Vector{Vector{jdouble}},), arg0)
end

function remove_data(obj::SimpleRegression, arg0::jdouble, arg1::jdouble)
    return jcall(obj, "removeData", void, (jdouble, jdouble), arg0, arg1)
end


text:
__precompile__(true)
module SOFA

if isfile(joinpath(dirname(@__FILE__),"..","deps","deps.jl"))
    include("../deps/deps.jl")
else
    error("libsofa_c not properly installed. Please run Pkg.build(\"SOFA\")")
end

# Use static arrays
using StaticArrays

####################
# Header Constants #
####################

const WGS84 = 1
const GRS80 = 2
const WGS72 = 3

#########################
# Additional Structures #
#########################

export iauASTROM
"""
Star-independent astrometry parameters

Note:
    - Vectors eb, eh, em and v are all with respect to BCRS axes.
"""
mutable struct iauASTROM
    pmt::Float64                        # PM time interval (SSB, Julian years)
    eb::NTuple{3, Float64}            # SSB to observer (vector, au)
    eh::NTuple{3, Float64}            # Sun to observer (unit vector)
    em::Float64                         # distance from Sun to observer (au)
    v::NTuple{3, Float64}             # barycentric observer velocity (vector, c)
    bm1::Float64                        # sqrt(1-|v|^2): reciprocal of Lorenz factor
    bpn::NTuple{3, NTuple{3, Float64}}  # bias-precession-nutation matrix
    along::Float64                      # longitude + s' + dERA(DUT) (radians)
    phi::Float64                        # geodetic latitude (radians)
    xpl::Float64                        # polar motion xp wrt local meridian (radians)
    ypl::Float64                        # polar motion yp wrt local meridian (radians)
    sphi::Float64                       # sine of geodetic latitude
    cphi::Float64                       # cosine of geodetic latitude
    diurab::Float64                     # magnitude of diurnal aberration vector
    eral::Float64                       # "local" Earth rotation angle (radians)
    refa::Float64                       # refraction constant A (radians)
    refb::Float64                       # refraction constant B (radians)

    function iauASTROM(;pmt::Real=0.0,
               em::Real=0.0,
               bm1::Real=0.0,
               along::Real=0.0,
               phi::Real=0.0,
               xpl::Real=0.0,
               ypl::Real=0.0,
               sphi::Real=0.0,
               cphi::Real=0.0,
               diurab::Real=0.0,
               eral::Real=0.0,
               refa::Real=0.0,
               refb::Real=0.0)

        new(convert(Float64, pmt),
            (0.0, 0.0, 0.0),
            (0.0, 0.0, 0.0),
            convert(Float64, em),
            (0.0, 0.0, 0.0),
            convert(Float64, bm1),
            ((0.0, 0.0, 0.0),(0.0, 0.0, 0.0),(0.0, 0.0, 0.0)),
            convert(Float64, along),
            convert(Float64, phi),
            convert(Float64, xpl),
            convert(Float64, ypl),
            convert(Float64, sphi),
            convert(Float64, cphi),
            convert(Float64, diurab),
            convert(Float64, eral),
            convert(Float64, refa),
            convert(Float64, refb),
            )
    end
end

export iauLDBODY
"""
Body parameters for light deflection
"""
mutable struct iauLDBODY
    bm::Float64            # mass of the body (solar masses)
    dl::Float64            # deflection limiter (radians^2/2)
    pv::Array{Float64, 2}  # barycentric PV of the body (au, au/day)

    function iauLDBODY(;bm::Real=0.0, dl::Real=0.0,
                        pv=[0.0 0.0 0.0; 0.0 0.0 0.0])

        if size(pv) != (2, 3)
            error("Invalid size for rnpb. Must be a (2, 3).")
        end

        new(convert(Float64, bm), convert(Float64, dl), convert(Array{Float64, 2}, pv))
    end
end

####################
# Include Wrappers #
####################

include("a2af.jl")
include("a2tf.jl")
include("ab.jl")
include("ae2hd.jl")
include("af2a.jl")
include("anp.jl")
include("anpm.jl")
include("apcg.jl")
include("apcg13.jl")
include("apci.jl")
include("apci13.jl")
include("apco.jl")
include("apco13.jl")
include("apcs.jl")
include("apcs13.jl")
include("aper.jl")
include("aper13.jl")
include("apio.jl")
include("apio13.jl")
include("atci13.jl")
include("atciq.jl")
include("atciqn.jl")
include("atciqz.jl")
include("atco13.jl")
include("atic13.jl")
include("aticq.jl")
include("aticqn.jl")
include("atio13.jl")
include("atioq.jl")
include("atoc13.jl")
include("atoi13.jl")
include("atoiq.jl")
include("bi00.jl")
include("bp00.jl")
include("bp06.jl")
include("bpn2xy.jl")
include("c2i00a.jl")
include("c2i00b.jl")
include("c2i06a.jl")
include("c2ibpn.jl")
include("c2ixy.jl")
include("c2ixys.jl")
include("c2s.jl")
include("c2t00a.jl")
include("c2t00b.jl")
include("c2t06a.jl")
include("c2tcio.jl")
include("c2teqx.jl")
include("c2tpe.jl")
include("c2txy.jl")
include("cal2jd.jl")
include("cp.jl")
include("cpv.jl")
include("cr.jl")
include("d2dtf.jl")
include("d2tf.jl")
include("dat.jl")
include("dtdb.jl")
include("dtf2d.jl")
include("eceq06.jl")
include("ecm06.jl")
include("ee00.jl")
include("ee00a.jl")
include("ee00b.jl")
include("ee06a.jl")
include("eect00.jl")
include("eform.jl")
include("eo06a.jl")
include("eors.jl")
include("epb.jl")
include("epb2jd.jl")
include("epj.jl")
include("epj2jd.jl")
include("epv00.jl")
include("eqec06.jl")
include("eqeq94.jl")
include("era00.jl")
include("fad03.jl")
include("fae03.jl")
include("faf03.jl")
include("faju03.jl")
include("fal03.jl")
include("falp03.jl")
include("fama03.jl")
include("fame03.jl")
include("fane03.jl")
include("faom03.jl")
include("fapa03.jl")
include("fasa03.jl")
include("faur03.jl")
include("fave03.jl")
include("fk45z.jl")
include("fk52h.jl")
include("fk5hip.jl")
include("fk5hz.jl")
include("fk54z.jl")
include("fk425.jl")
include("fk524.jl")
include("fw2m.jl")
include("fw2xy.jl")
include("g2icrs.jl")
include("gc2gd.jl")
include("gc2gde.jl")
include("gd2gc.jl")
include("gd2gce.jl")
include("gmst00.jl")
include("gmst06.jl")
include("gmst82.jl")
include("gst00a.jl")
include("gst00b.jl")
include("gst06.jl")
include("gst06a.jl")
include("gst94.jl")
include("h2fk5.jl")
include("hd2ae.jl")
include("hd2pa.jl")
include("hfk5z.jl")
include("icrs2g.jl")
include("ir.jl")
include("jd2cal.jl")
include("jdcalf.jl")
include("ld.jl")
include("ldn.jl")
include("ldsun.jl")
include("lteceq.jl")
include("ltecm.jl")
include("lteqec.jl")
include("ltp.jl")
include("ltpb.jl")
include("ltpecl.jl")
include("ltpequ.jl")
include("num00a.jl")
include("num00b.jl")
include("num06a.jl")
include("numat.jl")
include("nut00a.jl")
include("nut00b.jl")
include("nut06a.jl")
include("nut80.jl")
include("nutm80.jl")
include("obl06.jl")
include("obl80.jl")
include("p06e.jl")
include("p2pv.jl")
include("p2s.jl")
include("pap.jl")
include("pas.jl")
include("pb06.jl")
include("pdp.jl")
include("pfw06.jl")
include("plan94.jl")
include("pmat00.jl")
include("pmat06.jl")
include("pmat76.jl")
include("pm.jl")
include("pmp.jl")
include("pmpx.jl")
include("pmsafe.jl")
include("pn.jl")
include("pn00.jl")
include("pn00a.jl")
include("pn00b.jl")
include("pn06a.jl")
include("pn06.jl")
include("pnm00a.jl")
include("pnm00b.jl")
include("pnm06a.jl")
include("pnm80.jl")
include("pom00.jl")
include("ppp.jl")
include("ppsp.jl")
include("pr00.jl")
include("prec76.jl")
include("pv2p.jl")
include("pv2s.jl")
include("pvdpv.jl")
include("pvm.jl")
include("pvmpv.jl")
include("pvppv.jl")
include("pvstar.jl")
include("pvtob.jl")
include("pvu.jl")
include("pvup.jl")
include("pvxpv.jl")
include("pxp.jl")
include("refco.jl")
include("rm2v.jl")
include("rv2m.jl")
include("rx.jl")
include("rxp.jl")
include("rxpv.jl")
include("rxr.jl")
include("ry.jl")
include("rz.jl")
include("s00a.jl")
include("s00b.jl")
include("s00.jl")
include("s06a.jl")
include("s06.jl")
include("s2c.jl")
include("s2p.jl")
include("s2pv.jl")
include("s2xpv.jl")
include("sepp.jl")
include("seps.jl")
include("sp00.jl")
include("starpm.jl")
include("starpv.jl")
include("sxp.jl")
include("sxpv.jl")
include("taitt.jl")
include("taiut1.jl")
include("taiutc.jl")
include("tcbtdb.jl")
include("tcgtt.jl")
include("tdbtcb.jl")
include("tdbtt.jl")
include("tf2a.jl")
include("tf2d.jl")
include("tpors.jl")
include("tporv.jl")
include("tpsts.jl")
include("tpstv.jl")
include("tpxes.jl")
include("tpxev.jl")
include("tr.jl")
include("trxp.jl")
include("trxpv.jl")
include("tttai.jl")
include("tttcg.jl")
include("tttdb.jl")
include("ttut1.jl")
include("ut1tai.jl")
include("ut1tt.jl")
include("ut1utc.jl")
include("utctai.jl")
include("utcut1.jl")
include("xy06.jl")
include("xys00a.jl")
include("xys00b.jl")
include("xys06a.jl")
include("zp.jl")
include("zpv.jl")
include("zr.jl")

end # module SOFA


text:
InputFolder = './Images/CrazyCells/';
OutputFolder = './Results/Images/CrazyCells/';
Lbl = 1;

@iA = '*_C00*.tif';

@fxg_sBlobDetPatch [iA] > [S];
params.GaussianGradRad = 1.5;
params.GaussianVoteRad = 7;
params.GradMagThr = 0.2;
params.Rmin = 10;
params.Rmax = 20;
params.NAngles = 36;
params.Delta = [pi/4 pi/8];
params.DScale = [1];
params.Thr = 0.225;
/endf

@fxgs_lSeededPolarGeod [iA, S] > [L];
params.ThDiv = 180;
params.ObjRad = 30;
params.MinArea = 175;
params.Method = 'simple'; %rk4 %euler
/endf

/show iA > S;
/show iA > L;
/keep L > tif;

max_stars_repo_name: SebastienTs/LOBSTER

max_issues_repo_name: SebastienTs/LOBSTER

max_forks_repo_name: SebastienTs/LOBSTER


text:
# N.B. This file is maintained in TensorFlowBuilder source
module API
import Base: source_path
apipath = joinpath(dirname(source_path()), "..", "src","API")
for fname in sort(filter(fn -> ismatch(r"^T.*\.jl$",fn), readdir(apipath)))
  include(joinpath("API", fname))
  modname = symbol(splitext(fname)[1])
  @eval using .$modname
end

end


text:
module LocalProjections

using BSplines: BSplineBasis, basismatrix
using FFTW: fft!
using LinearAlgebra: I, cholesky!, svd!, ldiv!, inv!, mul!
using StatsBase: CovarianceEstimator, RegressionModel, StatisticalModel, CoefTable, TestStat
using StatsFuns: normccdf, norminvccdf, tdistccdf, tdistinvccdf
using Tables

import Base: ==, show, size, length, vec
import StatsBase: coef, vcov, stderror, confint, coeftable, modelmatrix, residuals
import Tables: getcolumn

# Reexport objects from StatsBase
export coef, vcov, stderror, confint, coeftable, modelmatrix, residuals

export hamilton_filter,
       TransformedVar,
       Cum,
       datafile,

       OLS,
       AbstractEstimator,
       LeastSquaresLP,
       AbstractEstimatorResult,
       LeastSquaresLPResult,
       LocalProjectionResult,
       lp,

       Ridge,
       SearchCriterion,
       LOOCV,
       GCV,
       AIC,
       SmoothAlgorithm,
       DemmlerReinsch,
       DirectSolve,
       ModelSelection,
       GridSearch,
       grid,
       ModelSelectionResult,
       GridSearchResult,
       SmoothLP,
       SmoothLPResult,

       SimpleVCE,
       HRVCE,
       LongRunVariance,
       HARVCE,
       EqualWeightedCosine,
       EWC,
       criticalvalue,
       pvalue,

       ImpulseResponse,
       irf

include("utils.jl")
include("lp.jl")
include("slp.jl")
include("vce.jl")
include("irf.jl")

end # module


text:
module BLS12381FieldTest

using Test

using TowerFields.BLS12381Field

const A2 = (BLS12381Field.Q - 1), (BLS12381Field.Q - 2)
const B2 = (BLS12381Field.Q - 2), (BLS12381Field.Q - 3)
const C2 = (BLS12381Field.Q - 3), (BLS12381Field.Q - 4)

const A6 = (A2, B2, C2)
const B6 = (B2, C2, A2)
const C6 = (C2, A2, B2)
const D6 = (C2, B2, A2)

const A12 = (A6, C6)
const B12 = (B6, D6)

@testset "add: FQ12" begin
    let + = BLS12381Field.:+
        @test A12 + B12 == (((4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559784, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559782), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559782, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559780), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559783, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559781)), ((4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559781, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559779), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559784, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559782), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559784, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559782)))
    end
end

@testset "sub: FQ12" begin
    let - = BLS12381Field.:-
        @test A12 - B12 == (((1, 1), (1, 1), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559785, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559785)), ((0, 0), (1, 1), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786))) == (((1, 1), (1, 1), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559785, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559785)), ((0, 0), (1, 1), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786)))
    end
end

@testset "mul: FQ12" begin
    let * = BLS12381Field.:*
        @test A12 * B12 == (((4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559692, 46), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559731, 59), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559750, 68)), ((4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559712, 53), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559740, 63), (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559757, 72)))
    end
end

@testset "pow: FQ12" begin
    let ^ = BLS12381Field.:^,  * = BLS12381Field.:*
        @test A12 ^ 3 == (A12 * A12) * A12
    end
end

end


text:
module Gilbert

using Distributions
import Params
using Util

export GilbertChannel, iterate!, interfere!, berawgn, capacity, transmission_successes

type GilbertChannel
    # channel frequency, in Hz
    freq :: Float64
    # channel bandwidth, used here for increasing data locality hopefully
    bandwidth :: Float64
    noise :: Float64 # noise, in watt
    n0 :: Float64 # noise density, in dBm
    state :: Int # current state
    interference :: Float64 # current interference in the channel
    # noises, in dBmW
    noises :: Array{Float64, 1}
    A :: Array{Float64, 2} # transition probabilities

    function GilbertChannel(freq, noises, A)
        c = new()
        c.freq = freq
        c.noises = vec(noises)
        c.state = int(rand() <= 0.5) + 1
        c.bandwidth = Params.chan_bw
        c.n0 = c.noises[c.state]
        c.noise = toWatt(c.n0) * c.bandwidth
        c.interference = 0
        c.A = A
        c
    end

end

const states = eye(size(Params.noise, 1))

function interfere!(c :: GilbertChannel, power, pos)
    d = sqrt(pos.x ^ 2 + pos.y ^ 2)
    power *= (3e8 / (4 * pi * d * c.freq)) .^ 2
    c.interference += power
    nothing
end

function iterate!(c :: GilbertChannel)
    c.state = rand(Categorical(c.A[:, c.state]))
    c.n0 = c.noises[c.state]
    c.noise = toWatt(c.n0) * c.bandwidth
    c.interference = 0
    nothing
end

function berawgn(c :: GilbertChannel, E_b)
    0.5 * erfc(sqrt(E_b / ((c.noise + c.interference) / c.bandwidth)))
end

function capacity(c :: GilbertChannel, power, pos)
    # Do not use Shannon capacity, since we're using QPSK with a fixed bandwidth
    # and it's suboptimal
    # d = sqrt(pos.x ^ 2 + pos.y ^ 2)
    # power *= (3e8 / (4 * pi * d * c.freq)) .^ 2
    # c.bandwidth * log2(1 + power / c.noise)
    # Assuming we're using a fixed bitrate
    Params.bitrate
end

function success_prob(c :: GilbertChannel, E_b)
    n = Params.pkt_size
    k = Params.pkt_redundancy
    p = berawgn(c, E_b)
    # use binomial sum to calculate successful transmission probability
    log_prob = logsumexp((k+1) .* [log1p(-p), log(p)]) - log1p(-2p) + (n-k) * log1p(-p)
    exp(log_prob)
end

function transmission_successes(c :: GilbertChannel, power, bitrate, x, y, indoor=false)
    d = sqrt(x ^ 2 + y ^ 2)
    # use Hata model for outdoor loss
    loss = 32.4 + 20 * (log10(c.freq / 1e9) + log10(d))
    if indoor
        # use COST-231 path loss eqn for indoor to get received power
        l_e = 7
        l_ge = 6 # approx. for all incidence angles
        Γ1 = Params.Indoor.walls * 7
        Γ2 = 0.6 * Params.Indoor.d_indoor * 0.55 # integrate for all incidence angles
        l_indoor = l_e + l_ge + max(Γ1, Γ2)
        loss += l_indoor
    end
    P_r = 10 ^ (log10(power) - (loss / 10))
    # compute energy per bit
    E_b = P_r / bitrate
    # compute per-packet success rate
    success_rate = success_prob(c, E_b)
    #rand(Binomial(n_pkt, success_rate))
    # we're generating single packets now
    rand(Bernoulli(success_rate))
end

end


text:
# Test parameter function methods
@testset "Parameter Function Methods" begin
    # setup the needed info
    m = InfiniteModel()
    @infinite_parameter(m, t in [0, 1])
    @infinite_parameter(m, x[1:2] in [-1, 1])
    func = ParameterFunction(sin, IC.VectorTuple(t), [1], [1])
    object = ParameterFunctionData(func, "test")
    idx = ParameterFunctionIndex(1)
    fref = ParameterFunctionRef(m, idx)
    gvref = GeneralVariableRef(m, 1, ParameterFunctionIndex)
    bad_vref = ParameterFunctionRef(m, ParameterFunctionIndex(-1))
    # JuMP.owner_model
    @testset "JuMP.owner_model" begin
        @test owner_model(fref) === m
        @test owner_model(gvref) === m
    end
    # JuMP.index
    @testset "JuMP.index" begin
        @test index(fref) == idx
        @test index(gvref) == idx
    end
    # dispatch_variable_ref
    @testset "dispatch_variable_ref" begin
        @test isequal(dispatch_variable_ref(m, idx), fref)
        @test isequal(dispatch_variable_ref(gvref), fref)
    end
    # _add_data_object
    @testset "_add_data_object" begin
        @test InfiniteOpt._add_data_object(m, object) == idx
    end
    # _data_dictionary
    @testset "_data_dictionary" begin
        @test InfiniteOpt._data_dictionary(fref) === m.param_functions
        @test InfiniteOpt._data_dictionary(gvref) === m.param_functions
    end
    # JuMP.is_valid
    @testset "JuMP.is_valid" begin
        @test is_valid(m, fref)
        @test is_valid(m, gvref)
    end
    # _data_object
    @testset "_data_object" begin
        @test InfiniteOpt._data_object(fref) === object
        @test InfiniteOpt._data_object(gvref) === object
        @test_throws ErrorException InfiniteOpt._data_object(bad_vref)
    end
    # _core_variable_object
    @testset "_core_variable_object" begin
        @test InfiniteOpt._core_variable_object(fref) === func
        @test InfiniteOpt._core_variable_object(gvref) === func
    end
    # _object_numbers
    @testset "_object_numbers" begin
        @test InfiniteOpt._object_numbers(fref) == [1]
    end
    # _parameter_numbers
    @testset "_parameter_numbers" begin
        @test InfiniteOpt._parameter_numbers(fref) == [1]
    end
    # JuMP.name
    @testset "JuMP.name" begin
        @test name(fref) == "test"
        @test name(gvref) == "test"
        @test name(bad_vref) == ""
    end
    # JuMP.set_name
    @testset "JuMP.set_name" begin
        @test isa(set_name(fref, "new"), Nothing)
        @test name(fref) == "new"
        @test isa(set_name(gvref, "new2"), Nothing)
        @test name(fref) == "new2"
        @test_throws ErrorException set_name(bad_vref, "")
    end
    # _measure_dependencies
    @testset "_measure_dependencies" begin
        @test InfiniteOpt._measure_dependencies(fref) == MeasureIndex[]
        @test InfiniteOpt._measure_dependencies(gvref) == MeasureIndex[]
    end
    # _constraint_dependencies
    @testset "_constraint_dependencies" begin
        @test InfiniteOpt._constraint_dependencies(fref) == InfOptConstraintIndex[]
        @test InfiniteOpt._constraint_dependencies(gvref) == InfOptConstraintIndex[]
    end
    # _semi_infinite_variable_dependencies
    @testset "_semi_infinite_variable_dependencies" begin
        @test InfiniteOpt._semi_infinite_variable_dependencies(fref) == SemiInfiniteVariableIndex[]
        @test InfiniteOpt._semi_infinite_variable_dependencies(gvref) == SemiInfiniteVariableIndex[]
    end
    # _derivative_dependencies
    @testset "_derivative_dependencies" begin
        @test InfiniteOpt._derivative_dependencies(fref) == DerivativeIndex[]
        @test InfiniteOpt._derivative_dependencies(gvref) == DerivativeIndex[]
    end
    # raw_parameter_refs
    @testset "raw_parameter_refs" begin
        @test isequal(raw_parameter_refs(fref), IC.VectorTuple(t))
        @test isequal(raw_parameter_refs(gvref), IC.VectorTuple(t))
    end
    # parameter_refs
    @testset "parameter_refs" begin
        @test isequal(parameter_refs(fref), (t, ))
        @test isequal(parameter_refs(gvref), (t, ))
    end
    # parameter_list
    @testset "parameter_list" begin
        @test isequal(parameter_list(fref), [t])
        @test isequal(parameter_list(gvref), [t])
    end
    # raw_function
    @testset "raw_function" begin
        @test raw_function(fref) == sin
        @test raw_function(gvref) == sin
    end
    # call_function
    @testset "call_function" begin
        @test call_function(fref, 0) == 0
        @test call_function(gvref, 0) == 0
    end
    # test used_by_semi_infinite_variable
    @testset "used_by_semi_infinite_variable" begin
        @test !used_by_semi_infinite_variable(fref)
        push!(InfiniteOpt._semi_infinite_variable_dependencies(fref),
              SemiInfiniteVariableIndex(1))
        @test used_by_semi_infinite_variable(fref)
        empty!(InfiniteOpt._semi_infinite_variable_dependencies(fref))
    end
    # test used_by_derivative
    @testset "used_by_derivative" begin
        @test !used_by_derivative(fref)
        push!(InfiniteOpt._derivative_dependencies(fref), DerivativeIndex(1))
        @test used_by_derivative(fref)
        empty!(InfiniteOpt._derivative_dependencies(fref))
    end
    # test used_by_measure
    @testset "used_by_measure" begin
        @test !used_by_measure(fref)
        push!(InfiniteOpt._measure_dependencies(fref), MeasureIndex(1))
        @test used_by_measure(fref)
        empty!(InfiniteOpt._measure_dependencies(fref))
    end
    # test used_by_constraint
    @testset "used_by_constraint" begin
        @test !used_by_constraint(fref)
        push!(InfiniteOpt._constraint_dependencies(fref), InfOptConstraintIndex(1))
        @test used_by_constraint(fref)
        empty!(InfiniteOpt._constraint_dependencies(fref))
    end
    # test is_used
    @testset "is_used" begin
        @test !is_used(fref)
        push!(InfiniteOpt._constraint_dependencies(fref), InfOptConstraintIndex(1))
        @test is_used(fref)
        empty!(InfiniteOpt._constraint_dependencies(fref))
    end
    # test _update_param_var_mapping
    @testset "_update_param_var_mapping" begin
        @test InfiniteOpt._update_param_var_mapping(fref, IC.VectorTuple(t)) isa Nothing
        @test used_by_parameter_function(t)
        empty!(InfiniteOpt._parameter_function_dependencies(t))
    end
    # test _delete_data_object
    @testset "_delete_data_object" begin
        @test InfiniteOpt._delete_data_object(fref) isa Nothing
        @test length(InfiniteOpt._data_dictionary(fref)) == 0
        @test !is_valid(m, fref)
    end
    # test build_parameter_function
    @testset "build_parameter_function" begin
        f3(ts, xs, a...; b...) = 42
        # test errors
        @test_throws ErrorException build_parameter_function(error, sin, t, bob = 1)
        @test_throws ErrorException build_parameter_function(error, sin, x[1])
        @test_throws ErrorException build_parameter_function(error, sin, (t, x))
        @test_throws ErrorException build_parameter_function(error, sin, 2)
        # test normal
        @test build_parameter_function(error, (a, b) -> 2, (t, x)) isa ParameterFunction
        @test build_parameter_function(error, f3, (t, x)) isa ParameterFunction
        @test build_parameter_function(error, (ts, xs) -> f3(ts, xs, 1), (t, x)) isa ParameterFunction
        @test build_parameter_function(error, (ts, xs) -> f3(ts, xs, d = 1), (t, x)) isa ParameterFunction
        @test build_parameter_function(error, sin, t) isa ParameterFunction
    end
    # test add_parameter_function
    @testset "add_parameter_function" begin
        # test does not belong
        @infinite_parameter(InfiniteModel(), t2 in [0, 1])
        func = build_parameter_function(error, (a, b) -> 2, (t2, x))
        @test_throws VariableNotOwned{GeneralVariableRef} add_parameter_function(m, func)
        # test normal
        func = build_parameter_function(error, (a, b) -> 2, (t, x))
        fref = GeneralVariableRef(m, 2, ParameterFunctionIndex)
        @test isequal(add_parameter_function(m, func, "test"), fref)
        @test name(fref) == "test"
        @test isequal(parameter_refs(fref), (t, x))
        @test used_by_parameter_function(t)
        # test default name
        func = build_parameter_function(error, cos, t)
        fref = GeneralVariableRef(m, 3, ParameterFunctionIndex)
        @test isequal(add_parameter_function(m, func), fref)
        @test name(fref) == "cos"
    end
    # test parameter_function
    @testset "parameter_function" begin
        f4(ts, xs, a...; b...) = 42
        # test normal
        @test parameter_function(sin, t) isa GeneralVariableRef
        @test parameter_function(sin, t, name = "name") isa GeneralVariableRef
        @test parameter_function((ts, xs) -> f4(ts, xs, 1, d = 1), (t, x)) isa GeneralVariableRef
        # test errors
        @test_throws ErrorException parameter_function(sin, (t, x))
    end
    # test making other objects
    @testset "Other Objects" begin
        f = parameter_function((a,b) -> 2, (t, x))
        # test making semi_infinite variable
        d = Dict{Int, Float64}(1 => 0)
        @test add_variable(m, build_variable(error, f, d)) isa GeneralVariableRef
        # test making derivative
        @test deriv(f, t) isa GeneralVariableRef
    end
end

# Test the parameter function methods for macro definition
@testset "Parameter Function Macro" begin
    # setup
    m = InfiniteModel()
    @infinite_parameter(m, t in [0, 1])
    @infinite_parameter(m, x[1:2] in [0, 1], independent = true)
    f5(t, x, a...; b...) = 42
    # test _expr_replace!
    @testset "_expr_replace!" begin
        @test InfiniteOpt._expr_replace!(:(t -> f(t, x)), :t, :y) == :(y -> f(y, x))
        @test InfiniteOpt._expr_replace!(:((t, x[1]) -> f(t, x[1])), :(x[1]), :y) == :((t, y) -> f(t, y))
        @test InfiniteOpt._expr_replace!(:t, :t, :y) == :y
        @test InfiniteOpt._expr_replace!(:t, :f, :y) == :t
    end
    # test _extract_parameters
    @testset "_extract_parameters" begin
        @test InfiniteOpt._extract_parameters(:y) == esc(:y)
        @test InfiniteOpt._extract_parameters(:(x[1])) == esc(:(x[1]))
        ex = :((t, x[1]))
        @test InfiniteOpt._extract_parameters(ex).args[1] == ex
        @test InfiniteOpt._extract_parameters(ex).args[1] !== ex
    end
    # test _process_func_expr
    @testset "_process_func_expr" begin
        # test normal
        @test InfiniteOpt._process_func_expr(error, :(f(t, x))) == (esc(:f), esc(:(t, x)), false)
        anon = :((t, x) -> f(t, x, 1, d = 1))
        @test InfiniteOpt._process_func_expr(error, anon) == (esc(anon), esc(:(t,x)), true)
        anon = :((t, x[1]) -> sin(t + x[1]))
        @test eval(InfiniteOpt._process_func_expr(error, anon)[1].args[1])(0.5, 0.2) == sin(0.5 + 0.2)
        anon = :(t[i] -> t[i] + 3)
        @test eval(InfiniteOpt._process_func_expr(error, anon)[1].args[1])(2) == 5
        # test errors
        @test_throws ErrorException InfiniteOpt._process_func_expr(error, :(f(t, d = 2)))
        @test_throws ErrorException InfiniteOpt._process_func_expr(error, :(f(x, t; d = 2)))
        @test_throws ErrorException InfiniteOpt._process_func_expr(error, :(f >= 2))
        @test_throws ErrorException InfiniteOpt._process_func_expr(error, :(f[t, x]))
    end
    # test @parameter_function
    @testset "@parameter_function" begin
        # test errors
        @test_macro_throws ErrorException @parameter_function(m)
        @test_macro_throws ErrorException @parameter_function(m, func = f5)
        @test_macro_throws ErrorException @parameter_function(m, y == sin(t), Int)
        @test_macro_throws ErrorException @parameter_function(m, [1:2])
        @test_macro_throws ErrorException @parameter_function(m, "a$(1)" == f5(t, x))
        @test_macro_throws ErrorException @parameter_function(m, a[m = 1:2] == f5(t, x))
        @test_macro_throws ErrorException @parameter_function(Model(), sin(t))
        @test_macro_throws ErrorException @parameter_function(m, [a...] == sin(t))
        # test anonymous singular
        idx = 1
        ref = GeneralVariableRef(m, idx, ParameterFunctionIndex)
        @test isequal(@parameter_function(m, f5(t, x), base_name = "a"), ref)
        @test name(ref) == "a"
        @test raw_function(ref) == f5
        @test isequal(parameter_refs(ref), (t, x))
        idx += 1
        ref = GeneralVariableRef(m, idx, ParameterFunctionIndex)
        @test isequal(@parameter_function(m, f5(t, x)), ref)
        @test name(ref) == "f5"
        @test raw_function(ref) == f5
        @test isequal(parameter_refs(ref), (t, x))
        idx += 1
        # test anonymous single argument multi-dim
        refs = [GeneralVariableRef(m, idx + i, ParameterFunctionIndex) for i in 0:1]
        @test isequal(@parameter_function(m, [1:2] == f5(t, x)), refs)
        @test isequal(parameter_refs(refs[1]), (t, x))
        @test raw_function(refs[2]) == f5
        @test name.(refs) == ["f5", "f5"]
        idx += 2
        refs = [GeneralVariableRef(m, idx + i, ParameterFunctionIndex) for i in 0:1]
        @test @parameter_function(m, [i = 1:2; i >= 1] == (sin, cos)[i](t)) isa JuMPC.SparseAxisArray
        @test isequal(parameter_refs(refs[1]), (t,))
        @test raw_function(refs[2]) == cos
        @test raw_function(refs[1]) == sin
        @test name(refs[1]) == "sin"
        @test name(refs[2]) == "cos"
        idx += 2
        # test explicit single
        ref = GeneralVariableRef(m, idx, ParameterFunctionIndex)
        @test isequal(@parameter_function(m, a == f5(t, x), base_name = "bob"), ref)
        @test name(ref) == "bob"
        @test raw_function(ref) == f5
        @test isequal(parameter_refs(ref), (t, x))
        idx += 1
        ref = GeneralVariableRef(m, idx, ParameterFunctionIndex)
        @test isequal(@parameter_function(m, c == (t, x) -> f5(t, x, 2, d = 1)), ref)
        @test name(ref) == "c"
        @test raw_function(ref) != f5
        @test raw_function(ref)(1, [1, 1]) == 42
        @test isequal(parameter_refs(ref), (t, x))
        idx += 1
        # test explicit multi-dim
        refs = [GeneralVariableRef(m, idx + i, ParameterFunctionIndex) for i in 0:1]
        @test isequal(@parameter_function(m, d[1:2] == f5(t, x)), refs)
        @test isequal(parameter_refs(refs[1]), (t, x))
        @test raw_function(refs[2]) == f5
        @test name.(refs) == ["d[1]", "d[2]"]
        idx += 2
        refs = [GeneralVariableRef(m, idx + i, ParameterFunctionIndex) for i in 0:1]
        @test isequal(@parameter_function(m, e[1:2] == (t, x) -> f5(t, x, 2; s = 1)), refs)
        @test isequal(parameter_refs(refs[1]), (t, x))
        @test raw_function(refs[2]) != f5
        @test name.(refs) == ["e[1]", "e[2]"]
        idx += 2
        # test infinite parameter with reference
        refs = [GeneralVariableRef(m, idx + i, ParameterFunctionIndex) for i in 0:1]
        @test isequal(@parameter_function(m, [i = 1:2] == (t, x[i]) -> sin(t + x[i])), refs)
        @test isequal(parameter_refs.(refs), [(t, x[1]), (t, x[2])])
        @test call_function.(refs, 0.5, 0.2) == [sin(0.5 + 0.2), sin(0.5 + 0.2)]
        @test name.(refs) == ["", ""]
        idx += 2
    end
end

# Test the basic extensions
@testset "Base Extensions" begin
    # setup model
    m = InfiniteModel()
    @variable(m, z)
    @variable(m, y)
    aff = 2z + 42
    quad = z^2 + 2z
    nlp = sin(z)
    # test convert
    @testset "Base.convert (NLPExpr)" begin
        @test isequal(convert(NLPExpr, 1), one(NLPExpr))
        @test isequal(convert(NLPExpr, z), NLPExpr(Node(NodeData(z))))
        @test isequal(convert(NLPExpr, aff), NLPExpr(Node(NodeData(aff))))
        @test isequal(convert(NLPExpr, quad), NLPExpr(Node(NodeData(quad))))
        @test convert(NLPExpr, nlp) === nlp
    end
    # test isequal for UnorderedPair
    @testset "Base.isequal (JuMP.UnorderedPair)" begin
        @test isequal(UnorderedPair(z, z), UnorderedPair(z, z))
        @test isequal(UnorderedPair(z, y), UnorderedPair(y, z))
        @test !isequal(UnorderedPair(z, y), UnorderedPair(z, z))
    end
    # test isequal for expressions
    @testset "Base.isequal (Expr Fallbacks)" begin
        @test !isequal(z, 2)
        @test !isequal(2, z)
        @test !isequal(z, aff)
        @test !isequal(z, quad)
        @test !isequal(nlp, aff)
    end
end

# Test _interrogate_variables
@testset "_interrogate_variables" begin
    # setup model
    m = InfiniteModel()
    @variable(m, z)
    @variable(m, y)
    aff = 2z + 42
    quad = z^2 + 2z
    nlp = sin(z) + aff
    # test constant
    @testset "Constant" begin
        @test InfiniteOpt._interrogate_variables(i -> error, 42) isa Nothing
    end
    # test variable
    @testset "Variable" begin
        a = [0]
        @test InfiniteOpt._interrogate_variables(i -> a[1] += 1, z) isa Nothing
        @test a[1] == 1
    end
    # test AffExpr
    @testset "AffExpr" begin
        a = []
        @test InfiniteOpt._interrogate_variables(i -> push!(a, i), aff) isa Nothing
        @test isequal(a, [z])
    end
    # test QuadExpr
    @testset "QuadExpr" begin
        a = []
        @test InfiniteOpt._interrogate_variables(i -> push!(a, i), quad) isa Nothing
        @test isequal(a, [z, z, z])
    end
    # test NLPExpr
    @testset "NLPExpr" begin
        a = []
        @test InfiniteOpt._interrogate_variables(i -> push!(a, i), nlp) isa Nothing
        @test isequal(a, [z, z])
    end
    # test array of expressions
    @testset "AbstractArray" begin
        a = []
        @test InfiniteOpt._interrogate_variables(i -> push!(a, i), [nlp, aff]) isa Nothing
        @test isequal(a, [z, z, z])
    end
end

# Test _all_function_variables
@testset "_all_function_variables" begin
    # initialize model and references
    m = InfiniteModel()
    @infinite_parameter(m, par in [0, 1])
    @variable(m, inf, Infinite(par))
    @variable(m, pt, Point(inf, 0))
    @variable(m, finite)
    data = TestData(par, 0, 5)
    meas = Measure(finite, data, Int[], Int[], true)
    object = MeasureData(meas, "test")
    mindex = MeasureIndex(1)
    @test InfiniteOpt._add_data_object(m, object) == mindex
    meas = InfiniteOpt._make_variable_ref(m, mindex)
    dinf = @deriv(inf, par)
    # test for variable reference
    @testset "Variable" begin
        @test isequal(InfiniteOpt._all_function_variables(par), [par])
        @test isequal(InfiniteOpt._all_function_variables(inf), [inf])
        @test isequal(InfiniteOpt._all_function_variables(meas), [meas])
        @test isequal(InfiniteOpt._all_function_variables(dinf), [dinf])
    end
    # test for GenericAffExpr
    @testset "AffExpr" begin
        # make expressions
        aff1 = meas + 2par + finite - dinf
        aff2 = zero(GenericAffExpr{Float64, GeneralVariableRef})
        # test expressions
        @test isempty(setdiff(InfiniteOpt._all_function_variables(aff1),
                              [meas, par, finite, dinf]))
        @test InfiniteOpt._all_function_variables(aff2) == GeneralVariableRef[]
    end
    # test for GenericQuadExpr
    @testset "QuadExpr" begin
        # make expressions
        quad1 = pt^2 + inf * pt - meas + 2par + finite - dinf
        quad2 = pt^2 + inf * pt
        quad3 = zero(GenericQuadExpr{Float64, GeneralVariableRef})
        # test expressions
        @test isempty(setdiff(InfiniteOpt._all_function_variables(quad1),
                      [meas, par, finite, dinf, pt, inf]))
        @test isempty(setdiff(InfiniteOpt._all_function_variables(quad2),
                              [pt, inf]))
        @test InfiniteOpt._all_function_variables(quad3) == GeneralVariableRef[]
    end
    # test for Array of expressions
    @testset "AbstractArray" begin
        # make expressions
        ex1 = [inf, pt]
        ex2 = [inf + pt, meas + pt]
        # test expressions
        @test isempty(setdiff(InfiniteOpt._all_function_variables(ex1),
                      [pt, inf]))
        @test isempty(setdiff(InfiniteOpt._all_function_variables(ex2),
                              [pt, inf, meas]))
    end
    # test for Array of expressions
    @testset "NLPExpr" begin
        # make expressions
        nlp = sin(pt) + inf / pt
        # test expressions
        @test isempty(setdiff(InfiniteOpt._all_function_variables(nlp),
                      [pt, inf]))
    end
    # test backup
    @testset "Fallback" begin
        @variable(Model(), x)
        @test_throws ErrorException InfiniteOpt._all_function_variables(x)
    end
end

# Test _object_numbers
@testset "_object_numbers" begin
    # initialize model and references
    m = InfiniteModel()
    @infinite_parameter(m, par in [0, 1])
    @infinite_parameter(m, pars[1:2] in [0, 1])
    @variable(m, inf, Infinite(par))
    @variable(m, inf2, Infinite(par, pars))
    @variable(m, pt, Point(inf, 0))
    @variable(m, finite)
    var = build_variable(error, inf2, Dict{Int, Float64}(1 => 0.5), check = false)
    red = add_variable(m, var)
    # test for finite variable reference
    @testset "FiniteVariable" begin
        @test InfiniteOpt._object_numbers(pt) == []
        @test InfiniteOpt._object_numbers(finite) == []
    end
    # test for infinite variable reference
    @testset "InfiniteVariable" begin
        @test InfiniteOpt._object_numbers(inf) == [1]
    end
    # test for parameter reference
    @testset "Parameter" begin
        @test InfiniteOpt._object_numbers(par) == [1]
        @test InfiniteOpt._object_numbers(pars[1]) == [2]
    end
    # test for semi-infinite variable reference
    @testset "SemiInfiniteInfinite" begin
        @test InfiniteOpt._object_numbers(red) == [2]
    end
    # test for GenericAffExpr
    @testset "AffExpr" begin
        # make expressions
        aff1 = inf + inf2 + pt - 3
        aff2 = pt + finite - 2
        # test expressions
        @test sort!(InfiniteOpt._object_numbers(aff1)) == [1, 2]
        @test InfiniteOpt._object_numbers(aff2) == []
    end
    # test for GenericQuadExpr
    @testset "QuadExpr" begin
        # make expressions
        quad1 = inf * inf2 + inf + inf2 + pt - 3 - par
        quad2 = pt * pt + pt + finite - 2
        # test expressions
        @test sort!(InfiniteOpt._object_numbers(quad1)) == [1, 2]
        @test InfiniteOpt._object_numbers(quad2) == []
    end
    # test for NLPExpr
    @testset "NLPExpr" begin
        # make expressions
        nlp = sin(inf)
        # test expressions
        @test InfiniteOpt._object_numbers(nlp) == [1]
    end
end

# Test _parameter_numbers
@testset "_parameter_numbers" begin
    # initialize model and references
    m = InfiniteModel()
    @infinite_parameter(m, par in [0, 1])
    @infinite_parameter(m, pars[1:2] in [0, 1])
    @variable(m, inf, Infinite(par))
    @variable(m, inf2, Infinite(par, pars))
    @variable(m, pt, Point(inf, 0))
    @variable(m, finite)
    var = build_variable(error, inf2, Dict{Int, Float64}(1 => 0.5), check = false)
    red = add_variable(m, var)
    # test for finite variable reference
    @testset "FiniteVariable" begin
        @test InfiniteOpt._parameter_numbers(pt) == []
        @test InfiniteOpt._parameter_numbers(finite) == []
    end
    # test for infinite variable reference
    @testset "InfiniteVariable" begin
        @test InfiniteOpt._parameter_numbers(inf) == [1]
        @test InfiniteOpt._parameter_numbers(inf2) == [1, 2, 3]
    end
    # test for parameter reference
    @testset "Parameter" begin
        @test InfiniteOpt._parameter_numbers(par) == [1]
        @test InfiniteOpt._parameter_numbers(pars[2]) == [3]
    end
    # test for semi-infinite variable reference
    @testset "SemiInfiniteInfinite" begin
        @test InfiniteOpt._parameter_numbers(red) == [2, 3]
    end
    # test for GenericAffExpr
    @testset "AffExpr" begin
        # make expressions
        aff1 = inf + inf2 + pt - 3
        aff2 = pt + finite - 2
        # test expressions
        @test sort!(InfiniteOpt._parameter_numbers(aff1)) == [1, 2, 3]
        @test InfiniteOpt._parameter_numbers(aff2) == []
    end
    # test for GenericQuadExpr
    @testset "QuadExpr" begin
        # make expressions
        quad1 = inf * inf2 + inf + inf2 + pt - 3 - par
        quad2 = pt * pt + pt + finite - 2
        # test expressions
        @test sort!(InfiniteOpt._parameter_numbers(quad1)) == [1, 2, 3]
        @test InfiniteOpt._parameter_numbers(quad2) == []
    end
    # test for NLPExpr
    @testset "NLPExpr" begin
        # make expressions
        nlp = sin(inf2)
        # test expressions
        @test sort!(InfiniteOpt._parameter_numbers(nlp)) == [1, 2, 3]
    end
end

# Test _model_from_expr
@testset "_model_from_expr" begin
    # initialize model and references
    m = InfiniteModel()
    @variable(m, hd)
    # test for variable reference
    @testset "Variable" begin
        @test InfiniteOpt._model_from_expr(hd) === m
    end
    # test for GenericAffExpr
    @testset "AffExpr" begin
        # make expressions
        aff1 = hd + 2
        aff2 = zero(JuMP.GenericAffExpr{Float64, GeneralVariableRef})
        # test expressions
        @test InfiniteOpt._model_from_expr(aff1) === m
        @test InfiniteOpt._model_from_expr(aff2) isa Nothing
    end
    # test for GenericQuadExpr
    @testset "QuadExpr" begin
        # make expressions
        quad1 = hd * hd + hd + 1
        quad2 = zero(JuMP.GenericQuadExpr{Float64, GeneralVariableRef})
        quad3 = hd * hd + 1
        # test expressions
        @test InfiniteOpt._model_from_expr(quad1) === m
        @test InfiniteOpt._model_from_expr(quad2) isa Nothing
        @test InfiniteOpt._model_from_expr(quad3) === m
    end
    # test for NLPExpr
    @testset "NLPExpr" begin
        # make expressions
        nlp1 = sin(hd)
        nlp2 = zero(NLPExpr)
        nlp3 = 2 + sin(hd^2)
        # test expressions
        @test InfiniteOpt._model_from_expr(nlp1) === m
        @test InfiniteOpt._model_from_expr(nlp2) isa Nothing
        @test InfiniteOpt._model_from_expr(nlp3) === m
    end
    # test for Vector{GeneralVariableRef}
    @testset "Vector{GeneralVariableRef}" begin
        vrefs1 = GeneralVariableRef[]
        vrefs2 = [hd]
        # test expressions
        @test InfiniteOpt._model_from_expr(vrefs1) isa Nothing
        @test InfiniteOpt._model_from_expr(vrefs2) === m
    end
    # test Fallback
    @testset "Fallback" begin
        @test_throws ErrorException InfiniteOpt._model_from_expr(:bad)
    end
end

# Test _remove_variable
@testset "_remove_variable" begin
    # initialize model and references
    m = InfiniteModel()
    @infinite_parameter(m, par in [0, 1])
    @variable(m, inf, Infinite(par))
    @variable(m, pt, Point(inf, 0))
    @variable(m, finite)
    # test for GenericAffExpr
    @testset "AffExpr" begin
        # make expressions
        aff1 = pt + 2par + finite
        aff2 = zero(GenericAffExpr{Float64, GeneralVariableRef})
        # test expressions
        @test isa(InfiniteOpt._remove_variable(aff1, finite), Nothing)
        @test !haskey(aff1.terms, finite)
        @test isa(InfiniteOpt._remove_variable(aff2, inf), Nothing)
    end
    # test for GenericQuadExpr
    @testset "QuadExpr" begin
        # make expressions
        quad1 = pt^2 + inf * pt + 2par + finite
        quad2 = zero(GenericQuadExpr{Float64, GeneralVariableRef})
        # test expressions
        quad = copy(quad1)
        @test isa(InfiniteOpt._remove_variable(quad, inf), Nothing)
        @test !haskey(quad.aff.terms, inf)
        @test !haskey(quad.terms, UnorderedPair{GeneralVariableRef}(inf, pt))
        quad = copy(quad1)
        @test isa(InfiniteOpt._remove_variable(quad, pt), Nothing)
        @test !haskey(quad.terms, UnorderedPair{GeneralVariableRef}(inf, pt))
        @test !haskey(quad.terms, UnorderedPair{GeneralVariableRef}(pt, pt))
        @test isa(InfiniteOpt._remove_variable(quad2, inf), Nothing)
    end
    # test for NLPExpr
    @testset "NLPExpr" begin
        # make expressions
        nlp1 = sin(3pt)
        nlp2 = pt^2.3 + max(inf, pt)
        nlp3 = cos(pt^2 + pt) / (2pt + 2inf)
        # test expressions
        @test InfiniteOpt._remove_variable(nlp1, pt) isa Nothing
        @test isequal(nlp1, sin(zero(zero(GenericAffExpr{Float64, GeneralVariableRef}))))
        @test InfiniteOpt._remove_variable(nlp2, pt) isa Nothing
        @test isequal(nlp2, zero(NLPExpr)^2.3 + max(inf, 0.0))
        @test InfiniteOpt._remove_variable(nlp3, inf) isa Nothing
        @test isequal(nlp3, cos(pt^2 + pt) / (2pt))
    end
    # test for AbstractArray
    @testset "AbstractArray" begin
        # make expressions
        ex = [pt + 2par + finite, 2inf + pt]
        # test expressions
        @test isa(InfiniteOpt._remove_variable(ex, finite), Nothing)
        @test !haskey(ex[1].terms, finite)
    end
end

# Test map_expression
@testset "map_expression" begin
    # setup model
    m = InfiniteModel()
    @variable(m, z)
    @variable(m, y)
    aff = 2z + 42
    quad = z^2 + 2z
    nlp = (sin(z) + aff) ^ 3.4
    @variable(Model(), x)
    # test variable
    @testset "Variable" begin
        @test isequal(map_expression(v -> x, z), x)
    end
    # test AffExpr
    @testset "AffExpr" begin
        @test isequal(map_expression(v -> x, aff), 2x + 42)
    end
    # test QuadExpr
    @testset "QuadExpr" begin
        @test isequal(map_expression(v -> x, quad), x^2 + 2x)
    end
    # test NLPExpr
    @testset "NLPExpr" begin
        @test isequal(map_expression(v -> z, nlp), (sin(z) + (2z + 42)) ^ 3.4)
        @test isequal(map_expression(v -> v^3, sin(y)), sin(y^3))
    end
end

# Test _set_variable_coefficient!
@testset "_set_variable_coefficient!" begin
    # initialize model and references
    m = InfiniteModel()
    @infinite_parameter(m, par in [0, 1])
    @infinite_parameter(m, par2 in [0, 1])
    @variable(m, x, Infinite(par))
    @variable(m, y, Infinite(par, par2))
    @variable(m, z)
    # test with GeneralVariableRef
    @testset "GeneralVariableRef" begin
        @test isequal_canonical(InfiniteOpt._set_variable_coefficient!(x, x, 2), 2 * x)
        @test isequal_canonical(InfiniteOpt._set_variable_coefficient!(z, x, 2), z + 2x)
    end
    # test with GenericAffExpr
    @testset "AffExpr" begin
        @test isequal_canonical(InfiniteOpt._set_variable_coefficient!(x + z, x, 2), 2x + z)
        @test isequal_canonical(InfiniteOpt._set_variable_coefficient!(x + z, y, 2), x + z + 2y)
    end
    # test with GenericQuadExpr
    @testset "QuadExpr" begin
        @test isequal_canonical(InfiniteOpt._set_variable_coefficient!(y ^2 + x, x, 2), y^2 + 2x)
        @test isequal_canonical(InfiniteOpt._set_variable_coefficient!(y^2 + x, y, 2), y^2 + x + 2y)
    end
    # test fallabck
    @testset "Fallback" begin
        @test_throws ErrorException InfiniteOpt._set_variable_coefficient!(2, x, 2)
    end
end

# Test parameter reference methods
@testset "Parameter References" begin
    m = InfiniteModel()
    @infinite_parameter(m, t in [0, 1])
    @infinite_parameter(m, y in [0, 1])
    @infinite_parameter(m, x[1:3] in [0, 1])
    @variable(m, z)
    @expression(m, c1, 2z)
    @expression(m, c2, z + t + x[1])
    # test _make_param_tuple_element (IndependentParameterIndex)
    @testset "_make_param_tuple_element (Independent)" begin
        @test isequal(InfiniteOpt._make_param_tuple_element(m, index(t)), t)
        @test isequal(InfiniteOpt._make_param_tuple_element(m, index(y)), y)
    end
    # test _make_param_tuple_element (DependentParametersIndex)
    @testset "_make_param_tuple_element (Dependent)" begin
        obj_idx = index(first(x)).object_index
        @test isequal(InfiniteOpt._make_param_tuple_element(m, obj_idx), x)
    end
    # test parameter_refs
    @testset "parameter_refs" begin
        @test parameter_refs(c1) == ()
        @test isequal(parameter_refs(c2), (t, x))
        @test parameter_refs(zero(AffExpr)) == ()
    end
end


text:
module Example
export domath
domath(x) = x + 2
end