text:
function initialenvperiodic(mps::SymMatrixProductState{Tv},
                            mpo::SymMatrixProductOperator{Tv};
                            isometry::Symbol=:R) where {Tv<:Number}
    lx = mps.lx
    env = Vector{SymTensor{Tv, 4}}(undef, lx+2)

    lchr = mps.matrices[1].legs[1].chrs[1]
    rchr = mps.matrices[lx].legs[3].chrs[1]

    ##NOTE: assuming mpo has charge 0 at both ends!
    # mpo.matrices[1].legs[1].chrs[1]
    # mpo.matrices[lx].legs[3].chrs[1]

    wleg = mpo.tensors[1].legs[1]
    env[1] = SymTensor(eye(Tv, wleg.chrs.+lchr, wleg.dims),
                       (wleg, STLeg(+1, [lchr], [1])),
                       (reverseleg(wleg), STLeg(-1, [lchr], [1])))

    wleg = mpo.tensors[lx].legs[3]
    env[lx+2] = SymTensor(eye(Tv, wleg.chrs.-rchr, wleg.dims),
                          (reverseleg(wleg), STLeg(-1, [rchr], [1])),
                          (wleg, STLeg(+1, [rchr], [1])))

    if isometry == :R
        for l = lx:-1:1
            mps.center == 1 || error("MPS center has to be 1")
            env[l+1] = _mpsupdateright(env[l+2], mps.matrices[l], mpo.tensors[l])
        end
    elseif isometry == :L
        for l = 1:lx
            mps.center == lx || error("MPS center has to be $lx")
            env[l+1] = _mpsupdateleft(env[l], mps.matrices[l], mpo.tensors[l])
        end
    else
        error("Invalid isometry value $isometry")
    end
    return env
end

function initialenvperiodic(mps::SymMatrixProductState{ComplexF64},
                            mpo::SymMatrixProductOperator{Float64};
                            isometry::Symbol=:R)
    initialenv(mps,
               convert(MatrixProductOperator{ComplexF64}, mpo),
               isometry=isometry)
end

function dmrg2sitesweep_periodic!(mps::SymMatrixProductState{Tv},
                                  mpo::SymMatrixProductOperator{Tv},
                                  env::Vector{SymTensor{Tv, 4}};
                                  maxdim::Int=200,
                                  tol::Float64=1.e-9,
                                  lanczostol::Float64=1.e-7,
                                  krylovdim::Int=5,
                                  krylovmaxiter::Int=8,
                                  verbose::Bool=false) where {Tv<:Number}
    lx = mps.lx
    d = mps.d

    mps.center == 1 || error("The center of MPS has to be 1 for dmrg L->R->L")

    energies = Vector{Float64}()

    A = mps.matrices[1]
    for l = 1:lx-2
        AA = contract(A, (1,2,-1), mps.matrices[l+1], (-1,3,4))
        es, vs, info = eigsolve(v->_applymps2site(v, env[l], env[l+3],
                                                  mpo.tensors[l], mpo.tensors[l+1]),
                                AA, 1, :SR, ishermitian=true,
                                tol=lanczostol,
                                krylovdim=krylovdim,
                                maxiter=krylovmaxiter)
        v = vs[1]
        e = es[1]
        verbose && println("Sweep L2R: bond $l, $(l+1) -> energy $e")
        verbose && println("normres = $(info.normres[1]), #iterations = $(info.numiter), #applications = $(info.numops)\n")
        push!(energies, e)

        vreleg = fuselegs(fuselegs(v, +1, 1, 2), -1, 2, 2)
        #vreleg = SymMatrix(v, [1,2], [3,4])
        U, S, Vt = svdtrunc(vreleg, maxdim=maxdim, tol=tol)

        mps.matrices[l] = unfuseleg(U, 1, A.legs[1:2])
        mps.dims[l+1] = size(S, 1)

        env[l+1] = _mpsupdateleft(env[l], mps.matrices[l], mpo.tensors[l])

        A = unfuseleg(S*Vt, 2, AA.legs[3:4])
    end

    l = lx-1
    AA = contract(A, (1,2,-1), mps.matrices[l+1], (-1,3,4))
    es, vs, info = eigsolve(v->_applymps2site(v, env[l], env[l+3],
                                              mpo.tensors[l], mpo.tensors[l+1]),
                            AA, 1, :SR, ishermitian=true,
                            tol=lanczostol,
                            krylovdim=krylovdim,
                            maxiter=krylovmaxiter)

    v = vs[1]
    e = es[1]
    verbose && println("Sweep L2R: bond $l, $(l+1) -> energy $e")
    verbose && println("normres = $(info.normres[1]), #iterations = $(info.numiter), #applications = $(info.numops)\n")
    push!(energies, e)

    for l = lx-1:-1:2
        vreleg = fuselegs(fuselegs(v, +1, 1, 2), -1, 2, 2)
        #vreleg = SymMatrix(v, [1,2], [3,4])
        U, S, Vt = svdtrunc(vreleg, maxdim=maxdim, tol=tol)

        mps.matrices[l+1] = unfuseleg(Vt, 2, AA.legs[3:4])
        mps.dims[l+1] = size(S, 2)

        env[l+2] = _mpsupdateright(env[l+3], mps.matrices[l+1], mpo.tensors[l+1])

        A = unfuseleg(U*S, 1, AA.legs[1:2])
        AA = contract(mps.matrices[l-1], (1,2,-1), A, (-1,3,4))

        es, vs, info = eigsolve(v->_applymps2site(v, env[l-1], env[l+2],
                                                  mpo.tensors[l-1], mpo.tensors[l]),
                                AA, 1, :SR, ishermitian=true,
                                tol=lanczostol,
                                krylovdim=krylovdim,
                                maxiter=krylovmaxiter)
        v = vs[1]
        e = es[1]
        verbose && println("Sweep R2L: bond $(l-1), $l -> energy $e")
        verbose && println("normres = $(info.normres[1]), #iterations = $(info.numiter), #applications = $(info.numops)\n")
        push!(energies, e)
    end
    l = 1
    vreleg = fuselegs(fuselegs(v, +1, 1, 2), -1, 2, 2)
    #vreleg = SymMatrix(v, [1,2], [3,4])
    U, S, Vt = svdtrunc(vreleg, maxdim=maxdim, tol=tol)

    mps.matrices[l+1] = unfuseleg(Vt, 2, AA.legs[3:4])
    mps.dims[l+1] = size(S, 2)

    env[l+2] = _mpsupdateright(env[l+3], mps.matrices[l+1], mpo.tensors[l+1])

    mps.matrices[l] = unfuseleg(U*S, 1, AA.legs[1:2])
    return energies
end

max_stars_repo_name: amiragha/mps

max_issues_repo_name: amiragha/mps

max_forks_repo_name: amiragha/mps


text:
replace_index(A::scal,iold,inew) = A
replace_index(A::param,iold,inew) = param(A.name,A.state,(n-> n==iold ? inew : n).(A.inds))
replace_index(A::ExpVal,iold,inew) = ExpVal(replace_index(A.A,iold,inew))
replace_index(A::Corr,iold,inew) = Corr(replace_index(A.A,iold,inew))
replace_index(A::Union{δ,σminus,σplus},iold,inew) = basetype(A)((n-> n==iold ? inew : n).(A.inds))
replace_index(A::Union{BosonDestroy,BosonCreate,FermionDestroy,FermionCreate},iold,inew) = basetype(A)(A.name,(n-> n==iold ? inew : n).(A.inds)...)
replace_index(A::σ,iold,inew) = σ(A.a,(n-> n==iold ? inew : n).(A.inds))
replace_index(A::OpProd,iold,inew) = replace_index(A.A,iold,inew)*replace_index(A.B,iold,inew)
replace_index(A::OpSum,iold,inew) = replace_index(A.A,iold,inew) + replace_index(A.B,iold,inew)
replace_index(A::OpSumAnalytic,iold,inew) = begin
    (A.ind==iold || A.ind==inew) && throw(ArgumentError("replace_index in OpSumAnalytic cannot have iold ($iold) or inew ($inew) be the same as the sum index ($(A.ind))!"))
    tmp = replace_index(A.A,iold,inew)
    # we have to be careful here - when replacing an index inside the expression, there might be reorderings that
    # have be done with the same index explicitly to make sure that the commutator shows up
    # so take out the term with the same index explicitly, and redo that one term
    OpSumAnalytic(A.ind,tmp) - replace_index(tmp,A.ind,inew) + replace_index(replace_index(A.A,A.ind,iold),iold,inew)
end
replace_index(A::Operator,reps) = begin
    Anew = A
    for (iold,inew) in reps
        Anew = replace_index(Anew,iold,inew)
    end
    Anew
end

function exchange_inds(A::Operator,i1,i2)
    ss = gensym()
    A = replace_index(A,i1,ss)
    A = replace_index(A,i2,i1)
    A = replace_index(A,ss,i2)
    A
end

distribute_indices!(inds,A::scal) = A
distribute_indices!(inds,A::param) = param(A.name,A.state,(popfirst!(inds) for _ in A.inds)...)
distribute_indices!(inds,A::ExpVal) = ExpVal(distribute_indices!(inds,A.A))
distribute_indices!(inds,A::Corr) = Corr(distribute_indices!(inds,A.A))
distribute_indices!(inds,A::Union{σminus,σplus}) = basetype(A)((popfirst!(inds) for _ in A.inds)...)
distribute_indices!(inds,A::Union{BosonDestroy,BosonCreate,FermionDestroy,FermionCreate}) = basetype(A)(A.name,(popfirst!(inds) for _ in A.inds)...)
distribute_indices!(inds,A::σ) = σ(A.a,(popfirst!(inds) for _ in A.inds)...)
distribute_indices!(inds,A::OpProd) = distribute_indices!(inds,A.A)*distribute_indices!(inds,A.B)
distribute_indices!(inds,A::OpSum) = distribute_indices!(inds,A.A) + distribute_indices!(inds,A.B)
# on purpose do not define this for OpSumAnalytic or δ

indextuple(A::scal)::OpIndices = ()
indextuple(A::Union{param,δ,BosonDestroy,BosonCreate,FermionDestroy,FermionCreate,σ,σminus,σplus})::OpIndices = A.inds
indextuple(A::Union{OpProd,OpSum})::OpIndices = (indextuple(A.A)...,indextuple(A.B)...)
indextuple(A::Union{ExpVal,Corr})::OpIndices = indextuple(A.A)
indextuple(A::OpSumAnalytic)::OpIndices = (A.ind,indextuple(A.A)...)
indexset(A) = Set{OpIndex}(indextuple(A))
sumindextuple(A::Operator)::OpIndices = ()
sumindextuple(A::Union{OpProd,OpSum})::OpIndices = (sumindextuple(A.A)...,sumindextuple(A.B)...)
sumindextuple(A::Union{ExpVal,Corr})::OpIndices = sumindextuple(A.A)
sumindextuple(A::OpSumAnalytic)::OpIndices = (A.ind,sumindextuple(A.A)...)
sumindexset(A) = Set{OpIndex}(sumindextuple(A))

"`extindices(A::Operator)` return externally visible indices of an expression"
extindices(A::Operator) = [ind for ind in indextuple(A) if !in(ind,sumindextuple(A))]

"`symmetric_index_nums(A::Operator)` return sequence of numbers of exchange-symmetric indices"
function symmetric_index_nums(A::Operator)
    inds = extindices(A)
    Nsyms = [1]
    for ii=2:length(inds)
        if A == exchange_inds(A,inds[ii-1],inds[ii])
            Nsyms[end] += 1
        else
            push!(Nsyms,1)
        end
    end
    Nsyms
end

"sum indices have no semantic meaning, so rename them in case they happen to occur in the other expression"
function ensure_compatible_sumind(S::OpSumAnalytic,A::Operator)
    Ainds = indextuple(A)
    if S.ind in Ainds
        oldinds = Set{OpIndex}((Ainds...,indextuple(S)...))
        m = match(r"(.*)_([0-9]+)",string(S.ind))
        indstem, ii = (m === nothing) ? (string(S.ind), 1) : (m.captures[1], 1+parse(Int,m.captures[2]))
        while (newind = Symbol(indstem,:_,ii)) in oldinds
            ii += 1
        end
        OpSumAnalytic(newind,replace_index(S.A,S.ind,newind))
    else
        S
    end
