text:
using Multirate
using Winston

function wgn(n::Int; power::Real=1)
    return power * (randn(n) + randn(n)im)
end

function powerspectrum( x::Vector, window::Function = blackman )
    xLen = length( x )
    xWin = x .* window( xLen )
    10*log10.(fftshift(abs2.(fft( xWin ))))
end

function channelizerplots( signal::Vector, channelizedSignals::Matrix )
    (samplesPerChannel,Nchannels) = size( channelizedSignals )
    # Create plot tables to hold original spectrum plus spectrum and signal traces of each channel
    table              = Table(3,1)
    subTable           = Table(2,Nchannels)

    # Compute the spectrum of the original signal and add it to the table
    signalSpectrum     = powerspectrum( signal )
    p                  = plot( linspace(-0.5,0.5,length(signalSpectrum)), signalSpectrum )
    setattr( p, "title", "Original Signal" )
    table[1,1]         = p
    ylim(-10,60)

    table[2,1]         = plot( indices(signal,1), real(signal), "-b", indices(signal,1), imag(signal), "-r" )

    freqs = linspace( -0.5, 0.5, samplesPerChannel )
    t     = linspace( 0, Nchannels*samplesPerChannel-1, samplesPerChannel )

    # Plot the spectrum/time-domain traces of each channel and add them to the subtable
    for channel in 1:Nchannels
        thisSignal          = channelizedSignals[:,channel]
        spectrum            = powerspectrum( thisSignal )
        sp                  = plot( freqs, spectrum ); ylim(-10,60)
        setattr( sp, "title", "Channel $channel" )
        tp                  = plot( t, real(thisSignal), "-b", t, imag(thisSignal), "-r" )
        if Nchannels > 3
            setattr( sp.y1, "ticklabels", [])
            setattr( sp.x1, "ticklabels", [])
            setattr( tp.y1, "ticklabels", [])
            setattr( tp.x1, "ticklabels", [])
        end
        subTable[1,channel] = sp
        subTable[2,channel] = tp
    end

    # Position the subtable traces below the main spectrum trace
    table[3,1] = subTable

    return table
end

function segments(n; alpha=0.5)
    s0 = 1
    n0 = n
    segs = []

    while n > 0
        s=min(n, round(Int, alpha*rand()*n0))

        if s > 0
            push!(segs, s0:s0+s-1)
            n -= s
            s0 += s
        end
    end

    return segs
end

const Th = Float64
const Tx = Complex128 # Datatype for x
const ƒs = 1.0        # Input sample rate

const Nchannels = 35
const samplesPerChannel = 85000

# Construct a linear chirp signal from ƒ = -0.5 to -0.5
const n                   = Nchannels * samplesPerChannel
const t                   = 0:n-1

const ψ = π * (t / n - 1) .* t

const signal             = exp.(Array{Tx}(ψ) * 1im / ƒs) + wgn( n, power=0.1)

# Instantiate a channelizer with Nchannels
const channelizer        = Channelizer( Th, Tx, Nchannels, 32 )

# channelizedSignals = filt( channelizer, signal )
channelizedSignals = Array{Tx}(0, Nchannels)
for segment in segments(samplesPerChannel)
    expandedSegment = (segment.start-1)*Nchannels+1 : segment.stop*Nchannels
    @printf("Channelizing segment %s as %s\n", segment, expandedSegment)
    @time channelizedSignals = [channelizedSignals; filt( channelizer, signal[expandedSegment] )]
end

# Create the table of plots
table = channelizerplots( signal, channelizedSignals )

winOpen = [true]
win = Winston.window("Channelizer Example", 1500, 1000, path -> winOpen[1] = false)
display(win, table)

while(winOpen[1])
    sleep(0.1)
end


text:
push!(LOAD_PATH, ".")

module BinaryIndividual

include("utility.jl")

using IntegerIndividual

abstract type AbstractBinaryIndividual <: IntegerIndividual.AbstractIntegerIndividual{Int64} end

GeneType = Int64

@define BinaryIndividual begin
  BinaryIndividual.IntegerIndividual.@IntegerIndividual
end

struct BinaryIndividualType <: AbstractBinaryIndividual
  @BinaryIndividual

  function BinaryIndividualType(x...)
    args = build(x...)
    new(args[1], args[2], args[3])
  end
end

function build(ng::Integer)
  return IntegerIndividual.build(ng, fill((0, 1), ng))
end

function build(ind::AbstractBinaryIndividual)
  return IntegerIndividual.build(ind)
end

end

ext: jl

max_stars_repo_name: Markhyz/Julia-Genetic-Algorithm

max_issues_repo_name: Markhyz/Julia-Genetic-Algorithm

max_forks_repo_name: Markhyz/Julia-Genetic-Algorithm


text:
using JSON
using Glob

raw_ec_records = [JSON.parsefile(a) for a in ARGS]

# 3x3 arrays of counts, 2 symbols, 4 levels
ec_stats = zeros(9, 2, 4)

for frames in raw_ec_records
    for frame in frames
        key_levels = ["mvf-l1" => 1, "mvf-l2" => 2, "mvf-l3" => 3, "mvf-l4" => 4]
        for key in keys(key_levels)
            if haskey(frame, key)
                for r in frame[key]
                    sym = r[1] + 1
                    ctx = r[3] + 1
                    ec_stats[ctx, sym, key_levels[key]] += 1
                end
            end
        end
    end
end

for level in 1:4
    totals = ec_stats[:,1,level] .+ ec_stats[:,2,level]
    totals[find(isnan,totals)] = 0.0
    probs = ec_stats[:,1,level] ./ totals
    probs[find(isnan,probs)] = 0.0
    probs = int(round(probs * 32768))
    println("LEVEL $level:")
    println("Probabilties:")
    println(probs)
    println("Totals:")
    println(totals)
    println()
end

max_stars_repo_name: junaidnaseer/daala

max_issues_repo_name: junaidnaseer/daala

max_forks_repo_name: junaidnaseer/daala


text:
function show(io::IO, x::DoubleFloat{T}) where {T<:IEEEFloat}
    str = string(x)
    print(io, str)
end

function show(io::IO, x::DoubleFloat{DoubleFloat{T}}) where {T<:IEEEFloat}
    str = string(x)
    print(io, str)
end

function showtyped(io::IO, x::DoubleFloat{T}) where {T<:IEEEFloat}
    str = stringtyped(x)
    print(io, str)
end

function showtyped(io::IO, x::DoubleFloat{DoubleFloat{T}}) where {T<:IEEEFloat}
    str = stringtyped(x)
    print(io, str)
end

function showtyped(x::DoubleFloat{T}) where {T<:IEEEFloat}
    str = stringtyped(x)
    print(str)
end

function showtyped(x::DoubleFloat{DoubleFloat{T}}) where {T<:IEEEFloat}
    str = stringtyped(x)
    print(str)
end


text:
import Pkg

if VERSION >= v"1.5-" && !isdir(joinpath(DEPOT_PATH[1], "registries", "General"))
    Pkg.Registry.add("General")
end


text:
@testset " Analog forecasting " begin

    import AnalogDataAssimilation: normalise!, sample_discrete
    import DifferentialEquations: ODEProblem, solve

    n = 10
    M = rand(n, 3)

    normalise!(M)

    @test sum(M) ≈ 1.0

    x = range(0, stop = 2π, length = 10) |> collect
    x .= sin.(x)
    normalise!(x)

    σ = 10.0
    ρ = 28.0
    β = 8.0 / 3

    dt_integration = 0.01
    dt_states = 1
    dt_obs = 8
    parameters = [σ, ρ, β]
    var_obs = [1]
    nb_loop_train = 10^2
    nb_loop_test = 10
    sigma2_catalog = 0.0
    sigma2_obs = 2.0

    ssm = StateSpaceModel(
        lorenz63,
        dt_integration,
        dt_states,
        dt_obs,
        parameters,
        var_obs,
        nb_loop_train,
        nb_loop_test,
        sigma2_catalog,
        sigma2_obs,
    )

    # compute u0 to be in the attractor space
    u0 = [8.0; 0.0; 30.0]
    tspan = (0.0, 5.0)
    prob = ODEProblem(ssm.model, u0, tspan, parameters)
    u0 = last(solve(prob, reltol = 1e-6, save_everystep = false))

    xt, yo, catalog = generate_data(ssm, u0)

    results = []
    for regression in [:local_linear, :locally_constant, :increment]
        for sampling in [:gaussian, :multinomial]
            f = AnalogForecasting(
                50,
                xt,
                catalog;
                regression = regression,
                sampling = sampling,
            )
            for method in [AnEnKS(100), AnEnKF(100), AnPF(100)]
                println(" $regression, $sampling, $method ")
                DA = DataAssimilation(f, xt, ssm.sigma2_obs)
                time = @elapsed x̂ = forecast(DA, yo, method, progress = false)
                rmse = RMSE(xt, x̂)
                push!(
                    results,
                    (
                        regression,
                        sampling,
                        method,
                        round(rmse, digits = 3),
                        round(time, digits = 1),
                    ),
                )
                @test rmse < 2.0
            end
        end
    end

    println()
    for column in ["REGRESSION", "SAMPLING", "METHOD", "RMSE", "TIME"]
        print(rpad(column, 20, " "))
    end
    println()
    for res in sort(results, by = v -> v[4])

        for r in res
            print(rpad(r, 20, " "))
        end
        println()

    end

end


text:
using SpectralLearning
using Documenter

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

makedocs(;
    modules=[SpectralLearning],
    authors="Cédric Simal, University of Namur",
    repo="https://github.com/csimal/SpectralLearning.jl/blob/{commit}{path}#{line}",
    sitename="SpectralLearning.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://csimal.github.io/SpectralLearning.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
    ],
)

deploydocs(;
    repo="github.com/csimal/SpectralLearning.jl",
    devbranch="main",
)


text:
"""
    vortices = findvortices(ψ<:Field)

Locate vortices as `2π` phase windings around plaquettes on a cartesian spatial grid.

Requires a 2D wavefunction `ψ(x,y)` on a cartesian grid specified by vectors `x`, `y`.

`vortices` - array of vortex coordinates `x,y` and charges `q`.

Each row is of the form `[x, y, cv]`, and the array is sorted into lexical order
according to the vortex `x` coordinates.
"""
function findvortices(psi::Field;periodic=false)
    @unpack ψ,x,y = psi
    vort = findvortices_grid(psi)
    if !periodic
        vort = remove_vortices_edge(vort,psi)
    end

    for (j,vortex) in enumerate(vort)
        v = try
        psi_int,xint,yint = zoom_interp(ψ,x,y,vortex.xv,vortex.yv,periodic=periodic) #periodic: peridic indices here
        v1 = findvortices_grid(Torus(psi_int,xint,yint))
        vint = remove_vortices_edge(v1,Torus(psi_int,xint,yint))[1]
        psi_int,xint,yint = zoom_interp(psi_int,xint,yint,vint.xv,vint.yv)
        v1 = findvortices_grid(Torus(psi_int,xint,yint))
        vint = remove_vortices_edge(v1,Torus(psi_int,xint,yint))[1]
        catch nothing
        end
        v != nothing && (vort[j] = v)    # NOTE fallback to grid if zoom fails
    end
    if periodic
        Lx,Ly = last(x)-first(x),last(y)-first(y)
        vdat = vortex_array(vort)
        xx,yy,qq = vdat[:,1],vdat[:,2],vdat[:,3]
        @. xx[xx>Lx/2] -= Lx
        @. xx[xx<-Lx/2] += Lx
        @. yy[yy>Ly/2] -= Ly
        @. yy[yy<-Lx/2] += Ly
        vort = PointVortex.(xx,yy,qq)
    end
    return vort
end

#TODO add tests for periodic

function findvortices_grid(psi::Torus;shift=true)
    vort = findvortices_jumps(psi,shift=shift)
    varray = vortex_array(vort)
    vort = sortslices(varray,dims=1)
    return PointVortex(vort)
end

function findvortices_grid(psi::Sphere;shift=true)
    @unpack ψ = psi
    windvals = phase_jumps(angle.(ψ),2)
    vort = findvortices_jumps(psi,shift=shift)
    rawvort = vortex_array(vort)

    # North pole winding. - sign means polar vortex co-rotating with w > 0
    w1 = sum(windvals[1,:])
    (sign(w1) != 0) && (rawvort = [rawvort; 0.0 0.0 -w1])
    # South pole winding. + sign means co-rotating with w > 0
    w2 = sum(windvals[end,:])
    (sign(w2) != 0) && (rawvort = [rawvort; pi 0.0 w2])

    vort = sortslices(vort,dims=1)
    return PointVortex(vort)
end

"""
    psiz,xz,yz = zoom(psi,x,y,xv,yv,win=1)

Zoom in near (xv,yv) with a window `win=1`, which gives a 4x4 local grid.
"""
function zoom_grid(psi,x,y,xv,yv;win=1,periodic=false)
    dx,dy = Δ(x),Δ(y)
    nx,ny = size(psi)
    ix = isapprox.(x,xv,atol=dx) |> findfirst
    iy = isapprox.(y,yv,atol=dy) |> findfirst
    ixw = (ix-win):(ix+win+1)
    iyw = (iy-win):(iy+win+1)
    if !periodic
        psiz,xz,yz = psi[ixw,iyw],x[ixw],y[iyw]
    else
        ixp,iyp = mod1.(ixw,nx),mod1.(iyw,ny) # periodic indices
        psiz = psi[ixp,iyp]
        xz = (x[ix]-win*dx):dx:(x[ix]+(win+1)*dx) # local x vector
        yz = (y[iy]-win*dy):dy:(y[iy]+(win+1)*dy) # local y vector
    end
    return psiz,xz,yz
end

