text:
using LightGraphs: AbstractSimpleGraph

## Convolution layers accepting AbstractSimpleGraph

function GCNConv(g::AbstractSimpleGraph, ch::Pair{<:Integer,<:Integer}, σ = identity;
                 init = glorot_uniform, T::DataType=Float32, bias::Bool=true)
    w = T.(init(ch[2], ch[1]))
    b = bias ? T.(init(ch[2])) : zeros(T, ch[2])
    fg = FeaturedGraph(g)
    GCNConv(w, b, σ, fg)
end

function ChebConv(g::AbstractSimpleGraph, ch::Pair{<:Integer,<:Integer}, k::Integer;
                  init = glorot_uniform, T::DataType=Float32, bias::Bool=true)
    b = bias ? T.(init(ch[2])) : zeros(T, ch[2])
    fg = FeaturedGraph(g)
    ChebConv(T.(init(ch[2], ch[1], k)), b, fg, k, ch[1], ch[2])
end

function GraphConv(g::AbstractSimpleGraph, ch::Pair{<:Integer,<:Integer}, aggr=:add;
                   init = glorot_uniform, T::DataType=Float32, bias::Bool=true)
    w1 = T.(init(ch[2], ch[1]))
    w2 = T.(init(ch[2], ch[1]))
    b = bias ? T.(init(ch[2])) : zeros(T, ch[2])
    GraphConv(FeaturedGraph(g), w1, w2, b, aggr)
end

function GATConv(g::AbstractSimpleGraph, ch::Pair{<:Integer,<:Integer}; heads=1,
                 concat::Bool=true, negative_slope=0.2, init=glorot_uniform,
                 T::DataType=Float32, bias::Bool=true)
    w = T.(init(ch[2]*heads, ch[1]))
    b = bias ? T.(init(ch[2]*heads)) : zeros(T, ch[2]*heads)
    a = T.(init(2*ch[2], heads, 1))
    GATConv(FeaturedGraph(g), w, b, a, negative_slope, ch, heads, concat)
end

function GatedGraphConv(g::AbstractSimpleGraph, out_ch::Integer, num_layers::Integer;
                        aggr=:add, init=glorot_uniform, T::DataType=Float32)
    w = T.(init(out_ch, out_ch, num_layers))
    gru = GRUCell(out_ch, out_ch)
    GatedGraphConv(FeaturedGraph(g), w, gru, out_ch, num_layers, aggr)
end

EdgeConv(g::AbstractSimpleGraph, nn; aggr::Symbol=:max) = EdgeConv(FeaturedGraph(g), nn, aggr)


text:
"""
    setcolor("gold")
    setcolor("darkturquoise")

Set the current color to a named color. This use the definitions in Colors.jl to convert a
string to RGBA eg `setcolor("gold")` or "green", "darkturquoise", "lavender", etc. The list
is at `Colors.color_names`.

Use `sethue()` for changing colors without changing current opacity level.

`sethue()` and `setcolor()` return the three or four values that were used:

    julia> setcolor(sethue("red")..., .8)

    (1.0, 0.0, 0.0, 0.8)

    julia> sethue(setcolor("red")[1:3]...)

    (1.0, 0.0, 0.0)

You can also do:

    using Colors
    sethue(colorant"red")

See also [`setcolor`](@ref).
"""
function setcolor(col::AbstractString)
    temp = parse(RGBA, col)
    # set Luxor settings
    set_current_redvalue(temp.r)
    set_current_greenvalue(temp.g)
    set_current_bluevalue(temp.b)
    set_current_alpha(temp.alpha)
    # and set Cairo context too
    Cairo.set_source_rgba(get_current_cr(), temp.r, temp.g, temp.b, temp.alpha)
    return (temp.r, temp.g, temp.b, temp.alpha)
end

"""
    setcolor(r, g, b)
    setcolor(r, g, b, alpha)
    setcolor(color)
    setcolor(col::Colors.Colorant)
    setcolor(sethue("red")..., .2)

Set the current color.

Examples:

    setcolor(convert(Colors.HSV, Colors.RGB(0.5, 1, 1)))
    setcolor(.2, .3, .4, .5)
    setcolor(convert(Colors.HSV, Colors.RGB(0.5, 1, 1)))

    for i in 1:15:360
       setcolor(convert(Colors.RGB, Colors.HSV(i, 1, 1)))
       ...
    end

See also [`sethue`](@ref).
"""
function setcolor(col::Colors.Colorant)
  temp = convert(RGBA, col)
  setcolor(temp.r, temp.g, temp.b, temp.alpha)
  return (temp.r, temp.g, temp.b, temp.alpha)
end

function setcolor(r, g, b, a = 1.0)
    set_current_redvalue(r)
    set_current_greenvalue(g)
    set_current_bluevalue(b)
    set_current_alpha(a)
    Cairo.set_source_rgba(get_current_cr(), r, g, b, a)
    return (r, g, b, a)
end

"""
Set the current color to a string using a macro.

For example:

    setcolor"red"
"""
macro setcolor_str(ex)
    isa(ex, String) || error("colorant requires literal strings")
    col = parse(RGBA, ex)
    quote
        set_current_redvalue($col.r)
        set_current_greenvalue($col.g)
        set_current_bluevalue($col.b)
        set_current_alpha($col.alpha)
        Cairo.set_source_rgba(get_current_cr(), get_current_redvalue(),
           get_current_greenvalue(), get_current_bluevalue(), $col.alpha)
    end
end

"""
    sethue("black")
    sethue(0.3, 0.7, 0.9)
    setcolor(sethue("red")..., .2)

Set the color without changing opacity.

`sethue()` is like `setcolor()`, but we sometimes want to change the current color without
changing alpha/opacity. Using `sethue()` rather than `setcolor()` doesn't change the current
alpha opacity.

See also [`setcolor`](@ref).
"""
function sethue(col::AbstractString)
    temp = parse(RGBA,  col)
    set_current_redvalue(temp.r)
    set_current_greenvalue(temp.g)
    set_current_bluevalue(temp.b)

    # use current alpha, not incoming one
    Cairo.set_source_rgba(get_current_cr(), get_current_redvalue(),
        get_current_greenvalue(), get_current_bluevalue(), get_current_alpha())
    return (temp.r, temp.g, temp.b)
end

"""
    sethue(col::Colors.Colorant)

Set the color without changing the current alpha/opacity:
"""
function sethue(col::Colors.Colorant)
    temp = convert(RGBA,  col)
    set_current_redvalue(temp.r)
    set_current_greenvalue(temp.g)
    set_current_bluevalue(temp.b)
    # use current alpha
    Cairo.set_source_rgba(get_current_cr(), temp.r, temp.g, temp.b, get_current_alpha())
    return (temp.r, temp.g, temp.b)
end

"""
    sethue(0.3, 0.7, 0.9)

Set the color's `r`, `g`, `b` values. Use `setcolor(r, g, b, a)` to set transparent colors.
"""
function sethue(r, g, b)
    set_current_redvalue(r)
    set_current_greenvalue(g)
    set_current_bluevalue(b)
    # use current alpha
    Cairo.set_source_rgba(get_current_cr(), r, g, b, get_current_alpha())
    return (r, g, b)
end

"""
    sethue((r, g, b))

Set the color to the tuple's values.
"""
sethue(col::NTuple{3, Number}) = sethue(col...)

"""
    sethue((r, g, b, a))

Set the color to the tuple's values.
"""
sethue(col::NTuple{4, Number}) = sethue(col...)

"""
    setcolor((r, g, b))

Set the color to the tuple's values.
"""
setcolor(col::NTuple{3, Number}) = setcolor(col...)

"""
    setcolor((r, g, b, a))

Set the color to the tuple's values.
"""
setcolor(col::NTuple{4, Number}) = setcolor(col...)

"""
    setopacity(alpha)

Set the current opacity to a value between 0 and 1. This modifies the alpha value of the
current color.
"""
function setopacity(a)
    # use current RGB values
    set_current_alpha(a)
    Cairo.set_source_rgba(get_current_cr(), get_current_redvalue(),
        get_current_greenvalue(), get_current_bluevalue(), a)
    return a
end

"""
    setgray(n)
    setgrey(n)

Set the color to a gray level of `n`, where `n` is between 0 and 1.
"""
setgray(n) = sethue(n, n, n)
setgrey(n) = setgray(n)

"""
    randomhue()

Set a random hue, without changing the current alpha opacity.
"""
function randomhue()
  rrand, grand, brand = rand(3)
  sethue(rrand, grand, brand)
  return (rrand, grand, brand)
end

"""
    randomcolor()

Set a random color. This may change the current alpha opacity too.
"""
function randomcolor()
  rrand, grand, brand, arand = rand(4)
  setcolor(rrand, grand, brand, arand)
  return (rrand, grand, brand, arand)
end

# compositing operators
const blendingmodes = ["clear", "source", "over", "in", "out", "atop", "dest", "dest_over", "dest_in", "dest_out", "dest_atop", "xor", "add", "saturate", "multiply", "screen", "overlay", "darken", "lighten"]

const blendingoperators = [Cairo.OPERATOR_CLEAR, Cairo.OPERATOR_SOURCE, Cairo.OPERATOR_OVER, Cairo.OPERATOR_IN, Cairo.OPERATOR_OUT, Cairo.OPERATOR_ATOP, Cairo.OPERATOR_DEST, Cairo.OPERATOR_DEST_OVER, Cairo.OPERATOR_DEST_IN, Cairo.OPERATOR_DEST_OUT, Cairo.OPERATOR_DEST_ATOP, Cairo.OPERATOR_XOR, Cairo.OPERATOR_ADD, Cairo.OPERATOR_SATURATE, Cairo.OPERATOR_MULTIPLY, Cairo.OPERATOR_SCREEN, Cairo.OPERATOR_OVERLAY, Cairo.OPERATOR_DARKEN, Cairo.OPERATOR_LIGHTEN]

#=
Not yet supported in Cairo.jl?

Cairo.OPERATOR_COLOR_DODGE, Cairo.OPERATOR_COLOR_BURN, Cairo.OPERATOR_HARD_LIGHT, Cairo.OPERATOR_SOFT_LIGHT, Cairo.OPERATOR_DIFFERENCE, Cairo.OPERATOR_EXCLUSION, Cairo.OPERATOR_HSL_HUE, Cairo.OPERATOR_HSL_SATURATION, Cairo.OPERATOR_HSL_COLOR, Cairo.OPERATOR_HSL_LUMINOSITY
=#

"""
    setmode(mode::AbstractString)

Set the compositing/blending mode. `mode` can be one of:

- `"clear"` Where the second object is drawn, the first is completely removed.
- `"source"` The second object is drawn as if nothing else were below.
- `"over"` The default mode: like two transparent slides overlapping.
- `"in"` The first object is removed completely, the second is only drawn where the first was.
- `"out"` The second object is drawn only where the first one wasn't.
- `"atop"` The first object is mostly intact, but mixes both objects in the overlapping area. The second object object is not drawn elsewhere.
- `"dest"` Discard the second object completely.
- `"dest_over"` Like "over" but draw second object below the first
- `"dest_in"` Keep the first object whereever the second one overlaps.
- `"dest_out"` The second object is used to reduce the visibility of the first where they overlap.
- `"dest_atop"` Like "over" but draw second object below the first.
- `"xor"` XOR where the objects overlap
- `"add"` Add the overlapping areas together
- `"saturate"` Increase Saturation where objects overlap
- `"multiply"` Multiply where objects overlap
- `"screen"` Input colors are complemented and multiplied, the product is complemented again. The result is at least as light as the lighter of the input colors.
- `"overlay"` Multiplies or screens colors, depending on the lightness of the destination color.
- `"darken"` Selects the darker of the color values in each component.
- `"lighten"` Selects the lighter of the color values in each component.

See the [Cairo documentation](https://www.cairographics.org/operators/) for details.
"""
function setmode(operator::AbstractString)
    indx = findfirst(isequal(operator), blendingmodes)
    if indx !== nothing
        Cairo.set_operator(get_current_cr(), blendingoperators[indx])
    end
end

"""
    getmode()

Return the current compositing/blending mode as a string.
"""
function getmode()
    return blendingmodes[Cairo.get_operator(get_current_cr()) + 1]
end

"""
    mask(point::Point, focus::Point, radius)
        max = 1.0,
        min = 0.0,
        easingfunction = easingflat)

Calculate a value between 0 and 1 for a `point` relative to a circular area
defined by `focus` and `radius`. The value will approach `max` (1.0) at the
center of the circular area, and `min` (0.0) at the circumference.
"""
function mask(point::Point, focus::Point, radius;
        max = 1.0,
        min = 0.0,
        easingfunction = easingflat)
    angle = slope(focus, point)
    d = distance(focus, point)
    dref = distance(focus, focus + polar(radius, angle))
    if d < dref
        k = rescale(d, 0.0, dref, max, min)
        ratio = easingfunction(k, 0.0, 1.0, 1.0)
    else
        ratio = 0.0
    end
    return ratio
end

"""
    mask(point::Point, focus::Point, width, height)
        max = 1.0,
        min = 0.0,
        easingfunction = easingflat)

Calculate a value between 0 and 1 for a `point` relative to a rectangular
area defined by `focus`, `width`, and `height`. The value will approach
`max` (1.0) at the center, and `min` (0.0) at the edges.
"""
function mask(point::Point, focus::Point, width, height;
    max = 1.0,
    min = 0.0,
    easingfunction = easingflat)

    bb = BoundingBox(box(focus, width, height, vertices=true))
    ptcross = pointcrossesboundingbox(point, bb)
    d = distance(focus, point)
    dref = distance(focus, ptcross)
    if d < dref
        k = rescale(d, 0.0, dref, max, min)
        ratio = easingfunction(k, 0.0, 1.0, 1.0)
    else
        ratio = 0.0
    end
    return ratio
end

ext: jl


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, Pkg.Types

name = "ROCmDeviceLibs"
version = v"4.2.0"

# Collection of sources required to build ROCm-Device-Libs
sources = [
    ArchiveSource("https://github.com/RadeonOpenCompute/ROCm-Device-Libs/archive/rocm-$(version).tar.gz",
                  "34a2ac39b9bb7cfa8175cbab05d30e7f3c06aaffce99eed5f79c616d0f910f5f"),
]