end

ext: jl


text:
function LoggerInformation!(sys::System,comm::MPI.Comm,root::Int64)
    if sys.thermologger!=NoLogger()
        LoggerThermo!(sys,comm,root)
    end
end

function LoggerThermo!(sys::System,comm::MPI.Comm,root::Int64)
    if sys.first_step[1] || sys.current_step[1]%sys.thermologger.freq==0.0
        sys.thermologger.Info[sys.thermologger.index[1]][1]=sys.current_step[1]
        sys.thermologger.Info[sys.thermologger.index[1]][2]=sys.current_temp[1]
        index=3
        if sys.thermologger.Momentum
            sys.thermologger.Info[sys.thermologger.index[1]][index]=sys.current_momentum[1]
            index+=1
        end
        if MPI.Comm_rank(comm)==root
            step=sys.current_step[1]
            temp=sys.current_temp[1]
            @show step,temp
        end
        sys.thermologger.index[1]+=1
    end
    if sys.current_step[1]==sys.steps+sys.start_step-1
        if MPI.Comm_rank(comm)==root
            if sys.thermologger.Write
                write_log(sys,sys.thermologger)
            end
        end
    end
end

function write_log(sys::System,logger::ThermoLogger)
    io=open(logger.File,"w")
    string_out="Step Temp"
    if logger.Momentum
        string_out*=" Momentum"
    end
    string_out*="\n"
    write(io,string_out)

    for i in sys.thermologger.Info
        index=3
        string_out=""
        string_out*=string(Int(i[1]))*" "
        string_out*=string(i[2])*" "
        if sys.thermologger.Momentum
            string_out*=string(i[index])*" "
            index+=1
        end
        string_out*="\n"
        write(io,string_out)
    end
    close(io)
end


text:
using MathProgBase
using MathProgBase.SolverInterface

# Include linprog.jl tests
if isdefined(Base, :pathof)
    include(joinpath(dirname(pathof(MathProgBase)), "..", "test", "linprog.jl"))
    include(joinpath(dirname(pathof(MathProgBase)), "..", "test", "linproginterface.jl"))
else
    include(joinpath(Pkg.dir("MathProgBase"), "test", "linprog.jl"))
    include(joinpath(Pkg.dir("MathProgBase"), "test", "linproginterface.jl"))
end

@testset "MathProgBase" begin
    solver = OSQPMathProgBaseInterface.OSQPSolver(eps_abs = 1e-7, eps_rel = 1e-16)
    MathProgBase.setparameters!(solver, Silent=true)

    @testset "linprog" begin
        linprogtest(solver)
    end

    @testset "linproginterface" begin
        linprogsolvertest(solver, 1e-03)
    end

    @testset "quadprog" begin
        # modified from joinpath(Pkg.dir("MathProgBase"), "test", "quadprog.jl"):
        sol = quadprog([0., 0., 0.],[2. 1. 0.; 1. 2. 1.; 0. 1. 2.],[1. 2. 3.; 1. 1. 0.],'>',[4., 1.],-Inf,Inf,solver)
        @test sol.status == :Optimal
        @test isapprox(sol.objval, 130/70, atol=1e-6)
        @test isapprox(norm(sol.sol[1:3] - [0.5714285714285715,0.4285714285714285,0.8571428571428572]), 0.0, atol=1e-6)
    end

    @testset "QP1" begin
        # modified from joinpath(Pkg.dir("MathProgBase"), "test", "quadprog.jl"):
        m = LinearQuadraticModel(solver)
        loadproblem!(m, [1. 2. 3.; 1. 1. 0.],[-Inf,-Inf,-Inf],[Inf,Inf,Inf],[0.,0.,0.],[4., 1.],[Inf,Inf], :Min)

        setquadobj!(m,diagm(0 => [10.0,10.0,10.0]))
        rows = [1, 2, 2, 2, 3, 3, 3]
        cols = [1, 1, 1, 2, 2, 3, 3]
        vals = Float64[2, 0.5, 0.5, 2, 1, 1, 1]
        setquadobj!(m,rows,cols,vals)

        m2 = copy(m)

        verify_solution = function (m)
            stat = status(m)
            @test stat == :Optimal
            @test isapprox(getobjval(m), 130/70, atol=1e-6)
            @test isapprox(norm(getsolution(m) - [0.5714285714285715,0.4285714285714285,0.8571428571428572]), 0.0, atol=1e-6)
            @test getsolvetime(m) > 0
        end

        optimize!(m)
        verify_solution(m)

        setwarmstart!(m2, getsolution(m) .+ 0.1)
        optimize!(m2)
        verify_solution(m2)
    end

    @testset "basic_QP" begin
        # same QP as test/basic.jl: "basic_QP" but using MathProgBase
        P = sparse([11. 0.; 0. 0.])
        q = [3.; 4]
        A = sparse([-1 0; 0 -1; -1 -3; 2 5; 3 4])
        u = [0.; 0.; -15; 100; 80]
        l = fill(-Inf, length(u))

        verify_solution = function (m)
            tol = 1e-5

            @test isapprox(norm(getsolution(m) - [0.; 5.]), 0., atol=tol)
            @test isapprox(norm(getconstrduals(m) - [-1.666666666666; 0.; -1.3333333; 0.; 0.]), 0., atol=tol)
            @test isapprox(getobjval(m), 20., atol=tol)
        end

        m1 = LinearQuadraticModel(solver)
        loadproblem!(m1, A, [-Inf, -Inf], [Inf, Inf], q, l, u, :Min)
        m2 = copy(m1)
        setquadobj!(m1, P)
        optimize!(m1)
        verify_solution(m1)

        setquadobj!(m2, findnz(triu(P))...) # triu to avoid duplicate elements
        optimize!(m2)
        verify_solution(m2)
    end

    @testset "Unsupported behavior" begin
        m = LinearQuadraticModel(solver)
        loadproblem!(m, [1. 2. 3.; 1. 1. 0.],[-Inf,-Inf,-Inf],[Inf,Inf,Inf],[0.,0.,0.],[4., 1.],[Inf,Inf], :Min)
        @test_throws ErrorException setvartype!(m, [:Cont, :Bin, :Cont])
    end

    @testset "Getters/setters" begin
        m = LinearQuadraticModel(solver)
        loadproblem!(m, [1. 2. 3.; 1. 1. 0.],[-Inf,-Inf,-Inf],[Inf,Inf,Inf],[0.,0.,0.],[4., 1.],[Inf,Inf], :Min)

        @test getrawsolver(m) isa OSQP.Model

        @test getsense(m) == :Min

        @test getvarLB(m) == [-Inf, -Inf, -Inf]
        @test getvarUB(m) == [Inf, Inf, Inf]

        @test getconstrLB(m) == [4., 1.]
        setconstrLB!(m, [-4., Inf])
        @test getconstrLB(m) == [-4., Inf]
        @test getconstrUB(m) == [Inf, Inf]
        setconstrUB!(m, [5., 8.])
        @test getconstrUB(m) == [5., 8.]

        @test getconstrmatrix(m) == [1. 2. 3.; 1. 1. 0.]
        @test numlinconstr(m) == 2

        @test getvartype(m) == [:Cont, :Cont, :Cont]
    end
end


text:
## Julia script to randomly decide the author of first authors
## Claudia (November 2020)

using Random
s = 9159277212
Random.seed!(s);
people = ["chunrong", "liule", "luke", "zhiwen"] ##alphabetical
people[randperm(length(people))]

max_stars_repo_name: solislemuslab/mycovirus-website

max_issues_repo_name: solislemuslab/bioklustering

max_forks_repo_name: solislemuslab/bioklustering


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

using Random, Serialization