"""
    psiz,xz,yz = zoom_interp(psi,x,y,xv,yv,win=1,nz=30)

Zoom in near (xv,yv) with a window `win=1`, which gives a 4x4 local grid.
The wavefunction psi is interpolated onto a 30x30 domain inside the local box.
"""
function zoom_interp(psi,x,y,xv,yv;win=1,nz=30,periodic=false)
    psiz, xz, yz = zoom_grid(psi,x,y,xv,yv,win=win,periodic=periodic)
    psi_itp = interpolate((xz,yz), psiz, Gridded(Linear()))
    xint,yint = LinRange(xz[1],xz[end],nz),LinRange(yz[1],yz[end],nz)
    psi_int = psi_itp(xint,yint)
    return psi_int,xint,yint
end

function findvortices_jumps(psi::Field;shift=true)
    @unpack x,y,ψ = psi
    phase = angle.(ψ)

    # Nearest neighbour phase jumps
    diffx,diffy = phase_jumps(phase,1),phase_jumps(phase,2)

    # Plaquette loop integrals with in-place memory recycling
    circshift!(phase,diffx,(0,1))
    diffx .-= phase; diffx .-= diffy
    circshift!(phase,diffy,(1,0))
    diffx .+= phase

    # Windings
    ixp,iyp,vp = find_where(diffx .> 0.0)
    xp = x[ixp]; yp = y[iyp]; np = length(vp)
    ixn,iyn,vn = find_where(diffx .< 0.0)
    xn = x[ixn]; yn = y[iyn]; nn = length(vn)

    if shift
        dx,dy = Δ(x),Δ(y)
        xp .-= dx/2; yp .-= dy/2; xn .-= dx/2; yn .-= dy/2
    end

    vortices = [xn yn -vn; xp yp vp]

    return PointVortex(vortices)
end

@doc raw"""
    circ_mask(x,y,R)

Return boolean `true` when $\sqrt{x^2+y^2}\leq R$, otherwise return `false`. Default supplied to `keep_vortices`, which allows a user supplied mask that returns a boolean.

See also: [`keep_vortices`](@ref)
"""
circ_mask(x,y,R) = hypot(x,y)<=R

@doc raw"""
    vortm = keep_vortices(vort,mask)

Return vortices in `vort` specified by where `mask(x,y)` is `true`. The default (circular) mask returns `true` when $\sqrt{x^2+y^2}\leq R$. User can supply any mask that returns boolean values.

For the default (circular) mask, set the radius as

`vortm = keep_vortices(vort,(x,y)->circ_mask(x,y,R))`.

Specify a boolean mask using

`vortm = keep_vortices(vort,(x,y)->mymask(x,y,args...)`.

See also: [`circ_mask`](@ref)
"""
function keep_vortices(vort,mask=(x,y)->circ_mask(x,y,1.0))
    vortm = PointVortex[]
    for v in vort
        x,y = pos(v)
        if mask(x,y)
            push!(vortm,v)
        end
    end
    return vortm
end


text:
using CUDA.CUSPARSE
using LinearAlgebra, SparseArrays

@testset "LinearAlgebra" begin
    @testset "$f(A)±$h(B) $elty" for elty in [Float32, Float64, ComplexF32, ComplexF64],
                                     f in (identity, transpose), #adjoint),
                                     h in (identity, transpose)#, adjoint)
        # adjoint need the support of broadcast for `conj()` to work with `CuSparseMatrix`.
        n = 10
        alpha = rand()
        beta = rand()
        A = sprand(elty, n, n, rand())
        B = sprand(elty, n, n, rand())

        dA = CuSparseMatrixCSR(A)
        dB = CuSparseMatrixCSR(B)

        C = f(A) + h(B)
        dC = f(dA) + h(dB)
        @test C ≈ collect(dC)

        C = f(A) - h(B)
        dC = f(dA) - h(dB)
        @test C ≈ collect(dC)
    end

    @testset "A±$f(B) $elty" for elty in [Float32, Float64, ComplexF32, ComplexF64],
                                 f in (CuSparseMatrixCSR, CuSparseMatrixCSC, x->CuSparseMatrixBSR(x,1))
        n = 10
        A = sprand(elty, n, n, rand())
        B = sprand(elty, n, n, rand())

        dA = CuSparseMatrixCSR(A)
        dB = CuSparseMatrixCSR(B)

        C = A + B
        dC = dA + f(dB)
        @test C ≈ collect(dC)

        C = B + A
        dC = f(dB) + dA
        @test C ≈ collect(dC)

        C = A - B
        dC = dA - f(dB)
        @test C ≈ collect(dC)

        C = B - A
        dC = f(dB) - dA
        @test C ≈ collect(dC)
    end

    @testset "dense(A)$(op)sparse(B) $elty" for elty in [Float32, Float64, ComplexF32, ComplexF64],
                                                op in [+, -]
        n = 10
        A = rand(elty, n, n)
        B = sprand(elty, n, n, rand())

        dA = CuArray(A)
        dB = CuSparseMatrixCSR(B)

        C = op(A, B)
        dC = op(dA, dB)
        @test C ≈ collect(dC)
        @test dC isa CuMatrix{elty}

        C = op(B, A)
        dC = op(dB, dA)
        @test C ≈ collect(dC)
        @test dC isa CuMatrix{elty}
    end

    @testset "$f(A)*b $elty" for elty in [Float32, Float64, ComplexF32, ComplexF64],
                                 f in (identity, transpose, adjoint)
        n = 10
        alpha = rand()
        beta = rand()
        A = sprand(elty, n, n, rand())
        b = rand(elty, n)
        c = rand(elty, n)
        alpha = beta = 1.0
        c = zeros(elty, n)

        dA = CuSparseMatrixCSR(A)
        db = CuArray(b)
        dc = CuArray(c)

        # test with empty inputs
        @test Array(dA * CUDA.zeros(elty, n, 0)) == zeros(elty, n, 0)

        mul!(c, f(A), b, alpha, beta)
        mul!(dc, f(dA), db, alpha, beta)
        @test c ≈ collect(dc)

        A = A + transpose(A)
        dA = CuSparseMatrixCSR(A)

        @assert issymmetric(A)
        mul!(c, f(Symmetric(A)), b, alpha, beta)
        mul!(dc, f(Symmetric(dA)), db, alpha, beta)
        @test c ≈ collect(dc)
    end

    @testset "$f(A)*$h(B) $elty" for elty in [Float32, Float64, ComplexF32, ComplexF64],
                                     f in (identity, transpose, adjoint),
                                     h in (identity, transpose, adjoint)
        if CUSPARSE.version() <= v"10.3.1" &&
            (h ∈ (transpose, adjoint) && f != identity) ||
            (h == adjoint && elty <: Complex)
            # These combinations are not implemented in CUDA10
            continue
        end

        n = 10
        alpha = rand()
        beta = rand()
        A = sprand(elty, n, n, rand())
        B = rand(elty, n, n)
        C = rand(elty, n, n)

        dA = CuSparseMatrixCSR(A)
        dB = CuArray(B)
        dC = CuArray(C)

        mul!(C, f(A), h(B), alpha, beta)
        mul!(dC, f(dA), h(dB), alpha, beta)
        @test C ≈ collect(dC)

        A = A + transpose(A)
        dA = CuSparseMatrixCSR(A)

        @assert issymmetric(A)
        mul!(C, f(Symmetric(A)), h(B), alpha, beta)
        mul!(dC, f(Symmetric(dA)), h(dB), alpha, beta)
        @test C ≈ collect(dC)
    end

    @testset "dense(A)*sparse(B) $elty" for elty in [Float32, Float64, ComplexF32, ComplexF64]
        n = 10
        A = rand(elty, n, n)
        B = sprand(elty, n, n, rand())

        dA = CuArray(A)
        dB = CUSPARSE.CuSparseMatrixCSR(B)

        C = A * B
        dC = dA * dB
        @test C ≈ collect(dC)
        @test dC isa CuMatrix{elty}

        C = B * A
        dC = dB * dA
        @test C ≈ collect(dC)
        @test dC isa CuMatrix{elty}

        C = B * B
        dC = dB * dB
        @test C ≈ collect(dC)
        @test dC isa CuMatrix{elty}
    end

    @testset "issue #1095 ($elty)" for elty in [Float32, Float64, ComplexF32, ComplexF64]
        # Test non-square matrices
        n, m, p = 10, 20, 4
        alpha = rand()
        beta = rand()
        A = sprand(elty, n, m, rand())
        B = rand(elty, m, p)
        C = rand(elty, n, p)

        dA = CuSparseMatrixCSR(A)
        dB = CuArray(B)
        dC = CuArray(C)

        mul!(C, A, B, alpha, beta)
        mul!(dC, dA, dB, alpha, beta)
        @test C ≈ collect(dC)

        mul!(B, transpose(A), C, alpha, beta)
        mul!(dB, transpose(dA), dC, alpha, beta)
        @test B ≈ collect(dB)

        mul!(B, adjoint(A), C, alpha, beta)
        mul!(dB, adjoint(dA), dC, alpha, beta)
        @test B ≈ collect(dB)
    end

    @testset "CuSparseMatrixCSR($f) $elty" for f in [transpose, adjoint], elty in [Float32, ComplexF32]
        S = f(sprand(elty, 10, 10, 0.1))
        @test SparseMatrixCSC(CuSparseMatrixCSR(S)) ≈ S

        S = sprand(elty, 10, 10, 0.1)
        T = f(CuSparseMatrixCSR(S))
        @test SparseMatrixCSC(CuSparseMatrixCSC(T)) ≈ f(S)

        S = sprand(elty, 10, 10, 0.1)
        T = f(CuSparseMatrixCSC(S))
        @test SparseMatrixCSC(CuSparseMatrixCSR(T)) ≈ f(S)
    end
end


text:
module VariableCellShapeMolecularDynamics

include("Geometry.jl")
include("Force.jl")
include("Integrators.jl")
include("Thermostats.jl")

end # module


text:
function _linear_interpolation(n, x, y, xᵢ)
    i = 0
    if xᵢ >= x[n-1]
        i = n - 1
    else
        while xᵢ > x[i+1]
            i += 1
        end
    end
    m = (y[i+1] - y[i]) / (x[i+1] - x[i])
    return y[i] + m * (xᵢ - x[i])
end


text:
using VertexEliminationOrders
using Test

import LightGraphs as lg

import VertexEliminationOrders as VEO

@testset "VertexEliminationOrders.jl" begin
    # Test the graph io.
    g = graph_from_gr("../examples/test.gr")
    @test lg.nv(g) == 27
    @test lg.ne(g) == 36
end

include("graph_tests.jl")
include("heuristic_tests.jl")
include("branch_and_bound_tests.jl")


text:
struct NoMoreFilesError <: Exception end
Base.showerror(io::IO, e::NoMoreFilesError) = print(io, "No more block files")

struct MagicBytesError <: Exception
    bytes :: UInt32
end
Base.showerror(io::IO, e::MagicBytesError) =
    print(io, "Wrong Magic Bytes: ", string(e.bytes, base = 16))


text:
using Discord,Logging,Dates
import Pkg
discv=string(Pkg.installed()["Discord"])
jlv=VERSION
token=ENV["DISCORD_TOKEN"]
cl=Client(token; presence=(game=(name=string("Julia $(jlv) Discord.jl $(discv)"), type=AT_GAME),status="dnd"),prefix="jl.")
hid=convert(UInt64,parse(Int,ENV["HID"]))
module Sandbox end
function codeblock(val)
s = val === nothing ? "nothing" : string(val)
return "```julia\n$s\n```"
end
function parsecode(code::AbstractString)
return try
Meta.parse("begin $code end")
catch e
:(sprint(showerror, $e))
end
end
function eval_codeblock(c::Client, msg::Message, code::Expr)
if msg.author.id!=hid
return
end
result = try
@eval Sandbox $code
catch e
sprint(showerror, e)
end
reply(c, msg, codeblock(result))
end
function cmd(msg::Message,l::Array{String},op::Bool=false)
if op && msg.author.id!=hid
return false
end
for pfx in l
if occursin(pfx,lowercase(msg.content))
return true
end
end
return false
end
function log(s)
write(stdout,string(s,"\n"))
flush(stdout)
end
function msghandler(cl::Client, e::MessageCreate)
heartbeat_ping(cl)
if e.message.author.id==me(cl).id
return
end
if cmd(e.message,["all.tst","jl.tst"])
reply(cl,e.message,"I'm up!")
end
if cmd(e.message,["jl.ping"])
reply(cl,e.message,"Pong!")
end
if cmd(e.message,["jl.pong"])
reply(cl,e.message,"Ping!")
end
if cmd(e.message,["jl.stop","all.stop","jl.close"],true)
reply(cl,e.message,"Goodbye!")
close(cl)
end
if cmd(e.message,["jl.ver","jl.vers","all.ver","all.vers"])
reply(cl,e.message,"```\nJulia Version:                    $(jlv)\nDiscord.jl Version:               $(discv)\n```")
end
if cmd(e.message,["jl.lat","all.lat"])
global lat=heartbeat_ping(cl)
while lat==Nothing()
global lat=heartbeat_ping(cl)
end
global lat=string(Dates.value(lat))
global startlat
reply(cl,e.message,"```\nDiscord.jl Latency Now:      $(lat)\nDiscord.jl Latency On Boot:  $(startlat)\n```")
end
if cmd(e.message,["jl.token","all.token"],true)
reply(cl,e.message,":white_check_mark: Check your DMs! :white_check_mark:")
dm=fetchval(create_dm(cl;recipient_id=hid))
create(cl,Message,dm; content="Here is the token you requested!\n```\n$(token)\n```")
log("$(e.message.author.username)#$(e.message.author.discriminator)<@!$(e.message.author.id)> requested this bot's token and it was sent to them")
end
if cmd(e.message,["jl.token","all.token"],false)&&e.message.author.id!=hid
reply(cl,e.message,":x: You don't have the required permission. This incident has been logged. :x:")
log("$(e.message.author.username)#$(e.message.author.discriminator)<@!$(e.message.author.id)}> requested this bot's token and it was not sent to them because they did not have the required permission")
end
end
function readyhandler(cl::Client, e::Ready)
global startlat=heartbeat_ping(cl)
global tries=0
while startlat==Nothing()
global tries+=1
if tries==50
global startlat=Dates.Millisecond(50)
break
end
global startlat=heartbeat_ping(cl)
end
global startlat=string(Dates.value(startlat))
global clusr=me(cl)
log(string("We have logged in as ",clusr.username,"#",clusr.discriminator,"<@!",clusr.id,">"))
end
add_command!(cl, :eval, eval_codeblock;parsers=[parsecode], pattern=r"^eval ```(?:julia)?\n(.*)\n```")
add_handler!(cl,MessageCreate,msghandler)
add_handler!(cl,Ready,readyhandler)
open(cl)
wait(cl)