# Bash recipe for building across all platforms
script = raw"""
cd ${WORKSPACE}/srcdir/ROCm-Device-Libs*/
mkdir build && cd build

# we set CMAKE_TOOLCHAIN_FILE because it builds a host executable for use in the build process
# we don't ship any executable code, so this is ok
cmake -DCMAKE_PREFIX_PATH=${prefix} \
      -DCMAKE_INSTALL_PREFIX=${prefix} \
      -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN%.*}_clang.cmake \
      -DLLVM_DIR="${prefix}/lib/cmake/llvm" \
      -DClang_DIR="${prefix}/lib/cmake/clang" \
      -DLLD_DIR="${prefix}/lib/cmake/ldd" \
      ..
make -j${nproc}
make install
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = [
    Platform("x86_64", "linux"; libc="glibc"),
    Platform("x86_64", "linux"; libc="musl"),
]

#platforms = [p for p in supported_platforms() if Sys.islinux(p)]

# The products that we will ensure are always built
products = [
    FileProduct("amdgcn/bitcode/", :bitcode_path),
]

# Dependencies that must be installed before this package can be built
dependencies = [
    BuildDependency(PackageSpec(; name="LLVM_full_jll", version=v"12.0.1")),
    Dependency("Zlib_jll"),
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies;
               julia_compat="1.7",
               preferred_gcc_version=v"8", preferred_llvm_version=v"11")

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
using DrWatson
@quickactivate
using HierarchicalAD
using FileIO, BSON
using StatsBase
using ProgressMeter
using Colors

N_samples = 100000

font_size = 24
img_size = (28, 28)
fonts = ["Georgia", "", "Arial", "Ubuntu Mono", "Free Mono", "Eufm10", "Lobster Two", "Purisa", "Manjari Thin", "Chilanka", "Uroob", "MathJax_Typewriter"]
accents = ["", " Bold"]
digs = 0:9
cols = collect(keys(Colors.color_names))
rots = [-20, -10, -5, -3, 0, 3, 5, 10, 20]
shearxs = -20:20
shearys = -20:20
zooms =0.9:0.01:1.2

sample_input() = map(x->sample(x,1)[1], (fonts, accents, digs, cols, rots, shearxs, shearys, zooms))

inputs = map(i->sample_input(), 1:N_samples)
inputf = datadir("digits_rgb/labels.bson")
save(inputf, Dict(:labels => inputs))

@info "Generating digits..."
outputs = @showprogress map(i->HierarchicalAD.create_digit_rgb(font_size, img_size, i...), inputs)
outputf = datadir("digits_rgb/digits.bson")
save(outputf, Dict(:digits=> outputs))

max_stars_repo_name: vitskvara/HierarchicalAD

max_issues_repo_name: vitskvara/HierarchicalAD

max_forks_repo_name: vitskvara/HierarchicalAD


text:
using Nextion
using Test

@testset "radio" begin

    nexSerial = NexSerial("/dev/ttyUSB0")

    nexRadio0 = NexRadio(nexSerial, Name("r0"), cid=ComponentID(8))
    nexRadio1 = NexRadio(nexSerial, Name("r1"), cid=ComponentID(9))
    nexRadio2 = NexRadio(nexSerial, Name("r2"), cid=ComponentID(10))

    send(nexSerial, "page pg_dsb_chk_rad")

    nexRadio0.value = false
    nexRadio1.value = false
    nexRadio2.value = false

    @test !nexRadio0.value

    sleep(1)

    nexRadio0.value = true

    @test nexRadio0.value

    sleep(1)

    nexRadio0.value = false

    @test !nexRadio0.value

    sleep(1)

    close(nexSerial)

    @test true

end


text:
using Swagger
using Test

const gencmd = joinpath(dirname(@__FILE__()), "petstore", "generate.sh")

include("utilstests.jl")

@testset "Swagger" begin
    @testset "Utils" begin
        test_longpoll_exception_check()
    end
    @testset "Code generation" begin
        # set the current julia executable to be used henceforth
        ("JULIA" in keys(ENV)) || (ENV["JULIA"] = joinpath(Sys.BINDIR, "julia"))

        @info("Generating petstore", gencmd)
        run(`$gencmd`)
    end
    @testset "Petstore" begin
        if get(ENV, "RUNNER_OS", "") == "Linux"
            @info("Running petstore tests")
            include("petstore/runtests.jl")
        else
            @info("Skipping petstore tests in non Linux environment (can not run petstore docker on OSX or Windows)")
        end
    end
end


text:
struct GeneralizedEstimatingEquation <: GeneralizedEstimatingEquationModel
    GEE
    β
    ϕ::Real
    μ
    η
    d::Distribution
    l::Link
    R
end

struct Model{T<:AbstractFloat}
    X::Matrix{T}
    y::Vector{T}
    d::Distribution
    l::Link
end

mutable struct GeeDens
    yᵢ::Vector
    Xᵢ::Vector
    μᵢ::Vector
    rᵢ::Vector
    iter::Real
    converged::Bool
end

function GeeModel(f::FormulaTerm, data, d::Distribution, l::Link, contrasts = Dict{Symbol,Any}())
    sch = schema(f, data, contrasts)
    f = apply_schema(f, sch)
    y, X = modelcols(f, data)
    Model(X, y, d, l)
end

function GeeDens(y, X, μ, r, id)
    uid = unique(id)
    Xᵢ, yᵢ, μᵢ, rᵢ = [], [], [], []
    for ident in uid
        keep = id .== ident
        push!(Xᵢ, X[keep, :])
        push!(yᵢ, y[keep])
        push!(μᵢ, μ[keep])
        push!(rᵢ, r[keep])
    end
    GeeDens(yᵢ, Xᵢ, μᵢ, rᵢ, 0, false)
end

Base.size(x::GeeDens) = (n = size(x.Xᵢ, 1), m =  maximum(size.(x.Xᵢ, 1)))

function GeneralizedEstimatingEquation(
    f::FormulaTerm,
    data,
    d::Distribution,
    l::Link = canonicallink(d),
    id = [],
    corstr::CorrelationStructure = Independence;
    contrasts = Dict{Symbol,Any}(),
    maxitr::Integer = 10,
    tol::Real = 0.0001
    )

    Xy = GeeModel(f, data, d, l, contrasts)  # extract X and y from a formula
    ifit = glm(Xy.X, Xy.y, d, l)            # conduct initial fit using glm
    β = coef(ifit)                          # extract initial coefficient estimates
    params = GeeDens(Xy.X, Xy.y, ifit.rr.mu, ifit.rr.wrkresid, id) # create Dens predict object where necessary components split by id

    GeneralizedEstimatingEquation(params, d, l, β, corstr, maxitr = maxitr, tol = tol)
end

function GeneralizedEstimatingEquation(
    x,
    d::Distribution,
    l::Link,
    beta,
    corstr;
    maxitr::Integer = 10,
    tol::Real = 0.0001)

    β = copy(beta)
    n, m = size(x)

    local ϕ, D, V, R
    while x.iter <= maxitr
        x.iter += 1

        e = pearson.(d, x.yᵢ, x.μᵢ)
        ϕ = phi(e)
        α = updateα(corstr, n, m, e, ϕ)
        R = corstr(m, α)
        V = [updateV(R, μ) for μ in x.μᵢ]
        D = [updateD(d, X, μ) for (X, μ) in zip(x.Xᵢ, x.μᵢ)]
        βnew = updateβ(β, D, V, x.rᵢ)

        if maximum(abs.((βnew .- β) ./ (β .+ eps(0.0)))) < tol
            x.converged = true
            break
        else
            β = βnew
            x.μᵢ = [X*β for X in x.Xᵢ]
            x.rᵢ = [y - μ for (y, μ) in zip(x.yᵢ, x.μᵢ)]
        end
    end

    μ = collect(Iterators.flatten(x.μᵢ))
    η = linkfun.(l, μ)
    return GeneralizedEstimatingEquation(x, β, ϕ, μ, η, d, l, R)
end

function updateβ(β, D, V, r)
    K = size(D, 1)
    β + sum([D'[j] * V[j]^-1 * D[j] for j in 1:K])^-1 * sum([D'[j] * V[j]^-1 * r[j] for j in 1:K])
end


text:
using FoodCachingFitting
using Test

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


text:
using DashBootstrapComponents, DashHtmlComponents

list_group = html_div([
    dbc_listgroup(
        [
            dbc_listgroupitem("Item 1"),
            dbc_listgroupitem("Item 2"),
            dbc_listgroupitem("Item 3"),
        ],
        horizontal=true,
        className="mb-2",
    ),
    dbc_listgroup(
        [
            dbc_listgroupitem("Item 1"),
            dbc_listgroupitem("Item 2"),
            dbc_listgroupitem("Item 3"),
        ],
        horizontal="lg",
    ),
]);

max_stars_repo_name: harisbal/dash-bootstrap-components

max_issues_repo_name: harisbal/dash-bootstrap-components

max_forks_repo_name: harisbal/dash-bootstrap-components


text:
"Filters HMM outout and filters out desired matches"
function extract_rRNA_names(names_file::String, r16s::String, t16s::String, minl::Int, input::String)
    namesf = open(names_file, "w")

    # get read limit
    r_data = split(r16s, ":")
    r_star = parse(Int64, r_data[1])
    r_end = parse(Int64, r_data[2])
    println(stderr, "Filtering out matches in reads between $r_star:$r_end")

    # get red limit
    t_data = split(t16s, ":")
    t_star = parse(Int64, t_data[1])
    t_end = parse(Int64, t_data[2])
    t_star, t_end = sort([t_star, t_end])
    r_star, r_end = sort([r_star, r_end])
    println(stderr, "Filtering out matches in template between $t_star:$t_end")
    chosen_reads = Set{String}()
    # read the hmm output
    open(input) do f
        line = 1
        while !eof(f)
            x = readline(f)
            x = lstrip(x)
            if x[1] != '#'
                parts = split(x)
                rname = parts[1]
                ts = parse(Int64, parts[5])
                te = parse(Int64, parts[6])
                rs = parse(Int64, parts[9])
                re = parse(Int64, parts[10])
                ts, te = sort([ts, te])
                rs, re = sort([rs, re])

                if ((re-rs+1) >= minl) && (ts >= t_star) && (ts <= t_end) && (te >= t_star) && (te <= t_end) && (rs >= r_star) && (rs <= r_end) && (re >= r_star) && (re <= r_end)
                    println(namesf, rname)
                    push!(chosen_reads, rname)
                end
            end
            line += 1
        end
    end
    close(namesf)
    return chosen_reads
end


text:
function foo()
    a = 10
    b = a
end

function main()
    foo()
end


text:
import Dagger: Thunk
export show_plan

function node_label(io, t::Thunk, c)
    if isa(t.f, Function)
        println(io, "$(t.id) [label=\"$(t.f)\"]")
    else
        println(io, "$(t.id) [label=\"fn\"]")
    end
    c
end

function node_label(io, t,c)
    l = replace(string(t), "\"", "")
    println(io, dec(hash(t)), " [label=\"$l\"]")
end

global _part_labels = Dict()

function node_label(io, t::Chunk, c)
    _part_labels[t]="part_$c"
    c+1
end

function node_id(t::Thunk)
    t.id
end

function node_id(t)
    dec(hash(t))
end

function node_id(t::Chunk)
    _part_labels[t]
end

function write_dag(io, t)
    !istask(t) && return
    deps = dependents(t)
    c=1
    for k in keys(deps)
        c = node_label(io, k, c)
    end
    for (k, v) in deps
        for dep in v
            if isa(k, Union{Chunk, Thunk})
                println(io, "$(node_id(k)) -> $(node_id(dep))")
            end
        end
    end
end

function show_plan(t::Thunk)
    io = IOBuffer()
    write_dag(io, t)
    """digraph {
        graph [layout=dot, rankdir=TB];
        $(String(take!(io)))
    }"""
end

function show_plan(c)
    t = thunkize(Context(), stage(Context(), c))
    show_plan(t)
end

function show_plan(t::Tuple)
    show_plan(TupleCompute(t))
end

# function printing

argname(x::Symbol) = x

function argname(x)
    @assert x.head == :(::)
    x.args[1]
end

function show_statement(io, x)
    if x.head == :return
        x = x.args[1]
    end
    print(io, x)
end

function fnbody(io, x)
    body = x.args[3]
    statements = filter(x -> !isa(x, LineNumberNode), body.args)
    for s in statements
        show_statement(io, s)
    end
end

function show_ast(io, f)
    ast = Base.uncompressed_ast(f.code)
    args = map(x -> string(argname(x)), ast.args[1])
    write(io, "(", join(args, ','), ") -> ")
    fnbody(io, ast)
end

function showfn(io, f::Function)
    if isa(f, Function)
        show(io, f)
    else
        show_ast(io, f)
    end
end
showfn(io, f) = show(io, f)


text:
module DataWrapper

using JavaCall

const AbsoluteDate = @jimport org.orekit.time.AbsoluteDate
const AbstractListCrawler = @jimport org.orekit.data.AbstractListCrawler
const AbstractSelfFeedingLoader = @jimport org.orekit.data.AbstractSelfFeedingLoader
const BodiesElements = @jimport org.orekit.data.BodiesElements
const CelestialBodies = @jimport org.orekit.bodies.CelestialBodies
const Class = @jimport java.lang.Class
const ClassLoader = @jimport java.lang.ClassLoader
const ClasspathCrawler = @jimport org.orekit.data.ClasspathCrawler
const CompositeDataContext = @jimport org.orekit.data.CompositeDataContext
const DataContext = @jimport org.orekit.data.DataContext
const DataFilter = @jimport org.orekit.data.DataFilter
const DataLoader = @jimport org.orekit.data.DataLoader
const DataProvider = @jimport org.orekit.data.DataProvider
const DataProvidersManager = @jimport org.orekit.data.DataProvidersManager
const DelaunayArguments = @jimport org.orekit.data.DelaunayArguments
const DirectoryCrawler = @jimport org.orekit.data.DirectoryCrawler
const ExceptionalDataContext = @jimport org.orekit.data.ExceptionalDataContext
const FieldAbsoluteDate = @jimport org.orekit.time.FieldAbsoluteDate
const FieldBodiesElements = @jimport org.orekit.data.FieldBodiesElements
const FieldDelaunayArguments = @jimport org.orekit.data.FieldDelaunayArguments
const File = @jimport java.io.File
const FilesListCrawler = @jimport org.orekit.data.FilesListCrawler
const Frames = @jimport org.orekit.frames.Frames
const FundamentalNutationArguments = @jimport org.orekit.data.FundamentalNutationArguments
const GeoMagneticFields = @jimport org.orekit.models.earth.GeoMagneticFields
const GravityFields = @jimport org.orekit.forces.gravity.potential.GravityFields
const GzipFilter = @jimport org.orekit.data.GzipFilter
const IERSConventions = @jimport org.orekit.utils.IERSConventions
const InputStream = @jimport java.io.InputStream
const JString = @jimport java.lang.String
const LazyLoadedCelestialBodies = @jimport org.orekit.bodies.LazyLoadedCelestialBodies
const LazyLoadedDataContext = @jimport org.orekit.data.LazyLoadedDataContext
const LazyLoadedFrames = @jimport org.orekit.frames.LazyLoadedFrames
const LazyLoadedGeoMagneticFields = @jimport org.orekit.models.earth.LazyLoadedGeoMagneticFields
const LazyLoadedGravityFields = @jimport org.orekit.forces.gravity.potential.LazyLoadedGravityFields
const LazyLoadedTimeScales = @jimport org.orekit.time.LazyLoadedTimeScales
const List = @jimport java.util.List
const Map = @jimport java.util.Map
const NamedData = @jimport org.orekit.data.NamedData
const NamedData_StreamOpener = @jimport org.orekit.data.NamedData$StreamOpener
const NetworkCrawler = @jimport org.orekit.data.NetworkCrawler
const NutationCodec = @jimport org.orekit.data.NutationCodec
const Object = @jimport java.lang.Object
const Pattern = @jimport java.util.regex.Pattern
const PoissonSeries = @jimport org.orekit.data.PoissonSeries
const PoissonSeriesParser = @jimport org.orekit.data.PoissonSeriesParser
const PoissonSeries_CompiledSeries = @jimport org.orekit.data.PoissonSeries$CompiledSeries
const PolynomialNutation = @jimport org.orekit.data.PolynomialNutation
const PolynomialParser = @jimport org.orekit.data.PolynomialParser
const PolynomialParser_Unit = @jimport org.orekit.data.PolynomialParser$Unit
const RealFieldElement = @jimport org.hipparchus.RealFieldElement
const SeriesTerm = @jimport org.orekit.data.SeriesTerm
const Set = @jimport java.util.Set
const SimpleTimeStampedTableParser = @jimport org.orekit.data.SimpleTimeStampedTableParser
const SimpleTimeStampedTableParser_RowConverter = @jimport org.orekit.data.SimpleTimeStampedTableParser$RowConverter
const TimeScale = @jimport org.orekit.time.TimeScale
const TimeScales = @jimport org.orekit.time.TimeScales
const URL = @jimport java.net.URL
const UnixCompressFilter = @jimport org.orekit.data.UnixCompressFilter
const ZipJarCrawler = @jimport org.orekit.data.ZipJarCrawler

export AbstractListCrawler
export AbstractSelfFeedingLoader
export BodiesElements
export ClasspathCrawler
export CompositeDataContext
export DataContext
export DataFilter
export DataLoader
export DataProvider
export DataProvidersManager
export DefaultDataContextHolder
export DelaunayArguments
export DirectoryCrawler
export ExceptionalDataContext
export FieldBodiesElements
export FieldDelaunayArguments
export FilesListCrawler
export FundamentalNutationArguments
export GeneralTerm
export GzipFilter
export LazyLoadedDataContext
export LuniSolarTerm
export NamedData
export NetworkCrawler
export NoFarPlanetsTerm
export NutationCodec
export PlanetaryTerm
export PoissonSeries
export PoissonSeriesParser
export PolynomialNutation
export PolynomialParser
export SeriesTerm
export SimpleTimeStampedTableParser
export TideTerm
export UnixCompressFilter
export ZipJarCrawler
export add
export add_default_providers
export add_filter
export add_input
export add_provider
export apply_all_filters
export build_term
export clear_filters
export clear_loaded_data_names
export clear_providers
export compile
export decode
export derivative
export encode
export equals
export evaluate_all
export feed
export filter
export get_celestial_bodies
export get_class
export get_cos_coeff
export get_d
export get_d_dot
export get_data_providers_manager
export get_date
export get_default
export get_degree
export get_f
export get_f_dot
export get_frames
export get_gamma
export get_gamma_dot
export get_geo_magnetic_fields
export get_gravity_fields
export get_inputs
export get_key
export get_l
export get_l_dot
export get_l_ju
export get_l_ju_dot
export get_l_ma
export get_l_ma_dot
export get_l_me
export get_l_me_dot
export get_l_ne
export get_l_ne_dot
export get_l_prime
export get_l_prime_dot
export get_l_sa
export get_l_sa_dot
export get_l_ur
export get_l_ur_dot
export get_l_ve
export get_l_ve_dot
export get_le
export get_le_dot
export get_loaded_data_names
export get_name
export get_non_polynomial_size
export get_omega
export get_omega_dot
export get_pa
export get_pa_dot
export get_polynomial
export get_providers
export get_sin_coeff
export get_stream_opener
export get_tc
export get_time_scales
export hash_code
export is_supported
export load_data
export notify
export notify_all
export parse
export remove_provider
export set_default
export set_timeout
export still_accepts_data
export to_string
export value
export wait
export with_doodson
export with_first_delaunay
export with_first_planetary
export with_gamma
export with_optional_column
export with_polynomial_part
export with_sin_cos

include("abstract_list_crawler.jl")
include("abstract_self_feeding_loader.jl")
include("bodies_elements.jl")
include("classpath_crawler.jl")
include("composite_data_context.jl")
include("data_context.jl")
include("data_filter.jl")
include("data_loader.jl")
include("data_provider.jl")
include("data_providers_manager.jl")
include("default_data_context_holder.jl")
include("delaunay_arguments.jl")
include("directory_crawler.jl")
include("exceptional_data_context.jl")
include("field_bodies_elements.jl")
include("field_delaunay_arguments.jl")
include("files_list_crawler.jl")
include("fundamental_nutation_arguments.jl")
include("general_term.jl")
include("gzip_filter.jl")
include("lazy_loaded_data_context.jl")
include("luni_solar_term.jl")
include("named_data.jl")
include("network_crawler.jl")
include("no_far_planets_term.jl")
include("nutation_codec.jl")
include("planetary_term.jl")
include("poisson_series.jl")
include("poisson_series_parser.jl")
include("polynomial_nutation.jl")
include("polynomial_parser.jl")
include("series_term.jl")
include("simple_time_stamped_table_parser.jl")
include("tide_term.jl")
include("unix_compress_filter.jl")
include("zip_jar_crawler.jl")

end


text:
using Base: TwicePrecision
using StaticRanges: TPVal

@testset "twice precision" begin
    tp = TwicePrecision(1)

    @test TPVal(tp) == TPVal{Int,1,0}()
    @test TwicePrecision(TPVal(tp)) == tp
    @test TPVal{Int}(tp) == TPVal{Int,1,0}()
    @test TPVal{Float64}(tp) == TPVal{Float64,1.0,0.0}()
    @test convert(TwicePrecision{Float64}, TPVal{Int,1,0}()) == TwicePrecision(1.0)

    tpval = TPVal(tp)

    @test eltype(tpval) == eltype(tp)
    @test eltype(typeof(tpval)) == eltype(tp)

    @test StaticRanges.tp2val(1) == 1
    @test StaticRanges.tp2val(tp) == tpval
    @test Int(tpval) == Int(tp)
    @test convert(Int, tpval) == Int(tp)
end


text: Dict{String,Any}("neg" => Dict{String,Any}("value" => "0.03","type" => "float"),"zero" => Dict{String,Any}("value" => "3.0","type" => "float"),"pointupper" => Dict{String,Any}("value" => "310.0","type" => "float"),"lower" => Dict{String,Any}("value" => "300.0","type" => "float"),"upper" => Dict{String,Any}("value" => "300.0","type" => "float"),"pos" => Dict{String,Any}("value" => "300.0","type" => "float"),"pointlower" => Dict{String,Any}("value" => "310.0","type" => "float"))

max_stars_repo_name: SmiteWindows/julia

max_issues_repo_name: SmiteWindows/julia

max_forks_repo_name: SmiteWindows/julia


text:
using Plots, Distributions, LatexStrings

## Figure 2 - robust ellipsoids

a1 = rand(Normal(10,2), 100)
a2 = rand(Normal(5,3), 100)

scatter(a1, a2, label = "observations", title="Distribution of (a1, a2)")
scatter!((10,5), shape =:square,label="nominal")

# create an ellipse in the sky
pts = Plots.partialcircle(0,2π,200)
x1, y1 = Plots.unzip(pts)
x2, y2 = Plots.unzip(pts)
x1 = 2x1 + 10
y1 += 3y1 + 5
x2 = 3x2 + 10
y2 += 5.5y2 + 5

plot!(Shape(x2,y2), label="Gamma2", opacity=.1)
plot!(Shape(x1,y1), label="Gamma1", opacity=.1)

savefig("Figure2.pdf")

## Figure 3 - classifier

using JuMP, Ipopt

# Generating random multivariate data.
data11 = rand(Normal(8, 4), 100)
data12 = rand(Normal(10, 2), 100)
data1 = [data11 data12]

data01 = rand(Normal(2, 6), 100)
data02 = rand(Normal(5, 2), 100)
data0 = [data01 data02]

scatter(data1[:,1], data1[:,2], label="Pos. obs.")
scatter!(data0[:,1], data0[:,2], label="Neg. obs.")

function classify(data1, data0, δ)
    m = Model(solver = IpoptSolver())

    @variable(m, u[1:100] >= 0)
    @variable(m, v[1:100] >= 0)
    @variable(m, a[1:2])
    @variable(m, b)

    @constraint(m, error1[i=1:100], sum(a[j]*data1[i,j] for j = 1:2) + b - u[i] <= -1)
    @constraint(m, error0[i=1:100], sum(a[j]*data0[i,j] for j = 1:2) + b + v[i] >= 1)

# This parameter trades off accuracy and robustness for the classifier
    @objective(m, Min, sum(u[i] for i=1:100) + sum(v[i] for i=1:100) + δ*(sum(a[i]^2 for i=1:2)))

    solve(m);

    return getvalue(a), getvalue(b)
end

a, b = classify(data1, data0, 0.5)

# Calculating the points on plane defined by a and b
x1 = linspace(-10,20,100);
x2 = -(b + a[1]*x1)/ a[2];
# boundaries of the slab
x2u = -(b + 1 + a[1]*x1)/ a[2];
x2d = -(b - 1 + a[1]*x1)/ a[2];
plot!(x1, [x2u x2 x2d],
    xlabel = "x_1",
    ylabel = "x_2",
    label= [ "", "Classifier", ""] ,
    color=[:green :green :green],
    linestyle=[ :dot :solid :dot],
    )

savefig("Figure3.pdf")


text:
using RobustAndOptimalControl, ControlSystems

G = tf(200, [10, 1])*tf(1, [0.05, 1])^2     |> ss
Gd = tf(100, [10, 1])                       |> ss
W1 = tf([1, 2], [1, 1e-6])                  |> ss
Gs = G*W1
Ks, γmin = glover_mcfarlane(Gs, 1.1)
@test γmin ≈ 2.34 atol=0.005

if isinteractive()
    bodeplot([G, Gs, Gs*Ks]) |> display

    plot( step(Gd*feedback(1, G*W1), 3))
    plot!(step(Gd*feedback(1, G*W1*Ks), 3)) |> display

    nyquistplot([G*W1, G*W1*Ks], ylims=(-2,1), xlims=(-2, 1), Ms_circles=1.5) |> display
end

W1h = hanus(W1)
@test W1h.nu == 2W1.nu


text:
"""
    import_highlights(csv::String, target::String; quiet::Bool=false) -> Nothing