a = parse(BigInt,"123456789012345678901234567890")
b = parse(BigInt,"123456789012345678901234567891")
c = parse(BigInt,"246913578024691357802469135780")
d = parse(BigInt,"-246913578024691357802469135780")
ee = typemax(Int64)
@testset "basics" begin
    @test BigInt <: Signed
    @test big(1) isa Signed

    let x = big(1)
        @test signed(x) === x
        @test convert(Signed, x) === x
        @test Signed(x) === x
        @test_throws MethodError convert(Unsigned, x) # could change in the future
    end
    @test a+BigInt(1) == b
    @test typeof(a+1) == BigInt
    @test a+1 == b
    @test isequal(a+1, b)
    @test b == a+1
    @test !(b == a)
    @test b > a
    @test b >= a
    @test !(b < a)
    @test !(b <= a)

    @test typeof(a * 2) == BigInt
    @test a*2 == c
    @test c-a == a
    @test c == a + a
    @test c+1 == a+b

    @test typeof(d) == BigInt
    @test d == -c

    @test typeof(BigInt(ee)) == BigInt
    @test BigInt(ee)+1 == parse(BigInt,"9223372036854775808")
    @testset "printing" begin
        #Multiple calls for sanity check, since we're doing direct memory manipulation
        @test string(a) == "123456789012345678901234567890"
        @test string(b) == "123456789012345678901234567891"
        @test string(c) == "246913578024691357802469135780"
        @test string(d) == "-246913578024691357802469135780"
        @test string(a) == "123456789012345678901234567890"
    end
    @testset "constructors" begin
        @test typeof(BigInt(typemax(Int8))) == BigInt
        @test typeof(BigInt(typemax(Int16))) == BigInt
        @test typeof(BigInt(typemax(Int32))) == BigInt
        @test typeof(BigInt(typemax(Int64))) == BigInt
        @test typeof(BigInt(typemax(Int128))) == BigInt

        @test typeof(BigInt(true)) == BigInt
        @test typeof(BigInt(typemax(UInt8))) == BigInt
        @test typeof(BigInt(typemax(UInt16))) == BigInt
        @test typeof(BigInt(typemax(UInt32))) == BigInt
        @test typeof(BigInt(typemax(UInt64))) == BigInt
        @test typeof(BigInt(typemax(UInt128))) == BigInt

        @test typeof(BigInt(BigInt(1))) == BigInt

        for x in (Int16(0), 1, 3//4, big(5//6), big(9))
            @test big(typeof(x)) == typeof(big(x))
            @test big(typeof(complex(x, x))) == typeof(big(complex(x, x)))
        end
    end
    @testset "division" begin
        oz = big(1 // 0)
        zo = big(0 // 1)

        @test_throws DivideError() oz / oz
        @test oz == oz / one(oz)
        @test -oz == oz / (-one(oz))
        @test zero(oz) == one(oz) / oz
        @test_throws DivideError() zo / zo
        @test one(zo) / zo == big(1//0)
        @test -one(zo) / zo == big(-1//0)
    end
end
@testset "div, fld, mod, rem" begin
    for i = -10:10, j = [-10:-1; 1:10]
        @test div(BigInt(i), BigInt(j)) == div(i,j)
        @test fld(BigInt(i), BigInt(j)) == fld(i,j)
        @test mod(BigInt(i), BigInt(j)) == mod(i,j)
        @test rem(BigInt(i), BigInt(j)) == rem(i,j)
    end
end
@testset "copysign / sign" begin
    x = BigInt(1)
    y = BigInt(-1)
    @test copysign(x, y) == y
    @test copysign(y, x) == x

    @test sign(BigInt(-3)) == -1
    @test sign(BigInt( 0)) == 0
    @test sign(BigInt( 3)) == 1
end

@testset "Signed addition" begin
    @test a+Int8(1) == b
    @test a+Int16(1) == b
    @test a+Int32(1) == b
    @test a+Int64(1) == b
    @test a+Int128(1) == b
    @test Int8(1)+ a == b
    @test Int16(1)+a == b
    @test Int32(1)+a == b
    @test Int64(1)+a == b
    @test b+Int8(-1) == a
    @test b+Int16(-1) == a
    @test b+Int32(-1) == a
    @test b+Int64(-1) == a
    @test Int8(-1)+ b == a
    @test Int16(-1)+b == a
    @test Int32(-1)+b == a
    @test Int64(-1)+b == a
end
@testset "Unsigned addition" begin
    @test a+true == b
    @test a+UInt8(1) == b
    @test a+UInt16(1) == b
    @test a+UInt32(1) == b
    @test a+UInt64(1) == b
    @test a+UInt128(1) == b
    @test true+a == b
    @test UInt8(1)+ a == b
    @test UInt16(1)+a == b
    @test UInt32(1)+a == b
    @test UInt64(1)+a == b
end
@testset "Signed subtraction" begin
    @test b-Int8(1) == a
    @test b-Int16(1) == a
    @test b-Int32(1) == a
    @test b-Int64(1) == a
    @test Int8(1)- b == -a
    @test Int16(1)-b == -a
    @test Int32(1)-b == -a
    @test Int64(1)-b == -a
    @test a-Int8(-1) == b
    @test a-Int16(-1) == b
    @test a-Int32(-1) == b
    @test a-Int64(-1) == b
    @test Int8(-1)- a == -b
    @test Int16(-1)-a == -b
    @test Int32(-1)-a == -b
    @test Int64(-1)-a == -b
end
@testset "Unsigned subtraction" begin
    @test b-true == a
    @test b-UInt8(1) == a
    @test b-UInt16(1) == a
    @test b-UInt32(1) == a
    @test b-UInt64(1) == a
    @test true-b == -a
    @test UInt8(1)- b == -a
    @test UInt16(1)-b == -a
    @test UInt32(1)-b == -a
    @test UInt64(1)-b == -a
end
@testset "Signed multiplication" begin
    @test a*Int8(1) == a
    @test a*Int16(1) == a
    @test a*Int32(1) == a
    @test a*Int64(1) == a
    @test Int8(1)* a == a
    @test Int16(1)*a == a
    @test Int32(1)*a == a
    @test Int64(1)*a == a
    @test a*Int8(-1) == -a
    @test a*Int16(-1) == -a
    @test a*Int32(-1) == -a
    @test a*Int64(-1) == -a
    @test Int8(-1)* a == -a
    @test Int16(-1)*a == -a
    @test Int32(-1)*a == -a
    @test Int64(-1)*a == -a
end
@testset "Unsigned multiplication" begin
    @test a*true == a
    @test a*UInt8(1) == a
    @test a*UInt16(1) == a
    @test a*UInt32(1) == a
    @test a*UInt64(1) == a
    @test true*a == a
    @test UInt8(1)* a == a
    @test UInt16(1)*a == a
    @test UInt32(1)*a == a
    @test UInt64(1)*a == a
end

@testset "bitshifts" begin
    @test BigInt(5) << 3 == 40
    @test BigInt(5) >> 1 == 2
    @test BigInt(-5) << 3 == -40
    @test BigInt(-5) >> 1 == -3
    @test BigInt(5) >> -3 == 40
    @test BigInt(5) << -1 == 2
    @test BigInt(-5) >> -3 == -40
    @test BigInt(-5) << -1 == -3
end
@testset "boolean ops" begin
    @test ~BigInt(123) == -124
    @test BigInt(123) & BigInt(234) == 106
    @test BigInt(123) | BigInt(234) == 251
    @test BigInt(123) ⊻ BigInt(234) == 145

    @test gcd(BigInt(48), BigInt(180)) == 12
    @test lcm(BigInt(48), BigInt(180)) == 720
end
@testset "combinatorics" begin
    @test factorial(BigInt(40)) == parse(BigInt,"815915283247897734345611269596115894272000000000")
    @test binomial(BigInt(1), -1) == BigInt(0)
    @test binomial(BigInt(1), 2)  == BigInt(0)
    @test binomial(BigInt(-53), 42) == parse(BigInt,"959509335087854414441273718")
    @test binomial(BigInt(113), BigInt(42)) == parse(BigInt,"18672199984318438125634054194360")
end
let a, b
    a = rand(1:100, 10000)
    b = map(BigInt, a)
    @test sum(a) == sum(b)
    @test 0 == sum(BigInt[]) isa BigInt
    @test prod(b) == foldl(*, b)
    @test 1 == prod(BigInt[]) isa BigInt
end

@testset "Iterated arithmetic" begin
    local a, b, c, d, f, g
    a = parse(BigInt,"315135")
    b = parse(BigInt,"12412")
    c = parse(BigInt,"3426495623485904783478347")
    d = parse(BigInt,"-1398984130")
    f = parse(BigInt,"2413804710837418037418307081437315263635345357386985747464")
    g = parse(BigInt,"-1")

    @test +(a, b) == parse(BigInt,"327547")
    @test 327547 == sum((a, b)) isa BigInt
    @test +(a, b, c) == parse(BigInt,"3426495623485904783805894")
    @test 3426495623485904783805894 == sum((a, b, c)) isa BigInt
    @test +(a, b, c, d) == parse(BigInt,"3426495623485903384821764")
    @test 3426495623485903384821764 == sum((a, b, c, d)) isa BigInt
    @test +(a, b, c, d, f) == parse(BigInt,"2413804710837418037418307081437318690130968843290370569228")
    @test 2413804710837418037418307081437318690130968843290370569228 == sum((a, b, c, d, f)) isa BigInt
    @test +(a, b, c, d, f, g) == parse(BigInt,"2413804710837418037418307081437318690130968843290370569227")
    @test 2413804710837418037418307081437318690130968843290370569227 == sum((a, b, c, d, f, g)) isa BigInt

    @test *(a, b) == parse(BigInt,"3911455620")
    @test *(a, b, c) == parse(BigInt,"13402585563389346256121263521460140")
    @test *(a, b, c, d) == parse(BigInt,"-18750004504148804423388563022070650287578200")
    @test *(a, b, c, d, f) == parse(BigInt,"-45258849200337190631492857400003938881995610529251881450243326128168934937055005474972396281351684800")
    @test *(a, b, c, d, f, g) == parse(BigInt,"45258849200337190631492857400003938881995610529251881450243326128168934937055005474972396281351684800")

    @test xor(a, b) == parse(BigInt,"327299")
    @test xor(a, b, c) == parse(BigInt,"3426495623485904783798472")
    @test xor(a, b, c, d) == parse(BigInt,"-3426495623485906178489610")
    @test xor(a, b, c, d, f) == parse(BigInt,"-2413804710837418037418307081437316711364709261074607933698")
    @test xor(a, b, c, d, f, g) == parse(BigInt,"2413804710837418037418307081437316711364709261074607933697")

    @test nand(a, b) == parse(BigInt,"-125")
    @test ⊼(a, b) == parse(BigInt,"-125")

    @test nor(a, b) == parse(BigInt,"-327424")
    @test ⊽(a, b) == parse(BigInt,"-327424")

    @test (&)(a, b) == parse(BigInt,"124")
    @test (&)(a, b, c) == parse(BigInt,"72")
    @test (&)(a, b, c, d) == parse(BigInt,"8")
    @test (&)(a, b, c, d, f) == parse(BigInt,"8")
    @test (&)(a, b, c, d, f, g) == parse(BigInt,"8")

    @test (|)(a, b) == parse(BigInt,"327423")
    @test (|)(a, b, c) == parse(BigInt,"3426495623485904783802111")
    @test (|)(a, b, c, d) == parse(BigInt,"-1396834561")
    @test (|)(a, b, c, d, f) == parse(BigInt,"-1358954753")
    @test (|)(a, b, c, d, f, g) == parse(BigInt,"-1")
end

@testset "bit operations" begin
    for x in (315135, 12412, 3426495623485904783478347)
        @test trailing_ones(big(x)) == trailing_ones(x)
        @test trailing_zeros(big(x)) == trailing_zeros(x)
        @test count_ones(big(x)) == count_ones(x)
        @test count_zeros(-big(x)) == count_zeros(-x)
    end

    @test_throws DomainError trailing_zeros(big(0))
    @test_throws DomainError trailing_ones(big(-1)) # -1 is all ones

    @test_throws DomainError count_zeros(big(0))
    @test_throws DomainError count_zeros(big(rand(UInt)))
    @test_throws DomainError count_ones(big(-1))
    @test_throws DomainError count_ones(-big(rand(UInt))-1)
end

# Large Fibonacci to exercise BigInt
# from Bill Hart, https://groups.google.com/group/julia-dev/browse_frm/thread/798e2d1322daf633
function mul(a::Vector{BigInt}, b::Vector{BigInt})
   x = a[2]*b[2]
   c = Vector{BigInt}(undef, 3)
   c[1] = a[1]*b[1] + x
   c[2] = a[1]*b[2] + a[2]*b[3]
   c[3] = x + a[3]*b[3]
   return c
end

function bigfib(n)
    n == 0 && return BigInt(0)
    n -= 1
    r = [BigInt(1), BigInt(1), BigInt(0)]
    s = [BigInt(1), BigInt(0), BigInt(1)]
    while true
       (n & 1) == 1 && (s = mul(s,r))
       (n >>= 1) == 0 && return s[1]
       r = mul(r,r)
    end
end
@test [bigfib(n) for n=0:10] == [0,1,1,2,3,5,8,13,21,34,55]

let s, n = bigfib(1000001)
    @test ndigits(n) == 208988
    @test mod(n,big(10)^15) == 359244926937501
    @test div(n,big(10)^208973) == 316047687386689

    s = string(n)
    @test length(s) == 208988
    @test endswith(s, "359244926937501")
    @test startswith(s, "316047687386689")
end

@testset "digits" begin
    n = Int64(2080310129088201558)
    N = big(n)
    for base in (2,7,10,11,16,30,50,62,64,100), pad in (0,1,10,100)
        @test digits(n; base, pad) == digits(N; base, pad)
        @test digits(-n; base, pad) == digits(-N; base, pad)
        @test digits!(Vector{Int}(undef, pad), n; base) == digits!(Vector{Int}(undef, pad), N; base)
    end
end

# serialization (#5133)
let n = parse(BigInt, "359334085968622831041960188598043661065388726959079837"),
    b = IOBuffer()
    serialize(b, n)
    seek(b, 0)
    @test deserialize(b) == n
end

@testset "issue #5873" begin
    @test ndigits(big(90)) == 2
    @test ndigits(big(99)) == 2
    ndigits_mismatch(n) = ndigits(n) != ndigits(BigInt(n))
    @test !any(ndigits_mismatch, 8:9)
    @test !any(ndigits_mismatch, 64:99)
    @test !any(ndigits_mismatch, 512:999)
    @test !any(ndigits_mismatch, 8192:9999)
end
# The following should not crash (#16579)
ndigits(big(rand(Int)), base=rand(63:typemax(Int)))
ndigits(big(rand(Int)), base=big(2)^rand(2:999))

for x in big.([-20:20; rand(Int)])
    for _base in -1:1
        @test_throws DomainError ndigits(x, base=_base)
    end
end

@test Base.ndigits0zpb(big(0), big(rand(2:100))) == 0

# digits with BigInt bases (#16844)
@test digits(big(2)^256, base = big(2)^128) == [0, 0, 1]

@testset "conversion from float" begin
    @test BigInt(2.0) == BigInt(2.0f0) == BigInt(big(2.0)) == 2
    @test_throws InexactError convert(BigInt, 2.1)
    @test_throws InexactError convert(BigInt, big(2.1))
end
@testset "truncation" begin
    # cf. issue #13367
    for T = (Float16, Float32, Float64)
        @test trunc(BigInt, T(2.1)) == 2
        @test unsafe_trunc(BigInt, T(2.1)) == 2
        @test round(BigInt, T(2.1)) == 2
        @test floor(BigInt, T(2.1)) == 2
        @test ceil(BigInt, T(2.1)) == 3

        @test_throws InexactError trunc(BigInt, T(Inf))
        @test_throws InexactError round(BigInt, T(Inf))
        @test_throws InexactError floor(BigInt, T(Inf))
        @test_throws InexactError ceil(BigInt, T(Inf))
    end
end

@testset "string(::BigInt)" begin
    # cf. issue #18849"
    # bin, oct, dec, hex should not call sizeof on BigInts
    # when padding is desired
    padding = 4
    low = big(4)
    high = big(2^20)
    @test string(low, pad = padding, base = 2) == "0100"
    @test string(low, pad = padding, base = 8) == "0004"
    @test string(low, pad = padding, base = 10) == "0004"
    @test string(low, pad = padding, base = 16) == "0004"

    @test string(high, pad = padding, base = 2) == "100000000000000000000"
    @test string(high, pad = padding, base = 8) == "4000000"
    @test string(high, pad = padding, base = 10) == "1048576"
    @test string(high, pad = padding, base = 16) == "100000"

    @test string(-low, pad = padding, base = 2) == "-0100" # handle negative numbers correctly
    @test string(-low, pad = padding, base = 8) == "-0004"
    @test string(-low, pad = padding, base = 10) == "-0004"
    @test string(-low, pad = padding, base = 16) == "-0004"

    @test string(-high, pad = padding, base = 2) == "-100000000000000000000"
    @test string(-high, pad = padding, base = 8) == "-4000000"
    @test string(-high, pad = padding, base = 10) == "-1048576"
    @test string(-high, pad = padding, base = 16) == "-100000"

    # cf. issue #13367
    @test string(big(3), base = 2) == "11"
    @test string(big(9), base = 8) == "11"
    @test string(-big(9), base = 8) == "-11"
    @test string(big(12), base = 16) == "c"

    # respect 0-padding on big(0)
    for base in (2, 8, 10, 16)
        @test string(big(0), base=base, pad=0) == ""
    end
    @test string(big(0), base = rand(2:62), pad = 0) == ""
end

@test isqrt(big(4)) == 2
@test isqrt(big(5)) == 2

@test big(5)^true == big(5)
@test big(5)^false == one(BigInt)

@testset "math ops returning BigFloat" begin
    # operations that when applied to Int64 give Float64, should give BigFloat
    @test typeof(exp(a)) == BigFloat
    @test typeof(exp2(a)) == BigFloat
    @test typeof(exp10(a)) == BigFloat
    @test typeof(expm1(a)) == BigFloat
    @test typeof(cosh(a)) == BigFloat
    @test typeof(sinh(a)) == BigFloat
    @test typeof(tanh(a)) == BigFloat
    @test typeof(sech(a)) == BigFloat
    @test typeof(csch(a)) == BigFloat
    @test typeof(coth(a)) == BigFloat
    @test typeof(cbrt(a)) == BigFloat
    @test typeof(tan(a)) == BigFloat
    @test typeof(cos(a)) == BigFloat
    @test typeof(sin(a)) == BigFloat
end

# Issue #24298
@test mod(BigInt(6), UInt(5)) == mod(6, 5)

@test iseven(zero(BigInt))
@test isodd(BigInt(typemax(UInt)))

@testset "cmp has values in [-1, 0, 1], issue #28780" begin
    # _rand produces values whose log2 is better distributed than rand
    _rand(::Type{BigInt}, n=1000) = let x = big(2)^rand(1:rand(1:n))
        rand(-x:x)
    end
    _rand(F::Type{<:AbstractFloat}) = F(_rand(BigInt, round(Int, log2(floatmax(F))))) + rand(F)
    _rand(T) = rand(T)
    for T in (Base.BitInteger_types..., BigInt, Float64, Float32, Float16)
        @test cmp(big(2)^130, one(T)) === 1
        @test cmp(-big(2)^130, one(T)) === -1
        c = cmp(_rand(BigInt), _rand(T))
        @test c ∈ (-1, 0, 1)
        @test c isa Int
        (T <: Integer && T !== BigInt) || continue
        x = rand(T)
        @test cmp(big(2)^130, x) === cmp(x, -big(2)^130) === 1
        @test cmp(-big(2)^130, x) === cmp(x, big(2)^130) === -1
        @test cmp(big(x), x) === cmp(x, big(x)) === 0
    end
    c = cmp(_rand(BigInt), _rand(BigInt))
    @test c ∈ (-1, 0, 1)
    @test c isa Int
end

@testset "generic conversion from Integer" begin
    x = rand(Int128)
    @test BigInt(x) % Int128 === x
    y = rand(UInt128)
    @test BigInt(y) % UInt128 === y
end

@testset "conversion from typemin(T)" begin
    @test big(Int8(-128)) == big"-128"
    @test big(Int16(-32768)) == big"-32768"
    @test big(Int32(-2147483648)) == big"-2147483648"
    @test big(Int64(-9223372036854775808)) == big"-9223372036854775808"
    @test big(Int128(-170141183460469231731687303715884105728)) == big"-170141183460469231731687303715884105728"
end

@testset "type conversion with Signed, Unsigned" begin
    x = BigInt(typemin(Int128)) - 1
    @test x % Signed === x
    @test_throws MethodError x % Unsigned
    y = BigInt(1)
    @test y % Signed === y
    @test_throws MethodError y % Unsigned
end

@testset "conversion to Float" begin
    x = big"2"^256 + big"2"^(256-53) + 1
    @test Float64(x) == reinterpret(Float64, 0x4ff0000000000001)
    @test Float64(-x) == -Float64(x)
    x = (x >> 1) + 1
    @test Float64(x) == reinterpret(Float64, 0x4fe0000000000001)
    @test Float64(-x) == -Float64(x)

    x = big"2"^64 + big"2"^(64-24) + 1
    @test Float32(x) == reinterpret(Float32, 0x5f800001)
    @test Float32(-x) == -Float32(x)
    x = (x >> 1) + 1
    @test Float32(x) == reinterpret(Float32, 0x5f000001)
    @test Float32(-x) == -Float32(x)

    x = big"2"^15 + big"2"^(15-11) + 1
    @test Float16(x) == reinterpret(Float16, 0x7801)
    @test Float16(-x) == -Float16(x)
    x = (x >> 1) + 1
    @test Float16(x) == reinterpret(Float16, 0x7401)
    @test Float16(-x) == -Float16(x)

    for T in (Float16, Float32, Float64)
        n = exponent(floatmax(T))
        @test T(big"2"^(n+1)) === T(Inf)
        @test T(big"2"^(n+1) - big"2"^(n-precision(T))) === T(Inf)
        @test T(big"2"^(n+1) - big"2"^(n-precision(T)) - 1) === floatmax(T)
    end
end

a = Rational{BigInt}(12345678901234567890123456789, 987654321987654320)
b = Rational{BigInt}(12345678902222222212111111109, 987654321987654320)
c = Rational{BigInt}(24691357802469135780246913578, 987654321987654320)
d = Rational{BigInt}(- 12345678901234567890123456789, 493827160993827160)
e = Rational{BigInt}(12345678901234567890123456789, 12345678902222222212111111109)
@testset "big rational basics" begin
    @test a+BigInt(1) == b
    @test typeof(a+1) == Rational{BigInt}
    @test a+1 == b
    @test isequal(a+1, b)
    @test b == a+1
    @test !(b == a)
    @test b > a
    @test b >= a
    @test !(b < a)
    @test !(b <= a)

    @test typeof(a * 2) == Rational{BigInt}
    @test a*2 == c
    @test c-a == a
    @test c == a + a
    @test c+1 == a+b

    @test typeof(d) == Rational{BigInt}
    @test d == -c

    @test e == a // b

    @testset "gmp cmp" begin
        @test Base.GMP.MPQ.cmp(b, a) ==  1
        @test Base.GMP.MPQ.cmp(a, b) == -1
        @test Base.GMP.MPQ.cmp(a, a) ==  0
    end

    @testset "division errors" begin
        oz = Rational{BigInt}(0, 1)
        zo = Rational{BigInt}(1, 0)

        @test oz + oz == 3 * oz == oz
        @test oz // zo == oz
        @test zo // oz == zo

        @test_throws DivideError() zo - zo
        @test_throws DivideError() zo + (-zo)
        @test_throws DivideError() zo * oz
        @test_throws DivideError() oz // oz
        @test_throws DivideError() zo // zo
    end

    @testset "big infinities" begin
        oz   = Rational{BigInt}(1, 0)
        zo   = Rational{BigInt}(0, 1)
        o    = Rational{BigInt}(1, 1)

        @test oz + zo    == oz
        @test zo - oz    == -oz
        @test zo + (-oz) == -oz
        @test -oz + zo   == -oz

        @test (-oz) * (-oz) == oz
        @test (-oz) * oz    == -oz

        @test o // zo       == oz
        @test (-o) // zo    == -oz

        @test Rational{BigInt}(-1, 0) == -1//0
        @test Rational{BigInt}(1, 0) == 1//0
    end
end

aa = 1//2
bb = -1//3
cc = 3//2
a = Rational{BigInt}(aa)
b = Rational{BigInt}(bb)
c = Rational{BigInt}(cc)
t = Rational{BigInt}(0, 1)
@testset "big rational inplace" begin
    @test Base.GMP.MPQ.add!(t, a, b) == 1//6
    @test t == 1//6
    @test Base.GMP.MPQ.add!(t, t) == 1//3
    @test t == 1//3

    @test iszero(Base.GMP.MPQ.sub!(t, t))
    @test iszero(t)
    @test Base.GMP.MPQ.sub!(t, b, c) == -11//6
    @test t == -11//6

    @test Base.GMP.MPQ.mul!(t, a, b) == -1//6
    @test t == -1//6
    @test Base.GMP.MPQ.mul!(t, t) == 1//36
    @test t == 1//36
    @test iszero(Base.GMP.MPQ.mul!(t, Rational{BigInt}(0)))

    @test Base.GMP.MPQ.div!(t, a, b) == -3//2
    @test t == -3//2
    @test Base.GMP.MPQ.div!(t, a) == -3//1
    @test t == -3//1

    @test aa == a && bb == b && cc == c

    @testset "set" begin
        @test Base.GMP.MPQ.set!(a, b) == b
        @test a == b == bb

        Base.GMP.MPQ.add!(a, b, c)
        @test b == bb

        @test Base.GMP.MPQ.set_z!(a, BigInt(0)) == 0
        @test iszero(a)
        @test Base.GMP.MPQ.set_z!(a, BigInt(3)) == 3
        @test a == BigInt(3)

        @test Base.GMP.MPQ.set_ui(1, 2)      == 1//2
        @test Base.GMP.MPQ.set_ui(0, 1)      == 0//1
        @test Base.GMP.MPQ.set_ui!(a, 1, 2)  == 1//2
        @test a == 1//2

        @test Base.GMP.MPQ.set_si(1, 2)      == 1//2
        @test Base.GMP.MPQ.set_si(-1, 2)     == -1//2
        @test Base.GMP.MPQ.set_si!(a, -1, 2) == -1//2
        @test a == -1//2
    end

    @testset "infinities" begin
        oz   = Rational{BigInt}(1, 0)
        zo   = Rational{BigInt}(0, 1)
        oo   = Rational{BigInt}(1, 1)

        @test Base.GMP.MPQ.add!(zo, oz) == oz
        @test zo == oz
        zo = Rational{BigInt}(0, 1)

        @test Base.GMP.MPQ.sub!(zo, oz) == -oz
        @test zo == -oz
        zo = Rational{BigInt}(0, 1)

        @test Base.GMP.MPQ.add!(zo, -oz) == -oz
        @test zo == -oz
        zo = Rational{BigInt}(0, 1)

        @test Base.GMP.MPQ.sub!(zo, -oz) == oz
        @test zo == oz
        zo = Rational{BigInt}(0, 1)

        @test Base.GMP.MPQ.mul!(-oz, -oz) == oz
        @test Base.GMP.MPQ.mul!(-oz, oz)  == -oz
        @test Base.GMP.MPQ.mul!(oz, -oz)  == -1//0
        @test oz == -1//0
        oz = Rational{BigInt}(1, 0)

        @test Base.GMP.MPQ.div!(oo, zo) == oz
        @test oo == oz
        oo = Rational{BigInt}(1, 1)

        @test Base.GMP.MPQ.div!(-oo, zo) == -oz
    end
end

max_stars_repo_name: SmiteWindows/julia

max_issues_repo_name: SmiteWindows/julia

max_forks_repo_name: SmiteWindows/julia


text:
using JuMP
include("../benchmark.jl")

function max_cut_model(n::Int64,r::Int64,edge_list::Array{Tuple{Int64,Int64},1})
    #edges = [(i,i+1) for i = 1:(n-1)]
    m = Model()

    #start_mat = randn(n,r)
    #
    #for i = 1:n
    #  start_mat[i,:] = start_mat[i,:] / norm(start_mat[i,:],2)
    #end

    @variable(m, x[i=1:n,k=1:r],start=randn() / sqrt(r))
    nedges = length(edge_list)
    @NLobjective(m, Min, sum(x[i,k] * x[j,k] for k = 1:r for (i,j) in edge_list) / 2.0 - nedges / 2.0)
    for i = 1:n
      @NLconstraint(m, sum(x[i,k]^2 for k=1:r) == 1)
    end

    return m
    #
end
edge_list = Array{Tuple{Int64,Int64},1}()
n = 200
for sample = 1:(20 * n)
  edge = (rand(1:n),rand(1:n))
  if edge[1] < edge[2] && !(edge in edge_list)
    push!(edge_list,edge)
  end
end

m = max_cut_model(n,6,edge_list)

pars = Class_parameters()
#pars.aggressive_dual_threshold = 1e-4
#pars.primal_bounds_dual_feas = true
iter, status, hist, t, err = one_phase_solve(m,pars);

using Ipopt
nlp_raw = MathProgNLPModel(m);
IpoptSolve(nlp_raw)


text:
abstract type AbstractQuadraticCost <: AbstractCost end

function (cost::AbstractQuadraticCost)(x::AbstractVector, u::AbstractVector)
    @unpack Q_func, R_func = cost
    Q_func(x) + u'*R_func(x)*u
end

"""
[1, Eq. (16)]
# Refs
[1] T. Bian and Z.-P. Jiang, “Reinforcement Learning and Adaptive Optimal Control for Continuous-Time Nonlinear Systems: A Value Iteration Approach,” IEEE Trans. Neural Netw. Learning Syst., pp. 1–10, 2021, doi: 10.1109/TNNLS.2020.3045087.
"""
struct QuadraticInInputCost <: AbstractQuadraticCost
    Q_func
    R_func
end

struct QuadraticCost <: AbstractQuadraticCost
    Q::AbstractMatrix
    R::AbstractMatrix
    Q_func
    R_func
    function QuadraticCost(Q, R)
        # assert ispossemidef(Q)... something like it?
        @assert isposdef(R)
        Q_func(x) = x'*Q*x
        R_func(x) = R
        new(Q, R, Q_func, R_func)
    end
end


text:
Base.@deprecate contiguous_view ContiguousView
Base.@deprecate strided_view StridedView
Base.@deprecate unsafe_view unsafe_aview
Base.@deprecate view aview


text:
using Rotolo
using Base.Markdown

global_theme = """
	{text-align: center;padding: 5px;}
	 @media print { .slide {break-before: always;} }
	.markdown {font-size: x-large;}
	.katex {font-size: xx-large;}
	h1 {font-size: 20mm;
	    text-align: center;
			border: black;
      border-style: solid;
			background-color: lightblue;}
	"""

Rotolo.endsession()

@session Slides
# @redirect Markdown.MD HTML Katex
@redirect Markdown.MD HTML
sleep(2)

HTML("<style>$global_theme</style>")

@container slide0 class=>"slide"
md"## Himmelblau's function"
@style md"*From Wikipedia, the free encyclopedia*" style=>"font-size:x-small"

@container slide1 class=>"slide"
md"# Introduction"

md"""
	In mathematical optimization, Himmelblau's function is a multi-modal function,
	used to test the performance of optimization algorithms. The function is defined by:
	"""

@container slide2 class=>"slide"
md"# Definition"

# Katex("f(x,y)=(x^2+y-11)^2+(x+y^2-7)^2", true)


text:
# length-2 StaticVectors or 2x2 StaticMatrices of Fields or LinOps are what we
# consider "Field or Op" arrays, for which we define some special behavior
# note: these are non-concrete types to accomodate ∇ which is a custom
# StaticVector rather than an SVector (this doesn't hurt performance anywhere)
const FieldOrOpVector{F<:FieldOrOp}    = StaticVector{2,F}
const FieldOrOpMatrix{F<:FieldOrOp}    = StaticMatrix{2,2,F}
const FieldOrOpRowVector{F<:FieldOrOp} = Adjoint{<:Any,<:FieldOrOpVector{F}}
const FieldOrOpArray{F<:FieldOrOp}     = Union{FieldOrOpVector{F}, FieldOrOpMatrix{F}, FieldOrOpRowVector{F}}
# or just Fields (in this case, they are concrete)
const FieldVector{F<:Field}    = SVector{2,F}
const FieldMatrix{F<:Field}    = SMatrix{2,2,F,4}
const FieldRowVector{F<:Field} = FieldOrOpRowVector{F}
const FieldArray{F<:Field}     = FieldOrOpArray{F}

### broadcasting
# FieldArray broadcasting wins over Field and FieldTuple broadcasting, so go
# through the broadcast expression, wrap all Field and FieldTuple args in Refs,
# then forward to StaticArrayStyle broadcasting
struct FieldOrOpArrayStyle{N} <: AbstractArrayStyle{N} end
(::Type{<:FieldOrOpArrayStyle})(::Val{N}) where {N} = FieldOrOpArrayStyle{N}()
BroadcastStyle(::Type{<:FieldOrOpVector}) = FieldOrOpArrayStyle{1}()
BroadcastStyle(::Type{<:FieldOrOpMatrix}) = FieldOrOpArrayStyle{2}()
BroadcastStyle(S::FieldOrOpArrayStyle, ::FieldTupleStyle) = S
instantiate(bc::Broadcasted{<:FieldOrOpArrayStyle}) = bc
function copy(bc::Broadcasted{FieldOrOpArrayStyle{N}}) where {N}
    bc′ = convert(Broadcasted{StaticArrayStyle{N}}, map_bc_args(fieldvector_data,bc))
    materialize(bc′)
end
fieldvector_data(f::FieldOrOp) = Ref(f)
fieldvector_data(x) = x

# non-broadcasted algebra
for f in (:/, :\, :*)
    if f != :/
        @eval ($f)(A::Field, B::FieldOrOpArray) = broadcast($f, A, B)
    end
    if f != :\
        @eval ($f)(A::FieldOrOpArray, B::Field) = broadcast($f, A, B)
    end
end

# this makes Vector{Diagonal}' * Vector{Field} work right
dot(D::DiagOp{<:Field{B}}, f::Field) where {B} = conj(D.diag) .* B(f)

# needed since v .* f is not type stable
*(v::FieldOrOpVector, f::Field) = @SVector[v[1]*f, v[2]*f]
*(v::FieldOrOpVector, w::FieldOrOpRowVector) = @SMatrix[v[1]*w[1] v[1]*w[2]; v[2]*w[1] v[2]*w[2]]
*(f::Field, v::FieldOrOpVector) = @SVector[f*v[1], f*v[2]]
*(f::Field, v::FieldOrOpRowVector) = @SVector[(f*v[1])', (f*v[2])']'
*(v::FieldOrOpRowVector, w::FieldOrOpVector) = v[1]*w[1] + v[2]*w[2]

# ffs how is something this simple broken in StaticArrays...
adjoint(L::FieldOrOpMatrix) = @SMatrix[L[1,1]' L[2,1]'; L[1,2]' L[2,2]']

# eventually replace having to do this by hand with Cassette-based solution
mul!(f::Field, v::FieldOrOpRowVector{<:Diagonal}, w::FieldVector) =
    ((@. f = v[1].diag * w[1] + v[2].diag * w[2]); f)
mul!(f::Field, v::FieldOrOpRowVector{<:Diagonal}, x::Diagonal, w::FieldVector) =
    ((@. f = x.diag * (v[1].diag * w[1] + v[2].diag * w[2])); f)
mul!(v::FieldOrOpVector{<:Diagonal}, M::FieldOrOpMatrix{<:Diagonal}, w::FieldOrOpVector{<:Diagonal}) =
    ((@. v[1].diag = M[1,1].diag*w[1].diag + M[1,2].diag*w[2].diag); (@. v[2].diag = M[2,1].diag*w[1].diag + M[2,2].diag*w[2].diag); v)
mul!(v::FieldVector, M::FieldOrOpMatrix{<:Diagonal}, w::FieldVector) =
    ((@. v[1] = M[1,1].diag*w[1] + M[1,2].diag*w[2]); (@. v[2] = M[2,1].diag*w[1] + M[2,2].diag*w[2]); v)
mul!(v::FieldVector, w::FieldOrOpVector{<:Diagonal}, f::Field) =
    ((@. v[1] = w[1].diag * f); (@. v[2] = w[2].diag * f); v)
mul!(v::FieldVector, x::Diagonal, w::FieldOrOpVector{<:Diagonal}, f::Field) =
    ((@. v[1] = x.diag * w[1].diag * f); (@. v[2] = x.diag * w[2].diag * f); v)
# only thing needed for TupleAdjoints
mul!(v::FieldVector, f::TupleAdjoint, w::FieldVector) = (mul!(v[1], f, w[1]); mul!(v[2], f, w[2]); v)

function pinv!(dst::FieldOrOpMatrix, src::FieldOrOpMatrix)
    a,b,c,d = src
    det⁻¹ = pinv(@. a*d-b*c)
    @. dst[1,1] =  det⁻¹ * d
    @. dst[1,2] = -det⁻¹ * b
    @. dst[2,1] = -det⁻¹ * c
    @. dst[2,2] =  det⁻¹ * a
    dst
end

promote_rule(::Type{F}, ::Type{<:Scalar}) where {F<:Field} = F
arithmetic_closure(::F) where {F<:Field} = F


text:
# Initial conditions for thermogeostrophic balance for the thermal
# shallow water equations. Adapted for the sphere from the planar
# configuration in section 5.2 of:
#     Eldred, Dubos and Kritsikis, JCP 379, 2018

const H₀ = 5960.0
const U₀ = 20.0
const C₀ = 0.1

function uθ(θϕr)
  θ,ϕ,r = θϕr
  u = U₀*cos(ϕ)
  u
end

# Initial velocity
function u₀(xyz)
  θϕr = xyz2θϕr(xyz)
  u   = uθ(θϕr)
  spherical_to_cartesian_matrix(θϕr)⋅VectorValue(u,0,0)
end

function havg(xyz)
  -1.0*U₀*Ωₑ*xyz[3]*xyz[3]/rₑ/g + H₀
end

# Initial fluid depth
function h₀(xyz)
  θϕr   = xyz2θϕr(xyz)
  θ,ϕ,r = θϕr
  h = havg(xyz)
  Rc = π/8.0
  θc = -π/2.0 # mountain top longitude
  ϕc = +π/6.0 # mountain top latitude
  rc = sqrt((θ - θc)*(θ - θc) + (ϕ - ϕc)*(ϕ - ϕc))
  if rc < Rc
    h = h + 200.0*(1.0 - rc/Rc)
  end
  h
end

function s₀(xyz)
  #h = h₀(xyz)
  h = havg(xyz)
  s = g*(1.0 + C₀*H₀*H₀/h/h)
  s
end

function S₀(xyz)
  h = h₀(xyz)
  s = s₀(xyz)
  S = s*h
  S
end

# Topography
function topography(xyz)
  0.0
end

max_stars_repo_name: santiagobadia/GridapGeosciences

max_issues_repo_name: santiagobadia/GridapGeosciences

max_forks_repo_name: santiagobadia/GridapGeosciences


text:
"""
Assets

This package provides implementations of `Instrument` for various financial assets:

- `Cash`: which is based on a particular currency type, along with the minor unit.
- `Stock`: which represents a general common stock.

It also provides a specialized `Position` for `Cash that uses the currency's minor unit.

See README.md for the full documentation

Copyright 2019-2020, Eric Forgy, Scott P. Jones and other contributors

Licensed under MIT License, see LICENSE.md
"""
module Assets

using Currencies, FixedPointDecimals, Instruments

export Position, Currency, Cash, cash, @cash, unit, code, name
export Stock, stock, @stock

"`Cash` is an implementation of `Instrument` represented by a singleton type, with its currency symbol and the number of digits in the minor units, typically 0, 2, or 3, as parameters."
struct Cash{S, N} <: Instrument{S,Currency{S}}
    function Cash{S,N}() where {S,N}
        unit(S) === N || error("Currency minor unit does not match.")
        new{S,N}()
    end
end

function Instruments.Position(::Type{I},amt) where {S,N,I<:Cash{S,N}}
    T = FixedDecimal{Int,N}
    Position{I,T}(T(amt))
end

"Return a cash instrument type."
function cash end

cash(S::Symbol) = Cash{S,unit(S)}

cash(::Type{Currency{S}}) where {S} = cash(S)

macro cash(syms)
    args = syms isa Expr ? syms.args : [syms]
    for nam in args
        @eval __module__ const $nam = Assets.$nam
    end
end

Currencies.unit(::Type{Cash{S,N}}) where {S,N} = N

Currencies.code(::Type{C}) where {S,C<:Cash{S}} = code(S)

Currencies.name(::Type{C}) where {S,C<:Cash{S}} = name(S)

"""`Stock` is an implementation of a simple `Instrument` represented by a singleton type with a stock symbol and currency, e.g. `Stock{:MSFT,ccy"USD"}`. The currency can be omitted and it will default to USD, e.g. `Stock(:MSFT)`."""
struct Stock{S,C} <: Instrument{S,C} end

function Instruments.Position(::Type{I},amt) where {I<:Stock}
    Position{I,Int}(amt)
end

Stock(S::Symbol, C::Type{<:Currency}=Currency{:USD}) = Stock{S,C}()

stock(S::Symbol, C::Type{<:Currency}=Currency{:USD}) = Stock{S,C}

macro stock(syms)
    args = syms isa Expr ? syms.args : [syms]
    for nam in args
        @eval __module__ const $nam = typeof(Position(Assets.Stock{$(QuoteNode(nam)),Assets.Currency{:USD}},0))
    end
end

# Contruct cash position types for convenience.
for (s,(ccy,u,c,n)) in Currencies.allpairs()
    @eval const $s = typeof(Position($(cash(ccy)),0))
end

end # module Assets


text:
export AbstractSpanProcessor, CompositSpanProcessor, SimpleSpanProcessor

"""
Each span processor must implement the following methods:

  - [`on_start!(span_processor::AbstractSpanProcessor, span::AbstractSpan)`](@ref)
  - [`on_end!(span_processor::AbstractSpanProcessor, span::AbstractSpan)`](@ref)
  - [`shut_down!(span_processor::AbstractSpanProcessor)`](@ref)
  - [`force_flush!(span_processor::AbstractSpanProcessor)`](@ref)
"""
abstract type AbstractSpanProcessor end

"""
    CompositSpanProcessor(processors...)

A wrapper of different concrete span processors. Users can also `push!` new span processors into it after construction.

See also [`SimpleSpanProcessor`](@ref).
"""
struct CompositSpanProcessor <: AbstractSpanProcessor
    span_processors::Vector{Any}
    function CompositSpanProcessor(ps...)
        new([ps...])
    end
end

for f in (:on_start!, :on_end!, :shut_down!)
    @eval function $f(sp::CompositSpanProcessor, args...)
        # ??? spawn
        for p in sp.span_processors
            $f(p, args...)
        end
    end
end

function force_flush!(sp::CompositSpanProcessor, timeout_millis = 30_000)
    res = fill(false, length(sp.span_processors))
    @sync for (i, p) in enumerate(sp.span_processors)
        @async res[i] = force_flush!(p, timeout_millis)
    end
    all(res)
end

Base.push!(sp::CompositSpanProcessor, p::AbstractSpanProcessor) =
    push!(sp.span_processors, p)

Base.empty!(sp::CompositSpanProcessor) = empty!(sp.span_processors)
Base.getindex(sp::CompositSpanProcessor, args...) = getindex(sp.span_exporter, args...)
Base.setindex!(sp::CompositSpanProcessor, args...) = setindex!(sp.span_exporter, args...)

#####

"""
    SimpleSpanProcessor(span_exporter)

Export each span immediately when [`on_end!`](@ref) is called on this processor.
"""
struct SimpleSpanProcessor{T} <: AbstractSpanProcessor
    span_exporter::T
end

"""
    on_start!(ssp::SimpleSpanProcessor, span)
"""
on_start!(ssp::SimpleSpanProcessor, span) = nothing

"""
    on_end!(ssp::SimpleSpanProcessor, span)

The `span` is exported immediately if it is sampled.
"""
function on_end!(ssp::SimpleSpanProcessor, span)
    if span_context(span).trace_flag.sampled
        export!(ssp.span_exporter, [span])
    end
end

shut_down!(ssp::SimpleSpanProcessor) = shut_down!(ssp.span_exporter)

force_flush!(ssp::SimpleSpanProcessor, args...) = force_flush!(ssp.span_exporter)

#####

# TODO: BatchSpanProcessor
# https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#batching-processor


text:
####
#### Chebyshev on [-1,1]
####

export Chebyshev

"""
$(TYPEDEF)

The first `N` Chebyhev polynomials of the first kind, defined on `[-1,1]`.
"""
struct Chebyshev{K} <: FunctionBasis
    "Grid specification."
    grid_kind::K
    "The number of basis functions."
    N::Int
    @doc """
    Chebyshev polynomials (of the first kind) on ``[-1, 1]``.

    !!! note
        This is not meant to be used directly as a basis, but as a building block, eg in
        [`univariate_basis`](@ref) and [`smolyak_basis`](@ref).
    """
    function Chebyshev(grid_kind::K, N::Int) where K
        if grid_kind ≡ EndpointGrid()
            @argcheck N ≥ 2
        else
            @argcheck N ≥ 1
        end
        new{K}(grid_kind, N)
    end
end

@inline dimension(basis::Chebyshev) = basis.N

@inline domain(::Chebyshev) = (-1, 1)

function Base.show(io::IO, chebyshev::Chebyshev)
    @unpack grid_kind, N = chebyshev
    print(io, "Chebyshev polynomials (1st kind), ", grid_kind, ", dimension: ", N)
end

####
#### basis function iterator
####

struct ChebyshevIterator{T}
    x::T
    N::Int
end

Base.eltype(::Type{<:ChebyshevIterator{T}}) where {T} = T

Base.length(itr::ChebyshevIterator) = itr.N

basis_at(basis::Chebyshev, x::Real) = ChebyshevIterator(x, basis.N)

function Base.iterate(itr::ChebyshevIterator)
    @unpack x = itr
    one(x), (2, one(x), x)
end

function Base.iterate(itr::ChebyshevIterator{T}, (i, fp, fpp)) where T
    @unpack x, N = itr
    i > N && return nothing
    f = 2 * x * fp - fpp
    f::T, (i + 1, f, fp)
end

####
#### grids
####

function gridpoint(::Type{T}, basis::Chebyshev{InteriorGrid}, i::Integer) where {T <: Real}
    @unpack N = basis
    @argcheck 1 ≤ i ≤ N         # FIXME use boundscheck
    cospi((2*(N - i) + 1) / T(2 * N))
end

function gridpoint(::Type{T}, basis::Chebyshev{EndpointGrid}, i::Integer) where {T <: Real}
    @unpack N = basis
    @argcheck 1 ≤ i ≤ N         # FIXME use boundscheck
    cospi((N - i) ./ T(N - 1))
end


text:
#!/usr/bin/julia -f

import FunctionWrappers
import FunctionWrappers: FunctionWrapper
using Compat
using Compat.Test

struct CallbackF64
    f::FunctionWrapper{Float64,Tuple{Int}}
end
(cb::CallbackF64)(v) = cb.f(v)
gen_closure(x) = y->x + y

@testset "As field" begin
    f1 = @inferred CallbackF64(identity)
    f2 = @inferred CallbackF64(sin)
    f3 = @inferred CallbackF64(gen_closure(2))
    @test typeof(f1) == typeof(f2) == typeof(f3)
    @test @inferred(f1(1)) === 1.0
    @test @inferred(f2(1)) === sin(1)
    @test @inferred(f3(1)) === 3.0
end

const F64AnyFunc = FunctionWrapper{Float64,Tuple{Any}}

@testset "Any input" begin
    f1 = @inferred F64AnyFunc(identity)
    f2 = @inferred F64AnyFunc(gen_closure(2))
    @test typeof(f1) === typeof(f2)
    @test @inferred(f1(1)) === 1.0
    @test @inferred(f1(1.0)) === 1.0
    @test @inferred(f1(1f0)) === 1.0
    @test @inferred(f2(1)) === 3.0
end

const F64F64Func = FunctionWrapper{Float64,Tuple{Float64}}

@testset "Convert" begin
    f1 = @inferred F64F64Func(sin)
    f2 = @inferred F64F64Func(f1)
    f3 = @inferred convert(F64F64Func, f1)
    @test f1 === f2
    @test f1 === f3
end

const NumberAnyFunc = FunctionWrapper{Number,Tuple{Any}}

@testset "Abstract Return" begin
    @test NumberAnyFunc(sin)(1) === sin(1)
    @test NumberAnyFunc(identity)(1) === 1
end

@testset "Precompile" begin
    @test FunctionWrappers.identityAnyAny(1) === 1
end

struct SingletonType
end

@testset "Void" begin
    identityVoidVoid = FunctionWrapper{Cvoid,Tuple{Cvoid}}(identity)
    @test identityVoidVoid(nothing) === nothing
    f1 = (a, b)->b
    fIntVoidInt = FunctionWrapper{Int,Tuple{Cvoid,Int}}(f1)
    @test fIntVoidInt(nothing, 1) === 1

    # Void return type ignores actual value
    identityVoidInt = FunctionWrapper{Cvoid,Tuple{Int}}(identity)
    @test identityVoidInt(1) === nothing

    # Void return type ignores actual value
    identitySInt = FunctionWrapper{SingletonType,Tuple{Int}}(identity)
    @test_throws MethodError identitySInt(1)
end

@testset "Convert" begin
    identityIntF64 = FunctionWrapper{Int,Tuple{Float64}}(identity)
    @test identityIntF64(1.0) === 1
    @test identityIntF64(1) === 1

    identityF64Int = FunctionWrapper{Float64,Tuple{Int}}(identity)
    @test identityF64Int(1) === 1.0
    @test identityF64Int(1.0) === 1.0
end


text:
#InspectDR: Drawing Smith/polar grids with Cairo layer
#-------------------------------------------------------------------------------

#TODO: Try to collect Smith chart code in this module, if it makes sense.

#==Constants
===============================================================================#
const SMITHLABEL_OFFSET = Float64(2) #Device units from intercept

#==Types
===============================================================================#

#==Base functions
===============================================================================#
function smithlabel(v::Real)
	vint = round(Int, v)
	if vint == v
		return "$vint"
	else
		return "$v"
	end
end

function render_rcircle(ctx::CairoContext, c::DReal)
	pctr = Point2D(c / (1+c), 0)
	radius = 1 / (1+c)
	Cairo.arc(ctx, pctr.x, pctr.y, radius, 0, 2pi)
	Cairo.stroke(ctx)
end
render_rcircles(ctx::CairoContext, clist::Vector{DReal}) =
	(for c in clist; render_rcircle(ctx, c); end)

function render_xcircle(ctx::CairoContext, c::DReal)
	radius = 1/c
	Cairo.arc(ctx, 1, radius, radius, 0, 2pi)
	Cairo.stroke(ctx)
	Cairo.arc(ctx, 1, -radius, radius, 0, 2pi)
	Cairo.stroke(ctx)
end
render_xcircles(ctx::CairoContext, clist::Vector{DReal}) =
	(for c in clist; render_xcircle(ctx, c); end)

#xflip: Mirror x-direction for admittance(Y)-labels
function render_rcirclelabel(ctx::CairoContext, xf::Transform2D, pt::Point2D, xflip::Bool, lbl::String)
	xscale = xflip ? -1 : 1
	xalign = xflip ? ALIGN_LEFT : ALIGN_RIGHT
	pt = map2dev(xf, Point2D(xscale*pt.x, pt.y))
	render(ctx, lbl, Point2D(pt.x-xscale*SMITHLABEL_OFFSET, pt.y+SMITHLABEL_OFFSET),
		align=ALIGN_TOP|xalign
	)
end
function render_rcirclelabel(ctx::CairoContext, xf::Transform2D, xflip::Bool, refscale::Real, c::DReal)
	xintercept = (c-1)/(c+1)
	pt = Point2D(xintercept, 0)
	cstr = smithlabel(c*refscale)
	tstr = "$cstr"
	render_rcirclelabel(ctx, xf, pt, xflip, tstr)
end
render_rcirclelabels(ctx::CairoContext, xf::Transform2D, xflip::Bool, refscale::Real, clist::Vector{DReal}) =
	(for c in clist; render_rcirclelabel(ctx, xf, xflip, refscale::Real, c); end)

#xflip: Mirror x-direction for admittance(Y)-labels
function render_xcirclelabel(ctx::CairoContext, xf::Transform2D, pt::Point2D, xflip::Bool, lbl::String)
	xscale = xflip ? -1 : 1
	corr = -xscale*xf.xs/xf.ys #Correct for aspect ratio
	#Compute text angle:
	Θ = atan(pt.x, pt.y*corr)
	if xflip; Θ+=pi; end

	#Compute text position, including offset:
	pt = Point2D(xscale*pt.x, pt.y)
	vpos = map2dev(xf, Vector2D(pt)) #Directional vector of label position
	voffset = (SMITHLABEL_OFFSET/vecnorm(vpos))*vpos
	pt = map2dev(xf, pt)+voffset
	render(ctx, lbl, pt, angle=Θ, align=ALIGN_BOTTOM|ALIGN_HCENTER)
end
function render_xcirclelabel(ctx::CairoContext, xf::Transform2D, xflip::Bool, refscale::Real, c::DReal)
	radius = 1/c
	#Compute intercept with 0dB circle (r=1):
	y = 2*radius/(1+radius*radius)
	x = 1-y*radius

	cstr = smithlabel(c*refscale)
	tstr = "$(cstr)j"
	render_xcirclelabel(ctx, xf, Point2D(x, y), xflip, tstr)
	tstr = "-$(cstr)j"
	render_xcirclelabel(ctx, xf, Point2D(x, -y), xflip, tstr)
end
render_xcirclelabels(ctx::CairoContext, xf::Transform2D, xflip::Bool, refscale::Real, clist::Vector{DReal}) =
	(for c in clist; render_xcirclelabel(ctx, xf, xflip, refscale, c); end)

#==Extensions to base functionnality
===============================================================================#

#Split complex input data into real/imag components:
function getrealimag(d::Vector{T}) where T<:Number
	x = Array{DReal}(undef, length(d))
	y = Array{DReal}(undef, length(d))
	for i in 1:length(d)
		x[i] = convert(DReal, real(d[i]))
		y[i] = convert(DReal, imag(d[i]))
	end
	return (x, y)
end

function map2axis(input::T, x::InputXfrm1DSpec{:real}, y::InputXfrm1DSpec{:imag}) where T<:IDataset
	(x, y) = getrealimag(input.y)
	return IDataset{false}(x, y) #Assume new re/im data is not sorted.
end

#==High-level rendering functions
===============================================================================#
function render_grid(canvas::PCanvas2D, lyt::PlotLayout, grid::GridSmith)
	ctx = canvas.ctx #WANTCONST
	graphbb = canvas.graphbb #WANTCONST
	xflip = !grid.zgrid #WANTCONST Flip x-axis for admittance(Y)-grid lines

Cairo.save(ctx) #-----
	setclip(ctx, graphbb)

	#Set transform through Cairo to so it can deal with circles:
	setxfrm(ctx, canvas.xf)
	if xflip
		Cairo.scale(ctx, -1, 1)
	end
	setlinestyle(ctx, lyt.line_smithminor)
		render_rcircles(ctx, grid.minorR)
		render_xcircles(ctx, grid.minorX)
	setlinestyle(ctx, lyt.line_smithmajor)
		render_rcircles(ctx, grid.majorR)
Cairo.restore(ctx) #-----

Cairo.save(ctx) #-----
	setclip(ctx, graphbb)

	#Draw X=0 line:
	setlinestyle(ctx, lyt.line_smithminor)
	y = map2dev(canvas.xf, Point2D(0, 0)).y
	drawline(ctx::CairoContext, Point2D(graphbb.xmin, y), Point2D(graphbb.xmax, y))

	#Draw labels:
	setfont(ctx, lyt.font_ticklabel)
	render_rcirclelabels(ctx, canvas.xf, xflip, grid.ref, grid.labelR)
	render_rcirclelabel(ctx, canvas.xf, Point2D(1,0), xflip, "∞")
	render_xcirclelabels(ctx, canvas.xf, xflip, grid.ref, grid.labelX)

Cairo.restore(ctx) #-----
	nothing
end

function render_axes(canvas::PCanvas2D, lyt::PlotLayout, grid::GridSmith, xs::AxisScale, ys::AxisScale, xticklabels::Bool)
	render_graphframe(canvas, lyt.frame_data)

	#Display grid:
	#TODO: make it possible to disable?
	cgrid = coord_grid(grid, xs, ys, canvas.ext)
	render_ticks(canvas, lyt, cgrid, xs, ys, xticklabels)
end

#Last line


text:
using Resonance
using CairoMakie

etohsamples = CSV.read("data/wrangled/etohsamples.csv", DataFrame, stringtype=String)

# Note: had to delete empty "C1162_3E_1A" "M1162_3E_1A" columns from C8-pos (they were duplicated)
#
# Note: "M0855_1E_1A" missing from HILIC pos and neg

c18neg = load_metabolites("data/metabolites/21_0924_VKC_C18-neg_results.xlsx")
c8pos = load_metabolites("data/metabolites/21_0924_VKC_C8-pos_results.xlsx")
hneg = load_metabolites("data/metabolites/21_0924_VKC_HILIC-neg_results.xlsx")
hpos = load_metabolites("data/metabolites/21_0924_VKC_HILIC-pos_results.xlsx")

for df in [c18neg, c8pos, hneg, hpos]
    select!(df, Not(r"^PREF"))
end

c8pos = c8pos[:, names(c18neg)]
hneg = hneg[:, names(c18neg)]
hpos = hpos[:, names(c18neg)]

metabs = vcat(c18neg, c8pos, hneg, hpos)
metabs[!, :uid] = [join(p, "_") for p in zip(metabs.Method, metabs.Compound_ID)]
select!(metabs, :uid, Cols(:))

# rename to new sample ids
metab_samples = names(metabs)[9:end]
rename_dict = Dict((old=>new for (old, new) in zip(etohsamples.sid_old, etohsamples.sample)))
rename_dict["C1162_3E_1A"] = "FE01852" # should have been 4E
rename_dict["C1227_3E_1A"] = "FE01922" # should have been 4E
rename_dict["M0932_7E_1A"] = "FE01759" # should have been C0932

rename_dict = Dict(k => rename_dict[k] for k in keys(rename_dict) if k in metab_samples)
rename!(metabs, rename_dict)
metab_samples = names(metabs)[9:end]

metabsamplesmeta = @rsubset samplemeta begin
    !ismissing(:sample)
    :sample in metab_samples
end

metabs = metabs[:, [(1:8)..., (sortperm(names(metabs)[9:end]) .+ 8)...]]

# normalize
using Statistics

fill_vals = select(metabs, AsTable(propertynames(metabs)[9:end]) => ByRow(minimum∘skipmissing) => :fill_vals).fill_vals .÷ 2
metabs[!, 9:end] .= coalesce.(metabs[!, 9:end], fill_vals)

meds = median.(eachcol(select(metabs, names(metabs)[9:end])))
globmed = median(meds)

for i in 9:size(metabs, 2)
    metabs[!, i] ./= (meds[i-8] / globmed)
end

CSV.write("data/wrangled/metabolites.csv", metabs)

max_stars_repo_name: Klepac-Ceraj-Lab/ResonanceAnalysis

max_issues_repo_name: Klepac-Ceraj-Lab/ResonanceAnalysis

max_forks_repo_name: Klepac-Ceraj-Lab/ResonanceAnalysis


text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: redshift_data
using AWS.Compat
using AWS.UUIDs

"""
    cancel_statement(id)
    cancel_statement(id, params::Dict{String,<:Any})

Cancels a running query. To be canceled, a query must be running.

# Arguments
- `id`: The identifier of the SQL statement to cancel. This value is a universally unique
  identifier (UUID) generated by Amazon Redshift Data API. This identifier is returned by
  ExecuteStatment and ListStatements.

"""
cancel_statement(Id; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("CancelStatement", Dict{String, Any}("Id"=>Id); aws_config=aws_config)
cancel_statement(Id, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("CancelStatement", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Id"=>Id), params)); aws_config=aws_config)

"""
    describe_statement(id)
    describe_statement(id, params::Dict{String,<:Any})

Describes the details about a specific instance when a query was run by the Amazon Redshift
Data API. The information includes when the query started, when it finished, the query
status, the number of rows returned, and the SQL statement.

# Arguments
- `id`: The identifier of the SQL statement to describe. This value is a universally unique
  identifier (UUID) generated by Amazon Redshift Data API. This identifier is returned by
  ExecuteStatment and ListStatements.

"""
describe_statement(Id; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("DescribeStatement", Dict{String, Any}("Id"=>Id); aws_config=aws_config)
describe_statement(Id, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("DescribeStatement", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Id"=>Id), params)); aws_config=aws_config)

"""
    describe_table(cluster_identifier, database)
    describe_table(cluster_identifier, database, params::Dict{String,<:Any})

Describes the detailed information about a table from metadata in the cluster. The
information includes its columns. A token is returned to page through the column list.
Depending on the authorization method, use one of the following combinations of request
parameters:    AWS Secrets Manager - specify the Amazon Resource Name (ARN) of the secret
and the cluster identifier that matches the cluster in the secret.    Temporary credentials
- specify the cluster identifier, the database name, and the database user name. Permission
to call the redshift:GetClusterCredentials operation is required to use this method.

# Arguments
- `cluster_identifier`: The cluster identifier. This parameter is required when
  authenticating using either AWS Secrets Manager or temporary credentials.
- `database`: The name of the database that contains the tables to be described. If
  ConnectedDatabase is not specified, this is also the database to connect to with your
  authentication credentials.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ConnectedDatabase"`: A database name. The connected database is specified when you
  connect with your authentication credentials.
- `"DbUser"`: The database user name. This parameter is required when authenticating using
  temporary credentials.
- `"MaxResults"`: The maximum number of tables to return in the response. If more tables
  exist than fit in one response, then NextToken is returned to page through the results.
- `"NextToken"`: A value that indicates the starting point for the next set of response
  records in a subsequent request. If a value is returned in a response, you can retrieve the
  next set of records by providing this returned NextToken value in the next NextToken
  parameter and retrying the command. If the NextToken field is empty, all response records
  have been retrieved for the request.
- `"Schema"`: The schema that contains the table. If no schema is specified, then matching
  tables for all schemas are returned.
- `"SecretArn"`: The name or ARN of the secret that enables access to the database. This
  parameter is required when authenticating using AWS Secrets Manager.
- `"Table"`: The table name. If no table is specified, then all tables for all matching
  schemas are returned. If no table and no schema is specified, then all tables for all
  schemas in the database are returned
"""
describe_table(ClusterIdentifier, Database; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("DescribeTable", Dict{String, Any}("ClusterIdentifier"=>ClusterIdentifier, "Database"=>Database); aws_config=aws_config)
describe_table(ClusterIdentifier, Database, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("DescribeTable", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterIdentifier"=>ClusterIdentifier, "Database"=>Database), params)); aws_config=aws_config)

"""
    execute_statement(cluster_identifier, sql)
    execute_statement(cluster_identifier, sql, params::Dict{String,<:Any})

Runs an SQL statement, which can be data manipulation language (DML) or data definition
language (DDL). This statement must be a single SQL statement. Depending on the
authorization method, use one of the following combinations of request parameters:    AWS
Secrets Manager - specify the Amazon Resource Name (ARN) of the secret and the cluster
identifier that matches the cluster in the secret.    Temporary credentials - specify the
cluster identifier, the database name, and the database user name. Permission to call the
redshift:GetClusterCredentials operation is required to use this method.

# Arguments
- `cluster_identifier`: The cluster identifier. This parameter is required when
  authenticating using either AWS Secrets Manager or temporary credentials.
- `sql`: The SQL statement text to run.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Database"`: The name of the database. This parameter is required when authenticating
  using temporary credentials.
- `"DbUser"`: The database user name. This parameter is required when authenticating using
  temporary credentials.
- `"SecretArn"`: The name or ARN of the secret that enables access to the database. This
  parameter is required when authenticating using AWS Secrets Manager.
- `"StatementName"`: The name of the SQL statement. You can name the SQL statement when you
  create it to identify the query.
- `"WithEvent"`: A value that indicates whether to send an event to the Amazon EventBridge
  event bus after the SQL statement runs.
"""
execute_statement(ClusterIdentifier, Sql; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("ExecuteStatement", Dict{String, Any}("ClusterIdentifier"=>ClusterIdentifier, "Sql"=>Sql); aws_config=aws_config)
execute_statement(ClusterIdentifier, Sql, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("ExecuteStatement", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterIdentifier"=>ClusterIdentifier, "Sql"=>Sql), params)); aws_config=aws_config)

"""
    get_statement_result(id)
    get_statement_result(id, params::Dict{String,<:Any})

Fetches the temporarily cached result of an SQL statement. A token is returned to page
through the statement results.

# Arguments
- `id`: The identifier of the SQL statement whose results are to be fetched. This value is
  a universally unique identifier (UUID) generated by Amazon Redshift Data API. This
  identifier is returned by ExecuteStatment and ListStatements.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: A value that indicates the starting point for the next set of response
  records in a subsequent request. If a value is returned in a response, you can retrieve the
  next set of records by providing this returned NextToken value in the next NextToken
  parameter and retrying the command. If the NextToken field is empty, all response records
  have been retrieved for the request.
"""
get_statement_result(Id; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("GetStatementResult", Dict{String, Any}("Id"=>Id); aws_config=aws_config)
get_statement_result(Id, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("GetStatementResult", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Id"=>Id), params)); aws_config=aws_config)

"""
    list_databases(cluster_identifier)
    list_databases(cluster_identifier, params::Dict{String,<:Any})

List the databases in a cluster. A token is returned to page through the database list.
Depending on the authorization method, use one of the following combinations of request
parameters:    AWS Secrets Manager - specify the Amazon Resource Name (ARN) of the secret
and the cluster identifier that matches the cluster in the secret.    Temporary credentials
- specify the cluster identifier, the database name, and the database user name. Permission
to call the redshift:GetClusterCredentials operation is required to use this method.

# Arguments
- `cluster_identifier`: The cluster identifier. This parameter is required when
  authenticating using either AWS Secrets Manager or temporary credentials.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Database"`: The name of the database. This parameter is required when authenticating
  using temporary credentials.
- `"DbUser"`: The database user name. This parameter is required when authenticating using
  temporary credentials.
- `"MaxResults"`: The maximum number of databases to return in the response. If more
  databases exist than fit in one response, then NextToken is returned to page through the
  results.
- `"NextToken"`: A value that indicates the starting point for the next set of response
  records in a subsequent request. If a value is returned in a response, you can retrieve the
  next set of records by providing this returned NextToken value in the next NextToken
  parameter and retrying the command. If the NextToken field is empty, all response records
  have been retrieved for the request.
- `"SecretArn"`: The name or ARN of the secret that enables access to the database. This
  parameter is required when authenticating using AWS Secrets Manager.
"""
list_databases(ClusterIdentifier; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("ListDatabases", Dict{String, Any}("ClusterIdentifier"=>ClusterIdentifier); aws_config=aws_config)
list_databases(ClusterIdentifier, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("ListDatabases", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterIdentifier"=>ClusterIdentifier), params)); aws_config=aws_config)

"""
    list_schemas(cluster_identifier, database)
    list_schemas(cluster_identifier, database, params::Dict{String,<:Any})

Lists the schemas in a database. A token is returned to page through the schema list.
Depending on the authorization method, use one of the following combinations of request
parameters:    AWS Secrets Manager - specify the Amazon Resource Name (ARN) of the secret
and the cluster identifier that matches the cluster in the secret.    Temporary credentials
- specify the cluster identifier, the database name, and the database user name. Permission
to call the redshift:GetClusterCredentials operation is required to use this method.

# Arguments
- `cluster_identifier`: The cluster identifier. This parameter is required when
  authenticating using either AWS Secrets Manager or temporary credentials.
- `database`: The name of the database that contains the schemas to list. If
  ConnectedDatabase is not specified, this is also the database to connect to with your
  authentication credentials.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ConnectedDatabase"`: A database name. The connected database is specified when you
  connect with your authentication credentials.
- `"DbUser"`: The database user name. This parameter is required when authenticating using
  temporary credentials.
- `"MaxResults"`: The maximum number of schemas to return in the response. If more schemas
  exist than fit in one response, then NextToken is returned to page through the results.
- `"NextToken"`: A value that indicates the starting point for the next set of response
  records in a subsequent request. If a value is returned in a response, you can retrieve the
  next set of records by providing this returned NextToken value in the next NextToken
  parameter and retrying the command. If the NextToken field is empty, all response records
  have been retrieved for the request.
- `"SchemaPattern"`: A pattern to filter results by schema name. Within a schema pattern,
  \"%\" means match any substring of 0 or more characters and \"_\" means match any one
  character. Only schema name entries matching the search pattern are returned.
- `"SecretArn"`: The name or ARN of the secret that enables access to the database. This
  parameter is required when authenticating using AWS Secrets Manager.
"""
list_schemas(ClusterIdentifier, Database; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("ListSchemas", Dict{String, Any}("ClusterIdentifier"=>ClusterIdentifier, "Database"=>Database); aws_config=aws_config)
list_schemas(ClusterIdentifier, Database, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("ListSchemas", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterIdentifier"=>ClusterIdentifier, "Database"=>Database), params)); aws_config=aws_config)

"""
    list_statements()
    list_statements(params::Dict{String,<:Any})

List of SQL statements. By default, only finished statements are shown. A token is returned
to page through the statement list.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of SQL statements to return in the response. If more
  SQL statements exist than fit in one response, then NextToken is returned to page through
  the results.
- `"NextToken"`: A value that indicates the starting point for the next set of response
  records in a subsequent request. If a value is returned in a response, you can retrieve the
  next set of records by providing this returned NextToken value in the next NextToken
  parameter and retrying the command. If the NextToken field is empty, all response records
  have been retrieved for the request.
- `"RoleLevel"`: A value that filters which statements to return in the response. If true,
  all statements run by the caller's IAM role are returned. If false, only statements run by
  the caller's IAM role in the current IAM session are returned. The default is true.
- `"StatementName"`: The name of the SQL statement specified as input to ExecuteStatement
  to identify the query. You can list multiple statements by providing a prefix that matches
  the beginning of the statement name. For example, to list myStatement1, myStatement2,
  myStatement3, and so on, then provide the a value of myStatement. Data API does a
  case-sensitive match of SQL statement names to the prefix value you provide.
- `"Status"`: The status of the SQL statement to list. Status values are defined as
  follows:    ABORTED - The query run was stopped by the user.    ALL - A status value that
  includes all query statuses. This value can be used to filter results.    FAILED - The
  query run failed.    FINISHED - The query has finished running.    PICKED - The query has
  been chosen to be run.    STARTED - The query run has started.    SUBMITTED - The query was
  submitted, but not yet processed.
"""
list_statements(; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("ListStatements"; aws_config=aws_config)
list_statements(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("ListStatements", params; aws_config=aws_config)

"""
    list_tables(cluster_identifier, database)
    list_tables(cluster_identifier, database, params::Dict{String,<:Any})

List the tables in a database. If neither SchemaPattern nor TablePattern are specified,
then all tables in the database are returned. A token is returned to page through the table
list. Depending on the authorization method, use one of the following combinations of
request parameters:    AWS Secrets Manager - specify the Amazon Resource Name (ARN) of the
secret and the cluster identifier that matches the cluster in the secret.    Temporary
credentials - specify the cluster identifier, the database name, and the database user
name. Permission to call the redshift:GetClusterCredentials operation is required to use
this method.

# Arguments
- `cluster_identifier`: The cluster identifier. This parameter is required when
  authenticating using either AWS Secrets Manager or temporary credentials.
- `database`: The name of the database that contains the tables to list. If
  ConnectedDatabase is not specified, this is also the database to connect to with your
  authentication credentials.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ConnectedDatabase"`: A database name. The connected database is specified when you
  connect with your authentication credentials.
- `"DbUser"`: The database user name. This parameter is required when authenticating using
  temporary credentials.
- `"MaxResults"`: The maximum number of tables to return in the response. If more tables
  exist than fit in one response, then NextToken is returned to page through the results.
- `"NextToken"`: A value that indicates the starting point for the next set of response
  records in a subsequent request. If a value is returned in a response, you can retrieve the
  next set of records by providing this returned NextToken value in the next NextToken
  parameter and retrying the command. If the NextToken field is empty, all response records
  have been retrieved for the request.
- `"SchemaPattern"`: A pattern to filter results by schema name. Within a schema pattern,
  \"%\" means match any substring of 0 or more characters and \"_\" means match any one
  character. Only schema name entries matching the search pattern are returned. If
  SchemaPattern is not specified, then all tables that match TablePattern are returned. If
  neither SchemaPattern or TablePattern are specified, then all tables are returned.
- `"SecretArn"`: The name or ARN of the secret that enables access to the database. This
  parameter is required when authenticating using AWS Secrets Manager.
- `"TablePattern"`: A pattern to filter results by table name. Within a table pattern,
  \"%\" means match any substring of 0 or more characters and \"_\" means match any one
  character. Only table name entries matching the search pattern are returned. If
  TablePattern is not specified, then all tables that match SchemaPatternare returned. If
  neither SchemaPattern or TablePattern are specified, then all tables are returned.
"""
list_tables(ClusterIdentifier, Database; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("ListTables", Dict{String, Any}("ClusterIdentifier"=>ClusterIdentifier, "Database"=>Database); aws_config=aws_config)
list_tables(ClusterIdentifier, Database, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = redshift_data("ListTables", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterIdentifier"=>ClusterIdentifier, "Database"=>Database), params)); aws_config=aws_config)


text:
function sqlite3_finalize(stmtptr::Ptr{Void})
    @windows_only return ccall(
        (:sqlite3_finalize, sqlite3_lib),
        stdcall,
        Cint,
        (Ptr{Void}, ),
        stmtptr
    )
    @unix_only return ccall(
        (:sqlite3_finalize, sqlite3_lib),
        Cint,
        (Ptr{Void}, ),
        stmtptr
    )
end


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

# InfiniteArrays (arrays with infinite size)

# This test file is designed to exercise support for generic sizing,
# even though infinite arrays aren't implemented in Base.

module InfiniteArrays

export OneToInf, Infinity

"""
   Infinity()

represents infinite cardinality. Note that `Infinity <: Integer` to support
being treated as an index.
"""
struct Infinity <: Integer end

Base.:(==)(::Infinity, ::Int) = false
Base.:(==)(::Int, ::Infinity) = false
Base.:(<)(::Int, ::Infinity) = true
Base.:(≤)(::Int, ::Infinity) = true
Base.:(≤)(::Infinity, ::Int) = false
Base.:(≤)(::Infinity, ::Infinity) = true
Base.:(-)(::Infinity, ::Int) = Infinity()
Base.:(+)(::Infinity, ::Int) = Infinity()
Base.:(:)(::Infinity, ::Infinity) = 1:0

"""
    OneToInf(n)

Define an `AbstractInfUnitRange` that behaves like `1:∞`, with the added
distinction that the limits are guaranteed (by the type system) to
be 1 and ∞.
"""
struct OneToInf{T<:Integer} <: AbstractUnitRange{T} end

OneToInf() = OneToInf{Int}()

Base.axes(r::OneToInf) = (r,)
Base.unsafe_indices(r::OneToInf) = (r,)
Base.unsafe_length(r::OneToInf) = Infinity()
Base.size(r::OneToInf) = (Infinity(),)
Base.first(r::OneToInf{T}) where {T} = oneunit(T)
Base.length(r::OneToInf{T}) where {T} = Infinity()
Base.last(r::OneToInf{T}) where {T} = Infinity()
Base.unitrange(r::OneToInf) = r
Base.oneto(::Infinity) = OneToInf()

end

max_stars_repo_name: udesou/julia

max_issues_repo_name: zhuangchaoxi/julia

max_forks_repo_name: zhuangchaoxi/julia


text:
function camelcase(cur_string::AbstractString)
  lowercasefirst(pascalcase(cur_string))
end