text:
using MultivariateStats
using LinearAlgebra
using Test
using StableRNGs
import Statistics: mean, cov, var

@testset "Factor Analysis" begin

    rng = StableRNG(34568)

    ## FA with zero mean

    X = randn(rng, 5, 10)
    Y = randn(rng, 3, 10)

    W = qr(randn(rng, 5, 5)).Q[:, 1:3]
    Ψ = fill(0.1, 5)
    M = FactorAnalysis(Float64[], W, Ψ)

    @test size(M) == (5, 3)
    @test mean(M) == zeros(5)
    @test loadings(M) == W
    @test var(M) == Ψ

    T = inv(I+W'*diagm(0 => 1 ./ var(M))*W)*W'*diagm(0 => 1 ./ var(M))
    @test predict(M, X[:,1]) ≈ T * X[:,1]
    @test predict(M, X) ≈ T * X

    R = cov(M)*W*inv(W'W)
    @test reconstruct(M, Y[:,1]) ≈ R * Y[:,1]
    @test reconstruct(M, Y) ≈ R * Y

    ## PCA with non-zero mean

    mval = rand(rng, 5)
    M = FactorAnalysis(mval, W, Ψ)

    @test size(M) == (5, 3)
    @test mean(M) == mval
    @test loadings(M) == W
    @test var(M) == Ψ

    @test predict(M, X[:,1]) ≈ T * (X[:,1] .- mval)
    @test predict(M, X) ≈ T * (X .- mval)

    @test reconstruct(M, Y[:,1]) ≈ R * Y[:,1] .+ mval
    @test reconstruct(M, Y) ≈ R * Y .+ mval

    ## prepare training data

    d = 5
    n = 1000

    R = collect(qr(randn(rng, d, d)).Q)
    @test R'R ≈ Matrix(I, 5, 5)
    rmul!(R, Diagonal(sqrt.([0.5, 0.3, 0.1, 0.05, 0.05])))

    X = R'randn(rng, 5, n) .+ randn(rng, 5)
    mval = vec(mean(X, dims=2))
    Z = X .- mval

    # facm (default) & faem
    fa_methods = [:cm, :em]

    fas = FactorAnalysis[]
    for method in fa_methods
        let M = fit(FactorAnalysis, X, method=method, maxiter=5000),
            P = projection(M),
            W = loadings(M)
        push!(fas,M)

        @test size(M) == (5, 4)
        @test mean(M) == mval
        @test P'P ≈ Matrix(I, 4, 4)
        @test all(isapprox.(cov(M), cov(X, dims=2), atol=1e-3))

        M = fit(FactorAnalysis, X; mean=mval, method=method)
        @test loadings(M) ≈ W

        M = fit(FactorAnalysis, Z; mean=0, method=method)
        @test loadings(M) ≈ W

        M = fit(FactorAnalysis, X; maxoutdim=3, method=method)
        P = projection(M)

        @test size(M) == (5, 3)
        @test P'P ≈ Matrix(I, 3, 3)
        end
    end

    # compare two algorithms
    M1, M2 = fas
    @test all(isapprox.(cov(M1), cov(M2), atol=1e-3)) # noise
    LL(m, x) = (-size(x,2)/2)*(size(x,1)*log(2π) + log(det(cov(m))) + tr(inv(cov(m))*cov(x, dims=2)))
    @test LL(M1, X) ≈ LL(M2, X) # log likelihood

    # test with different types
    XX = convert.(Float32, X)
    YY = convert.(Float32, Y)

    for method in (:cm, :em)
        MM = fit(FactorAnalysis, XX; method=method, maxoutdim=3)

        # mixing types
        predict(M, XX)
        predict(MM, X)
        reconstruct(M, YY)
        reconstruct(MM, Y)

        # type stability
        for func in (mean, projection, cov, var, loadings)
            @test eltype(func(M)) == Float64
            @test eltype(func(MM)) == Float32
        end
    end

    # views
    M = fit(FactorAnalysis, view(XX, :, 1:100), method=:cm, maxoutdim=3)
    M = fit(FactorAnalysis, view(XX, :, 1:100), method=:em, maxoutdim=3)
end


text:
module Dynstack

# using/import
using ZMQ

const _ProtoBuf_Top_ = @static isdefined(parentmodule(@__MODULE__), :_ProtoBuf_Top_) ? (parentmodule(@__MODULE__))._ProtoBuf_Top_ : parentmodule(@__MODULE__)

# includes
include("hotstorage.jl")
include("rollingmill.jl")
include("stacking.jl")

end


text:
function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
    Base.precompile(Tuple{Core.kwftype(typeof(CSV.Type)),NamedTuple{(:debug,),Tuple{Bool}},Type{CSV.File},CSV.Header{false,Parsers.Options{false,false,true,false,Missing,UInt8,Nothing},Array{UInt8,1}}})
    Base.precompile(Tuple{Type{CSV.File},String})
    Base.precompile(Tuple{Type{CSV.Header{false,Parsers.Options{false,false,true,false,Missing,UInt8,Nothing},Array{UInt8,1}}},String,Array{Symbol,1},Int64,Int64,UInt8,Array{UInt8,1},Int64,Int64,Int64,Parsers.Options{false,false,true,false,Missing,UInt8,Nothing},Nothing,Array{Int64,1},Array{Type,1},Array{UInt8,1},Array{Int64,1},Float64,Bool,Type{T} where T})
    Base.precompile(Tuple{typeof(CSV.detectcolumnnames),Array{UInt8,1},Int64,Int64,Int64,Parsers.Options{false,false,true,false,Missing,UInt8,Nothing},Int64,Bool})
    Base.precompile(Tuple{typeof(CSV.makechain),Type{Array{Union{Missing, Bool},1}},Array{Union{Missing, Bool},1},Int64,Int64,Array{Array{AbstractArray{T,1} where T,1},1},Int64})
    Base.precompile(Tuple{typeof(CSV.multithreadparse),Array{Type,1},Array{UInt8,1},Array{UInt8,1},Int64,Int64,Parsers.Options{false,false,true,false,Missing,UInt8,Nothing},Nothing,Int64,Int64,Float64,Array{CSV.RefPool,1},Int64,Dict{Type,Type},Bool,Type{T} where T,Int64,Int64,Bool})
    Base.precompile(Tuple{typeof(CSV.parsefilechunk!),Val{false},Int64,Dict{Type,Type},Array{AbstractArray{T,1} where T,1},Array{UInt8,1},Int64,Int64,Int64,Array{Int64,1},Float64,Array{CSV.RefPool,1},Int64,Int64,Array{Type,1},Array{UInt8,1},Bool,Parsers.Options{false,false,true,false,Missing,UInt8,Nothing},Nothing,Type{Tuple{}},Int})
    Base.precompile(Tuple{typeof(CSV.promote_types),Any,Any})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,Array{Union{Missing, Bool},1}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,ChainedVector{Union{Missing, Bool},Array{Union{Missing, Bool},1}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,PooledArrays.PooledArray{Union{Missing, String},UInt32,1,Array{UInt32,1}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,PooledArrays.PooledArray{Union{Missing, String},UInt32,1,ChainedVector{UInt32,Array{UInt32,1}}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{Dates.Date,1,Dates.Date,Missing,Array{Dates.Date,1}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{Dates.Date,1,Dates.Date,Missing,ChainedVector{Dates.Date,Array{Dates.Date,1}}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{Dates.DateTime,1,Dates.DateTime,Missing,Array{Dates.DateTime,1}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{Dates.DateTime,1,Dates.DateTime,Missing,ChainedVector{Dates.DateTime,Array{Dates.DateTime,1}}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{Dates.Time,1,Dates.Time,Missing,Array{Dates.Time,1}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{Dates.Time,1,Dates.Time,Missing,ChainedVector{Dates.Time,Array{Dates.Time,1}}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{Float64,1,Float64,Missing,Array{Float64,1}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{Float64,1,Float64,Missing,ChainedVector{Float64,Array{Float64,1}}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{Int64,1,Int64,Missing,Array{Int64,1}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{Int64,1,Int64,Missing,ChainedVector{Int64,Array{Int64,1}}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{String,1,UndefInitializer,Missing,Array{String,1}}}})
    isdefined(CSV, Symbol("#28#29")) && Base.precompile(Tuple{getfield(CSV, Symbol("#28#29")),Tuple{Symbol,SentinelArray{String,1,UndefInitializer,Missing,ChainedVector{String,Array{String,1}}}}})
    isdefined(CSV, Symbol("#34#39")) && Base.precompile(Tuple{getfield(CSV, Symbol("#34#39"))})
    isdefined(CSV, Symbol("#36#41")) && Base.precompile(Tuple{getfield(CSV, Symbol("#36#41"))})
end


text:
function intlog2(N::I) where {I <: Integer}
    # This version may be slightly faster when vectorized?
    # u = 0x4330000000000000 + N
    # d = reinterpret(Float64,u) - 4503599627370496.0
    # u = (reinterpret(Int64, d) >> 52) - 1023
    # This version is easier to read and understand how it works,
    # and probably faster when evaluated serially
    u = 8sizeof(I) - 1 - leading_zeros(N)
    Base.unsafe_trunc(I, u)
end
intlog2(::Type{T}) where {T} = intlog2(sizeof(T))
ispow2(x::Integer) = (x & (x - 1)) == zero(x)
nextpow2(W) = one(W) << (8sizeof(W) - leading_zeros(W-1))
prevpow2(W) = one(W) << (8sizeof(W) - leading_zeros(W)-1)
    # W -= 1
    # W |= W >> 1
    # W |= W >> 2
    # W |= W >> 4
    # W |= W >> 8
    # W |= W >> 16
    # W + 1

@generated function T_shift(::Type{T}) where {T}
    intlog2(sizeof(T))
end
@generated function pick_vector_width(::Type{T} = Float64) where {T}
    shift = T_shift(T)
    max(1, REGISTER_SIZE >>> shift)
end
@generated function pick_vector_width_shift(::Type{T} = Float64) where {T}
    shift = T_shift(T)
    W = max(1, REGISTER_SIZE >>> shift)
    Wshift = intlog2(W)
    W, Wshift
end
function downadjust_W_and_Wshift(N, W, Wshift)
    N > W && return W, Wshift
    TwoN = N << 1
    while W >= TwoN
        W >>>= 1
        Wshift -= 1
    end
    W, Wshift
end
function pick_vector_width_shift(N::Integer, ::Type{T} = Float64) where {T}
    W, Wshift = pick_vector_width_shift(T)
    downadjust_W_and_Wshift(N, W, Wshift)
end
function pick_vector_width(N::Integer, ::Type{T} = Float64) where {T}
    W = pick_vector_width(T)
    first(downadjust_W_and_Wshift(N, W, 0))
end
function pick_vector_width_shift(N::Integer, size_T::Integer)
    W = max(1, REGISTER_SIZE ÷ size_T)
    Wshift = intlog2(W)
    downadjust_W_and_Wshift(N, W, Wshift)
end
function pick_vector_width(N::Integer, size_T::Integer)
    W = max(1, REGISTER_SIZE ÷ size_T)
    first(downadjust_W_and_Wshift(N, W, 0))
end

pick_vector_width(::Symbol, T) = pick_vector_width(T)
pick_vector_width_shift(::Symbol, T) = pick_vector_width_shift(T)

@generated pick_vector_width(::Val{N}, ::Type{T} = Float64) where {N,T} = pick_vector_width(N, T)

@generated pick_vector_width_val(::Type{T} = Float64) where {T} = Val{pick_vector_width(T)}()
pick_vector_width_val(::Type{Bool}) = Val{16}()
@generated pick_vector_width_val(::Val{N}, ::Type{T} = Float64) where {N,T} = Val{pick_vector_width(Val(N), T)}()

@generated function pick_vector_width_val(vargs...)
    sT = 16
    for v ∈ vargs
        T = v.parameters[1]
        if T == Bool
            sTv = REGISTER_SIZE >> 3 # encourage W ≥ 8
        elseif !AVX2 && T <: Integer
            return Val{1}()
        else
            sTv = sizeof(T)
        end
        sT = min(sT, sTv)
    end
    Val{REGISTER_SIZE ÷ sT}()
end
@generated function adjust_W(::Val{N}, ::Val{W}) where {N,W}
    W1 = first(downadjust_W_and_Wshift(N, W, 0))
    Val{W1}()
end
pick_vector_width_val(::Val{N}, vargs...) where {N} = adjust_W(Val{N}(), pick_vector_width_val(vargs...))

@inline valmul(::Val{W}, i) where {W} = W*i
@inline valadd(::Val{W}, i) where {W} = W + i
@inline valsub(::Val{W}, i) where {W} = W - i
@inline valrem(::Val{W}, i) where {W} = i & (W - 1)
@inline valmuladd(::Val{W}, b, c) where {W} = W*b + c
@inline valmul(::Val{W}, i::T) where {W,T<:Integer} = (W % T)*i
@inline valadd(::Val{W}, i::T) where {W,T<:Integer} = (W % T) + i
@inline valsub(::Val{W}, i::T) where {W,T<:Integer} = (W % T) - i
@inline valrem(::Val{W}, i::T) where {W,T<:Integer} = i & ((W % T) - one(T))
@inline valmuladd(::Val{W}, b::T, c::T) where {W,T<:Integer} = (W % T)*b + c

@generated pick_vector(::Type{T}) where {T} = Vec{pick_vector_width(T),T}
pick_vector(N, T) = Vec{pick_vector_width(N, T),T}
@generated pick_vector(::Val{N}, ::Type{T}) where {N, T} =  pick_vector(N, T)

struct _MM{W,I<:Number}
    i::I
    @inline _MM{W}(i::T) where {W,T} = new{W,T}(i)
end
@inline _MM(::Val{W}) where {W} = _MM{W}(0)
@inline _MM(::Val{W}, i) where {W} = _MM{W}(i)
@inline _MM(::Val{W}, ::Static{I}) where {W,I} = _MM{W}(I)

@inline Base.:(+)(i::_MM{W}, j::Integer) where {W} = _MM{W}(i.i + j)
@inline Base.:(+)(i::Integer, j::_MM{W}) where {W} = _MM{W}(i + j.i)
@inline Base.:(+)(i::_MM{W}, ::Static{j}) where {W,j} = _MM{W}(i.i + j)
@inline Base.:(+)(::Static{i}, j::_MM{W}) where {W,i} = _MM{W}(i + j.i)
# @inline Base.:(+)(i::_MM{W}, j::_MM{W}) where {W} = _MM{W}(i.i + j.i)
@inline Base.:(-)(i::_MM{W}, j::Integer) where {W} = _MM{W}(i.i - j)
# @inline Base.:(-)(i::Integer, j::_MM{W}) where {W} = _MM{W}(i - j.i)
@inline Base.:(-)(i::_MM{W}, ::Static{j}) where {W,j} = _MM{W}(i.i - j)
# @inline Base.:(-)(::Static{i}, j::_MM{W}) where {W,i} = _MM{W}(i - j.i)
# @inline Base.:(-)(i::_MM{W}, j::_MM{W}) where {W} = _MM{W}(i.i - j.i)
# @inline Base.:(*)(i::_MM{W}, j) where {W} = _MM{W}(i.i * j)
# @inline Base.:(*)(i, j::_MM{W}) where {W} = _MM{W}(i * j.i)
# @inline Base.:(*)(i::_MM{W}, ::Static{j}) where {W,j} = _MM{W}(i.i * j)
# @inline Base.:(*)(::Static{i}, j::_MM{W}) where {W,i} = _MM{W}(i * j.i)
# @inline Base.:(*)(i::_MM{W}, j::_MM{W}) where {W} = _MM{W}(i.i * j.i)
@inline scalar_less(i, j) = i < j
@inline scalar_less(i::_MM, j::Integer) = i.i < j
@inline scalar_less(i::Integer, j::_MM) = i < j.i
@inline scalar_less(i::_MM, ::Static{j}) where {j} = i.i < j
@inline scalar_less(::Static{i}, j::_MM) where {i} = i < j.i
@inline scalar_less(i::_MM, j::_MM) = i.i < j.i
@inline scalar_greater(i, j) = i > j
@inline scalar_greater(i::_MM, j::Integer) = i.i > j
@inline scalar_greater(i::Integer, j::_MM) = i > j.i
@inline scalar_greater(i::_MM, ::Static{j}) where {j} = i.i > j
@inline scalar_greater(::Static{i}, j::_MM) where {i} = i > j.i
@inline scalar_greater(i::_MM, j::_MM) = i.i > j.i
@inline scalar_equal(i, j) = i == j
@inline scalar_equal(i::_MM, j::Integer) = i.i == j
@inline scalar_equal(i::Integer, j::_MM) = i == j.i
@inline scalar_equal(i::_MM, ::Static{j}) where {j} = i.i == j
@inline scalar_equal(::Static{i}, j::_MM) where {i} = i == j.i
@inline scalar_equal(i::_MM, j::_MM) = i.i == j.i
@inline scalar_notequal(i, j) = i != j
@inline scalar_notequal(i::_MM, j::Integer) = i.i != j
@inline scalar_notequal(i::Integer, j::_MM) = i != j.i
@inline scalar_notequal(i::_MM, ::Static{j}) where {j} = i.i != j
@inline scalar_notequal(::Static{i}, j::_MM) where {i} = i != j.i
@inline scalar_notequal(i::_MM, j::_MM) = i.i != j.i

@inline extract_data(i::_MM) = i.i


text:
#===============================================================================

    NumberOfChannels.jl

    abstract type defining number of data channels

    Author: Tom Price
    Date:   July 2019

===============================================================================#

abstract type NumberOfChannels                  	end
abstract type SingleChannel 	<: NumberOfChannels end
abstract type DualChannel   	<: NumberOfChannels end

count_channels(::Type{SingleChannel}) = 1
count_channels(::Type{DualChannel})   = 2

max_stars_repo_name: MakerButt/chaipcr

max_issues_repo_name: MakerButt/chaipcr

max_forks_repo_name: MakerButt/chaipcr


text:
@testset begin
    @test find_smallest_set_of_vertices(6, [[0,1],[0,2],[2,5],[3,4],[4,2]]) == [0, 3]
    @test find_smallest_set_of_vertices(5, [[0,1],[2,1],[3,1],[1,4],[2,4]]) == [0, 2, 3]
end


text:
function Vector2D(arg0::Vector{jdouble})
    return Vector2D((Vector{jdouble},), arg0)
end

function Vector2D(arg0::jdouble, arg1::Vector2D)
    return Vector2D((jdouble, Vector2D), arg0, arg1)
end

function Vector2D(arg0::jdouble, arg1::Vector2D, arg2::jdouble, arg3::Vector2D)
    return Vector2D((jdouble, Vector2D, jdouble, Vector2D), arg0, arg1, arg2, arg3)
end

function Vector2D(arg0::jdouble, arg1::Vector2D, arg2::jdouble, arg3::Vector2D, arg4::jdouble, arg5::Vector2D)
    return Vector2D((jdouble, Vector2D, jdouble, Vector2D, jdouble, Vector2D), arg0, arg1, arg2, arg3, arg4, arg5)
end

function Vector2D(arg0::jdouble, arg1::Vector2D, arg2::jdouble, arg3::Vector2D, arg4::jdouble, arg5::Vector2D, arg6::jdouble, arg7::Vector2D)
    return Vector2D((jdouble, Vector2D, jdouble, Vector2D, jdouble, Vector2D, jdouble, Vector2D), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)
end

function Vector2D(arg0::jdouble, arg1::jdouble)
    return Vector2D((jdouble, jdouble), arg0, arg1)
end

function add(obj::Vector2D, arg0::JVector)
    return jcall(obj, "add", Vector2D, (JVector,), arg0)
end

function add(obj::Vector2D, arg0::jdouble, arg1::JVector)
    return jcall(obj, "add", Vector2D, (jdouble, JVector), arg0, arg1)
end

function angle(::Type{Vector2D}, arg0::Vector2D, arg1::Vector2D)
    return jcall(Vector2D, "angle", jdouble, (Vector2D, Vector2D), arg0, arg1)
end

function cross_product(obj::Vector2D, arg0::Vector2D, arg1::Vector2D)
    return jcall(obj, "crossProduct", jdouble, (Vector2D, Vector2D), arg0, arg1)
end

function distance(::Type{Vector2D}, arg0::Vector2D, arg1::Vector2D)
    return jcall(Vector2D, "distance", jdouble, (Vector2D, Vector2D), arg0, arg1)
end

function distance(obj::Vector2D, arg0::Point)
    return jcall(obj, "distance", jdouble, (Point,), arg0)
end

function distance1(::Type{Vector2D}, arg0::Vector2D, arg1::Vector2D)
    return jcall(Vector2D, "distance1", jdouble, (Vector2D, Vector2D), arg0, arg1)
end

function distance1(obj::Vector2D, arg0::JVector)
    return jcall(obj, "distance1", jdouble, (JVector,), arg0)
end

function distance_inf(::Type{Vector2D}, arg0::Vector2D, arg1::Vector2D)
    return jcall(Vector2D, "distanceInf", jdouble, (Vector2D, Vector2D), arg0, arg1)
end

function distance_inf(obj::Vector2D, arg0::JVector)
    return jcall(obj, "distanceInf", jdouble, (JVector,), arg0)
end

function distance_sq(::Type{Vector2D}, arg0::Vector2D, arg1::Vector2D)
    return jcall(Vector2D, "distanceSq", jdouble, (Vector2D, Vector2D), arg0, arg1)
end

function distance_sq(obj::Vector2D, arg0::JVector)
    return jcall(obj, "distanceSq", jdouble, (JVector,), arg0)
end

function dot_product(obj::Vector2D, arg0::JVector)
    return jcall(obj, "dotProduct", jdouble, (JVector,), arg0)
end

function equals(obj::Vector2D, arg0::Object)
    return jcall(obj, "equals", jboolean, (Object,), arg0)
end

function get_norm(obj::Vector2D)
    return jcall(obj, "getNorm", jdouble, ())
end

function get_norm1(obj::Vector2D)
    return jcall(obj, "getNorm1", jdouble, ())
end

function get_norm_inf(obj::Vector2D)
    return jcall(obj, "getNormInf", jdouble, ())
end

function get_norm_sq(obj::Vector2D)
    return jcall(obj, "getNormSq", jdouble, ())
end

function get_space(obj::Vector2D)
    return jcall(obj, "getSpace", Space, ())
end

function get_x(obj::Vector2D)
    return jcall(obj, "getX", jdouble, ())
end

function get_y(obj::Vector2D)
    return jcall(obj, "getY", jdouble, ())
end

function get_zero(obj::Vector2D)
    return jcall(obj, "getZero", Vector2D, ())
end

function hash_code(obj::Vector2D)
    return jcall(obj, "hashCode", jint, ())
end

function is_infinite(obj::Vector2D)
    return jcall(obj, "isInfinite", jboolean, ())
end

function is_na_n(obj::Vector2D)
    return jcall(obj, "isNaN", jboolean, ())
end

function negate(obj::Vector2D)
    return jcall(obj, "negate", Vector2D, ())
end

function normalize(obj::Vector2D)
    return jcall(obj, "normalize", Vector2D, ())
end

function orientation(::Type{Vector2D}, arg0::Vector2D, arg1::Vector2D, arg2::Vector2D)
    return jcall(Vector2D, "orientation", jdouble, (Vector2D, Vector2D, Vector2D), arg0, arg1, arg2)
end

function scalar_multiply(obj::Vector2D, arg0::jdouble)
    return jcall(obj, "scalarMultiply", Vector2D, (jdouble,), arg0)
end

function subtract(obj::Vector2D, arg0::JVector)
    return jcall(obj, "subtract", Vector2D, (JVector,), arg0)
end

function subtract(obj::Vector2D, arg0::jdouble, arg1::JVector)
    return jcall(obj, "subtract", Vector2D, (jdouble, JVector), arg0, arg1)
end

function to_array(obj::Vector2D)
    return jcall(obj, "toArray", Vector{jdouble}, ())
end

function to_string(obj::Vector2D)
    return jcall(obj, "toString", JString, ())
end

function to_string(obj::Vector2D, arg0::NumberFormat)
    return jcall(obj, "toString", JString, (NumberFormat,), arg0)
end


text:
using Turing: WelfordVar, add_sample!, get_var, reset!
using Test

let
    D = 1000
    wv = WelfordVar(0, zeros(D), zeros(D))
    add_sample!(wv, randn(D))
    reset!(wv)

    # Check that reseting zeros everything.
    @test wv.n === 0
    @test wv.μ == zeros(D)
    @test wv.M == zeros(D)

    # Ensure that asking for the variance doesn't mutate the WelfordVar.
    add_sample!(wv, randn(D))
    add_sample!(wv, randn(D))
    μ, M = deepcopy(wv.μ), deepcopy(wv.M)

    @test wv.μ == μ
    @test wv.M == M
end

# Check that the estimated variance is approximately correct.
let
    D = 10
    wv = WelfordVar(0, zeros(D), zeros(D))

    for _ = 1:10000
        s = randn(D)
        add_sample!(wv, s)
    end

    var = get_var(wv)

    @test var ≈ ones(D) atol=0.1
end


text:
default_basesize(n::Integer) = max(1, cld(n, (8 * Threads.nthreads())))
default_basesize(xs) =
    default_basesize(SplittablesBase.amount(last(extract_transducer(xs))))

default_basesize(_, _, xs) = default_basesize(xs::AbstractArray)

# TODO: handle `Base.Fix2` etc.
# TODO: tune this; it's just copied from `findfirst`
default_basesize(::typeof(ThreadsX.any), _, xs) = 2^15

default_basesize(::typeof(ThreadsX.all), f, xs) =
    default_basesize(ThreadsX.any, f, xs)

default_basesize(::typeof(ThreadsX.findfirst), _, xs) = 2^15

default_basesize(::typeof(ThreadsX.findlast), f, xs) =
    default_basesize(ThreadsX.findfirst, f, xs)

# `@btime wait(Threads.@spawn nothing)` shows ~1 μs overhead of
# spawning a task.  So let's choose the basesize such that basecase
# takes much longer time than this (say 20 μs).

function default_basesize(
    ::typeof(ThreadsX.extrema),
    ::typeof(identity),
    xs::AbstractArray{T},
) where {T<:Integer}
    if isconcretetype(T)
        return 2^20 ÷ sizeof(T)
    end
    return default_basesize(xs)
end

default_basesize(
    ::typeof(ThreadsX.extrema),
    ::typeof(identity),
    ::AbstractArray{<:Union{Float32,Float64}},
) = 8192

default_basesize(
    ::typeof(ThreadsX.extrema),
    ::typeof(identity),
    ::AbstractArray{Float16},  # slower?
) = 2048


text:
"""
    foldx_dagger(op[, xf], xs; init, simd, basesize)
    transduce_dagger(op[, xf], init, xs; simd, basesize)

Extended distributed fold backed up by Dagger.
"""
(foldx_dagger, transduce_dagger)

const SIMDFlag = Union{Bool,Symbol,Val{true},Val{false},Val{:ivdep}}

issmall(reducible, basesize) = amount(reducible) <= basesize

foldx_dagger(op, xs; init = DefaultInit, kwargs...) =
    Transducers.fold(op, xs, DaggerEx(; kwargs...); init = init)

foldx_dagger(op, xf, xs; kwargs...) = foldx_dagger(op, xf(xs); kwargs...)

transduce_dagger(xf::Transducer, op, init, xs; kwargs...) =
    transduce_dagger(xf'(op), init, xs; kwargs...)

preprocess_darray(_, _) = nothing, nothing

function transduce_dagger(
    rf0,
    init,
    xs0;
    simd::SIMDFlag = Val(false),
    basesize::Union{Integer,Nothing} = nothing,
)
    rf, xs = retransform(rf0, xs0)
    # TODO: replace Threads.nthreads() with the number of workers
    basesize = max(1, basesize === nothing ? amount(xs) ÷ Threads.nthreads() : basesize)
    rf′, xs′ = preprocess_darray(maybe_usesimd(rf, simd), xs)
    if xs′ !== nothing
        thunk = _transduce_darray(rf′, init, xs′, basesize)
    else
        thunk = _delayed_reduce(maybe_usesimd(rf, simd), init, xs, basesize)
    end
    acc = collect(thunk)
    result = complete(rf, acc)
    if unreduced(result) isa DefaultInitOf
        throw(EmptyResultError(rf))
    end
    return result
end

function _delayed_reduce(rf, init, xs, basesize)
    if amount(xs) <= basesize
        return delayed(_reduce_basecase)(rf, init, xs)
    end
    left, right = halve(xs)
    a = _delayed_reduce(rf, init, left, basesize)
    b = _delayed_reduce(rf, init, right, basesize)
    return delayed(_combine)(rf, a, b)
end

@noinline _reduce_basecase(rf::F, init::I, reducible) where {F,I} =
    restack(foldl_nocomplete(rf, start(rf, init), reducible))

# Semantically correct but inefficient (eager) handling of `Reduced`.
# Not sure how to cancel `delayed` computation.
_combine(rf, a::Reduced, b::Reduced) = a
_combine(rf, a::Reduced, b) = a
_combine(rf::RF, a, b::Reduced) where {RF} = reduced(combine(rf, a, unreduced(b)))
_combine(rf::RF, a, b) where {RF} = combine(rf, a, b)

_mapreduce(f, op, init, xs) =
    if length(xs) == 0
        start(op, init)
    elseif length(xs) == 1
        a, = xs
        f(a)
    elseif length(xs) == 2
        a, b = xs
        op(f(a), f(b))
    else
        left, right = halve(xs)
        a = _mapreduce(f, op, init, left)
        b = _mapreduce(f, op, init, right)
        op(a, b)
    end

"""
    DaggerEx(; simd, basesize) :: Transducers.Executor

Fold Executor implemented using Dagger.jl.
"""
struct DaggerEx{K} <: Executor
    kwargs::K
end

Transducers.transduce(xf, rf::RF, init, xs, exc::DaggerEx) where {RF} =
    transduce_dagger(xf, rf, init, xs; exc.kwargs...)


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder

name = "qd"
version = v"2.3.22"

# Collection of sources required to build qd
sources = [
    "http://crd.lbl.gov/~dhbailey/mpdist/qd-2.3.22.tar.gz" =>
    "268e89ac68d21bebfba279fec2b82b18686509b020cd9a1868dcaac5e46fef72",
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/qd-*
./configure --prefix=$prefix --host=$target --enable-shared --disable-static
make -j${nproc}
make -j${nproc} install
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms_linux = [
    Linux(:aarch64, libc=:glibc),
    Linux(:armv7l, libc=:glibc, call_abi=:eabihf),
    Linux(:i686, libc=:glibc),
    Linux(:x86_64, libc=:glibc),
    Windows(:i686),
    Windows(:x86_64),
]
platforms_osx = [
    MacOS(:x86_64),
]

os = get(ENV, "TRAVIS_OS_NAME", nothing)
if os == "linux"
    platforms = platforms_linux
elseif os == "osx"
    platforms = platforms_osx
else
    platforms = [platforms_linux; platforms_osx]
end

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

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

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


text:
@testset "Density-dependent catchability" begin
    run_sims(DensityDependentQSpec, 1;
             prep_file = "prep.h5",
             csv = true,
             feather = true)

    # Construct all of the expected output file names
    output_files = joinpath.("densdepq",
                             "repl_01",
                             "densdepq_" .*
                             string.(1:length(sim_values(DensityDependentQSpec)),
                                     pad = 2) .*
                             ["_popstate.h5" "_popstate.csv" "_catch.csv" "_popstate.feather" "_catch.feather"])

    @test isdir("densdepq")
    @test isdir("densdepq", "repl_01")
    @test all(isfile.(output_files))
end


text:
@enum ResourceItemType begin
  i_material
  i_card_exp
  i_act_item
  i_diamond
  i_diamond_shard
  i_ap_item
  i_ap_base
  i_ap_supply
  i_ap_gameplay
  i_exp_player
  i_lim_ticket_10
  i_epgs
  i_ticket
  i_ticket_try
  i_ticket_recruit
  i_ticket_10
  i_ticket_inst_fin
  i_ticket_rand_prsv
  i_gold
  i_voucher_pick
  i_voucher_rand_m
  i_voucher_rand_c
  i_et_stage
  i_rep_coin
  i_crs_shop_coin
  i_crs_rune_coin
  i_social_pt
  i_hgg_shd
  i_lmtgs_coin
  i_lgg_shd
  i_activity_coin
  i_unknown
end
@enum ResourceClassType c_material c_normal c_consume c_none c_unknown

"""
"""
struct ResourceType
  id::String
  name::String
  item_type::ResourceItemType
  class_type::ResourceClassType
  abbrev::Union{String, Nothing}
  usage::String
  desc::String
  obtaining::Union{String, Nothing}
  rarity::Int8
  sort_id::Integer
end

function Base.show(io::IO, rt::ResourceType)
  print(io, "ResourceType($(rt.id), $(rt.name), $(rt.abbrev), $(rt.rarity))")
end

"""
  Used primarily in PlayerData, but must be pre-defined for GameData
"""
struct Resource
  val::Unsigned
  type::ResourceType

  Resource(val, type) = new(Base.convert(Unsigned, val), type)
end

function Base.show(io::IO, r::Resource)
  print(io, "Resource($(r.val), $(r.type.abbrev))")
end

"""
"""
struct FactoryRecipe
  product::Resource
  inputs::Array{Resource, 3}
  time::Dates.AbstractTime
  capacity::Int8
end

function Base.show(io::IO, fr::FactoryRecipe)
  print(io, "FactoryRecipe()")
end

"""
"""
struct WorkshopRecipe
  product::Resource
  inputs::Array{Resource, 3}
  lmd::Resource
  morale::Int8
end

function Base.show(io::IO, wr::WorkshopRecipe)
  print(io, "WorkshopRecipe()")
end

@enum PromotionPhase e0=0 e1=1 e2=2

@enum AtkType no_atk=0 melee=1 ranged=2
@enum DmgType no_dmg=0 phys_dmg=1 arts_dmg=2 true_dmg=3

"""
"""
struct OperatorBase
  id::String
  name::String
  rank::Int8

  function OperatorBase(id::String, name::String, rank::Integer)
    @assert 1 <= rank <= 6 "Rank must be between 1 and 6"
    return new(id, name, Int8(rank))
  end
end

"""
"""
struct EnemyFlags
  infected_creature::Bool
  possessed::Bool
  sarkaz::Bool
  drone::Bool
end

@enum EnemyRank ordinary=1 elite=2 leader=3
@enum EnemyGrade e=1 d=2 c=3 b=4 a=5 ap=6

"""
"""
struct EnemyBase
  id::String
  name::String
  species::String
  flavour_text::String
  rank::EnemyRank
  atk_type::AtkType
  dmg_type::DmgType
  hp::EnemyGrade
  atk::EnemyGrade
  def::EnemyGrade
  res::EnemyGrade
  special::String
  base_stats::Any # EnemyStats
end

function Base.show(io::IO, m::EnemyBase)
  print(io, "EnemyBase()")
end

"""
"""
struct Resistances
  silence::Bool
  stun::Bool
  sleep::Bool
end

"""
"""
struct EnemyStats
  id::Integer
  type::EnemyBase
  level::Integer
  hp::Integer
  regen::Float64
  atk::Integer
  atk_int::Float64
  atk_radius::Float64
  def::Integer
  res::Float64
  mov::Float64
  weight::Int8
  resistances::Resistances
end

function Base.show(io::IO, m::EnemyStats)
  print(io, "EnemyStats()")
end

"""
"""
struct Tile
  id::Integer
  name::String
  ascii_art::Char
end

function Base.show(io::IO, t::Tile)
  print(io, t.ascii_art)
end

"""
"""
struct Map
  tiles::Vector{Tile}
end

function Base.show(io::IO, m::Map)
  print(io, "Map()")
end

@enum DropRarity unknown=0 guranteed=1 common=2 uncommon=3 rare=4 very_rare=5 three_stars=10

"""
"""
struct Stage
  id::String
  # meta
  sanity_cost::Resource
  plan_cost::Resource
  rec_level::Integer
  # combat
  hp_seals::Integer
  enemy_count::Integer
  deployment_limit::Integer
  initial_cp::Integer
  max_cp::Integer
  enemies::Dict{EnemyStats, Integer}
  map::Map
  # rewards
  exp::Integer
  trust::Integer
  lmd::Resource
  first_drops::Dict{ResourceType, DropRarity}
  regular_drops::Dict{ResourceType, DropRarity}
  special_drops::Dict{ResourceType, DropRarity}
  extra_drops::Vector{ResourceType}
end

function Base.show(io::IO, s::Stage)
  print(io, "Stage()")
end

"""
"""
struct OperatorLevel
  level::Integer
  promotion::PromotionPhase
  xp::Integer
end

function OperatorLevel(
    level::Integer = 0,
    promotion::PromotionPhase = e0,
    xp::Integer = 0)
  return OperatorLevel(level, promotion, xp)
end

"""
"""
struct OperatorSkills
  rank::Integer
  mastery_1::Integer
  mastery_2::Integer
  mastery_3::Integer
end

function OperatorSkills(; rank::Integer = 1,
    m1::Integer = 0, m2::Integer = 0, m3::Integer = 0)
  @assert 1 <= rank <= 7 "skill rank must be between 1 and 7"
  for m in [m1, m2, m3]
    @assert 0 <= m <= 3 "skill mastery must be between 0 and 3"
  end
  return OperatorSkills(rank, m1, m2, m3)
end

"""
"""
struct Operator
  base::OperatorBase
  level::OperatorLevel
  skills::OperatorSkills
  trust::Integer
  potential::Integer
end

function Operator(
    base::OperatorBase,
    level::OperatorLevel = OperatorLevel(0, e0, 0),
    skills::OperatorSkills = OperatorSkills(),
    trust::Integer = 0,
    potential::Integer = 0)
  return Operator(base, level, skills, trust, potential)
end

"""
"""
struct StageReport
  id::String
  stars::Int8
  time::Dates.AbstractTime
  exp::Integer
  trust::Integer
  lmd::Resource
  drops::Dict{ResourceType, Integer}
end

function Base.show(io::IO, sr::StageReport)
  print(io, "StageReport()")
end

"""
"""
struct RecruitReport
  id::Integer
end

function Base.show(io::IO, rr::RecruitReport)
  print(io, "RecruitReport()")
end


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

module Reqs

import Base: ==
using ..Pkg2Types

# representing lines of REQUIRE files

abstract type Line end
struct Comment <: Line
    content::AbstractString
end
struct Requirement <: Line
    content::AbstractString
    package::AbstractString
    versions::VersionSet
    system::Vector{AbstractString}

    function Requirement(content::AbstractString)
        fields = split(replace(content, r"#.*$" => ""))
        system = AbstractString[]
        while !isempty(fields) && fields[1][1] == '@'
            push!(system, popfirst!(fields)[2:end])
        end
        isempty(fields) && throw(PkgError("invalid requires entry: $content"))
        package = popfirst!(fields)
        all(field->occursin(Base.VERSION_REGEX, field), fields) ||
            throw(PkgError("invalid requires entry for $package: $content"))
        versions = VersionNumber.(fields)
        issorted(versions) || throw(PkgError("invalid requires entry for $package: $content"))
        new(content, package, VersionSet(versions), system)
    end
end

function read(readable::Union{IO,Base.AbstractCmd})
    lines = Line[]
    for line in eachline(readable)
        push!(lines, occursin(r"^\s*(?:#|$)", line) ? Comment(line) : Requirement(line))
    end
    return lines
end
read(file::AbstractString) = isfile(file) ? open(read,file) : Line[]

end # module

max_stars_repo_name: djsegal/julia-fork

max_issues_repo_name: djsegal/julia-fork

max_forks_repo_name: djsegal/julia-fork


text:
using Hyperscript
using JSServe, Observables
using JSServe.DOM

using JSServe: Application, Session, evaljs, linkjs, update_dom!, div, active_sessions
using JSServe: @js_str, onjs, Button, TextField, Slider, JSString, Dependency, with_session

# Javascript & CSS dependencies can be declared locally and
# freely interpolated in the DOM / js string, and will make sure it loads
const ace = JSServe.Dependency(
    :ace,
    ["https://cdn.jsdelivr.net/gh/ajaxorg/ace-builds/src-min/ace.js"]
)

struct Editor
    source::Observable{String}
    theme::Observable{String}
    language::Observable{String}
end

function dom_handler(session, request)
    s = Style(css("div",
        position = "absolute",
        top = 0,
        right = 0,
        bottom = 0,
        left = 0,
    ))
    dom = DOM.div("""
    function test{
        return 1;
    }""")
    JSServe.onload(session, dom, js"""
        function (element){
            console.log(element)
            var editor = $ace.edit(element);
            editor.setTheme("ace/theme/chrome");
            editor.session.setMode("ace/mode/javascript");
            editor.setOptions({
                autoScrollEditorIntoView: true,
                copyWithEmptySelection: true,
            });

            editor.resize()
            // use setOptions method to set several options at once
            editor.setOptions({
                autoScrollEditorIntoView: true,
                copyWithEmptySelection: true,
            });
            // use setOptions method
            editor.setOption("mergeUndoDeltas", "always");

        }
    """)
    return DOM.div(DOM.style(styles(s)), s(dom))
end;

app = JSServe.Application(
    dom_handler,
    get(ENV, "WEBIO_SERVER_HOST_URL", "127.0.0.1"),
    parse(Int, get(ENV, "WEBIO_HTTP_PORT", "8081")),
    verbose = false
)
with_session() do session
    dom_handler(session, nothing)
end


text:
mutable struct MapClassGrp <: Map{GrpAbFinGen, NfOrdIdlSet, HeckeMap, MapClassGrp}
  header::MapHeader{GrpAbFinGen, NfOrdIdlSet}

  quo::Int
  princ_gens::Vector{Tuple{FacElem{NfOrdIdl,NfOrdIdlSet}, FacElem{nf_elem, AnticNumberField}}}
  small_gens::Vector{NfOrdIdl}
  function MapClassGrp()
    mp = new()
    mp.quo = -1
    return mp
  end
end

mutable struct SmallLLLRelationsCtx{T}
  A::NfOrdIdl
  b::Vector{T}
  bd::Int
  cnt::Int
  elt::T
  function SmallLLLRelationsCtx(a::T) where {T}
    n = new{T}()
    n.bd = 1
    n.cnt = 0
    return n
  end

  function SmallLLLRelationsCtx(::Type{T}) where T
    n = new{T}()
    n.bd = 1
    n.cnt = 0
    return n
  end
end

mutable struct NormCtx_split <: NormCtx
  O::NfAbsOrd{AnticNumberField, nf_elem}
  lp::Vector{Int}  #the primes
  lR::Vector{GaloisField} #the local (finite field) splitting field
  nb::Int #bound on the number of bits the norm is allowed to have
  lC::Vector{gfp_mat} # for each p in lp, the conjugates of the basis of O
  mp::Vector{gfp_mat} # for each p in lp, the conjugates of the basis of O
  np::Vector{gfp_mat} # for each p in lp, the conjugates of the basis of O
  e::crt_env
  function NormCtx_split(O::NfAbsOrd, nb::Int)
    p = p_start
    NC = new()
    NC.O = O
    NC.nb = nb
    NC.lp = Vector{Int}()
    NC.lR = Vector{GaloisField}()
    NC.lC = Vector{gfp_mat}()
    NC.mp = Vector{gfp_mat}()
    NC.np = Vector{gfp_mat}()
    B = basis(O)
    n = degree(O)
    while (true)
      p = next_prime(p)
      lP = prime_decomposition(O, p)
      if length(lP) < degree(O)
        continue
      end
      push!(NC.lp, p)
      R = GF(p, cached = false)
      push!(NC.lR, R)
      push!(NC.mp, zero_matrix(R, 1, degree(O)))
      push!(NC.np, zero_matrix(R, 1, degree(O)))
      M = Vector{Nemo.elem_type(R)}()
      for P = lP
        F, mF = ResidueFieldSmall(O, P[1])
        for x = B
          xp = mF(x)
          push!(M, R(coeff(xp, 0)))
        end
      end
      push!(NC.lC, matrix(R, n, n, M)')
      nb -= nbits(p)
      if nb <= 0
        NC.e = crt_env(fmpz[p for p = NC.lp])
        return NC
      end
    end
  end
end

mutable struct NormCtx_gen <: NormCtx
  nb::Int
  O::NfAbsOrd
  function NormCtx_gen(O::NfAbsOrd, nb::Int)
    NC = new()
    NC.nb = nb
    NC.O = O
    return NC
  end
end

mutable struct MapUnitGrp{T} <: Map{GrpAbFinGen, T, HeckeMap, MapUnitGrp}
  header::Hecke.MapHeader{GrpAbFinGen, T}

  # Only for non-maximal orders:
  OO_mod_F_mod_O_mod_F::GrpAbFinGenToAbsOrdQuoRingMultMap # a map from (OO/F*OO)^\times/(O/F)^\times to OO where OO is a maximal order and F the conductor

  function MapUnitGrp{T}() where {T}
    return new{T}()
  end
end

mutable struct MapSUnitModUnitGrpFacElem <: Map{GrpAbFinGen, FacElemMon{AnticNumberField}, HeckeMap, MapSUnitModUnitGrpFacElem}
  header::MapHeader{GrpAbFinGen, FacElemMon{AnticNumberField}}
  idl::Vector{NfOrdIdl}
  valuations::Vector{SRow{fmpz}}

  function MapSUnitModUnitGrpFacElem()
    return new()
  end
end

mutable struct MapSUnitGrpFacElem <: Map{GrpAbFinGen, FacElemMon{AnticNumberField}, HeckeMap, MapSUnitGrpFacElem}
  header::MapHeader{GrpAbFinGen, FacElemMon{AnticNumberField}}
  idl::Vector{NfOrdIdl}
  valuations::Vector{SRow{fmpz}}
  isquotientmap::Int

  function MapSUnitGrpFacElem()
    z = new()
    z.isquotientmap = -1
    return z
  end
end

mutable struct MapSUnitGrp <: Map{GrpAbFinGen, AnticNumberField, HeckeMap, MapSUnitGrp}
  header::MapHeader{GrpAbFinGen, AnticNumberField}
  idl::Vector{NfOrdIdl}

  function MapSUnitGrp()
    return new()
  end
end


text:
# Compound Expressions
z = begin
  x = 1
  y = 2
  x + y
end
println("z is ", z)

# Conditional Evaluation
# it is an error if the value of a conditional expression is anything but true or false, just like Java
if x < y
    println("x is less than y")
elseif x > y
    println("x is greater than y")
else
    println("x is equal to y")
end

# ternary operator
# To facilitate chaining, the operator associates from right to left
test(x, y) = println(x < y ? "x is less than y" : x > y ? "x is greater than y" : "x is equal to y")
test(1, 2)

# Short-Circuit Evaluation
# if <cond> <statement> = <cond> && <statement>
# if ! <cond> <statement> = <cond> || <statement>
t = true
f = false
println(t && f)
println(t || f)
function fact(n::Int)
  n >= 0 || error("n must be non-negative")
  n == 0 && return 1
  n * fact(n-1)
end
fact(5)
fact(0)
# fact(-1) ERROR: n must be non-negative

# Repeated Evaluation: Loops
# while loop
i = 1
while i <= 5
  println(i)
  global i += 1
end
# for loop
# key word "in" and "∈", for i in [1,4,0], for s ∈ ["foo","bar","baz"]
for i = 1:5
  println(i)
end
# multiple nested for loop
for i = 1:2, j = 3:4
  println((i, j))
  i = 0 # assignments to i will not be visible to subsequent iterations
end

# try/catch statement
g(x) = try
  sqrt(x)
catch
  sqrt(complex(x, 0))
end
println(g(-1))

max_stars_repo_name: startprogress/Hello-Julia

max_issues_repo_name: startprogress/Hello-Julia

max_forks_repo_name: startprogress/Hello-Julia


text:
include("generators.jl")
include("proof.jl")


text:
using Documenter
using Literate
using ElTopo

# try
#     using AbstractPlotting, GLMakie
#     @info "Animation with Makie is being made..."
#     let
#         cd(joinpath(@__DIR__,"src"))
#         include(joinpath(@__DIR__,"../examples/enright.jl"))
#     end
# catch end

function dropexecution(content)
    content = replace(content, "```@example" => "```julia")
    return content
end

Literate.markdown(joinpath(@__DIR__, "../examples/index.jl"), joinpath(@__DIR__,"src/"); credit = false, name = "index")

Literate.markdown(joinpath(@__DIR__, "../examples/enright.jl"), joinpath(@__DIR__,"src/"); credit = false, name = "enright", postprocess=dropexecution)

Literate.script(joinpath(@__DIR__, "../examples/sphere.jl"), joinpath(@__DIR__,"src/"); credit = false, name = "sphere")

makedocs(sitename="ElTopo.jl",pages = ["index.md","enright.md"])

deploydocs(
     repo = "github.com/akels/ElTopo.jl.git",
 )


text:
using ComplexDiff
using Documenter

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

makedocs(;
    modules=[ComplexDiff],
    authors="Qingyu Qu",
    repo="https://github.com/ErikQQY/ComplexDiff.jl/blob/{commit}{path}#{line}",
    sitename="ComplexDiff.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://ErikQQY.github.io/ComplexDiff.jl",
        assets=String[],
    ),

    pages=[
        "Home" => "index.md",
        "Principle" => "principle.md",
        "High Order derivative" => "highorder.md"
    ],
)

deploydocs(;
    repo="github.com/ErikQQY/ComplexDiff.jl",
    devbranch="master",
)


text:
using SymPy

function walk_expression(fun::Function, ex::Sym)
    as = map(args(ex)) do a
        walk_expression(fun, a)
    end
    if length(as) == 0 # Due to issue SymPy.jl#103
        ex
    else
        fun(func(ex)(as...))
    end
end

# Is there a nicer way?
is_exp(ex) = (func(ex) == func(exp(sympy[:Dummy]("x"))))

function trans_gaussian(ex, x)
    is_exp(ex) || return ex
    arg = args(ex)[1]
    A,B,C = symbols("__A __B __C")
    s = solve(A*(x+B)^2 + C - arg, [A,B,C])[1]
    ks = keys(s)
    all([S in ks for S in [A,B,C]]) || return ex
    # Would actually like to test for negative
    # definiteness here, but how?
    # s[A] < 0 || return ex
    p = simplify(s[A]*(x+s[B])^2 + s[C])
    exp(p)
end

export walk_expression, trans_gaussian


text:
using Pkg
Pkg.activate(@__DIR__) # Activating environment
Pkg.instantiate() # Downloads packages if needed

using CSV
using DataFrames
using AnnotationFusion

path = joinpath(dirname(@__DIR__), "data/COACH/")
savepath = joinpath(path, "aggregates")
mkpath(savepath)

file = joinpath(path, "COACH_scores.csv")
df = CSV.read(file, DataFrame)

raters = :ANNOTID
items = :SESSIONID
scores = [:SCO01, :SCO02, :SCO03, :SCO04, :SCO05]

## Initial preprocessing
# Consider only cases where a transcript is available
filter!(row -> row.Transcript == true, df)
anonymize!(df, raters)

for score in scores
    aggregates = Dict{String, Vector{Float64}}()
    annotations = dense(df, raters, items, score)

    for method in [Mean(), Median(), Copeland(scaling=:distribution), Copeland(scaling=:procrustes), TE(ntriplets=:all, scaling=:procrustes), TE(ntriplets=:all, scaling=:distribution)]
        aggregates[name(method)] = fuse(annotations, items, method)
        # if occursin("te", name(method))
        #     # aggregates[name(method)] = clamp.(aggregates[name(method)], 1, 7)
        # end
    end

   CSV.write(joinpath(savepath, string("COACH_", score, ".csv")), hcat(annotations[:,[items]], DataFrame(aggregates)))
end


text:
# ---
# title: 1394. Find Lucky Integer in an Array
# id: problem1394
# author: Tian Jun
# date: 2020-10-31
# difficulty: Easy
# categories: Array
# link: <https://leetcode.com/problems/find-lucky-integer-in-an-array/description/>
# hidden: true
# ---
#
# Given an array of integers `arr`, a lucky integer is an integer which has a
# frequency in the array equal to its value.
#
# Return _a lucky integer_  in the array. If there are multiple lucky integers
# return the **largest** of them. If there is no lucky integer return **-1**.
#
#
#
# **Example 1:**
#
#
#
#     Input: arr = [2,2,3,4]
#     Output: 2
#     Explanation: The only lucky number in the array is 2 because frequency[2] == 2.
#
#
# **Example 2:**
#
#
#
#     Input: arr = [1,2,2,3,3,3]
#     Output: 3
#     Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.
#
#
# **Example 3:**
#
#
#
#     Input: arr = [2,2,2,3,3]
#     Output: -1
#     Explanation: There are no lucky numbers in the array.
#
#
# **Example 4:**
#
#
#
#     Input: arr = [5]
#     Output: -1
#
#
# **Example 5:**
#
#
#
#     Input: arr = [7,7,7,7,7,7,7]
#     Output: 7
#
#
#
#
# **Constraints:**
#
#   * `1 <= arr.length <= 500`
#   * `1 <= arr[i] <= 500`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
using Pkg
pkg"instantiate"

max_stars_repo_name: braaannigan/makeYourOwnBinary

max_issues_repo_name: braaannigan/makeYourOwnBinary

max_forks_repo_name: braaannigan/makeYourOwnBinary


text:
Base.show(io::IO, @nospecialize(_::Index{x})) where x =
    if get(io, :limit, false)
        print(io, '↻', x)
    else
        Base.show_default(io, Index(x))
    end

Base.show(io::IO, @nospecialize(plan::AccessPlan)) =
    if get(io, :limit, false)
        print(io, "AccessPlan: ")
        for (n, i) in enumerate(plan.indices)
            n == 1 || print(io, " → ")
            print(io, indexname(i))
        end
    else
        Base.show_default(io, plan)
    end

Base.show(io::IO, @nospecialize(reducible::NDReducible)) =
    if get(io, :limit, false)
        println(io, "NDReducible with ", length(reducible.patterns), " arrays")
        for pattern in reducible.patterns
            print(io, "* ")
            _summary(io, pattern.indexable)
            println(io)
            print(io, "  ")
            for (n, i) in enumerate(pattern.indices)
                n == 1 || print(io, " ")
                print(io, indexname(i))
            end
            println(io)
        end
        show(io, reducible.plan)
    else
        Base.show_default(io, reducible)
    end

_summary(io, x) = summary(io, x)
function _summary(io, x::Broadcasted)
    ax = axes(x)
    if length(ax) == 1
        print(io, length(ax[1]), "-element")
    else
        for (n, a) in enumerate(ax)
            n == 1 || print(io, "x")
            print(io, length(a))
        end
    end
    print(io, " Broadcasted")
end


text:
# ---
# title: 1547. Minimum Cost to Cut a Stick
# id: problem1547
# author: Tian Jun
# date: 2020-10-31
# difficulty: Hard
# categories: Dynamic Programming
# link: <https://leetcode.com/problems/minimum-cost-to-cut-a-stick/description/>
# hidden: true
# ---
#
# Given a wooden stick of length `n` units. The stick is labelled from `0` to
# `n`. For example, a stick of length **6** is labelled as follows:
#
# ![](https://assets.leetcode.com/uploads/2020/07/21/statement.jpg)
#
# Given an integer array `cuts` where `cuts[i]` denotes a position you should
# perform a cut at.
#
# You should perform the cuts in order, you can change the order of the cuts as
# you wish.
#
# The cost of one cut is the length of the stick to be cut, the total cost is
# the sum of costs of all cuts. When you cut a stick, it will be split into two
# smaller sticks (i.e. the sum of their lengths is the length of the stick
# before the cut). Please refer to the first example for a better explanation.
#
# Return _the minimum total cost_ of the cuts.
#
#
#
# **Example 1:**
#
# ![](https://assets.leetcode.com/uploads/2020/07/23/e1.jpg)
#
#
#
#     Input: n = 7, cuts = [1,3,4,5]
#     Output: 16
#     Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:
#     ![](https://assets.leetcode.com/uploads/2020/07/21/e11.jpg)
#     The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.
#     Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).
#
# **Example 2:**
#
#
#
#     Input: n = 9, cuts = [5,6,1,4,2]
#     Output: 22
#     Explanation: If you try the given cuts ordering the cost will be 25.
#     There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.
#
#
#
#
# **Constraints:**
#
#   * `2 <= n <= 10^6`
#   * `1 <= cuts.length <= min(n - 1, 100)`
#   * `1 <= cuts[i] <= n - 1`
#   * All the integers in `cuts` array are **distinct**.
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
using PkgTemplates

t = Template(;
    user="ShozenD",
    dir="/Users/shozendan/Documents/",
    plugins=[
        Codecov(),
        AppVeyor(),
        GitHubActions(; linux=true, osx=true),
        GitLabCI(; coverage=true),
        Documenter{GitHubActions}()
    ]
)

t("JuliaPkgDev")

max_stars_repo_name: ShozenD/julia-pkg-dev

max_issues_repo_name: ShozenD/julia-pkg-dev

max_forks_repo_name: ShozenD/julia-pkg-dev


text:
using NeuralPDE
using Quadrature, Cubature, Cuba
using Flux, ModelingToolkit, GalacticOptim, Optim, DiffEqFlux
using Plots
using DelimitedFiles
using QuasiMonteCarlo
import ModelingToolkit: Interval, infimum, supremum

function diffusion(strategy, minimizer, maxIters)

    ##  DECLARATIONS
    @parameters x t
    @variables u(..)
    Dt = Differential(t)
    Dxx = Differential(x)^2

    eq = Dt(u(x,t)) - Dxx(u(x,t)) ~ -exp(-t) * (sin(pi * x) - pi^2 * sin(pi * x))

    bcs = [u(x,0) ~ sin(pi*x),
           u(-1,t) ~ 0.,
           u(1,t) ~ 0.]

    domains = [x ∈ Interval(-1.0,1.0),
               t ∈ Interval(0.0,1.0)]

    dx = 0.2; dt = 0.1
    xs,ts = [infimum(domain.domain):dx/10:supremum(domain.domain) for (dx,domain) in zip([dx,dt],domains)]

    indvars = [x,t]
    depvars = [u(x,t)]

    chain = FastChain(FastDense(2,10,Flux.σ),FastDense(10,10,Flux.σ),FastDense(10,1))

    losses = []
    error = []
    times = []

    dx_err = [0.2,0.1]

    error_strategy = GridTraining(dx_err)

    initθ = Float64.(DiffEqFlux.initial_params(chain))
    eltypeθ = eltype(initθ)
    parameterless_type_θ = DiffEqBase.parameterless_type(initθ)

    phi = NeuralPDE.get_phi(chain,parameterless_type_θ)
    derivative = NeuralPDE.get_numeric_derivative()

    _pde_loss_function = NeuralPDE.build_loss_function(eq,indvars,depvars,
                                             phi,derivative,nothing,chain,initθ,error_strategy)

    bc_indvars = NeuralPDE.get_variables(bcs,indvars,depvars)
    _bc_loss_functions = [NeuralPDE.build_loss_function(bc,indvars,depvars,
                                              phi,derivative,nothing,chain,initθ,error_strategy,
                                              bc_indvars = bc_indvar) for (bc,bc_indvar) in zip(bcs,bc_indvars)]

    train_sets = NeuralPDE.generate_training_sets(domains,dx_err,[eq],bcs,eltypeθ,indvars,depvars)
    train_domain_set, train_bound_set = train_sets

    pde_loss_functions = [NeuralPDE.get_loss_function(_pde_loss_function,
                                          train_domain_set[1],eltypeθ,
                                          parameterless_type_θ,error_strategy)]

    bc_loss_functions = [NeuralPDE.get_loss_function(bc,
                                          train_set,eltypeθ,
                                          parameterless_type_θ,error_strategy) for (train_set,bc) in zip(train_bound_set, _bc_loss_functions)]

    loss_functions =  [pde_loss_functions;bc_loss_functions]
    function loss_function_(θ,p)
        return sum(map(l->l(θ) ,loss_functions))
    end

    cb_ = function (p,l)
        deltaT_s = time_ns() #Start a clock when the callback begins, this will evaluate questo misurerà anche il calcolo degli uniform error

        ctime = time_ns() - startTime - timeCounter #This variable is the time to use for the time benchmark plot
        append!(times, ctime/10^9) #Conversion nanosec to seconds
        append!(losses, l)
        loss_ = loss_function_(p,nothing)
        append!(error, loss_)

        timeCounter = timeCounter + time_ns() - deltaT_s #timeCounter sums all delays due to the callback functions of the previous iterations

        return false
    end

    discretization = PhysicsInformedNN(chain,strategy; init_params =initθ)

    @named pde_system = PDESystem(eq,bcs,domains,indvars,depvars)
    prob = discretize(pde_system,discretization)

    timeCounter = 0.0
    startTime = time_ns() #Fix initial time (t=0) before starting the training

    res = GalacticOptim.solve(prob, minimizer; cb = cb_, maxiters = maxIters)
    phi = discretization.phi

    params = res.minimizer

    # Model prediction
    domain = [x,t]

    u_predict = reshape([first(phi([x,t],res.minimizer)) for x in xs for t in ts],(length(xs),length(ts)))

    return [error, params, domain, times, u_predict, losses]
end

maxIters = [(5000,5000,5000,5000,5000,5000),(300,300,300,300,300,300)] #iters for ADAM/LBFGS
# maxIters = [(5,5,5,5,5,5),(3,3,3,3,3,3)] #iters for ADAM/LBFGS

strategies = [#NeuralPDE.QuadratureTraining(quadrature_alg = CubaCuhre(), reltol = 1, abstol = 1e-3, maxiters = 10, batch = 10),
              NeuralPDE.QuadratureTraining(quadrature_alg = HCubatureJL(), reltol=1, abstol=1e-5, maxiters=100, batch = 0),
              NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLh(), reltol=1, abstol=1e-5, maxiters=100),
              NeuralPDE.QuadratureTraining(quadrature_alg = CubatureJLp(), reltol=1, abstol=1e-5, maxiters=100),
              NeuralPDE.GridTraining([0.2,0.1]),
              NeuralPDE.StochasticTraining(400 ; bcs_points= 50),
              NeuralPDE.QuasiRandomTraining(400 ; bcs_points= 50)]

strategies_short_name = [#"CubaCuhre",
                        "HCubatureJL",
                        "CubatureJLh",
                        "CubatureJLp",
                        #"CubaVegas",
                        #"CubaSUAVE"]
                        "GridTraining",
                        "StochasticTraining",
                        "QuasiRandomTraining"]

minimizers = [ADAM(0.001),
              #BFGS()]
              LBFGS()]

minimizers_short_name = ["ADAM",
                         "LBFGS"]
                        # "BFGS"]

# Run models
error_res =  Dict()
domains = Dict()
params_res = Dict()  #to use same params for the next run
times = Dict()
prediction = Dict()
losses_res = Dict()

print("Starting run")
## Convergence

for min =1:length(minimizers) # minimizer
      for strat=1:length(strategies) # strategy
            # println(string(strategies_short_name[strat], "  ", minimizers_short_name[min]))
            res = diffusion(strategies[strat], minimizers[min], maxIters[min][strat])
            push!(error_res, string(strat,min)     => res[1])
            push!(params_res, string(strat,min) => res[2])
            push!(domains, string(strat,min)        => res[3])
            push!(times, string(strat,min)        => res[4])
            push!(prediction, string(strat,min)        => res[5])
            push!(losses_res, string(strat,min)        => res[6])

      end
end

current_label = string(strategies_short_name[1], " + " , minimizers_short_name[1])
error = Plots.plot(times["11"], error_res["11"], yaxis=:log10, label = current_label)#, xlims = (0,100))#legend = true)#, size=(1200,700))
plot!(error, times["21"], error_res["21"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[1]))
plot!(error, times["31"], error_res["31"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[1]))
plot!(error, times["41"], error_res["41"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[1]))
plot!(error, times["51"], error_res["51"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[1]))
plot!(error, times["61"], error_res["61"], yaxis=:log10, label = string(strategies_short_name[6], " + " , minimizers_short_name[1]))

plot!(error, times["12"], error_res["12"], yaxis=:log10, label = string(strategies_short_name[1], " + " , minimizers_short_name[2]))
plot!(error, times["22"], error_res["22"], yaxis=:log10, label = string(strategies_short_name[2], " + " , minimizers_short_name[2]))
plot!(error, times["32"], error_res["32"], yaxis=:log10, label = string(strategies_short_name[3], " + " , minimizers_short_name[2]))
plot!(error, times["42"], error_res["42"], yaxis=:log10, label = string(strategies_short_name[4], " + " , minimizers_short_name[2]))
plot!(error, times["52"], error_res["52"], yaxis=:log10, label = string(strategies_short_name[5], " + " , minimizers_short_name[2]))
plot!(error, times["62"], error_res["62"], yaxis=:log10, title = string("Diffusion convergence ADAM/LBFGS"), ylabel = "log(error)",xlabel = "t", label = string(strategies_short_name[6], " + " , minimizers_short_name[2]))

using SciMLBenchmarks
SciMLBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])

max_stars_repo_name: SciML/SciMLBenchmarksOutput

max_issues_repo_name: SciML/SciMLBenchmarksOutput

max_forks_repo_name: SciML/SciMLBenchmarksOutput


text:
# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/Materials.jl/blob/master/LICENSE

using FEMMaterials, Tensors, Test

analysis, problem, element, bc_elements, ip = get_one_element_material_analysis(:IdealPlastic)
update!(element, "youngs_modulus", 200.0e3)
update!(element, "poissons_ratio", 0.3)
update!(element, "yield_stress", 100.0)

times = [0.0]
loads = [0.0]
dt = 0.5
E = 200.0e3
nu = 0.3
G = 0.5*E/(1+nu)
syield = 100.0
# vm = sqrt(3)*G*ga | ea = ga
ea = 2*syield/(sqrt(3)*G)
# Go to elastic border
push!(times, times[end]+dt)
push!(loads, loads[end] + ea*dt)
 # Proceed to plastic flow
push!(times, times[end]+dt)
push!(loads, loads[end] + ea*dt)
 # Reverse direction
push!(times, times[end]+dt)
push!(loads, loads[end] - ea*dt)
 # Continue and pass yield criterion
push!(times, times[end]+dt)
push!(loads, loads[end] - 2*ea*dt)
loading = ShearStrainLoading(times, loads)
update_bc_elements!(bc_elements, loading)

analysis.properties.t1 = maximum(times)
run!(analysis)
s31 = [tovoigt(ip("stress", t))[5] for t in times]
s31_expected = [0.0, syield/sqrt(3.0), syield/sqrt(3.0), 0.0, -syield/sqrt(3.0)]
@test isapprox(s31, s31_expected; rtol=1.0e-2)


text:
using Test
using LinearAlgebra
using Random
using KrylovKit

const n = 10
const N = 100

const η₀   = 0.75 # seems to be necessary to get sufficient convergence for GKL iteration with Float32 precision
const cgs = ClassicalGramSchmidt()
const mgs = ModifiedGramSchmidt()
const cgs2 = ClassicalGramSchmidt2()
const mgs2 = ModifiedGramSchmidt2()
const cgsr = ClassicalGramSchmidtIR(η₀)
const mgsr = ModifiedGramSchmidtIR(η₀)

Random.seed!(1234567)

include("linalg.jl")
include("factorize.jl")
include("linsolve.jl")
include("eigsolve.jl")
include("schursolve.jl")
include("svdsolve.jl")
include("expintegrator.jl")
include("recursivevec.jl")


text:
# Frequency
using Dates

abstract type Frequency end

struct NoFrequency <: Frequency end
struct Once <: Frequency end
struct Annual <: Frequency end
struct Semiannual <: Frequency end
struct EveryFourthMonth <: Frequency end
struct Quarterly <: Frequency end
struct Bimonthly <: Frequency end
struct Monthly <: Frequency end
struct EveryFourthWeek <: Frequency end
struct Biweekly <: Frequency end
struct Weekly <: Frequency end
struct Daily <: Frequency end
struct OtherFrequency <: Frequency end

# default value if no freq specified
value(::Frequency) = -1

value(::NoFrequency) = -1
value(::Once)			 	= 0
value(::Annual)			= 1
value(::Semiannual)		= 2
value(::EveryFourthMonth)  = 3
value(::Quarterly)		 	= 4
value(::Bimonthly)		 	= 6
value(::Monthly)			= 12
value(::EveryFourthWeek)  	= 13
value(::Biweekly)		 	= 26
value(::Weekly)			= 52
value(::Daily)			 	= 365
value(::OtherFrequency)   	= 999

period(::Annual) = Year(1)
period(::Semiannual) = Month(6)


text:
using MuZero

#=
@boardgame Connect4 (6,7) (21,21)
@actions [1,2,3,4]
@pieces [
    (name=:black, text="B", icon=(symbol="●", color="black")),
    (name=:red, text="R", icon=(symbol="●", color="red"))
]
=#

struct Connect4State <: AbstractBoardState
    board_state::BoardState{42}
end

Connect4State() = Connect4State(BoardState{42}())

#@todo change this to player "A" and "B"
const PLAYER_1_PIECES = [Piece(:black, "B", icon_symbol="●", icon_color="black", icon_size=60)]
const PLAYER_2_PIECES = [Piece(:red, "R", icon_symbol="●", icon_color="red", icon_size=60)]
const ALL_PIECES = [PLAYER_1_PIECES..., PLAYER_2_PIECES...]

MuZero.get_pieces(::Type{Connect4State}) = ALL_PIECES
MuZero.num_rows(::Type{Connect4State}) = 6
MuZero.num_cols(::Type{Connect4State}) = 7
MuZero.image_scale(::Type{Connect4State}) = 750
MuZero.image_title_offset(::Type{Connect4State}) = (75,45)
MuZero.actions(::Type{Connect4State}) = [1,2,3,4,5,6,7]

struct Connect4StateSVG
    s::Connect4State
end

struct Connect4 <: AbstractBoardGame
    history::Vector{<:Integer}
    states::Vector{Connect4State}
    rewards::Vector{Float32}
    function Connect4(history, states, rewards)
        @assert length(history) == length(rewards)
        @assert length(states) == (length(history) + 1)
        new(history, states, rewards)
    end
end

function Connect4()
    Connect4(
        Vector{Int8}(),
        [Connect4State()],
        Vector{Float32}(),
    )
end

Connect4(actions::Vector{<:Integer}) = init_game(Connect4, actions)

MuZero.getstatetype(::Type{Connect4}) = Connect4State

################################################

function MuZero.get_marker(g::Connect4, player::Integer, action::Integer)
    col_idx = action
    col = g[:, col_idx]
    row_idx = findlast(x->x==0, col)
    color = player == PLAYER_1 ? :black : :red
    piece = get_piece(g, color)
    Marker(row_idx, col_idx, piece)
end

function MuZero.get_winner(s::Connect4State)
    for player in [PLAYER_1, PLAYER_2]
        target = player * ones(UInt8, 4)
        for row_idx in 1:num_rows(s)
            for col_idx in 1:4
                if s[row_idx, col_idx:(col_idx+3)] == target
                    return player
                end
            end
        end
        for col_idx in 1:num_cols(s)
            for row_idx in 1:3
                if s[row_idx:(row_idx+3), col_idx] == target
                    return player
                end
            end
        end
    end
    nothing
end

function MuZero.legal_actions(g::Connect4)
    if game_is_won(g)
        return []
    end
    filter(col_idx->iszero(g[1,col_idx]), 1:num_cols(g))
end

function MuZero.getconfig(::Type{Connect4})
    config = make_board_game_config(
        Connect4,
        network_type=Incremental,
        max_moves=42,
        root_dirichlet_alpha=0.3,
        action_space_size=7, # Number of all possible actions in the game
        support_size = 10, # Value and reward are scaled (with almost sqrt) and encoded on a vector with a range of -support_size to support_size. Choose it so that support_size <= sqrt(max(abs(discounted reward)))
        observation_shape = (6, 7, 3),
        stacked_observations = 0, # Number of previous observations and previous actions to add to the current observation
        hidden_state_size = 32, # The 1-dimensional size of the encoded game state
        checkpoint_interval = 100, #  Number of training steps before using the model for self-playing
        num_actors = 3,
        weight_decay = 1e-3,
        lr_init=0.002f0,
        save_interval = 10000,
        num_unroll_steps=1,
    )
    config.batch_size = 10
    config.num_simulations = 10
    config.training_steps = 12000
    config
end

# @todo Remove this requirement
function MuZero.gettestfn(::Type{Connect4})
    function fn(n::Network)
        0.5
    end
end

function MuZero.policy_testset(t::Type{Connect4})
    d = Dict()
    d[Connect4([1,7,1,7,1,7])] = [1]
    d
end


text:
"""
    run_bot(f::Function, [tg::TelegramClient]; timeout = 10, brute_force_alive = false, offset = -1)

Run telegram bot, which executes function `f` repeatedly.

# Arguments

- `f`: function to run with the bot. As an input it receive [Message](https://core.telegram.org/bots/api#message) in the form of JSON3 object.
- `tg`: Telegram client, if not set then global telegram client is used.
- `timeout`: timeout limit of messages, defines when longpoll messages should be interrupted
- `brute_force_alive`: despite all measures, messages sometimes "hangs". You may use this argument to wake up telegram server regularly. When this option is set to `true` it works, but it is not recommended, since it makes additional calls. Consider this feature experimental and use at your own risk.
- `offset`: telegram message offset, useful if you have processed messages, but bot was interrupted and messages state was lost.
"""
function run_bot(f, tg::TelegramClient = DEFAULT_OPTS.client; timeout = 20, brute_force_alive = false, offset = -1)
    if brute_force_alive
        @async while true
            try
                getMe(tg)
                sleep(timeout ÷ 2)
            catch err
                @error err
            end
        end
    end

    while true
        try
            ignore_errors = true
            res = offset == -1 ? getUpdates(tg, timeout = timeout) : (ignore_errors = false;getUpdates(tg, timeout = timeout, offset = offset) )
            for msg in res
                try
                    f(msg)
                    offset = offset <= get(msg, :update_id, -1) ? get(msg, :update_id, -1) + 1 : offset
                catch err
                    @error err
                    if ignore_errors
                        offset = offset <= get(msg, :update_id, -1) ? get(msg, :update_id, -1) + 1 : offset
                    else
                        rethrow()
                    end
                end
            end
        catch err
            @error err
            if err isa InterruptException
                break
            end
        end
    end
end


text:
@testset "Tables" begin

    using DataFrames #Note: testing Tables via DataFrames.

    # DataFrame from Vector{Bedgraph.Record}.
    df = DataFrame(Bag.records)

    @test typeof(df) == DataFrame
    @test size(df) == (9,4)

    @test df.chrom == Bag.chroms
    @test df.first == Bag.firsts
    @test df.last == Bag.lasts
    @test df.value == Bag.values

    @test DataFrame(Bag.records) == Bag.records |> DataFrame

    # DataFrame from bedGraph file.
    df2 = DataFrame(load(Bag.file))

    @test typeof(df2) == DataFrame
    @test size(df2) == (9,4)

    @test df2.chrom == Bag.chroms
    @test df2.first == Bag.firsts
    @test df2.last == Bag.lasts
    @test df2.value == Bag.values

    @test DataFrame(load(Bag.file)) == load(Bag.file) |> DataFrame

    # DataFrame from headerless bedGraph file.
    df3 = DataFrame(load(Bag.file_headerless))
    @test typeof(df3) == DataFrame
    @test size(df3) == (9,4)

    @test df3.chrom == Bag.chroms
    @test df3.first == Bag.firsts
    @test df3.last == Bag.lasts
    @test df3.value == Bag.values

    @test DataFrame(load(Bag.file_headerless)) == load(Bag.file_headerless) |> DataFrame

    # Save and load from DataFrame.
    save(Bag.tmp_output_path, df)
    @test df == load(Bag.tmp_output_path) |> DataFrame

    df |> save(Bag.tmp_output_path)
    @test df == load(Bag.tmp_output_path) |> DataFrame

end # testset DataFrames


text:
# addition

# function (+){T<:Float120}(a::T,b::T)
function (+)(a::Float120,b::Float120)
    s1, s2 = eftAdd(a.hi,b.hi)
    t1, t2 = eftAdd(a.lo,b.lo)
    s2 += t1
    s1, s2 = eftAddGTE(s1,s2)
    s2 += t2
    s1, s2 = eftAddGTE(s1,s2)
    Float120(s1,s2)
end

function (+)(a::Float120,b::Float64)
    s1, s2 = eftAdd(a.hi,b)
    s2 += a.lo
    s1, s2 = eftAddGTE(s1,s2)
    Float120(s1,s2)
end

(+)(a::Float64,b::Float120) = (+)(b,a)
(+)(a::Float120,b::Signed) = (+)(a,convert(Float64,b))
(+)(a::Signed,b::Float120) = (+)(b,a)

(+)(a::Float120, b::Real) = (+)(promote(a,b)...)
(+)(a::Real, b::Float120) = (+)(promote(a,b)...)

# subtraction

function (-){T<:Float120}(a::T,b::T)
    s1, s2 = eftSub(a.hi,b.hi)
    t1, t2 = eftSub(a.lo,b.lo)
    s2 += t1
    s1, s2 = eftAddGTE(s1,s2)
    s2 += t2
    s1, s2 = eftAddGTE(s1,s2)
    Float120(s1,s2)
end

function (-)(a::Float120,b::Float64)
    s1, s2 = eftSub(a.hi,b)
    s2 += a.lo
    s1, s2 = eftAddGTE(s1,s2)
    Float120(s1,s2)
end

function (-)(a::Float64,b::Float120)
    s1, s2 = eftSub(a,b.hi)
    s2 -= b.lo
    s1, s2 = eftAddGTE(s1,s2)
    Float120(s1,s2)
end

(-)(a::Float120,b::Signed) = (-)(a,convert(Float64,b))
(-)(a::Signed,b::Float120) = (-)(convert(Float64,a),b)

(-)(a::Float120, b::Real) = (-)(promote(a,b)...)
(-)(a::Real, b::Float120) = (-)(promote(a,b)...)

# multiplication

function (sqr)(a::Float120)
  t1,t2 = eftMul(a.hi,a.hi)
  t3 = a.hi * a.lo
  t5 = t3 + t3
  t6 = t2 + t5
  t1,t6 = eftAddGTE(t1,t6)
  Float120(t1,t6)
end

function (*){T<:Float120}(a::T,b::T)
  t1,t2 = eftMul(a.hi,b.hi)
  t3 = a.hi * b.lo
  t4 = a.lo * b.hi
  t5 = t3 + t4
  t6 = t2 + t5
  t1,t6 = eftAddGTE(t1,t6)
  Float120(t1,t6)
end

function (*)(a::Float120,b::Float64)
  t1,t2 = eftMul(a.hi,b)
  t4 = a.lo * b
  t6 = t2 + t4
  t1,t6 = eftAddGTE(t1,t6)
  Float120(t1,t6)
end

(*)(a::Float64,b::Float120) = (*)(b,a)
(*)(a::Float120,b::Signed) = (*)(a,convert(Float64,b))
(*)(a::Signed,b::Float120) = (*)(convert(Float64,a),b)

(*)(a::Float120, b::Real) = (*)(promote(a,b)...)
(*)(a::Real, b::Float120) = (*)(promote(a,b)...)

function fma{T<:Float120}(a::T,b::T,c::T)
    hi,lo = eftFMAas2(a,b,c)
    Float120(hi,lo)
end

function fms{T<:Float120}(a::T,b::T,c::T)
    hi,lo = eftFMSas2(a,b,c)
    Float120(hi,lo)
end

# reciprocation

function (recip)(b::Float120)
  q1 = one(Float64) / b.hi
  r  = one(Float120) - q1*b

  q2 = r.hi / b.hi
  r = r - (q2 * b)

  q2 += r.hi / b.hi

  q3 = r.hi / b.hi

  q1,q2 = eftAdd(q1, q2)
  q1,q2 = eftAddAs2(q1,q2,q3)
  Float120(q1,q2)
end

# division

function (/){T<:Float120}(a::T,b::T)
  q1 = a.hi / b.hi
  r  = a - (q1 * b)

  q2 = r.hi / b.hi
  r = r - (q2 * b)

  q3 = r.hi / b.hi

  q1,q2 = eftAddGTE(q1, q2)
  q1,q2 = eftAddAs2(q1,q2,q3)
  Float120(q1,q2)
end

(/)(a::Float120, b::Real) = (/)(promote(a,b)...)
(/)(a::Real, b::Float120) = (/)(promote(a,b)...)

# powers

# roots

#=
      for a in [1e-15..1e18]
      relerr ~1.3e-32  (106 bits)
=#

function sqrt(a::Float120)
    if a.hi <= 0.0
       if a.hi == 0.0
           return zero(Float120)
       else
           throw(ArgumentError("sqrt expects a nonnegative base"))
       end
    #elseif (a.hi < 1.0e-18) | (a.hi > 1.0e18)
    #    throw(ArgumentError("sqrt arg ($a) outside domain"))
    end

    if (a.hi < 1.0e-7)  # -log2(1.0e-7) < (1/2) Float64 significand bits
        r = recip(a)
        s = sqrt(r)
        return recip(s)
    end
    # initial approximation to 1/sqrt(a)
    r = Float120(1.0/sqrt(a.hi), 0.0)
    r = r + divby2( r * (one(Float120) - (a*(r*r))) )
    r = r + divby2( r * (one(Float120) - (a*(r*r))) )
    r = r + divby2( r * (one(Float120) - (a*(r*r))) )

    r = a*r
    #divby2(r + a/r)
    r += a/r
    divby2(r)
end

function hypot(a::Float120, b::Float120)
    a = abs(a)
    b = abs(b)
    t, x = minmax(a,b)
    t = t/a
    t = sqr(t)
    t = sqrt(one(Digits30) + t)
    x * t
end

(hypot)(a::Float120, b::Real) = (hypot)(a, convert(Float120,b))
(hypot)(a::Real, b::Float120) = (hypot)(convert(Float120,a), b)