Import the highlights (and related data) into a CSV file from a PDF file or directory with
PDF files.

# Arguments
- `csv::String`: $(CSV_ARGUMENT)
- `target::String`: $(TARGET_PDF_ARGUMENT)

# Keywords
- `quiet::Bool=false`: if `true`, don't print to standard output

# Throws
- [`IntegrityCheckFailed`](@ref): $(INTEGRITY_CHECK_FAILED_EXCEPTION)
- Exceptions from: [`initialize`](@ref)

# Example
```jldoctest; output = false
using PDFHighlights
using Suppressor

path_to_pdf_dir = joinpath(pathof(PDFHighlights) |> dirname |> dirname, "test", "pdf")
path_to_pdf = joinpath(path_to_pdf_dir, "TestPDF.pdf")

_file, io = mktemp()
file = _file * ".csv"
mv(_file, file)

(@capture_out(import_highlights(file, path_to_pdf)) ==
\"\"\"

    CSV: "\$(basename(file))"
    PDF: "TestPDF.pdf"
    Highlights (found / added): 7 / 7

\"\"\") |> println

(@capture_out(import_highlights(file, path_to_pdf_dir)) ==
\"\"\"

    CSV: "\$(basename(file))"
    Directory: "pdf"
    Highlights (found / added): 7 / 0

\"\"\") |> println

@capture_out(import_highlights(file, path_to_pdf; quiet=true)) == ""

# output

true
true
true
```
"""
function import_highlights(csv::String, target::String; quiet::Bool=false)::Nothing

    try
        initialize(csv)
    catch
        throw(IntegrityCheckFailed(csv))
    end

    existing_lines = readlines(csv)

    all_highlights = String[]
    all_comments = String[]

    if isdir(target)

        new_lines = String[]

        for (root, dirs, files) in walkdir(target), file in files
            if endswith(file, ".pdf")

                path = joinpath(root, file)

                author, title = map(
                    collection -> replace.(collection, "\"" => "\"\""),
                    get_author_title(path)
                )

                highlights, comments, pages = get_highlights_comments_pages(path)

                replace!(highlight -> replace(highlight, "\"" => "\"\""), highlights)
                replace!(comment -> replace(comment, "\"" => "\"\""), comments)

                all_highlights = vcat(all_highlights, highlights)
                all_comments = vcat(all_comments, comments)

                new_lines = vcat(
                    new_lines,
                    string.(
                        "\"",
                        highlights,
                        "\",\"",
                        title,
                        "\",\"",
                        author,
                        "\",\"",
                        comments,
                        "\",",
                        pages
                    )
                )

            end
        end

    else

        author, title = map(
            collection -> replace.(collection, "\"" => "\"\""),
            get_author_title(target)
        )

        highlights, comments, pages = get_highlights_comments_pages(target)

        replace!(highlight -> replace(highlight, "\"" => "\"\""), highlights)
        replace!(comment -> replace(comment, "\"" => "\"\""), comments)

        all_highlights = highlights
        all_comments = comments

        new_lines = string.(
            "\"",
            highlights,
            "\",\"",
            title,
            "\",\"",
            author,
            "\",\"",
            comments,
            "\",",
            pages,
        )

    end

    # Get the number of highlights found in the pdf
    found = length(new_lines)

    # Filter existing strings
    new_lines = filter(line -> !(line in existing_lines), new_lines)

    # Get the number of highlights that will be added to the table
    added = length(new_lines)

    # Write the new lines
    if !isempty(new_lines)
        open(csv, "a") do io
            println(io, join(new_lines, '\n'))
        end
    end

    if !quiet
        if isdir(target)

            dir = normpath(target)
            basename_dir = basename(dir)

            if basename_dir == ""
                dir = basename(dirname(dir))
            else
                dir = basename_dir
            end

            println("""

                CSV: "$(basename(csv))"
                Directory: "$(basename(dir))"
                Highlights (found / added): $(found) / $(added)
            """)

        else

            println("""

                CSV: "$(basename(csv))"
                PDF: "$(basename(target))"
                Highlights (found / added): $(found) / $(added)
            """)

        end
    end

    return nothing

end


text:
# This file is a part of BAT.jl, licensed under the MIT License (MIT).

"""
    struct AHMIntegration <: IntegrationAlgorithm

Adaptive Harmonic Mean Integration algorithm
([Caldwell et al.](https://arxiv.org/abs/1808.08051)).

Constructors:

* ```$(FUNCTIONNAME)(; fields...)```

Fields:

$(TYPEDFIELDS)
"""
@with_kw struct AHMIntegration{
    WA<:WhiteningAlgorithm,
    AC<:AutocorLenAlgorithm
} <: IntegrationAlgorithm
    whitening::WA = CholeskyPartialWhitening()
    autocorlen::AC = GeyerAutocorLen()
    volumetype::Symbol = :HyperRectangle
    max_startingIDs::Int = 10000
    max_startingIDs_fraction::Float64 = 2.5
    rect_increase::Float64 = 0.1
    warning_minstartingids::Int = 16
    dotrimming::Bool = true

    """
    List of uncertainty estimation methods
    to use, first entry will be used for primary result. Valid values:

    * `:cov`: Integral uncertainty for integration regions is estimated based
      on covariance of integrals of subsets of samples in the regions

    * `:ess`: Integral uncertainty for integration regions is estimated based
      on estimated effective number of samples in each region.
    """
    uncertainty::Vector{Symbol} = [:cov]
end
export AHMIntegration

function bat_integrate_impl(target::DensitySampleVector, algorithm::AHMIntegration)
    hmi_data = HMIData(unshaped.(target))

    integrationvol = algorithm.volumetype

    uncertainty_est_mapping = Dict(
        :cov => ("cov_weighted" => hm_combineresults_covweighted!),
        :ess => ("ess_weighted" => hm_combineresults_analyticestimation!),
    )

    uncertainty_estimators = Dict(uncertainty_est_mapping[u] for u in algorithm.uncertainty)

    primary_uncertainty_estimator = uncertainty_est_mapping[first(algorithm.uncertainty)][1]

    hmi_settings = HMISettings(
        _amhi_whitening_func(algorithm.whitening),
        algorithm.max_startingIDs,
        algorithm.max_startingIDs_fraction,
        algorithm.rect_increase,
        true,
        algorithm.warning_minstartingids,
        algorithm.dotrimming,
        uncertainty_estimators
    )

    hm_integrate!(hmi_data, integrationvol, settings = hmi_settings)

    result = hmi_data.integralestimates[primary_uncertainty_estimator].final

    integral = Measurements.measurement(result.estimate, result.uncertainty)
    (result = integral, info = hmi_data) # this is needed to debug integration. can be removed later.
end

function bat_integrate_impl(target::AnySampleable, algorithm::AHMIntegration)
    npar = totalndof(varshape(target))
    samples = bat_sample(target).result::DensitySampleVector
    bat_integrate(samples, algorithm)
end


text:
# # Timing evolution and structure function evaluation

# Based on the `timing.f` test job.

using QCDNUM
using Printf

# Again, we start by defining the necessary inputs...

xmin = Float64.([1e-5, 0.2, 0.4, 0.6, 0.75])
iwt = Int32.([1, 2, 4, 8, 16])
ngx = 5
nxin = 100
iosp = 3
nx = 0
qlim = Float64.([2e0, 1e4])
wt = Float64.([1e0, 1e0])
ngq = 2
nqin = 50
nq = 1
itype = 1
filename = "weights/unpolarised.wgt"
iord = 3
as0 = 0.364
r20 = 2.0
q2c = 3.0
q2b = 25.0
q0 = 2.0
nfin = 0
iqt = 999;

def = Float64.([0., 0., 0., 0., 0.,-1., 0., 1., 0., 0., 0., 0., 0.,
      0., 0., 0., 0.,-1., 0., 0., 0., 1., 0., 0., 0., 0.,
      0., 0., 0.,-1., 0., 0., 0., 0., 0., 1., 0., 0., 0.,
      0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.,
      0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.,
      0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
      0., 0.,-1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.,
      0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
      0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
      0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
      0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
      0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]);

function func(ipdf, x)::Float64
    i = ipdf[]
    xb = x[]
    adbar = 0.1939875
    f = 0
    if (i == 0)
        ag = 1.7
        f = ag * xb^-0.1 * (1.0-xb)^5.0
    end
    if (i == 1)
        ad = 3.064320
        f = ad * xb^0.8 * (1.0-xb)^4.0
    end
    if (i == 2)
        au = 5.107200
        f = au * xb^0.8 * (1.0-xb)^3.0
    end
    if (i == 3)
        f = 0.0
    end
    if (i == 4)
        f = adbar * xb^-0.1 * (1.0-xb)^6.0
    end
    if (i == 5)
        f = adbar * xb^-0.1 * (1.0-xb)^6.0 * (1.0-xb)
    end
    if (i == 6)
        xdbar = adbar * xb^-0.1 * (1.0-xb)^6.0
        xubar = adbar * xb^-0.1 * (1.0-xb)^6.0 * (1.0-xb)
        f = 0.2 * (xdbar + xubar)
    end
    if (i == 7)
        f = 0.0
    end
    if (i == 8)
        f = 0.0
    end
    if (i == 9)
        f = 0.0
    end
    if (i == 10)
        f = 0.0
    end
    if (i == 11)
        f = 0.0
    end
    if (i == 12)
        f = 0.0
    end
    return f
end

func_c = @cfunction(func, Float64, (Ref{Int32}, Ref{Float64}))

proton = Float64.([4.,1.,4.,1.,4.,1.,0.,1.,4.,1.,4.,1.,4.])/9.0;
xx = Array{Float64}(undef, 1000)
q2 = Array{Float64}(undef, 1000)

roots = 300
shera = roots*roots
xlog1 = log(xmin[1])
xlog2 = log(0.99)
qlog1 = log(qlim[1])
qlog2 = log(qlim[ngq])
ntot = 1
while (ntot < 1001)
    rval = rand()
    xlog = xlog1 + rval*(xlog2-xlog1)
    xxxx = exp(xlog)
    rval = rand()
    qlog = qlog1 + rval*(qlog2-qlog1)
    qqqq = exp(qlog)
    if (qqqq <= xxxx*shera)
        xx[ntot] = xxxx
        q2[ntot] = qqqq
        global ntot += 1
    end
end

# Now, we set up QCDNUM and time many evolution and
# structure function evaluations.

QCDNUM.qcinit(-6, " ")
nx = QCDNUM.gxmake(xmin, iwt, ngx, nxin, iosp)
nq = QCDNUM.gqmake(qlim, wt, ngq, nqin)
nw = QCDNUM.fillwt(1)
nw = QCDNUM.zmfillw()
QCDNUM.setord(iord)
QCDNUM.setalf(as0, r20)
iqc = QCDNUM.iqfrmq(q2c)
iqb = QCDNUM.iqfrmq(q2b)
QCDNUM.setcbt(nfin, iqc, iqb, iqt)
iq0 = QCDNUM.iqfrmq(q0)

@printf(" Wait: 1000 evols and 2.10^6 stfs will take ... ")
@time begin
    for iter in 1:1000
        eps = QCDNUM.evolfg(itype, func_c, def, iq0)
        ff = QCDNUM.zmstfun(1, proton, xx, q2, 1000, 1)
        ff = QCDNUM.zmstfun(2, proton, xx, q2, 1000, 1)
    end
end


text:
"""
    GibbsKernel(; lengthscale)

# Definition

The Gibbs kernel is non-stationary generalisation of the squared exponential
kernel. The lengthscale parameter ``l`` becomes a function of
position ``l(x)``.

For a constant function``l(x) = c``, one recovers the standard squared exponential kernel
with lengthscale `c`.

```math
k(x, y; l) = \\sqrt{ \\left(\\frac{2 l(x) l(y)}{l(x)^2 + l(y)^2} \\right) }
\\quad \\rm{exp} \\left( - \\frac{(x - y)^2}{l(x)^2 + l(y)^2} \\right)
```

# References

Mark N. Gibbs. "Bayesian Gaussian Processes for Regression and Classication." PhD thesis, 1997

Christopher J. Paciorek and Mark J. Schervish. "Nonstationary Covariance Functions
for Gaussian Process Regression". NeurIPS, 2003

Sami Remes, Markus Heinonen, Samuel Kaski. "Non-Stationary Spectral Kernels". arXiV:1705.08736, 2017

Sami Remes, Markus Heinonen, Samuel Kaski. "Neural Non-Stationary Spectral Kernel". arXiv:1811.10978, 2018
"""
struct GibbsKernel{T} <: Kernel
    lengthscale::T
end

GibbsKernel(; lengthscale) = GibbsKernel(lengthscale)

function (k::GibbsKernel)(x, y)
    lengthscale = k.lengthscale
    lx = lengthscale(x)
    ly = lengthscale(y)
    l = invsqrt2 * hypot(lx, ly)
    kernel = (sqrt(lx * ly) / l) * with_lengthscale(SqExponentialKernel(), l)
    return kernel(x, y)
end


text:
abstract type Direction end
struct EveryDirection <: Direction end
struct HorizontalDirection <: Direction end
struct VerticalDirection <: Direction end

struct DGModel{BL,G,NFND,NFD,GNF,AS,DS,D}
  balancelaw::BL
  grid::G
  numfluxnondiff::NFND
  numfluxdiff::NFD
  gradnumflux::GNF
  auxstate::AS
  diffstate::DS
  direction::D
end
function DGModel(balancelaw, grid, numfluxnondiff, numfluxdiff, gradnumflux;
                 auxstate=create_auxstate(balancelaw, grid),
                 diffstate=create_diffstate(balancelaw, grid),
                 direction=EveryDirection())
  DGModel(balancelaw, grid, numfluxnondiff, numfluxdiff, gradnumflux, auxstate,
          diffstate, direction)
end

function (dg::DGModel)(dQdt, Q, ::Nothing, t; increment=false)
  bl = dg.balancelaw
  device = typeof(Q.data) <: Array ? CPU() : CUDA()

  grid = dg.grid
  topology = grid.topology

  dim = dimensionality(grid)
  N = polynomialorder(grid)
  Nq = N + 1
  Nqk = dim == 2 ? 1 : Nq
  Nfp = Nq * Nqk
  nrealelem = length(topology.realelems)

  Qvisc = dg.diffstate
  auxstate = dg.auxstate

  FT = eltype(Q)
  nviscstate = num_diffusive(bl, FT)

  lgl_weights_vec = grid.ω
  Dmat = grid.D
  vgeo = grid.vgeo
  sgeo = grid.sgeo
  vmapM = grid.vmapM
  vmapP = grid.vmapP
  elemtobndy = grid.elemtobndy
  polyorder = polynomialorder(dg.grid)

  Np = dofs_per_element(grid)

  communicate = !(isstacked(topology) &&
                  typeof(dg.direction) <: VerticalDirection)

  if hasmethod(update_aux!, Tuple{typeof(dg), typeof(bl), typeof(Q),
                                  typeof(auxstate), typeof(t)})
    update_aux!(dg, bl, Q, auxstate, t)
  end

  ########################
  # Gradient Computation #
  ########################
  if communicate
    MPIStateArrays.start_ghost_exchange!(Q)
    MPIStateArrays.start_ghost_exchange!(auxstate)
  end

  if nviscstate > 0

    @launch(device, threads=(Nq, Nq, Nqk), blocks=nrealelem,
            volumeviscterms!(bl, Val(dim), Val(polyorder), dg.direction, Q.data,
                             Qvisc.data, auxstate.data, vgeo, t, Dmat,
                             topology.realelems))

    if communicate
      MPIStateArrays.finish_ghost_recv!(Q)
      MPIStateArrays.finish_ghost_recv!(auxstate)
    end

    @launch(device, threads=Nfp, blocks=nrealelem,
            faceviscterms!(bl, Val(dim), Val(polyorder), dg.direction,
                           dg.gradnumflux, Q.data, Qvisc.data, auxstate.data,
                           vgeo, sgeo, t, vmapM, vmapP, elemtobndy,
                           topology.realelems))

    communicate && MPIStateArrays.start_ghost_exchange!(Qvisc)
  end

  ###################
  # RHS Computation #
  ###################
  @launch(device, threads=(Nq, Nq, Nqk), blocks=nrealelem,
          volumerhs!(bl, Val(dim), Val(polyorder), dg.direction, dQdt.data,
                     Q.data, Qvisc.data, auxstate.data, vgeo, t,
                     lgl_weights_vec, Dmat, topology.realelems, increment))

  if communicate
    if nviscstate > 0
      MPIStateArrays.finish_ghost_recv!(Qvisc)
    else
      MPIStateArrays.finish_ghost_recv!(Q)
      MPIStateArrays.finish_ghost_recv!(auxstate)
    end
  end

  @launch(device, threads=Nfp, blocks=nrealelem,
          facerhs!(bl, Val(dim), Val(polyorder), dg.direction,
                   dg.numfluxnondiff,
                   dg.numfluxdiff,
                   dQdt.data, Q.data, Qvisc.data,
                   auxstate.data, vgeo, sgeo, t, vmapM, vmapP, elemtobndy,
                   topology.realelems))

  # Just to be safe, we wait on the sends we started.
  if communicate
    MPIStateArrays.finish_ghost_send!(Qvisc)
    MPIStateArrays.finish_ghost_send!(Q)
  end
end

function init_ode_state(dg::DGModel, args...; device=arraytype(dg.grid) <: Array ? CPU() : CUDA(), commtag=888)
  array_device = arraytype(dg.grid) <: Array ? CPU() : CUDA()
  @assert device == CPU() || device == array_device

  bl = dg.balancelaw
  grid = dg.grid

  state = create_state(bl, grid, commtag)

  topology = grid.topology
  Np = dofs_per_element(grid)

  auxstate = dg.auxstate
  dim = dimensionality(grid)
  polyorder = polynomialorder(grid)
  vgeo = grid.vgeo
  nrealelem = length(topology.realelems)

  if device == array_device
    @launch(device, threads=(Np,), blocks=nrealelem,
            initstate!(bl, Val(dim), Val(polyorder), state.data, auxstate.data, vgeo,
                     topology.realelems, args...))
  else
    h_vgeo = Array(vgeo)
    h_state = similar(state, Array)
    h_auxstate = similar(auxstate, Array)
    h_auxstate .= auxstate
    @launch(device, threads=(Np,), blocks=nrealelem,
      initstate!(bl, Val(dim), Val(polyorder), h_state.data, h_auxstate.data, h_vgeo,
          topology.realelems, args...))
    state .= h_state
  end

  MPIStateArrays.start_ghost_exchange!(state)
  MPIStateArrays.finish_ghost_exchange!(state)

  return state
end

function indefinite_stack_integral!(dg::DGModel, m::BalanceLaw,
                                    Q::MPIStateArray, auxstate::MPIStateArray,
                                    t::Real)

  device = typeof(Q.data) <: Array ? CPU() : CUDA()

  grid = dg.grid
  topology = grid.topology

  dim = dimensionality(grid)
  N = polynomialorder(grid)
  Nq = N + 1
  Nqk = dim == 2 ? 1 : Nq

  FT = eltype(Q)

  vgeo = grid.vgeo
  polyorder = polynomialorder(dg.grid)

  # do integrals
  nintegrals = num_integrals(m, FT)
  nelem = length(topology.elems)
  nvertelem = topology.stacksize
  nhorzelem = div(nelem, nvertelem)

  @launch(device, threads=(Nq, Nqk, 1), blocks=nhorzelem,
          knl_indefinite_stack_integral!(m, Val(dim), Val(polyorder),
                                         Val(nvertelem), Q.data, auxstate.data,
                                         vgeo, grid.Imat, 1:nhorzelem,
                                         Val(nintegrals)))
end

function reverse_indefinite_stack_integral!(dg::DGModel, m::BalanceLaw,
                                            auxstate::MPIStateArray, t::Real)

  device = typeof(auxstate.data) <: Array ? CPU() : CUDA()

  grid = dg.grid
  topology = grid.topology

  dim = dimensionality(grid)
  N = polynomialorder(grid)
  Nq = N + 1
  Nqk = dim == 2 ? 1 : Nq

  FT = eltype(auxstate)

  vgeo = grid.vgeo
  polyorder = polynomialorder(dg.grid)

  # do integrals
  nintegrals = num_integrals(m, FT)
  nelem = length(topology.elems)
  nvertelem = topology.stacksize
  nhorzelem = div(nelem, nvertelem)

  @launch(device, threads=(Nq, Nqk, 1), blocks=nhorzelem,
          knl_reverse_indefinite_stack_integral!(Val(dim), Val(polyorder),
                                                 Val(nvertelem), auxstate.data,
                                                 1:nhorzelem,
                                                 Val(nintegrals)))
end

function nodal_update_aux!(f!, dg::DGModel, m::BalanceLaw, Q::MPIStateArray,
                           auxstate::MPIStateArray, t::Real)
  device = typeof(Q.data) <: Array ? CPU() : CUDA()

  grid = dg.grid
  topology = grid.topology

  dim = dimensionality(grid)
  N = polynomialorder(grid)
  Nq = N + 1
  nrealelem = length(topology.realelems)

  polyorder = polynomialorder(dg.grid)

  Np = dofs_per_element(grid)

  ### update aux variables
  @launch(device, threads=(Np,), blocks=nrealelem,
          knl_nodal_update_aux!(m, Val(dim), Val(polyorder), f!,
                          Q.data, auxstate.data, t, topology.realelems))
end

max_stars_repo_name: akshaysridhar/CLIMA

max_issues_repo_name: akshaysridhar/CLIMA

max_forks_repo_name: akshaysridhar/CLIMA


text:
# using Pkg
# Pkg.add(PackageSpec(name="Knet", rev="master"))

weightsdir = joinpath(@__DIR__, "..", "data", "pretrained")

@info "Downloading weights files"

download(
    "https://github.com/ianshmean/YOLO.jl/releases/download/v2-tiny-VOC/v2_tiny_voc.weights",
    joinpath(weightsdir, "v2_tiny", "voc2007", "v2_tiny_voc.weights"),
)

download(
    "https://pjreddie.com/media/files/yolov2-voc.weights",
    joinpath(weightsdir, "v2", "voc2007", "v2_voc.weights"),
)

@info "Build complete"


text:
using MAB

alg = Algorithms.EXP31( 3 )

# For Bernoulli Bandit
for i = 1:10
    idx = Algorithms.getArmIndex( alg )
    print( "Playing Arm#$idx .... " )
    r = rand()
    print( "Reward: $r\n" )
    Algorithms.updateReward!( alg, r )
    println( alg )
end

println( "Resetting the algorithm..." )
Algorithms.reset!( alg )

# For [0,1] Arms
for i = 1:10
    idx = Algorithms.getArmIndex( alg )
    print( "Playing Arm#$idx .... " )
    r = rand()
    print( "Reward: $r\n" )
    Algorithms.updateReward!( alg, r )
    println( alg )
end


text:
using Astroshaper
using Test

@testset "Astroshaper.jl" begin
    shapepath = "./ryugu_test.obj"
    shape = setShapeModel(shapepath; scale=1000)
    @time Astroshaper.sumTorqueOverSurface(shape, 1200, [1,0,0.])
    @time Astroshaper.sumTorqueOverSurface(shape, 1200, [1,0,0.])
    @test true
end

max_stars_repo_name: MasanoriKanamaru/Astroshaper

max_issues_repo_name: MasanoriKanamaru/Astroshaper

max_forks_repo_name: MasanoriKanamaru/Astroshaper


text:
# License is MIT: https://julialang.org/license
# The code in this file is originally copied from,
#   https://github.com/JuliaLang/julia/blob/2d5741174ce3e6a394010d2e470e4269ca54607f/base/reduce.jl#L147-L168
# and modified by Masaaki Nakamura since `mapreduce_imple()` is required but it
# was not public api.

@noinline function mapsum(f, A::AbstractVector,
                          ifirst::Integer, ilast::Integer, blksize::Int)
    if ifirst == ilast
        @inbounds a1 = A[ifirst]
        return f(a1)
    elseif ifirst + blksize > ilast
        # sequential portion
        @inbounds a1 = A[ifirst]
        @inbounds a2 = A[ifirst+1]
        v = f(a1) + f(a2)
        @simd for i in ifirst + 2 : ilast
            @inbounds ai = A[i]
            v = v + f(ai)
        end
        return v
    else
        # pairwise portion
        imid = (ifirst + ilast) >> 1
        v1 = mapsum(f, A, ifirst, imid, blksize)
        v2 = mapsum(f, A, imid+1, ilast, blksize)
        return v1 + v2
    end
end

"""
    mapsum(f, A::AbstractVector, ifirst::Integer=1, ilast::Integer=length(A))

Return the total summation of items in `A` from `istart`-th through `iend`-th
with applying a function `f`.

NOTE: This function doesn't check `ifirst` and `ilast`. Be careful to use.
"""
mapsum(f, A::AbstractVector, ifirst::Integer=1, ilast::Integer=length(A)) =
    mapsum(f, A, ifirst, ilast, 512)


text:
using GtkUtilities, Gtk.ShortNames, Cairo, GtkUtilities.Graphics
using Test

state = State(7)
e = lEntry(state)
set_gtk_property!(e, :name, "entry")
sc = lScale(state, :h, 1:10)
set_gtk_property!(sc, :name, "scale")
box = Box(:v)
win = Window(box, "Linked")
push!(box, e)
push!(box, sc)
showall(win)

@test get(state)  == 7
@test get(e)  == 7
@test get(sc) == 7
io = IOBuffer()
show(io, state)
@test String(take!(io)) == "State(7,\"entry\",\"scale\")"
set!(state, 5)
@test get(state)  == 5
@test get(e)  == 5
@test get(sc) == 5
set!(e, 9)
@test get(state)  == 9
@test get(e)  == 9
@test get(sc) == 9
set!(sc, 4)
@test get(state)  == 4
@test get(e)  == 4
@test get(sc) == 4

s = State("hello")
l = lLabel(s)
@test get(l) == "hello"
set!(l, "Gtk")
@test get(s) == "Gtk"

module IV

mutable struct Interval
    min::Float64
    max::Float64
end

end

c = Canvas()
win = Window(c)
s = State(IV.Interval(0,1))
link(s, c)

pat = pattern_create_linear(0,0.5,1,0.5)
pattern_add_color_stop_rgb(pat, 0, 0, 1, 0)
pattern_add_color_stop_rgb(pat, 1, 1, 0, 1)
draw(c) do widget
    ctx = getgc(widget)
    h = height(widget)
    w = width(widget)
    iv = get(s)
    bb = BoundingBox(iv.min, iv.max, 0, 1)
    set_coordinates(ctx, BoundingBox(0, w, 0, h), bb)
    rectangle(ctx, 0, 0, 1, 1)
    set_source(ctx, pat)
    fill(ctx)
end

showall(win)
sleep(0.5)
set!(s, IV.Interval(0.25, 0.75))
showall(win)


text:
using Base.Test, SDDiP, JuMP, GLPKMathProgInterface, Ipopt

@testset "Lagrangian" begin
    include("Lagrangian.jl")
end

@testset "SDDiP" begin
    include("SDDiP.jl")
end

@testset "@binarystate" begin
    include("binarystate.jl")
end


text:
module Dec9Part1

function check_validity(x::Array{Int64,1}, ref::Int64)::Bool
    x = collect(filter(y -> y <= ref, x))
    n_x = length(x)
    if n_x < 2
        return false
    else
        for i in 1:n_x - 1
            for j in i + 1:n_x
                if ref == x[i] + x[j]
                    return true
                end
            end
        end
    end
    return false
end
function main(file_path::String)::Union{Int64,Nothing}
    numbers = parse.(Int64, readlines(file_path))
    stride = 25
    n = length(numbers)
    for i in 1:n - (stride + 1)
        validity = check_validity(numbers[i:i + stride], numbers[i + stride])
        if !validity
            return numbers[i + stride]
        end
    end
    return nothing
end
end


text:
function outStr(s::StateResult)
    str = "$(s.starttime)"
    str = "$str,$(s.startstate[1])"
    str = "$str,$(s.result[1])"
    return str
end

function walkForward(fileStr::AbstractString,
                    inpath::AbstractString, output::AbstractString)
    e = MktEvent()
    dc = IODataCache()

    stateResults = StateResult[]
    results = StateResult[]

    cnt = 0
    f = open(joinpath(inpath, fileStr),"r")
    o = open( output,"w")
    while !eof(f)
        cnt += 1
        fillBinaryEvent!(f, dc, e) # get next market event
        state = [round((e.bid + e.ask)/2,3)]
        endTm = e.dt + Dates.Minute(10)
        s = StateResult(e.dt, endTm, state, [0., 0.],false)
        push!(stateResults,s)
        completed = processPairs(stateResults,e)
        map(x->println(o,outStr(x)),completed)
        # if cnt > 39500 break end
    end
    close(o)
    close(f)

    return results
end

max_stars_repo_name: Andy-P/PriceDist

max_issues_repo_name: Andy-P/PriceDist

max_forks_repo_name: Andy-P/PriceDist


text:
## memory_allocation.jl
#
## Author: Tom Price
## Date: January 2019
#
## Analyse memory usage in dispatch calls
## See https://docs.julialang.org/en/v0.6/manual/profile/#Memory-allocation-analysis-1
## Usage: julia --track-allocation=user memory_allocation.jl

# performance is better with dispatch calls
# in a function rather than global scope
function test_memory_allocation()
    # load dispatch calls & associated data
    test_functions = BSON.load("../test/data/dispatch_tests.bson")
    #
    # perform calls to force compilation
    check = test_dispatch(test_functions)
    println(check)
    #
    # all test results must be positive, or else an error will be raised
    @assert all(values(check))
    #
    # reset allocation counters
    Profile.clear_malloc_data()
    #
    # execute dispatch calls a second time
    check = test_dispatch(test_functions)
end

# start of main code >>

autorun = joinpath(Base.JULIA_HOME,Base.SYSCONFDIR,"julia/juliarc.jl")
# look for magic number
if !isfile(autorun) || all(map(
    x -> match(r"6004dbc584427ce1297c8e89e547057e",x)==nothing,
    readlines(autorun)))
    # if not found, run these three commands
    # which have not been included in the startup script:
    cd("/home/vagrant/chaipcr/bioinformatics/QpcrAnalysis")
    push!(LOAD_PATH,pwd())
    using QpcrAnalysis
end

import FactCheck: clear_results
import DataFrames: DataFrame
import DataStructures: OrderedDict
import BSON: bson
import JSON: json, parse, parsefile
test_memory_allocation()

# << end of main code

#

max_stars_repo_name: MakerButt/chaipcr

max_issues_repo_name: MakerButt/chaipcr

max_forks_repo_name: MakerButt/chaipcr


text:
function update_check_regularity!(
    state::Tuple{AbstractGraph, AbstractArray}, agent_idx::Integer,
    config::Config
)
    agent_list = state[2]
    this_agent = agent_list[agent_idx]
    if (abs(this_agent.opinion - this_agent.perceiv_publ_opinion) > config.opinion_treshs.check_unease)
        this_agent.check_regularity = config.agent_props.check_decrease * this_agent.check_regularity
    else
        this_agent.check_regularity = 1.0
    end
    return state
end

max_stars_repo_name: digitalemuendigkeit/twitter-abm

max_issues_repo_name: digitalemuendigkeit/twitter-abm

max_forks_repo_name: digitalemuendigkeit/twitter-abm


text:
using Documenter, OpenSMILES

makedocs(;
    modules=[OpenSMILES],
    format=Documenter.HTML(),
    pages=[
        "Home" => "index.md",
    ],
    repo="https://github.com/caseykneale/OpenSMILES.jl/blob/{commit}{path}#L{line}",
    sitename="OpenSMILES.jl",
    authors="Casey Kneale",
    assets=String[],
)

deploydocs(;
    repo="github.com/caseykneale/OpenSMILES.jl",
)


text:
arg_dict = Dict{String, Any}(
"physics" => "Advection",
"dimension" => 2,
"use_DG" => true,
"run_type" => 1,
"real_time" => true,
"order" => 1,
"Flux_name" => "avgFlux",
"IC_name" => "ICsinwavexy",
"numBC" => 0,
"delta_t" => 0.0005,
"t_max" => 1.375,
"smb_name" => "SRCMESHES/tri5_periodic_p4.smb",
"dmg_name" => ".null",
"output_freq" => 100,
"write_vis" => false,
"do_postproc" => true,
"exact_soln_func" => "ICsinwavexy",
"solve" => true
)


text:
using MOCNeutronTransport
@testset "LineSegment_3D" begin
    for T in [Float32, Float64]
        @testset "Constructors" begin
            p₁ = Point_3D( T(1) )
            p₂ = Point_3D( T(2) )
            l = LineSegment_3D(p₁,p₂)
            @test l.points[1] == p₁
            @test l.points[2] == p₂
        end
        @testset "Methods" begin
            # interpolation
            p₁ = Point_3D(T, 1, 1, 3)
            p₂ = Point_3D(T, 3, 3, 3)
            l = LineSegment_3D(p₁, p₂)
            @test l(0) == p₁
            @test l(1) == p₂
            p₃ = Point_3D(T, 2, 2, 3)
            @test l(1//2) == p₃
            typeof(l(1//2).x) == typeof(T.((2, 4, 6)))

#            # arc_length
#            p₁ = Point_3D(T, 1, 2, 3)
#            p₂ = Point_3D(T, 2, 4, 6)
#            l = LineSegment_3D(p₁, p₂)
#            @test arc_length(l) == sqrt(T(14))
#            @test typeof(arc_length(l)) == typeof(T(14))
#
#            # intersect
#            # -------------------------------------------
#            # basic intersection
#            l₁ = LineSegment_3D(Point_3D(T, 0,  1), Point_3D(T, 2, -1))
#            l₂ = LineSegment_3D(Point_3D(T, 0, -1), Point_3D(T, 2,  1))
#            bool, p = intersect(l₁, l₂)
#            @test bool
#            @test p == Point_3D(T, 1, 0)
#            @test typeof(p.x) == typeof(SVector(T.((1, 0, 0))))
#
#            # vertex intersection
#            l₂ = LineSegment_3D(Point_3D(T, 0, -1), Point_3D(T, 2, -1))
#            bool, p = l₁ ∩ l₂
#            @test bool
#            @test p == Point_3D(T, 2, -1)
#
#            # basic 3D intersection
#            l₁ = LineSegment_3D(Point_3D(T, 1, 0,  1), Point_3D(T, 1,  0, -1))
#            l₂ = LineSegment_3D(Point_3D(T, 0, 1, -1), Point_3D(T, 2, -1,  1))
#            bool, p = l₁ ∩ l₂
#            @test bool
#            @test p == Point_3D(T, 1, 0, 0)
#
#            # vertical
#            l₁ = LineSegment_3D(Point_3D(T, 0,  1), Point_3D(T, 2,   1))
#            l₂ = LineSegment_3D(Point_3D(T, 1, 10), Point_3D(T, 1, -10))
#            bool, p = intersect(l₁, l₂)
#            @test bool
#            @test p == Point_3D(T, 1, 1)
#
#            # nearly vertical
#            l₁ = LineSegment_3D(Point_3D(T, -1, -100000), Point_3D(T, 1,  100000))
#            l₂ = LineSegment_3D(Point_3D(T, -1,   10000), Point_3D(T, 1,  -10000))
#            bool, p = l₁ ∩ l₂
#            @test bool
#            @test p == Point_3D(T, 0, 0)
#
#            # parallel
#            l₁ = LineSegment_3D(Point_3D(T, 0, 1), Point_3D(T, 1, 1))
#            l₂ = LineSegment_3D(Point_3D(T, 0, 0), Point_3D(T, 1, 0))
#            bool, p = intersect(l₁, l₂)
#            @test !bool
#
#            # collinear
#            l₁ = LineSegment_3D(Point_3D(T, 0, 0), Point_3D(T, 2, 0))
#            l₂ = LineSegment_3D(Point_3D(T, 0, 0), Point_3D(T, 1, 0))
#            bool, p = intersect(l₁, l₂)
#            @test !bool
#
#            # line intersects, not segment (invalid t)
#            l₁ = LineSegment_3D(Point_3D(T, 0, 0), Point_3D(T, 2, 0    ))
#            l₂ = LineSegment_3D(Point_3D(T, 1, 2), Point_3D(T, 1, 1//10))
#            bool, p = l₁ ∩ l₂
#            @test !bool
#            @test p ≈ Point_3D(T, 1, 0) # the closest point on line 1
#
#            # line intersects, not segment (invalid s)
#            l₂ = LineSegment_3D(Point_3D(T, 0, 0), Point_3D(T, 2, 0    ))
#            l₁ = LineSegment_3D(Point_3D(T, 1, 2), Point_3D(T, 1, 1//10))
#            bool, p = intersect(l₁, l₂)
#            @test !bool
#            @test p ≈ Point_3D(T, 1, 0) # the closest point on line 1
        end
    end
end

max_stars_repo_name: KyleVaughn/MOCNeutronTransport

max_issues_repo_name: KyleVaughn/MOCNeutronTransport

max_forks_repo_name: KyleVaughn/MOCNeutronTransport


text:
# represents s*log(ε) + c as ε -> 0
struct LogNumber <: Number
    s::ComplexF64
    c::ComplexF64
end

@inline logpart(z::Number) = zero(z)
@inline finitepart(z::Number) = z

@inline logpart(l::LogNumber) = l.s
@inline finitepart(l::LogNumber) = l.c

Base.promote_rule(::Type{LogNumber}, ::Type{<:Number}) = LogNumber
Base.convert(::Type{LogNumber}, z::LogNumber) = z
Base.convert(::Type{LogNumber}, z::Number) = LogNumber(0, z)

==(a::LogNumber, b::LogNumber) = logpart(a) == logpart(b) && finitepart(a) == finitepart(b)
Base.isapprox(a::LogNumber, b::LogNumber; opts...) = ≈(logpart(a), logpart(b); opts...) && ≈(finitepart(a), finitepart(b); opts...)
Base.isapprox(a::LogNumber, b::Number; opts...) = ≈(a(1),b; opts...)
Base.isapprox(a::Number, b::LogNumber; opts...) = ≈(a,b(1); opts...)

(l::LogNumber)(ε) = logpart(l)*log(ε) + finitepart(l)

for op in (:real, :imag, :conj)
    @eval $op(l::LogNumber) = LogNumber($op(logpart(l)), $op(finitepart(l)))
end

for f in (:+, :-)
    @eval begin
        $f(a::LogNumber, b::LogNumber) = LogNumber($f(a.s, b.s), $f(a.c, b.c))
        $f(l::LogNumber, b::Number) = LogNumber(l.s, $f(l.c, b))
        $f(a::Number, l::LogNumber) = LogNumber($f(l.s), $f(a, l.c))
    end
end

-(l::LogNumber) = LogNumber(-l.s, -l.c)

for Typ in (:Bool, :Number)
    @eval begin
        *(l::LogNumber, b::$Typ) = LogNumber(l.s*b, l.c*b)
        *(a::$Typ, l::LogNumber) = LogNumber(a*l.s, a*l.c)
    end
end
/(l::LogNumber, b::Number) = LogNumber(l.s/b, l.c/b)

function exp(l::LogNumber)::ComplexF64
    if real(l.s) > 0
        0.0+0.0im
    elseif real(l.s) < 0
        Inf+Inf*im
    elseif real(l.s) == 0 && imag(l.s) == 0
        exp(l.c)
    else
        NaN + NaN*im
    end
end

Base.show(io::IO, x::LogNumber) = print(io, "($(logpart(x)))log ε + $(finitepart(x))")


text:
"""
    zp(p)

Zero a p-vector.

!!! warning "Deprecated"
    Use `fill!(p, 0.0)` instead.

### Returned ###

- `p`: zero p-vector

"""
zp

function _zp(p)
    ccall((:eraZp, liberfa), Cvoid, (Ptr{Cdouble},), p)
    return p
end

@deprecate zp(p) fill!(p, 0.0)

"""
    zpv(pv)

Zero a pv-vector.

!!! warning "Deprecated"
    Use `fill!.(pv, 0.0)` instead.

### Returned ###

- `p`: zero pv-vector

"""
zpv

function _zpv(pv)
    _pv = array_to_cmatrix(pv; n=3)
    ccall((:eraZpv, liberfa), Cvoid, (Ptr{Cdouble},), _pv)
    return cmatrix_to_array(_pv)
end

@deprecate zpv(pv) fill!.(pv, 0.0)

"""
    zr(r)

Initialize an r-matrix to the null matrix.

!!! warning "Deprecated"
    Use `fill!(r, 0.0)` instead.

### Returned ###

- `r`: r-matrix

"""
zr

function _zr(r)
    ccall((:eraZr, liberfa), Cvoid, (Ptr{Cdouble},), r)
    return r
end

@deprecate zr(r) fill!(r, 0.0)


text:
module SparsityPattern

using SparseArrays: SparseVector, SparseMatrixCSC

export sparsepattern, realize

abstract type AbstractSparsePattern end

"""
    SparseVectorPattern{Ti<:Integer}

Represents a sparsity pattern for a sparse vector.
"""
struct SparseVectorPattern{Ti<:Integer} <: AbstractSparsePattern
    n :: Int
    nzind :: Vector{Ti}
    accummap :: Vector{Int}
end

"""
    SparseMatrixPatternCSC{Ti<:Integer}

Represents a sparsity pattern for a matrix in CSC format.
"""
struct SparseMatrixPatternCSC{Ti<:Integer} <: AbstractSparsePattern
    m :: Int
    n :: Int
    colptr :: Vector{Ti}
    rowval :: Vector{Ti}
    accummap :: Vector{Int}
end

"""
    sparsepattern(I[, len])

Create a vector sparsity pattern with nonzero values at indices `I`,
of total length `len` (defaulting to the maximal index).
"""
sparsepattern(I::AbstractVector{<:Integer}, len::Integer) = sparsepattern!(Vector(I), len)
sparsepattern(I::AbstractVector{<:Integer}) = sparsepattern(I, maximum(I))

"""
    sparsepattern(I, J[, m, n])

Create a matrix sparsity pattern with nonzero values at indices
`(I[k], J[k])`, of total size (m,n) (defaulting to the maximal values
of `I` and `J` respectively).
"""
sparsepattern(I::AbstractVector{<:Integer}, J::AbstractVector{<:Integer}) =
    sparsepattern(I, J, maximum(I), maximum(J))

function sparsepattern(I::Vector{Ti}, J::Vector{Ti}, m::Integer, n::Integer) where Ti<:Integer
    col_target = Vector{Ti}(undef, n)
    csr_rowptr = Vector{Ti}(undef, m+1)
    csr_colval = Vector{Ti}(undef, length(I))
    csr_perm = Vector{Int}(undef, length(I))
    csc_colptr = Vector{Ti}(undef, n+1)
    csc_rowval = Vector{Ti}()
    csc_perm = Vector{Int}()
    sparsepattern!(I, J, m, n, col_target, csr_rowptr, csr_colval, csr_perm, csc_colptr, csc_rowval, csc_perm)
end

"""
    sparsepattern!(I, len)

Main driver of [`sparsitypattern`](@ref) for vectors, mutating and
re-using the first argument.
"""
function sparsepattern!(I::Vector{Ti}, len::Integer) where Ti<:Integer
    perm = sortperm(I)
    permute!(I, perm)

    accummap = ones(Ti, length(I))

    peek = 1
    target = 1
    for peek in 1:length(I)
        1 <= I[peek] <= len || throw(ArgumentError("Index $(I[peek]) out of range"))
        if I[peek] != I[target]
            target += 1
            I[target] = I[peek]
        end
        accummap[peek] = target
    end

    invpermute!(accummap, perm)
    resize!(I, target)
    SparseVectorPattern(len, I, accummap)
end

"""
   sparsepattern!(I, J, m, n, col_target::Vector{Ti},
                  csr_rowptr::Vector{Ti}, csr_colval::Vector{Ti}, csr_perm::Vector{Ti},
                  csc_colptr::Vector{Ti}, csc_rowval::Vector{Ti}, csc_perm::Vector{Ti})

Main driver of [`sparsitypattern`](@ref) for matrices, mutating and
re-using its arguments.

Input arrays `col_target`, `csr_rowptr`, `csr_colval`, `csr_perm`,
`csc_colptr`, `csc_rowval` and `csc_perm` constitute storage for
intermediate forms, and require

`lenght(col_target) >= n`
`length(csr_rowptr) >= m+1`
`length(csr_colval) >= length(I)`
`length(csr_perm) == length(I)`
`length(csc_colptr) >= n+1`
`length(csc_rowval) >= nnz`
`length(csc_perm) >= nnz`

The final two vectors will be resized when the number of nonzero
entries is known, in case they are not big enough.

You may reuse `I` and `J` for `csc_colptr` and `csc_rowval`.
"""
function sparsepattern!(I::Vector{Ti}, J::Vector{Ti}, m::Integer, n::Integer, col_target::Vector{Ti},
                        csr_rowptr::Vector{Ti}, csr_colval::Vector{Ti}, csr_perm::Vector{Ti},
                        csc_colptr::Vector{Ti}, csc_rowval::Vector{Ti}, csc_perm::Vector{Ti}) where Ti<:Integer
    # This function is adapted from SparseArrays.sparse! in base Julia
    # It is identical except for the handling of nonzeros
    nvals = length(I)

    # Compute number of occurences of each row
    fill!(csr_rowptr, 0)
    for i in I
        1 <= i <= m || throw(ArgumentError("Row index $i out of range"))
        csr_rowptr[i+1] += 1
    end

    # Compute CSR row-pointers shifted forward by one
    csr_rowptr[1] = 1
    _cumsum!(@view csr_rowptr[2:end])

    # Create a CSR representation with uncombined entries
    length(csr_perm) != nvals && resize!(csr_perm, nvals)
    for (peek, (i, j)) in enumerate(zip(I, J))
        1 <= j <= n || throw(ArgumentError("Column index $j out of range"))
        target = csr_rowptr[i+1]
        csr_rowptr[i+1] += 1
        csr_colval[target] = j
        csr_perm[peek] = target
    end

    # Sweep through the CSR representation, doing a number of things at once:
    # 1: calculate the column counts shifted by one
    # 2: detect and collapse repeated entries
    fill!(csc_colptr, zero(Ti))
    fill!(col_target, zero(Ti))
    target = one(Ti)              # Next unwritten entry in the compressed form
    last_row_target = one(Ti)     # Previous row's highest target index
    rowptr = csr_rowptr[1]        # Start of next row (in the uncompressed form)
    accummap = Vector{Ti}(undef, nvals)
    for row in 1:m
        rowptr_end = csr_rowptr[row+1]
        for peek in rowptr:csr_rowptr[row+1]-1
            col = csr_colval[peek]
            if col_target[col] < last_row_target
                col_target[col] = target
                csr_colval[target] = col
                accummap[peek] = target
                target += 1
                csc_colptr[col+1] += 1
            else
                accummap[peek] = col_target[col]
            end
        end
        last_row_target = target
        rowptr = rowptr_end
        csr_rowptr[row+1] = target
    end

    # Compute the CSC col-pointers shifted forward by one
    csc_colptr[1] = 1
    _cumsum!(@view csc_colptr[2:end])

    # Finalize the CSC form
    nnz = csr_rowptr[m+1] - 1
    length(csc_rowval) < nnz && resize!(csc_rowval, nnz)
    length(csc_perm) < nnz && resize!(csc_perm, nnz)
    for row in 1:m
        for peek in csr_rowptr[row]:csr_rowptr[row+1]-1
            col = csr_colval[peek]
            target = csc_colptr[col+1]
            csc_colptr[col+1] += 1
            csc_rowval[target] = row
            csc_perm[peek] = target
        end
    end

    # Backtrack the nzval accumulation map to original indices
    for i in 1:nvals
        accummap[i] = csc_perm[accummap[i]]
    end
    permute!(accummap, csr_perm)

    SparseMatrixPatternCSC(m, n, csc_colptr, csc_rowval, accummap)
end

"""
    realize(::Union{SparseVectorPattern,SparseMatrixPatternCSC}, V[, combine])

Create a sparse vector or matrix using the given sparsity pattern and
vector `V` of nonzeros.  Repeated entries are combined with the
`combine` function, defaulting to `|` for booleans and `+` otherwise.

The vector `V` must be as long as the original index vector(s) used to
create the pattern.
"""
realize(pattern::AbstractSparsePattern, V::AbstractVector) = realize(pattern, V, +)
realize(pattern::AbstractSparsePattern, V::AbstractVector{Bool}) = realize(pattern, V, |)

function realize(pattern::SparseVectorPattern, V::AbstractVector, combine::Function)
    nzval = _realize(pattern.accummap, length(pattern.nzind), V, combine)
    SparseVector(pattern.n, pattern.nzind, nzval)
end

function realize(pattern::SparseMatrixPatternCSC, V::AbstractVector, combine::Function)
    nzval = _realize(pattern.accummap, length(pattern.rowval), V, combine)
    SparseMatrixCSC(pattern.m, pattern.n, pattern.colptr, pattern.rowval, nzval)
end

function _realize(accummap, len, V::AbstractVector{Tv}, combine::Function) where Tv
    if length(V) != length(accummap)
        throw(ArgumentError("expected vector of length $(length(accummap)), got $(length(V))"))
    end

    nzval = zeros(Tv, len)
    for (target, value) in zip(accummap, V)
        nzval[target] = combine(nzval[target], value)
    end
    nzval
end

function _cumsum!(vec::AbstractVector{Ti}, accum=one(Ti)) where Ti
    for i in eachindex(vec)
        temp = vec[i]
        vec[i] = accum
        accum += temp
    end
end

end # module


text:
# derivatives can either be applied in fourier space by multipliying by im*k or
# in map space by finite differences. this tracks which option to use for a
# given field
abstract type ∂modes end
struct fourier∂ <: ∂modes end
struct map∂ <: ∂modes end
promote_rule(::Type{map∂}, ::Type{fourier∂}) = fourier∂

# Flat{Nside,θpix,∂mode} is a flat sky pixelization with `Nside` pixels per side
# and pixels of width `θpix` arcmins, where derivatives are done according to ∂mode
abstract type Flat{Nside,θpix,∂mode<:∂modes} <: Pix end

# for convenience
Flat(;Nside, θpix=θpix₀, ∂mode=fourier∂) = Flat{Nside,θpix,∂mode}
Nside(::Type{P}) where {N,P<:Flat{N}} = N

# default angular resolution used by a number of convenience constructors
θpix₀ = 1

@doc """
The number of FFTW threads to use. This must be set via e.g.:

    CMBLensing.FFTW_NUM_THREADS[] = 4

*before* creating any `FlatField` objects; subsequent changes to this variable
will be ignored. The default value is the environment variable `FFTW_NUM_THREADS`,
or if that is not specified its `Sys.CPU_THREADS÷2`.
"""
const FFTW_NUM_THREADS = Ref{Int}()
@init FFTW_NUM_THREADS[] = parse(Int,get(ENV,"FFTW_NUM_THREADS","$(Sys.CPU_THREADS÷2)"))

@generated function FlatInfo(::Type{T}, ::Type{Arr}, ::Val{θpix}, ::Val{Nside}) where {T<:Real, Arr<:AbstractArray, θpix, Nside}

    FFTW.set_num_threads(FFTW_NUM_THREADS[])

    Δx   = T(deg2rad(θpix/60))
    FFT  = plan_rfft(Arr{T}(undef,Nside,Nside))
    Δℓ   = T(2π/(Nside*Δx))
    nyq  = T(2π/(2Δx))
    Ωpix = T(Δx^2)
    x,k  = (ifftshift(-Nside÷2:(Nside-1)÷2),) .* (Δx,Δℓ)
    kmag = @. sqrt(k'^2 + k^2)
    ϕ    = @. angle(k' + im*k)[1:Nside÷2+1,:]
    sin2ϕ, cos2ϕ = @. sin(2ϕ), cos(2ϕ)
    if iseven(Nside)
        sin2ϕ[end, end:-1:(Nside÷2+2)] .= sin2ϕ[end, 2:Nside÷2]
    end

    @namedtuple(T, θpix, Nside, Δx, Δℓ, nyq, Ωpix, x, k, kmag, sin2ϕ=Arr(sin2ϕ), cos2ϕ=Arr(cos2ϕ), FFT)

end

function Cℓ_to_2D(::Type{P}, ::Type{T}, Cℓ) where {T,N,P<:Flat{N}}
    Complex{T}.(nan2zero.(Cℓ.(fieldinfo(P,T).kmag[1:N÷2+1,:])))
end

@doc doc"""
    pixwin(θpix, ℓ)

Returns the pixel window function for square flat-sky pixels of width `θpix` (in
arcmin) evaluated at some `ℓ`s. This is the scaling of k-modes, the scaling of
the power spectrum will be pixwin^2.
"""
pixwin(θpix, ℓ) = @. sinc(ℓ*deg2rad(θpix/60)/2π)


text:
using ITensors,
      Test

@testset "SiteSet" begin

  N = 10

  @testset "Star in operator strings" begin
    sites = spinHalfSites(N)
    Sz = op(sites,"Sz",2)
    SzSz = op(sites,"Sz * Sz",2)
    @test SzSz ≈ multSiteOps(Sz,Sz)
  end

end


text:
# module GroupsTests

using BenchmarkTools
using BenchmarkTools: TrialEstimate, Parameters
using Test
using Statistics

seteq(a, b) = length(a) == length(b) == length(intersect(a, b))

##################
# BenchmarkGroup #
##################

# setup #
#-------#

g1 = BenchmarkGroup(["1", "2"])

t1a = TrialEstimate(Parameters(time_tolerance = .05, memory_tolerance = .05), 32, 1, 2, 3)
t1b = TrialEstimate(Parameters(time_tolerance = .40, memory_tolerance = .40), 4123, 123, 43, 9)
tc = TrialEstimate(Parameters(time_tolerance = 1.0, memory_tolerance = 1.0), 1, 1, 1, 1)

g1["a"] = t1a
g1["b"] = t1b
g1["c"] = tc

g1copy = copy(g1)
g1similar = similar(g1)

g2 = BenchmarkGroup(["2", "3"])

t2a = TrialEstimate(Parameters(time_tolerance = .05, memory_tolerance = .05), 323, 1, 2, 3)
t2b = TrialEstimate(Parameters(time_tolerance = .40, memory_tolerance = .40), 1002, 123, 43, 9)

g2["a"] = t2a
g2["b"] = t2b
g2["c"] = tc

trial = BenchmarkTools.Trial(Parameters(), [1, 2, 5], [0, 1, 1], 3, 56)

gtrial = BenchmarkGroup([], Dict("t" => trial))

# tests #
#-------#

@test BenchmarkGroup() == BenchmarkGroup([], Dict())
@test length(g1) == 3
@test g1["a"] == t1a
@test g1["b"] == t1b
@test g1["c"] == tc
@test haskey(g1, "a")
@test !(haskey(g1, "x"))
@test seteq(keys(g1), ["a", "b", "c"])
@test seteq(values(g1), [t1a, t1b, tc])
@test iterate(g1) == iterate(g1.data)
@test iterate(g1, 1) == iterate(g1.data, 1)
@test seteq([x for x in g1], Pair["a"=>t1a, "b"=>t1b, "c"=>tc])

@test g1 == g1copy
@test seteq(keys(delete!(g1copy, "a")), ["b", "c"])
@test isempty(delete!(delete!(g1copy, "b"), "c"))
@test isempty(g1similar)
@test g1similar.tags == g1.tags

@test time(g1).data == Dict("a" => time(t1a), "b" => time(t1b), "c" => time(tc))
@test gctime(g1).data == Dict("a" => gctime(t1a), "b" => gctime(t1b), "c" => gctime(tc))
@test memory(g1).data == Dict("a" => memory(t1a), "b" => memory(t1b), "c" => memory(tc))
@test allocs(g1).data == Dict("a" => allocs(t1a), "b" => allocs(t1b), "c" => allocs(tc))
@test params(g1).data == Dict("a" => params(t1a), "b" => params(t1b), "c" => params(tc))

@test max(g1, g2).data == Dict("a" => t2a, "b" => t1b, "c" => tc)
@test min(g1, g2).data == Dict("a" => t1a, "b" => t2b, "c" => tc)
@test ratio(g1, g2).data == Dict("a" => ratio(t1a, t2a), "b" => ratio(t1b, t2b), "c" => ratio(tc, tc))
@test (judge(g1, g2; time_tolerance = 0.1, memory_tolerance = 0.1).data ==
       Dict("a" => judge(t1a, t2a; time_tolerance = 0.1, memory_tolerance = 0.1),
            "b" => judge(t1b, t2b; time_tolerance = 0.1, memory_tolerance = 0.1),
            "c" => judge(tc, tc; time_tolerance = 0.1, memory_tolerance = 0.1)))
@test (judge(ratio(g1, g2); time_tolerance = 0.1, memory_tolerance = 0.1) ==
       judge(g1, g2; time_tolerance = 0.1, memory_tolerance = 0.1))
@test ratio(g1, g2) == ratio(judge(g1, g2))

@test isinvariant(judge(g1, g1))
@test isinvariant(time, judge(g1, g1))
@test isinvariant(memory, judge(g1, g1))
@test !(isregression(judge(g1, g1)))
@test !(isregression(time, judge(g1, g1)))
@test !(isregression(memory, judge(g1, g1)))
@test !(isimprovement(judge(g1, g1)))
@test !(isimprovement(time, judge(g1, g1)))
@test !(isimprovement(memory, judge(g1, g1)))

@test BenchmarkTools.invariants(judge(g1, g2)).data == Dict("c" => judge(tc, tc))
@test BenchmarkTools.invariants(time, (judge(g1, g2))).data == Dict("c" => judge(tc, tc))
@test BenchmarkTools.invariants(memory, (judge(g1, g2))).data == Dict("a" => judge(t1a, t2a), "b" => judge(t1b, t2b), "c" => judge(tc, tc))
@test BenchmarkTools.regressions(judge(g1, g2)).data == Dict("b" => judge(t1b, t2b))
@test BenchmarkTools.regressions(time, (judge(g1, g2))).data == Dict("b" => judge(t1b, t2b))
@test BenchmarkTools.regressions(memory, (judge(g1, g2))).data == Dict()
@test BenchmarkTools.improvements(judge(g1, g2)).data == Dict("a" => judge(t1a, t2a))
@test BenchmarkTools.improvements(time, (judge(g1, g2))).data == Dict("a" => judge(t1a, t2a))
@test BenchmarkTools.improvements(memory, (judge(g1, g2))).data == Dict()

@test isinvariant(judge(g1, g1))
@test !(isinvariant(judge(g1, g2)))
@test isregression(judge(g1, g2))
@test !(isregression(judge(g1, g1)))
@test isimprovement(judge(g1, g2))
@test !(isimprovement(judge(g1, g1)))
@test invariants(judge(g1, g2)).data == Dict("c" => judge(tc, tc))
@test regressions(judge(g1, g2)).data == Dict("b" => judge(t1b, t2b))
@test improvements(judge(g1, g2)).data == Dict("a" => judge(t1a, t2a))

struct Bar end
@test BenchmarkTools.invariants(Bar()) == Bar()
@test BenchmarkTools.invariants(time, (Bar())) == Bar()
@test BenchmarkTools.invariants(memory, (Bar())) == Bar()
@test BenchmarkTools.regressions(Bar()) == Bar()
@test BenchmarkTools.regressions(time, (Bar())) == Bar()
@test BenchmarkTools.regressions(memory, (Bar())) == Bar()
@test BenchmarkTools.improvements(Bar()) == Bar()
@test BenchmarkTools.improvements(time, (Bar())) == Bar()
@test BenchmarkTools.improvements(memory, (Bar())) == Bar()

@test minimum(gtrial)["t"] == minimum(gtrial["t"])
@test median(gtrial)["t"] == median(gtrial["t"])
@test mean(gtrial)["t"] == mean(gtrial["t"])
@test maximum(gtrial)["t"] == maximum(gtrial["t"])
@test params(gtrial)["t"] == params(gtrial["t"])

######################################
# BenchmarkGroups of BenchmarkGroups #
######################################

# setup #
#-------#

groupsa = BenchmarkGroup()
groupsa["g1"] = g1
groupsa["g2"] = g2
g3a = addgroup!(groupsa, "g3", ["3", "4"])
g3a["c"] = TrialEstimate(Parameters(time_tolerance = .05, memory_tolerance = .05), 6341, 23, 41, 536)
g3a["d"] = TrialEstimate(Parameters(time_tolerance = .13, memory_tolerance = .13), 12341, 3013, 2, 150)

groups_copy = copy(groupsa)
groups_similar = similar(groupsa)

groupsb = BenchmarkGroup()
groupsb["g1"] = g1
groupsb["g2"] = g2
g3b = addgroup!(groupsb, "g3", ["3", "4"])
g3b["c"] = TrialEstimate(Parameters(time_tolerance = .05, memory_tolerance = .05), 1003, 23, 41, 536)
g3b["d"] = TrialEstimate(Parameters(time_tolerance = .23, memory_tolerance = .23), 25341, 3013, 2, 150)

groupstrial = BenchmarkGroup()
groupstrial["g"] = gtrial

# tests #
#-------#

@test time(groupsa).data == Dict("g1" => time(g1), "g2" => time(g2), "g3" => time(g3a))
@test gctime(groupsa).data == Dict("g1" => gctime(g1), "g2" => gctime(g2), "g3" => gctime(g3a))
@test memory(groupsa).data == Dict("g1" => memory(g1), "g2" => memory(g2), "g3" => memory(g3a))
@test allocs(groupsa).data == Dict("g1" => allocs(g1), "g2" => allocs(g2), "g3" => allocs(g3a))
@test params(groupsa).data == Dict("g1" => params(g1), "g2" => params(g2), "g3" => params(g3a))

for (k, v) in BenchmarkTools.leaves(groupsa)
    @test groupsa[k] == v
end

@test max(groupsa, groupsb).data == Dict("g1" => max(g1, g1), "g2" => max(g2, g2), "g3" => max(g3a, g3b))
@test min(groupsa, groupsb).data == Dict("g1" => min(g1, g1), "g2" => min(g2, g2), "g3" => min(g3a, g3b))
@test ratio(groupsa, groupsb).data == Dict("g1" => ratio(g1, g1), "g2" => ratio(g2, g2), "g3" => ratio(g3a, g3b))
@test (judge(groupsa, groupsb; time_tolerance = 0.1, memory_tolerance = 0.1).data ==
       Dict("g1" => judge(g1, g1; time_tolerance = 0.1, memory_tolerance = 0.1),
            "g2" => judge(g2, g2; time_tolerance = 0.1, memory_tolerance = 0.1),
            "g3" => judge(g3a, g3b; time_tolerance = 0.1, memory_tolerance = 0.1)))
@test (judge(ratio(groupsa, groupsb); time_tolerance = 0.1, memory_tolerance = 0.1) ==
       judge(groupsa, groupsb; time_tolerance = 0.1, memory_tolerance = 0.1))
@test ratio(groupsa, groupsb) == ratio(judge(groupsa, groupsb))

@test isinvariant(judge(groupsa, groupsa))
@test !(isinvariant(judge(groupsa, groupsb)))
@test isregression(judge(groupsa, groupsb))
@test !(isregression(judge(groupsa, groupsa)))
@test isimprovement(judge(groupsa, groupsb))
@test !(isimprovement(judge(groupsa, groupsa)))
@test invariants(judge(groupsa, groupsb)).data == Dict("g1" => judge(g1, g1), "g2" => judge(g2, g2))
@test regressions(judge(groupsa, groupsb)).data == Dict("g3" => regressions(judge(g3a, g3b)))
@test improvements(judge(groupsa, groupsb)).data == Dict("g3" => improvements(judge(g3a, g3b)))

@test minimum(groupstrial)["g"]["t"] == minimum(groupstrial["g"]["t"])
@test maximum(groupstrial)["g"]["t"] == maximum(groupstrial["g"]["t"])
@test median(groupstrial)["g"]["t"] == median(groupstrial["g"]["t"])
@test mean(groupstrial)["g"]["t"] == mean(groupstrial["g"]["t"])
@test params(groupstrial)["g"]["t"] == params(groupstrial["g"]["t"])

# tagging #
#---------#

@test groupsa[@tagged "1"] == BenchmarkGroup([], "g1" => g1)
@test groupsa[@tagged "2"] == BenchmarkGroup([], "g1" => g1, "g2" => g2)
@test groupsa[@tagged "3"] == BenchmarkGroup([], "g2" => g2, "g3" => g3a)
@test groupsa[@tagged "4"] == BenchmarkGroup([], "g3" => g3a)
@test groupsa[@tagged "3" && "4"] == groupsa[@tagged "4"]
@test groupsa[@tagged ALL && !("2")] == groupsa[@tagged !("2")]
@test groupsa[@tagged "1" || "4"] == BenchmarkGroup([], "g1" => g1, "g3" => g3a)
@test groupsa[@tagged ("1" || "4") && !("2")] == groupsa[@tagged "4"]
@test groupsa[@tagged !("1" || "4") && "2"] == BenchmarkGroup([], "g2" => g2)
@test groupsa[@tagged ALL] == groupsa
@test groupsa[@tagged !("1" || "3") && !("4")] == similar(groupsa)

gnest = BenchmarkGroup(["1"],
                       "2" => BenchmarkGroup(["3"], 1 => 1),
                       4 => BenchmarkGroup(["3"], 5 => 6),
                       7 => 8,
                       "a" => BenchmarkGroup(["3"], "a" => :a, (11, "b") => :b),
                       9 => BenchmarkGroup(["2"],
                                           10 => BenchmarkGroup(["3"]),
                                           11 => BenchmarkGroup()))

@test leaves(gnest) == [([7],8), ([4,5],6), (["2",1],1), (["a", (11, "b")], :b), (["a","a"], :a)]

@test gnest[@tagged 11 || 10] == BenchmarkGroup(["1"],
                                                "a" => BenchmarkGroup(["3"],
                                                                      (11, "b") => :b),
                                                9 => gnest[9])

@test gnest[@tagged "3"] == BenchmarkGroup(["1"], "2" => gnest["2"], 4 => gnest[4], "a" => gnest["a"],
                                           9 => BenchmarkGroup(["2"], 10 => BenchmarkGroup(["3"])))

@test gnest[@tagged "1" && "2" && "3"] == BenchmarkGroup(["1"], "2" => gnest["2"],
                                                          9 => BenchmarkGroup(["2"], 10 => BenchmarkGroup(["3"])))

k = 3 + im
gnest = BenchmarkGroup(["1"], :hi => BenchmarkGroup([], 1 => 1, k => BenchmarkGroup(["3"], 1 => 1)), 2 => 1)

@test gnest[@tagged "1"] == gnest
@test gnest[@tagged "1" && !(:hi)] == BenchmarkGroup(["1"], 2 => 1)
@test gnest[@tagged :hi && !("3")] == BenchmarkGroup(["1"], :hi => BenchmarkGroup([], 1 => 1))
@test gnest[@tagged k] == BenchmarkGroup(["1"], :hi => BenchmarkGroup([], k => BenchmarkGroup(["3"], 1 => 1)))

# indexing by BenchmarkGroup #
#----------------------------#

g = BenchmarkGroup()
d = Dict("1" => 1, "2" => 2, "3" => 3)
g["a"] = BenchmarkGroup([], copy(d))
g["b"] = BenchmarkGroup([], copy(d))
g["c"] = BenchmarkGroup([], copy(d))
g["d"] = BenchmarkGroup([], copy(d))
g["e"] = BenchmarkGroup([], "1" => BenchmarkGroup([], copy(d)),
                            "2" => BenchmarkGroup([], copy(d)),
                            "3" => BenchmarkGroup([], copy(d)))

x = BenchmarkGroup()
x["a"] = BenchmarkGroup([], "1" => '1', "3" => '3')
x["c"] = BenchmarkGroup([], "2" => '2')
x["d"] = BenchmarkGroup([], "1" => '1', "2" => '2', "3" => '3')
x["e"] = BenchmarkGroup([], "1" => x["a"], "3" => x["c"])

gx = BenchmarkGroup()
gx["a"] = BenchmarkGroup([], "1" => 1, "3" => 3)
gx["c"] = BenchmarkGroup([], "2" => 2)
gx["d"] = BenchmarkGroup([], "1" => 1, "2" => 2, "3" => 3)
gx["e"] = BenchmarkGroup([], "1" => g["e"]["1"][x["a"]], "3" => g["e"]["3"][x["c"]])

@test g[x] == gx

# indexing by Vector #
#--------------------#

g1 = BenchmarkGroup(1 => BenchmarkGroup("a" => BenchmarkGroup()))
g1[[1, "a", :b]] = "hello"
@test g1[[1, "a", :b]] == "hello"

g2 = BenchmarkGroup()
g2[[1, "a", :b]] = "hello"  # should create higher levels on the fly
@test g2[[1, "a", :b]] == "hello"

@test g1 == g2

# end # module


text:
module PandorasBoxWaterDrownController

using ..Ahorn, Maple

@mapdef Entity "pandorasBox/waterDrowningController" WaterDrowningController(x::Integer, y::Integer, mode="Swimming", maxDuration::Number=10.0)

const placements = Ahorn.PlacementDict(
    "Water Drowning Controller (Pandora's Box)" => Ahorn.EntityPlacement(
        WaterDrowningController
    )
)

const modes = String["Swimming", "Diving"]
const iconMatrix = [
    0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0;
    0 0 0 0 1 2 0 1 0 0 0 0 0 0 0 0;
    0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0;
    0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0;
    0 0 1 1 1 0 0 0 0 1 1 0 0 0 0 0;
    0 1 0 0 0 1 0 1 1 0 0 1 1 0 0 0;
    1 0 2 2 0 0 1 0 0 2 0 0 0 1 0 0;
    1 0 2 0 0 0 1 0 2 2 2 0 0 0 1 0;
    1 0 0 0 0 0 1 2 2 2 0 0 0 0 1 0;
    0 1 0 0 0 1 0 0 2 0 0 0 0 0 0 1;
    0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1;
    0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0;
    0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0;
    0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0;
    0 0 0 0 0 0 0 1 1 0 0 1 1 0 0 0;
    0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0;
]

const iconSurface = Ahorn.matrixToSurface(
    iconMatrix,
    [
        (0 / 255, 0 / 255, 0 / 255, 0.0),
        (192 / 255, 224 / 255, 247 / 255, 1.0),
        (255 / 255, 255 / 255, 255 / 255, 1.0),
    ]
)

Ahorn.editingOptions(entity::WaterDrowningController) = Dict{String, Any}(
    "mode" => modes
)

function Ahorn.selection(entity::WaterDrowningController)
    x, y = Ahorn.position(entity)

    return Ahorn.Rectangle(x - 10, y - 10, 20, 20)
end

tintColor = (137, 251, 255, 255) ./ 255

# TODO - Better render
function Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::WaterDrowningController, room::Maple.Room)
    Ahorn.Cairo.save(ctx)

    Ahorn.set_antialias(ctx, 1)
    Ahorn.set_line_width(ctx, 1);

    Ahorn.drawCircle(ctx, 0, 0, 10, (1.0, 1.0, 1.0, 1.0))
    Ahorn.drawImage(ctx, iconSurface, -8, -8)

    Ahorn.Cairo.restore(ctx)
end

end

max_stars_repo_name: DemoJameson/PandorasBox

max_issues_repo_name: DemoJameson/PandorasBox

max_forks_repo_name: DemoJameson/PandorasBox


text:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                   Chron.jl                                    #
#                                                                               #
#       A two-part framework for (1) estimating eruption/deposition age         #
#  distributions from complex mineral age spectra and (2) subsequently building #
#  a stratigraphic age model based on those distributions. Each step relies on  #
#  a Markov-Chain Monte Carlo model.                                            #
#                                                                               #
#    The first model uses an informative prior distribution to estimate the     #
#  times of first (i.e., saturation) and last  mineral crystallization (i.e.,   #
#  eruption/deposition).                                                        #
#                                                                               #
#    The second model uses the estimated (posterior) eruption/deposition ages   #
#  distributions along with the constraint of stratigraphic superposition to    #
#  produce an age-depth model                                                   #
#                                                                               #
#   Last modified by C. Brenhin Keller 2021-05-05                               #
#                                                                               #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

__precompile__()

module Chron

    using Reexport
    @reexport using NaNStatistics
    @reexport using StatGeochemBase

    # Basic statistics and UI resources
    using ProgressMeter: @showprogress, Progress, update!
    using LsqFit: curve_fit
    using KernelDensity: kde
    using DelimitedFiles

    # Bilinear exponential function
    using LoopVectorization
    include("Utilities.jl")
    # Functions for propagating systematic uncertainties
    using Distributions
    include("Systematic.jl")
    # Custom objects for holding Chron age data
    include("Objects.jl")
    # Intcal2013 calibration curve for radiocarbion
    include("Intcal.jl")
    # Functions for estimating extrema of a finite-range distribution
    include("DistMetropolis.jl")
    # Functions for stratigraphic modelling
    include("StratMetropolis.jl")

    using Plots; gr();
    include("Fitplot.jl")

    # Structs
    export ChronAgeData, HiatusData, StratAgeModelConfiguration, StratAgeModel

    # High-level functions
    export  StratMetropolis, StratMetropolisDist, StratMetropolis14C,
        tMinDistMetropolis, metropolis_min!, metropolis_min,
        metropolis_minmax!, metropolis_minmax,
        bilinear_exponential, bilinear_exponential_ll,
        plot_rankorder_errorbar, plot_rankorder_errorbar!,
        screen_outliers, BootstrapCrystDistributionKDE

    # Distributions
    export UniformDistribution, TriangularDistribution, HalfNormalDistribution, TruncatedNormalDistribution,
        EllisDistribution, MeltsZirconDistribution, MeltsVolcanicZirconDistribution

end # module