text:
# -- PRIVATE METHODS --------------------------------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------------------------------------------------- #

# -- PUBLIC METHODS ---------------------------------------------------------------------------------------------------- #
function compute_exponential_moving_average(data::DataFrame, startDate::Date, delay::Int64;
    timestampColKeySymbol::Symbol=Symbol("timestamp"), dataColKeySymbol::Symbol=Symbol("adjusted_close"))::PSResult

    # initialize -
    price_array = Array{Float64,1}()
    exponential_moving_average = Array{Float64,1}()

    # check: delay is non-negative?
    if (delay < 0)
        return PSResult(ArgumentError("delay parameter must be non-negative"))
    end

    # check: find the index of this date -
    idx_start_date = findfirst(x -> x == startDate, data[!, timestampColKeySymbol])
    if (idx_start_date === nothing)
        return PSResult(ArgumentError("the start date is not contained in the data set"))
    end

    try

        # populate the price array -
        (number_of_days, number_of_cols) = size(data)
        for index = idx_start_date:number_of_days
            value = data[index,dataColKeySymbol]
            push!(price_array, value)
        end

        # compute the SMA (start point) -
        tmp_array = Array{Float64,1}()
        for index = 1:delay
            value = price_array[index]
            push!(tmp_array, value)
        end
        SMA = mean(tmp_array)

        # what is the weight parameter -
        ω = 2.0 / (delay + 1.0)

        # compute -
        push!(exponential_moving_average, SMA)
        for index = 1:number_of_days

            price_value = price_array[index]
            EMA_old = exponential_moving_average[index]
            EMA_new = ω * price_value + (1.0 - ω) * EMA_old
            push!(exponential_moving_average, EMA_new)
        end

        # return -
        return PSResult(exponential_moving_average)
    catch error
        return PSResult(error)
    end
end

function compute_fibonacci_retracement_levels(data::DataFrame;
    dataColKeySymbol::Symbol=Symbol("adjusted_close"))::PSResult

    # initialize -
    fnrl_array = zeros(7, 2)
    fn_array = [0.0 0.236 0.382 0.5 0.618 0.786 1.0];

    try

        # find the min and the max in the data being passed in -
        min_value = minimum(data[!,dataColKeySymbol])
        max_value = maximum(data[!,dataColKeySymbol])
        𝝙 = max_value - min_value

        # compute the levels -
        for (index, level) in enumerate(fn_array)
            tmp = max_value - 𝝙 * level
            fnrl_array[index,1] = level
            fnrl_array[index,2] = tmp
        end

        # return -
        return PSResult{Array{Float64,2}}(fnrl_array)
    catch error
        return PSResult(error)
    end
end
# ---------------------------------------------------------------------------------------------------------------------- #


text:
"""
    @test_reference filename ex [kw...]

Tests that the expression `ex` evaluates to the same result as
stored in the given reference file, which is denoted by the
string `filename`. Executing the code in an interactive julia
session will trigger an interactive dialog if results don't
match. This dialog allows the user to create and/or update the
reference files.

The given string `filename` is assumed to be the relative path to
the file that contains the macro invocation. This likely means
that the path `filename` is relative to the `test/` folder of
your package.

The file-extension of `filename`, as well as the type of the
result of evaluating `ex`, determine how the actual value is
compared to the reference value. The default implementation will
do a simple equality check with the result of `FileIO.load`. This
means that it is the user's responsibility to have the required
IO package installed.

Colorant arrays (i.e.) receive special treatment. If the
extension of `filename` is `txt` then the package
`ImageInTerminal` will be used to create a string based cure
approximation of the image. This will have low storage
requirements and also allows to view the reference file in a
simple terminal using `cat`.

Another special file extension is `sha256` which will cause the
hash of the result of `ex` to be stored and compared as plain
text. This is useful for a convenient low-storage way of making
sure that the return value doesn't change for selected test
cases.

# Examples

```julia
# store as string using ImageInTerminal with encoding size (5,10)
@test_reference "camera.txt" testimage("cameraman") size=(5,10)

# using folders in the relative path is allowed
@test_reference "references/camera.png" testimage("cameraman")

# Images can also be stored as hash. Note however that this
# can only check for equality (no tolerance possible)
@test_reference "references/camera.sha256" testimage("cameraman")
```
"""
macro test_reference(reference, actual, kws...)
    dir = Base.source_dir()
    expr = :(test_reference(abspath(joinpath($dir, $(esc(reference)))), $(esc(actual))))
    for kw in kws
        (kw isa Expr && kw.head == :(=)) || error("invalid signature for @test_reference")
        push!(expr.args, Expr(:kw, kw.args...))
    end
    expr
end

function test_reference(filename::AbstractString, actual; kw...)
    test_reference(query_extended(filename), actual; kw...)
end

function query_extended(filename)
    file, ext = splitext(filename)
    # TODO: make this less hacky
    if uppercase(ext) == ".TXT"
        res = File{format"TXT"}(filename)
    elseif uppercase(ext) == ".SHA256"
        res = File{format"SHA256"}(filename)
    else
        res = query(filename)
    end
    res
end

ext: jl


text:
@testset "IntVarView.jl" begin
    @testset "IntVarViewMul" begin
        @testset "isempty()" begin
            trailer = SeaPearl.Trailer()
            domNotEmpty = SeaPearl.IntDomain(trailer, 20, 10)
            ax = SeaPearl.IntDomainViewMul(domNotEmpty, 4)

            @test !isempty(ax)

            emptyDom = SeaPearl.IntDomain(trailer, 0, 1)
            ay = SeaPearl.IntDomainViewMul(emptyDom, 4)
            @test isempty(ay)
        end

        @testset "length()" begin
            trailer = SeaPearl.Trailer()
            dom20 = SeaPearl.IntDomain(trailer, 20, 10)
            ax = SeaPearl.IntDomainViewMul(dom20, 4)
            @test length(ax) == 20

            dom2 = SeaPearl.IntDomain(trailer, 2, 0)
            ax = SeaPearl.IntDomainViewMul(dom2, 4)

            @test length(ax) == 2
        end

        @testset "in()" begin
            trailer = SeaPearl.Trailer()
            dom20 = SeaPearl.IntDomain(trailer, 3, 2)
            ax = SeaPearl.IntDomainViewMul(dom20, 4)

            @test !(2 in ax)
            @test !(3 in ax)
            @test 12 in ax
            @test !(13 in ax)
            @test 16 in ax
        end

        @testset "minimum()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 10, "x", trailer)
            axDom = SeaPearl.IntDomainViewMul(x.domain, 4)

            @test SeaPearl.minimum(axDom) == 20
        end

        @testset "removeAll!()" begin
            trailer = SeaPearl.Trailer()
            dom = SeaPearl.IntDomain(trailer, 3, 10)
            axDom = SeaPearl.IntDomainViewMul(dom, 4)

            removed = SeaPearl.removeAll!(axDom)

            @test isempty(axDom)
            @test removed == [44, 48, 52]
        end

        @testset "maximum()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 10, "x", trailer)
            axDom = SeaPearl.IntDomainViewMul(x.domain, 4)

            @test SeaPearl.maximum(axDom) == 40
        end

        @testset "remove!()" begin
            trailer = SeaPearl.Trailer()
            dom = SeaPearl.IntDomain(trailer, 3, 2)
            ax = SeaPearl.IntDomainViewMul(dom, 4)

            @test SeaPearl.remove!(ax, 12) == [12]

            @test !(12 in ax)
            @test length(ax) == 2
            @test SeaPearl.minimum(ax) == 16
        end

        @testset "removeAbove!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewMul(x.domain, 4)

            @test sort(SeaPearl.removeAbove!(axDom, 8)) == [12, 16, 20]

            @test length(axDom) == 2
            @test 8 in axDom
            @test 4 in axDom
            @test !(12 in axDom)

            @test sort(SeaPearl.removeAbove!(axDom, 2)) == [4, 8]

            @test isempty(axDom)

            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewMul(x.domain, 4)

            @test sort(SeaPearl.removeAbove!(axDom, 10)) == [12, 16, 20]
            @test length(axDom) == 2
            @test 8 in axDom
            @test 4 in axDom
            @test !(12 in axDom)
        end

        @testset "removeBelow!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewMul(x.domain, 4)

            @test sort(SeaPearl.removeBelow!(axDom, 8)) == [4]

            @test length(axDom) == 4
            @test 8 in axDom
            @test 12 in axDom
            @test !(4 in axDom)

            @test sort(SeaPearl.removeBelow!(axDom, 21)) == [8, 12, 16, 20]

            @test isempty(axDom)

            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewMul(x.domain, 4)

            @test sort(SeaPearl.removeBelow!(axDom, 6)) == [4]

            @test length(axDom) == 4
            @test 8 in axDom
            @test 12 in axDom
            @test !(4 in axDom)
        end

        @testset "iterate()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewMul(x.domain, 4)

            j = 4
            for i in axDom
                @test j == i
                j += 4
            end

            @test j == 24

        end

        @testset "updateMinFromRemovedVal!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewMul(x.domain, 4)

            @test SeaPearl.minimum(axDom) == 4

            SeaPearl.remove!(axDom, 4)
            SeaPearl.updateMinFromRemovedVal!(axDom, 4)

            @test SeaPearl.minimum(axDom) == 8
        end

        @testset "updateMaxFromRemovedVal!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewMul(x.domain, 4)

            @test SeaPearl.maximum(axDom) == 20

            SeaPearl.remove!(axDom, 20)
            SeaPearl.updateMaxFromRemovedVal!(axDom, 20)

            @test SeaPearl.maximum(axDom) == 16
        end

        @testset "updateBoundsFromRemovedVal!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewMul(x.domain, 4)

            SeaPearl.remove!(axDom, 20)
            SeaPearl.remove!(axDom, 4)
            SeaPearl.updateBoundsFromRemovedVal!(axDom, 20)
            SeaPearl.updateBoundsFromRemovedVal!(axDom, 4)

            @test SeaPearl.minimum(axDom) == 8
            @test SeaPearl.maximum(axDom) == 16
        end

        @testset "isbound()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(2, 6, "x", trailer)
            ax = SeaPearl.IntVarViewMul(x, 3, "ax")

            @test !SeaPearl.isbound(ax)

            SeaPearl.assign!(ax, 6)

            @test SeaPearl.isbound(ax)
        end

        @testset "assignedValue()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 5, "x", trailer)
            ax = SeaPearl.IntVarViewMul(x, 3, "ax")

            @test SeaPearl.assignedValue(ax) == 15

            y = SeaPearl.IntVar(5, 8, "y", trailer)
            ay = SeaPearl.IntVarViewMul(y, 3, "ay")
            @test_throws AssertionError SeaPearl.assignedValue(y)
        end

        @testset "rootVariable()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 5, "x", trailer)
            ax = SeaPearl.IntVarViewMul(x, 3, "ax")

            @test SeaPearl.rootVariable(SeaPearl.IntVarViewOpposite(ax, "-ax")) == x

            @test SeaPearl.rootVariable(x) == x
            @test SeaPearl.rootVariable(ax) == x
        end
    end
    @testset "IntVarViewOpposite" begin

        @testset "isempty()" begin
            trailer = SeaPearl.Trailer()
            domNotEmpty = SeaPearl.IntDomain(trailer, 20, 10)
            ax = SeaPearl.IntDomainViewOpposite(domNotEmpty)

            @test !isempty(ax)

            emptyDom = SeaPearl.IntDomain(trailer, 0, 1)
            ay = SeaPearl.IntDomainViewOpposite(emptyDom)
            @test isempty(ay)
        end

        @testset "length()" begin
            trailer = SeaPearl.Trailer()
            dom20 = SeaPearl.IntDomain(trailer, 20, 10)
            ax = SeaPearl.IntDomainViewOpposite(dom20)
            @test length(ax) == 20

            dom2 = SeaPearl.IntDomain(trailer, 2, 0)
            ax = SeaPearl.IntDomainViewOpposite(dom2)

            @test length(ax) == 2
        end

        @testset "in()" begin
            trailer = SeaPearl.Trailer()
            dom20 = SeaPearl.IntDomain(trailer, 3, 2)
            ax = SeaPearl.IntDomainViewOpposite(dom20)

            @test !(4 in ax)
            @test !(3 in ax)
            @test -3 in ax
            @test !(-6 in ax)
            @test -5 in ax
        end

        @testset "minimum()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 10, "x", trailer)
            axDom = SeaPearl.IntDomainViewOpposite(x.domain)

            @test SeaPearl.minimum(axDom) == -10
        end

        @testset "removeAll!()" begin
            trailer = SeaPearl.Trailer()
            dom = SeaPearl.IntDomain(trailer, 3, 10)
            axDom = SeaPearl.IntDomainViewOpposite(dom)

            removed = SeaPearl.removeAll!(axDom)

            @test isempty(axDom)
            @test removed == [-11, -12, -13]
        end

        @testset "maximum()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 10, "x", trailer)
            axDom = SeaPearl.IntDomainViewOpposite(x.domain)

            @test SeaPearl.maximum(axDom) == -5
        end

        @testset "remove!()" begin
            trailer = SeaPearl.Trailer()
            dom = SeaPearl.IntDomain(trailer, 3, 2)
            ax = SeaPearl.IntDomainViewOpposite(dom)

            @test SeaPearl.remove!(ax, -5) == [-5]

            @test !(-5 in ax)
            @test length(ax) == 2
            @test SeaPearl.minimum(ax) == -4
        end

        @testset "removeAbove!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOpposite(x.domain)

            @test sort(SeaPearl.removeAbove!(axDom, -4)) == [-3, -2, -1]

            @test length(axDom) == 2
            @test -4 in axDom
            @test -5 in axDom
            @test !(-3 in axDom)

            @test sort(SeaPearl.removeAbove!(axDom, -6)) == [-5, -4]

            @test isempty(axDom)
        end

        @testset "removeBelow!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOpposite(x.domain)

            @test sort(SeaPearl.removeBelow!(axDom, -4)) == [-5]

            @test length(axDom) == 4
            @test -4 in axDom
            @test -3 in axDom
            @test !(-5 in axDom)

            @test sort(SeaPearl.removeBelow!(axDom, 0)) == [-4, -3, -2, -1]

            @test isempty(axDom)
        end

        @testset "iterate()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOpposite(x.domain)

            j = -1
            for i in axDom
                @test j == i
                j -= 1
            end

            @test j == -6

        end

        @testset "updateMinFromRemovedVal!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOpposite(x.domain)

            @test SeaPearl.minimum(axDom) == -5

            SeaPearl.remove!(axDom, -5)
            SeaPearl.updateMinFromRemovedVal!(axDom, -5)

            @test SeaPearl.minimum(axDom) == -4
        end

        @testset "updateMaxFromRemovedVal!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOpposite(x.domain)

            @test SeaPearl.maximum(axDom) == -1

            SeaPearl.remove!(axDom, -1)
            SeaPearl.updateMaxFromRemovedVal!(axDom, -1)

            @test SeaPearl.maximum(axDom) == -2
        end

        @testset "updateBoundsFromRemovedVal!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOpposite(x.domain)

            SeaPearl.remove!(axDom, -5)
            SeaPearl.remove!(axDom, -1)
            SeaPearl.updateBoundsFromRemovedVal!(axDom, -5)
            SeaPearl.updateBoundsFromRemovedVal!(axDom, -1)

            @test SeaPearl.minimum(axDom) == -4
            @test SeaPearl.maximum(axDom) == -2
        end

        @testset "isbound()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(2, 6, "x", trailer)
            ax = SeaPearl.IntVarViewOpposite(x, "-x")

            @test !SeaPearl.isbound(ax)

            SeaPearl.assign!(ax, -5)

            @test SeaPearl.isbound(ax)
        end

        @testset "assignedValue()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 5, "x", trailer)
            ax = SeaPearl.IntVarViewOpposite(x, "-x")

            @test SeaPearl.assignedValue(ax) == -5

            y = SeaPearl.IntVar(5, 8, "y", trailer)
            ay = SeaPearl.IntVarViewOpposite(y, "-y")
            @test_throws AssertionError SeaPearl.assignedValue(y)
        end

        @testset "rootVariable()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 5, "x", trailer)
            ax = SeaPearl.IntVarViewOpposite(x, "-x")

            @test SeaPearl.rootVariable(x) == x
            @test SeaPearl.rootVariable(ax) == x
        end
    end

    @testset "IntVarViewOffset" begin
        @testset "isempty()" begin
            trailer = SeaPearl.Trailer()
            domNotEmpty = SeaPearl.IntDomain(trailer, 20, 10)
            ax = SeaPearl.IntDomainViewOffset(domNotEmpty, 4)

            @test !isempty(ax)

            emptyDom = SeaPearl.IntDomain(trailer, 0, 1)
            ay = SeaPearl.IntDomainViewOffset(emptyDom, 4)
            @test isempty(ay)
        end

        @testset "length()" begin
            trailer = SeaPearl.Trailer()
            dom20 = SeaPearl.IntDomain(trailer, 20, 10)
            ax = SeaPearl.IntDomainViewOffset(dom20, 4)
            @test length(ax) == 20

            dom2 = SeaPearl.IntDomain(trailer, 2, 0)
            ax = SeaPearl.IntDomainViewOffset(dom2, 4)

            @test length(ax) == 2
        end

        @testset "in()" begin
            trailer = SeaPearl.Trailer()
            dom20 = SeaPearl.IntDomain(trailer, 3, 2)
            ax = SeaPearl.IntDomainViewOffset(dom20, 4)

            @test !(2 in ax)
            @test !(3 in ax)
            @test 7 in ax
            @test !(10 in ax)
            @test 9 in ax
        end

        @testset "minimum()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 10, "x", trailer)
            axDom = SeaPearl.IntDomainViewOffset(x.domain, 4)

            @test SeaPearl.minimum(axDom) == 9
        end

        @testset "removeAll!()" begin
            trailer = SeaPearl.Trailer()
            dom = SeaPearl.IntDomain(trailer, 3, 10)
            axDom = SeaPearl.IntDomainViewOffset(dom, 4)

            removed = SeaPearl.removeAll!(axDom)

            @test isempty(axDom)
            @test removed == [15, 16, 17]
        end

        @testset "maximum()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 10, "x", trailer)
            axDom = SeaPearl.IntDomainViewOffset(x.domain, 4)

            @test SeaPearl.maximum(axDom) == 14
        end

        @testset "remove!()" begin
            trailer = SeaPearl.Trailer()
            dom = SeaPearl.IntDomain(trailer, 3, 2)
            ax = SeaPearl.IntDomainViewOffset(dom, 4)

            SeaPearl.remove!(ax, 7)

            @test !(7 in ax)
            @test length(ax) == 2
            @test SeaPearl.minimum(ax) == 8
        end

        @testset "removeAbove!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOffset(x.domain, 4)

            @test sort(SeaPearl.removeAbove!(axDom, 7)) == [8, 9]

            @test length(axDom) == 3
            @test 7 in axDom
            @test !(4 in axDom)
            @test !(9 in axDom)
            @test 5 in axDom

            @test sort(SeaPearl.removeAbove!(axDom, 2)) == [5, 6, 7]

            @test isempty(axDom)
        end

        @testset "removeBelow!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOffset(x.domain, 4)

            @test sort(SeaPearl.removeBelow!(axDom, 8)) == [5, 6, 7]

            @test length(axDom) == 2
            @test 8 in axDom
            @test 9 in axDom
            @test !(5 in axDom)
            @test !(4 in axDom)

            @test sort(SeaPearl.removeBelow!(axDom, 21)) == [8, 9]

            @test isempty(axDom)
        end

        @testset "iterate()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOffset(x.domain, 4)

            j = 5
            for i in axDom
                @test j == i
                j += 1
            end

            @test j == 10

        end

        @testset "updateMinFromRemovedVal!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOffset(x.domain, 4)

            @test SeaPearl.minimum(axDom) == 5

            SeaPearl.remove!(axDom, 5)
            SeaPearl.updateMinFromRemovedVal!(axDom, 5)

            @test SeaPearl.minimum(axDom) == 6
        end

        @testset "updateMaxFromRemovedVal!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOffset(x.domain, 4)

            @test SeaPearl.maximum(axDom) == 9

            SeaPearl.remove!(axDom, 9)
            SeaPearl.updateMaxFromRemovedVal!(axDom, 9)

            @test SeaPearl.maximum(axDom) == 8
        end

        @testset "updateBoundsFromRemovedVal!()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(1, 5, "x", trailer)
            axDom = SeaPearl.IntDomainViewOffset(x.domain, 4)

            SeaPearl.remove!(axDom, 9)
            SeaPearl.remove!(axDom, 5)
            SeaPearl.updateBoundsFromRemovedVal!(axDom, 9)
            SeaPearl.updateBoundsFromRemovedVal!(axDom, 5)

            @test SeaPearl.minimum(axDom) == 6
            @test SeaPearl.maximum(axDom) == 8
        end

        @testset "isbound()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(2, 6, "x", trailer)
            ax = SeaPearl.IntVarViewOffset(x, 3, "ax")

            @test !SeaPearl.isbound(ax)

            SeaPearl.assign!(ax, 6)

            @test SeaPearl.isbound(ax)
        end

        @testset "assignedValue()" begin
            trailer = SeaPearl.Trailer()
            x = SeaPearl.IntVar(5, 5, "x", trailer)
            ax = SeaPearl.IntVarViewOffset(x, 3, "ax")

            @test SeaPearl.assignedValue(ax) == 8

            y = SeaPearl.IntVar(5, 8, "y", trailer)
            ay = SeaPearl.IntVarViewOffset(y, 3, "ay")
            @test_throws AssertionError SeaPearl.assignedValue(y)
        end
    end
end


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

# tests for codegen and optimizations

const opt_level = Base.JLOptions().opt_level
const coverage = (Base.JLOptions().code_coverage > 0) || (Base.JLOptions().malloc_log > 0)
const Iptr = sizeof(Int) == 8 ? "i64" : "i32"

# `_dump_function` might be more efficient but it doesn't really matter here...
get_llvm(f::ANY, t::ANY, strip_ir_metadata=true, dump_module=false) =
    sprint(code_llvm, f, t, strip_ir_metadata, dump_module)

if opt_level > 0
    # Make sure getptls call is removed at IR level with optimization on
    @test !contains(get_llvm(identity, Tuple{String}), " call ")
end

jl_string_ptr(s::String) = ccall(:jl_string_ptr, Ptr{UInt8}, (Any,), s)
core_sizeof(o) = Core.sizeof(o)
function test_loads_no_call(ir, load_types)
    in_function = false
    load_idx = 1
    for line in eachline(IOBuffer(ir))
        if !in_function
            if startswith(line, "define ")
                in_function = true
            end
            continue
        end
        @test !contains(line, " call ")
        load_split = split(line, " load ", limit=2)
        if !coverage && length(load_split) >= 2
            @test load_idx <= length(load_types)
            if load_idx <= length(load_types)
                @test startswith(load_split[2], "$(load_types[load_idx]),")
            end
            load_idx += 1
        end
        if startswith(line, "}")
            break
        end
    end
    if !coverage
        @test load_idx == length(load_types) + 1
    end
end
if opt_level > 0
    # Make sure `jl_string_ptr` is inlined
    @test !contains(get_llvm(jl_string_ptr, Tuple{String}), " call ")
    s = "aaa"
    @test jl_string_ptr(s) == pointer_from_objref(s) + sizeof(Int)
    # String
    test_loads_no_call(get_llvm(core_sizeof, Tuple{String}), [Iptr])
    # String
    test_loads_no_call(get_llvm(core_sizeof, Tuple{SimpleVector}), [Iptr])
    # Array
    test_loads_no_call(get_llvm(core_sizeof, Tuple{Vector{Int}}), [Iptr])
    # As long as the eltype is known we don't need to load the elsize
    test_loads_no_call(get_llvm(core_sizeof, Tuple{Array{Any}}), [Iptr])
    # Check that we load the elsize
    test_loads_no_call(get_llvm(core_sizeof, Tuple{Vector}), [Iptr, "i16"])
end

max_stars_repo_name: nassarhuda/julia

max_issues_repo_name: nassarhuda/julia

max_forks_repo_name: nassarhuda/julia


text:
# set up the working directory
# path = pwd()
# push!(LOAD_PATH, chomp(path))

## Mute below if in the Git Action
import Pkg
Pkg.activate(@__DIR__)
Pkg.instantiate()

using Literate

const PWD     = joinpath(pwd())
const SRC_DIR = joinpath(PWD,"src")
const SRC_FILE = joinpath(SRC_DIR,"an_introduction_to_julia.jl")
const NB_DIR  = joinpath(pwd(),"notebook")

# Literate.notebook(inputfile, outputdir=pwd(); config::Dict=Dict(), kwargs...)
println("Converting *.jl to *.ipynb")
println("Writing out *.ipynb")

Literate.notebook( SRC_FILE , NB_DIR; )

# println(NB_DIR)


text: AbstractCTPF = Union{CTPF, gpuCTPF}


text:
using Coverage
cd(joinpath(@__DIR__, "..", "..")) do
    coverage = process_folder()
    covered_lines, total_lines = get_summary(coverage)
    mkdir("coverage")
    Coverage.LCOV.writefile("coverage/lcov.info", coverage)
    branch = strip(read(`git branch`, String), [' ', '*', '\n'])
    title = "on branch $(branch)"
    @show isfile("coverage/lcov.info")
    run(`genhtml -t $(title) -o coverage coverage/lcov.info`)
    percentage = covered_lines / total_lines * 100
    println("($(percentage)%) covered")
end


text:
using CSTParser

#=
utilities
=#

# scope
# -----

function scopeof(expr::CSTParser.EXPR)
    scope = CSTParser.scopeof(expr)
    if scope !== nothing
        return scope
    else
        if expr.typ == CSTParser.Call && expr.parent !== nothing && scopeof(expr.parent) == nothing
            return :call
        end

        if expr.typ == CSTParser.TupleH && expr.parent !== nothing && scopeof(expr.parent) == nothing
            return :tupleh
        end

        if iswhereclause(expr)
            return :where
        end

        if expr.typ == CSTParser.MacroCall
            return :macro
        end

        if expr.typ == CSTParser.Quote
            return :quote
        end
    end
    return nothing
end

# is utilities
# ------------

iscallexpr(expr::CSTParser.EXPR) = expr.typ === CSTParser.Call || expr.typ === CSTParser.MacroCall

ismacrocall(expr::CSTParser.EXPR) = expr.typ === CSTParser.MacroCall

function isinclude(expr::CSTParser.EXPR)
    expr.typ === CSTParser.Call &&
        length(expr.args) === 4 &&
        expr.args[1].val == "include" &&
        expr.args[3].val isa String &&
        endswith(expr.args[3].val, ".jl")
end

ismodule(expr::CSTParser.EXPR) =
    expr.typ === CSTParser.ModuleH || expr.typ === CSTParser.BareModule

function isdoc(expr::CSTParser.EXPR)
    expr.typ === CSTParser.MacroCall &&
        length(expr.args) >= 1 &&
        (
            expr.args[1].typ === CSTParser.GlobalRefDoc ||
            str_value(expr.args[1]) == "@doc"
        )
end

function ismultiplereturn(expr::CSTParser.EXPR)
    expr.typ === CSTParser.TupleH &&
        expr.args !== nothing &&
        !isempty(filter(a -> CSTParser.bindingof(a) !== nothing, expr.args))
end

function iswhereclause(expr::CSTParser.EXPR)
    expr.typ === CSTParser.WhereOpCall &&
        expr.parent !== nothing &&
        expr.args !== nothing
end

function isconstexpr(expr::CSTParser.EXPR)
    parent = CSTParser.parentof(expr)
    parent === nothing ? false : parent.typ === CSTParser.Const
end

# string utilities
# ----------------

function Base.countlines(expr::CSTParser.EXPR, text::String, pos::Int, full::Bool = true; eol = '\n')
    endpos = pos + (full ? expr.fullspan : expr.span)
    n = ncodeunits(text)
    s = nextind(text, clamp(pos - 1, 0, n))
    e = prevind(text, clamp(endpos, 1, n + 1))
    count(c -> c === eol, text[s:e])
end

"""
    str_value(x::CSTParser.EXPR)

Reconstruct source code from a `CSTParser.EXPR`.

Adapted from https://github.com/julia-vscode/DocumentFormat.jl/blob/b7e22ca47254007b5e7dd3c678ba27d8744d1b1f/src/passes.jl#L108.
"""
function str_value(x::CSTParser.EXPR)
    if x.typ === CSTParser.PUNCTUATION
        x.kind == CSTParser.Tokens.LPAREN && return "("
        x.kind == CSTParser.Tokens.LBRACE && return "{"
        x.kind == CSTParser.Tokens.LSQUARE && return "["
        x.kind == CSTParser.Tokens.RPAREN && return ")"
        x.kind == CSTParser.Tokens.RBRACE && return "}"
        x.kind == CSTParser.Tokens.RSQUARE && return "]"
        x.kind == CSTParser.Tokens.COMMA && return ", "
        x.kind == CSTParser.Tokens.SEMICOLON && return ";"
        x.kind == CSTParser.Tokens.AT_SIGN && return "@"
        x.kind == CSTParser.Tokens.DOT && return "."
        return ""
    elseif x.kind === CSTParser.Tokens.TRIPLE_STRING
        return string("\"\"\"", x.val, "\"\"\"")
    elseif x.kind === CSTParser.Tokens.STRING
        return string("\"", x.val, "\"")
    elseif x.kind === CSTParser.Tokens.EQ
        return " = "
    elseif x.kind === CSTParser.Tokens.WHERE
        return " where "
    elseif x.typ === CSTParser.Parameters
        return "; " * join(str_value(a) for a in x)
    elseif x.typ === CSTParser.IDENTIFIER || x.typ === CSTParser.LITERAL || x.typ === CSTParser.OPERATOR || x.typ === CSTParser.KEYWORD
        return CSTParser.str_value(x)
    else
        return join(str_value(a) for a in x)
    end
end

"""
    str_value_as_is(expr::CSTParser.EXPR, text::String, pos::Int)

Extract `expr`'s source from `text`, starting at `pos`. Similar to `str_value`, but doesn't
*reconstruct* the source code.
"""
function str_value_as_is(expr::CSTParser.EXPR, text::String, pos::Int)
    endpos = pos + expr.span
    n = ncodeunits(text)
    s = nextind(text, clamp(pos - 1, 0, n))
    e = prevind(text, clamp(endpos, 1, n + 1))
    strip(text[s:e])
end
str_value_as_is(bind::CSTParser.Binding, text::String, pos::Int) = str_value_as_is(bind.val, text, pos)
str_value_as_is(bind, text::String, pos::Int) = ""

# atom icon & types
# -----------------
# NOTE: need to keep this consistent with wstype/wsicon

static_type(bind::CSTParser.Binding) = static_type(bind.val)
function static_type(val::CSTParser.EXPR)
    if CSTParser.defines_function(val)
        "function"
    elseif CSTParser.defines_macro(val)
        "snippet"
    elseif CSTParser.defines_module(val)
        "module"
    elseif CSTParser.defines_struct(val) ||
           CSTParser.defines_abstract(val) ||
           CSTParser.defines_mutable(val) ||
           CSTParser.defines_primitive(val)
        "type"
    else
        isconstexpr(val) ? "constant" : "variable"
    end
end

static_icon(bind::CSTParser.Binding) = static_icon(bind.val)
function static_icon(val::CSTParser.EXPR)
    if CSTParser.defines_function(val)
        "λ"
    elseif CSTParser.defines_macro(val)
        "icon-mention"
    elseif CSTParser.defines_module(val)
        "icon-package"
    elseif CSTParser.defines_struct(val) ||
           CSTParser.defines_abstract(val) ||
           CSTParser.defines_mutable(val) ||
           CSTParser.defines_primitive(val)
        "T"
    else
        isconstexpr(val) ? "c" : "v"
    end
end

include("toplevel.jl")
include("local.jl")


text:
function percolation_preprocessor!(Φ, A)
    fc = percolation(A)

    threshold = sum(size(Φ) .- 1) * (1 - fc)

    for idx in CartesianIndices(Φ)
        if sum(Tuple(idx) .- 1) < threshold
            Φ[idx] = 0
        end
    end

    return nothing
end


text:
module StorageGraphs

export StorageGraph, add_nodes!, add_bulk!,
    nextid, paths_through, on_path, walkpath, walkdep, final_neighborhs,
    get_prop, has_prop, set_prop!, plot_graph,
    SGNativeFormat, SGJLDFormat, SGBSONFormat

using LightGraphs
using LightGraphs.SimpleGraphs: SimpleEdge

using GraphPlot

abstract type AbstractStorageGraph{T} <: AbstractGraph{T} end

struct StorageGraph{T<:Integer, N<:NamedTuple} <: AbstractStorageGraph{T}
    graph::SimpleDiGraph{T}
    data::Dict{T,N}
    paths::Dict{SimpleEdge{T},Set{T}}
    maxid::Ref{T}
    index::Dict{N,T}
end

function StorageGraph()
    g = SimpleDiGraph()
    T = eltype(g)
    data = Dict{T,NamedTuple}()
    paths = Dict{SimpleEdge{T},Set{T}}()
    maxid = Ref(one(T))
    index = Dict{NamedTuple,T}()

    StorageGraph(g, data, paths, maxid, index)
end

function StorageGraph{T}() where {T <: Integer}
    graph = SimpleDiGraph{T}()
    data = Dict{T,NamedTuple}()
    paths = Dict{SimpleEdge{T},Set{T}}()
    maxid = Ref(one(T))
    index = Dict{NamedTuple,T}()
    StorageGraph(graph, data, paths, maxid, index)
end

# converts StorageGraph{Int} to StorageGraph{UInt8}
function StorageGraph{T}(g::StorageGraph) where {T <: Integer}
    graph = SimpleDiGraph{T}(g.graph)
    data = Dict{T,NamedTuple}(g.data)
    k = SimpleEdge{T}.(keys(g.paths))
    paths = Dict{SimpleEdge{T},Set{T}}(k.=>values(g.paths))
    maxid = Ref{T}(g.maxid[])
    index = Dict{NamedTuple,T}(g.index)
    StorageGraph(graph, data, paths, maxid, index)
end

function StorageGraph(g::SimpleDiGraph{T}, data::Dict{T, N},
        paths::Dict{SimpleEdge{T},Set{T}}) where {T, N <: NamedTuple}
    maxid = Ref(maximum(maximum.(values(paths)))+one(T))
    index = Dict(values(data).=>keys(data))

    StorageGraph(g, data, paths, maxid, index)
end

include("interface.jl")
include("add.jl")
include("query.jl")
include("walk.jl")
include("persistence.jl")

function plot_graph(g; args...)
    format(s) = replace(string(s), r"Set\(\[(?<i>\d*(?>, \d*)*)\]\)"=>s"{\g<i>}")
    vlabels = [g.data[i] for i in vertices(g)]
    elabels = [format(g.paths[i]) for i in edges(g)]
    gplot(g; nodelabel=vlabels, edgelabel=elabels, args...)
end

end # module


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

@testset "Floating point numbers - basic tests" begin
    @test 4.00000000000001 ≈ 4.0
    @test 5.0 ≈ 4.999999999999993
    @test 4.000000002 ≉ 4.00300002
end
@testset "Other tolerance levels" begin
    @test 4.32 ≈ 4.3 rtol=0.1 atol=0.01
    @test 1.001 ≈ 1.002 rtol=0.001 atol=0.0001
    @test 4.5 ≉ 4.9 rtol=0.001 atol=0.001
end
@testset "Complex numbers" begin
    @test 1.0 + 1.0im ≈ 1.0 + 1.00000000000001im
    @test 0.9999999999999 + 1.0im ≈ 1.0 + 1.000000000000001im
    @test 0.9999 + 1.0im ≈ 1.0 + 1.1im rtol=0.0001 atol=1.1
end
@testset "Complex <-> reals" begin
    @test 1.0 + 0im ≈ 1.0000000000001
    @test 0.9999999999999 ≈ 1.0 + 0im
    @test 1.0+1im ≉ 1.000000000000001
end
@testset "Comparing NaNs" begin
    @test 4.0 ≉ NaN
    @test NaN ≉ 4.0
    @test complex(2.3,NaN) ≉ complex(NaN,2.3)
    @test NaN ≉ NaN
    @test complex(NaN,NaN) ≉ complex(NaN,NaN)
    @test complex(NaN,2.3) ≉ complex(NaN,2.3)
    @test complex(2.3,NaN) ≉ complex(2.3,NaN)
end
@testset "Comparing Infs" begin
    @test Inf ≈ Inf
    @test Inf ≉ 1
    @test Inf ≉ -Inf
    @test complex(0.0,Inf) ≈ complex(0.0,Inf)
    @test complex(0.0,Inf) ≉ complex(0.0,-Inf)
end
@testset "integers and rationals" begin
    @test 4 ≈ 4
    @test 4 ≈ 5 atol=1
    @test 4 ≉ 6 atol=1
    @test 4 ≉ 5

    @test 1//2+3im ≈ 1//2+3im
    @test 1//3 ≈ 0.33333333333333333
    @test 1//3 ≈ 0.3333 rtol=0.0001 atol=0.0001
    @test 1+1im ≈ 1im+1
end
# Notably missing from this test suite at the moment
# * Tests for other magnitudes of numbers - very small, very big, and combinations of small and big
# * Tests for various odd combinations of types, e.g. x::Integer ≈ y::Rational

# issue #12375:
@test 1e17 ≉ 1

@testset "Tests for arrays:" begin
    @test [1,2,3] ≈ [1,2,3+1e-9]
    @test [0,1] ≈ [1e-9, 1]
    @test [0,Inf] ≈ [0,Inf]
    @test [0,Inf] ≉ [0,-Inf]
end
@testset "issue #19936" begin
    for elty in (Float16,Float32,Float64)
        nan  = elty(NaN)
        half = elty(0.5)
        @test nan ≉ nan
        @test nan ≈ nan nans=true
        @test [half, nan, half] ≉ [half, nan, half]
        @test [half, nan, half] ≈ [half, nan, half] nans=true
    end
end

max_stars_repo_name: greimel/julia

max_issues_repo_name: greimel/julia

max_forks_repo_name: greimel/julia


text:
using SparseArrays

@testset "right_mul!" begin

    # NOTE
    # currently julia/sparsearrays does not implement a
    # mul!(C::StridedMatrix, X::StridedMatrix, A::SparseMatrixCSC)
    # instead it falls back to some generic matrix multiplciation in LinearAlgebra
    #
    # If this throws:
    # - check if mul!() is now specialized for the above type signature
    #   - if it is, remove right_mul! in helpers.jl & change right_muL! to mul! in
    #     slice_matrices.jl
    #   - otherwise, update the type signature
    #
    # see:
    # Julia PR: https://github.com/JuliaLang/julia/pull/24045
    # Julia Issue: https://github.com/JuliaLang/julia/issues/29956#issuecomment-440867024
    # MC PR: https://github.com/crstnbr/MonteCarlo.jl/pull/9
    # discourse: https://discourse.julialang.org/t/asymmetric-speed-of-in-place-sparse-dense-matrix-product/10256

    mul_dense_sparse_is_missing = !occursin("SparseArrays", string(which(mul!, (Matrix, Matrix, SparseMatrixCSC)).file))
    @test mul_dense_sparse_is_missing

    # check that right_mul! is correct
    for Lx in (4, 8)
        for Ly in (4, 8)
            M = rand(Lx, Ly)
            S = sparse(rand(Ly, Lx))
            X = rand(Lx, Lx)
            @test M * S == MonteCarlo.mul!(X, M, S)
        end
    end
end

@testset "Slice Matrices" begin
    m = HubbardModel(8, 1)
    dqmc = DQMC(m, beta=5.0)
    eT = dqmc.stack.hopping_matrix_exp
    eV = similar(dqmc.stack.eV)
    A = similar(eT)

    # No checkerboard
    for slice in rand(1:50, 2)
        MonteCarlo.interaction_matrix_exp!(dqmc, m, dqmc.field, eV, slice, 1.)

        # MonteCarlo.slice_matrix
        @test MonteCarlo.slice_matrix(dqmc, m, slice, 1.) ≈ eT * eT * eV
        @test MonteCarlo.slice_matrix(dqmc, m, slice, -1.) ≈ inv(eT * eT * eV)
        # MonteCarlo.slice_matrix!(dqmc, m, slice, 1., A)
        # @test A ≈ eT * eT * eV
        # MonteCarlo.slice_matrix!(dqmc, m, slice, -1., A)
        # @test A ≈ inv(eT * eT * eV)

        # MonteCarlo.multiply_slice_matrix...
        A = eT * eT * eV
        input = rand(size(A)...)
        result = A * input
        MonteCarlo.multiply_slice_matrix_left!(dqmc, m, slice, input)
        @test input ≈ result
        input = rand(size(A)...)
        result = input * A
        MonteCarlo.multiply_slice_matrix_right!(dqmc, m, slice, input)
        @test input ≈ result

        A = inv(eT * eT * eV)
        input = rand(size(A)...)
        result = A * input
        MonteCarlo.multiply_slice_matrix_inv_left!(dqmc, m, slice, input)
        @test input ≈ result
        input = rand(size(A)...)
        result = input * A
        MonteCarlo.multiply_slice_matrix_inv_right!(dqmc, m, slice, input)
        @test input ≈ result

        A = adjoint(eT * eT * eV)
        input = rand(size(A)...)
        result = A * input
        MonteCarlo.multiply_daggered_slice_matrix_left!(dqmc, m, slice, input)
        @test input ≈ result
    end

    # Checkerboard
    dqmc = DQMC(m, beta=5.0, checkerboard=true)

    for slice in rand(1:50, 2)
        MonteCarlo.interaction_matrix_exp!(dqmc, m, dqmc.field, eV, slice, 1.)

        # MonteCarlo.slice_matrix
        @test maximum(abs,
            MonteCarlo.slice_matrix(dqmc, m, slice, 1.) .- eT * eT * eV
        ) < 2dqmc.parameters.delta_tau
        @test maximum(abs,
            MonteCarlo.slice_matrix(dqmc, m, slice, -1.) .- inv(eT * eT * eV)
        ) < 2dqmc.parameters.delta_tau
        MonteCarlo.slice_matrix!(dqmc, m, slice, 1., A)
        @test maximum(abs, A .- eT * eT * eV) < 2dqmc.parameters.delta_tau
        MonteCarlo.slice_matrix!(dqmc, m, slice, -1., A)
        @test maximum(abs, A .- inv(eT * eT * eV)) < 2dqmc.parameters.delta_tau

        # MonteCarlo.multiply_slice_matrix...
        A = eT * eT * eV
        input = rand(size(A)...)
        result = A * input
        MonteCarlo.multiply_slice_matrix_left!(dqmc, m, slice, input)
        @test maximum(abs, input .- result) < 2dqmc.parameters.delta_tau
        input = rand(size(A)...)
        result = input * A
        MonteCarlo.multiply_slice_matrix_right!(dqmc, m, slice, input)
        @test maximum(abs, input .- result) < 2dqmc.parameters.delta_tau

        A = inv(eT * eT * eV)
        input = rand(size(A)...)
        result = A * input
        MonteCarlo.multiply_slice_matrix_inv_left!(dqmc, m, slice, input)
        @test maximum(abs, input .- result) < 2dqmc.parameters.delta_tau
        input = rand(size(A)...)
        result = input * A
        MonteCarlo.multiply_slice_matrix_inv_right!(dqmc, m, slice, input)
        @test maximum(abs, input .- result) < 2dqmc.parameters.delta_tau

        A = adjoint(eT * eT * eV)
        input = rand(size(A)...)
        result = A * input
        MonteCarlo.multiply_daggered_slice_matrix_left!(dqmc, m, slice, input)
        @test maximum(abs, input .- result) < 2dqmc.parameters.delta_tau
    end
end


text:
# compute the BSE in the t channel for a frequency tuple (w1, w2, w3) and a given kernel on all lattice sites
function compute_channel_t_BSE!(
    Λ      :: Float64,
    kernel :: Int64,
    w1     :: Int64,
    w2     :: Int64,
    w3     :: Int64,
    r      :: Reduced_lattice,
    m      :: Mesh,
    a1     :: Action,
    a2     :: Action,
    tbuff  :: NTuple{3, Matrix{Float64}},
    temp   :: Array{Float64, 3},
    corrs  :: Array{Float64, 3},
    eval   :: Int64,
    Γ_tol  :: NTuple{2, Float64}
    )      :: Nothing

    # reset buffer
    tbuff[1] .= 0.0

    # get frequency arguments
    t, vt, vtp = get_kernel_args(2, kernel, w1, w2, w3, m)

    # define integrand
    integrand!(b, v, dv) = compute_t_BSE!(Λ, b, v, dv, t, vt, vtp, r, m, a1, temp)

    # compute integral
    ref = Λ + 0.5 * t
    val = m.Ωt[end] + m.νt[end]
    integrate_log!((b, v, dv) -> integrand!(b, v, dv), tbuff,  2.0 * ref, 1.0 * val, eval, Γ_tol[1], Γ_tol[2], sgn = -1.0)
    integrate_lin!((b, v, dv) -> integrand!(b, v, dv), tbuff, -2.0 * ref, 0.0 * ref, eval, Γ_tol[1], Γ_tol[2])
    integrate_lin!((b, v, dv) -> integrand!(b, v, dv), tbuff,  0.0 * ref, 2.0 * ref, eval, Γ_tol[1], Γ_tol[2])
    integrate_log!((b, v, dv) -> integrand!(b, v, dv), tbuff,  2.0 * ref, 1.0 * val, eval, Γ_tol[1], Γ_tol[2])

    # correct boundaries
    integrand!(tbuff[1], -val, corrs[1, 2, w1])
    integrand!(tbuff[1],  val, corrs[2, 2, w1])

    # parse result
    for i in eachindex(a2.Γ)
        if kernel == 1
            @turbo a2.Γ[i].ch_t.q1[:, w1] .= view(tbuff[1], i, :)
        elseif kernel == 2
            @turbo a2.Γ[i].ch_t.q2_1[:, w1, w2] .= view(tbuff[1], i, :)
        elseif kernel == 3
            @turbo a2.Γ[i].ch_t.q2_2[:, w1, w3] .= view(tbuff[1], i, :)
        else
            @turbo a2.Γ[i].ch_t.q3[:, w1, w2, w3] .= view(tbuff[1], i, :)
        end
    end

    return nothing
end


text:
module Jax

using Adapt
using Requires
using LinearAlgebra

export jax, np, JaxArray, JaxNumber
export block_until_ready
export tojax

export jit, grad, vmap

include("PyUtils/PyUtils.jl")
using .PyUtils

include("Core/Core.jl")
using .Core

include("Random/random.jl")
using .Random

include("TreeUtil/TreeUtil.jl")
using .TreeUtil

include("common.jl")

include("operators.jl")
include("jaxfuncs.jl")
include("broadcast.jl")

include("scalars.jl")

include("lib/_common.jl")
include("lib/array.jl")
include("lib/base.jl")
include("lib/linalg.jl")
include("lib/mapreduce.jl")
include("lib/statistics.jl")

include("External/functors.jl")
include("External/nnlib.jl")

include("jit.jl")
include("vmap.jl")

function __init__()
    # Integration with other packages
    @require Flux = "587475ba-b771-5e3f-ad9e-33799f191a9c" begin
        include("External/flux.jl")
    end
end

# like gpu() from flux
tojax(m) = fmap(x -> adapt(JaxArray, x), m)

# adapt
struct ToArray end
Adapt.adapt_storage(::ToArray, xs::JaxArray) = convert(Array, xs)

Adapt.adapt_storage(::Type{<:JaxArray}, xs::Array) = JaxArray(xs)
Adapt.adapt_storage(::Type{<:Array}, xs::AbstractJaxArray) = convert(Array, xs)
convert_to_cpu(xs) = adapt(Array, xs)

Base.print_array(io::IO, X::JaxArray) =
    Base.print_array(io, adapt(ToArray(), X))

# show
Base._show_nonempty(io::IO, X::JaxArray, prefix::String) =
    Base._show_nonempty(io, adapt(ToArray(), X), prefix)
Base._show_empty(io::IO, X::JaxArray) =
    Base._show_empty(io, adapt(ToArray(), X))
Base.show_vector(io::IO, v::JaxArray, args...) =
    Base.show_vector(io, adapt(ToArray(), v), args...)

## collect to CPU (discarding wrapper type)

collect_to_cpu(xs::AbstractArray) = collect(adapt(ToArray(), xs))
#Base.collect(X::JaxArray) = collect_to_cpu(X)

end # module


text:
# Use
#    @warnpcfail precompile(args...)
# if you want to be warned when a precompile directive fails
macro warnpcfail(ex::Expr)
    modl = __module__
    file = __source__.file === nothing ? "?" : String(__source__.file)
    line = __source__.line
    quote
        $(esc(ex)) || @warn """precompile directive
     $($(Expr(:quote, ex)))
 failed. Please report an issue in $($modl) (after checking for duplicates) or remove this directive.""" _file=$file _line=$line
    end
end

function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
    @warnpcfail Base.precompile(Tuple{Type{replace_inds},Pair{QuIndex, QuIndex},Vararg{Pair{QuIndex, QuIndex}, N} where N})
    @warnpcfail Base.precompile(Tuple{typeof(*),Complex{Int},QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(*),Complex{Rational{Int}},QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(*),QuExpr,Int})
    @warnpcfail Base.precompile(Tuple{typeof(*),QuExpr,QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(+),Int,QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(+),QuExpr,Complex{Rational{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(+),QuExpr,Float64})
    @warnpcfail Base.precompile(Tuple{typeof(+),QuExpr,Int})
    @warnpcfail Base.precompile(Tuple{typeof(+),QuExpr,QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(+),Rational{Int},QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(-),Int,QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(-),QuExpr,Int})
    @warnpcfail Base.precompile(Tuple{typeof(==),QuExpr,QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(Avac),QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(CorrTup_isless),NTuple{4, Int},Tuple{Int, Int}})
    @warnpcfail Base.precompile(Tuple{typeof(CorrTup_isless),NTuple{6, Int},Tuple{Int, Int, Int}})
    @warnpcfail Base.precompile(Tuple{typeof(CorrTup_isless),NTuple{8, Int},NTuple{4, Int}})
    @warnpcfail Base.precompile(Tuple{typeof(_add_corrs!),QuExpr,QuTerm,Int,typeof(_add_with_normal_order!)})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,ComplexF64,ComplexF64})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,ComplexF64,Float64})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Complex{Int},Complex{Int}})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Complex{Int},Int})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Complex{Int},Rational{Int}})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Complex{Rational{Int}},Complex{Rational{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Complex{Rational{Int}},Int})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Complex{Rational{Int}},Rational{Int}})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Float64,Float64})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Int,Int})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Int,Rational{Int}})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Rational{Int},Int})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Rational{Int},Rational{Int}})
    @warnpcfail Base.precompile(Tuple{typeof(_add_sum_term!),QuExpr,QuTerm,Rational{Int}})
    @warnpcfail Base.precompile(Tuple{typeof(adjoint),QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(boson_ops),Symbol})
    @warnpcfail Base.precompile(Tuple{typeof(comm),QuExpr,QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(corr),QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(expval_as_corrs),QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(fermion_ops),Symbol})
    @warnpcfail Base.precompile(Tuple{typeof(isapprox),QuExpr,QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(isempty),QuTerm})
    @warnpcfail Base.precompile(Tuple{typeof(julia_expression),QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(julia_expression),Param,Nothing})
    @warnpcfail Base.precompile(Tuple{typeof(latex),Complex{Rational{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(latex),Float64})
    @warnpcfail Base.precompile(Tuple{typeof(latex),Int})
    @warnpcfail Base.precompile(Tuple{typeof(latex),QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(latex),QuTerm})
    @warnpcfail Base.precompile(Tuple{typeof(latex),Rational{Int}})
    @warnpcfail Base.precompile(Tuple{typeof(make_indices),Int,Int,Vararg{Any, N} where N})
    @warnpcfail Base.precompile(Tuple{typeof(make_indices),Int,Symbol,Vararg{Any, N} where N})
    @warnpcfail Base.precompile(Tuple{typeof(make_indices),Int,Symbol})
    @warnpcfail Base.precompile(Tuple{typeof(make_indices),Symbol,Int,Vararg{Any, N} where N})
    @warnpcfail Base.precompile(Tuple{typeof(make_indices),Symbol,Int})
    @warnpcfail Base.precompile(Tuple{typeof(make_indices),Symbol,String})
    @warnpcfail Base.precompile(Tuple{typeof(make_indices),Symbol,Symbol,Vararg{Any, N} where N})
    @warnpcfail Base.precompile(Tuple{typeof(normal_form),QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(param),Symbol,Char,Int,Vararg{Any, N} where N})
    @warnpcfail Base.precompile(Tuple{typeof(param),Symbol,Char,Int})
    @warnpcfail Base.precompile(Tuple{typeof(param),Symbol,Char,Symbol,Vararg{Any, N} where N})
    @warnpcfail Base.precompile(Tuple{typeof(param),Symbol,Char,Tuple{}})
    @warnpcfail Base.precompile(Tuple{typeof(param),Symbol,Char,Vector{Any}})
    @warnpcfail Base.precompile(Tuple{typeof(param),Symbol,Char,Vector{Int}})
    @warnpcfail Base.precompile(Tuple{typeof(param),Symbol,Char,Vector{Symbol}})
    @warnpcfail Base.precompile(Tuple{typeof(param),Symbol,Char})
    @warnpcfail Base.precompile(Tuple{typeof(parse_paramstr),String})
    @warnpcfail Base.precompile(Tuple{typeof(print),IOBuffer,BaseOperator})
    @warnpcfail Base.precompile(Tuple{typeof(print),IOBuffer,Corr})
    @warnpcfail Base.precompile(Tuple{typeof(print_term_scalar),IOBuffer,QuTerm,Complex{Int},Bool})
    @warnpcfail Base.precompile(Tuple{typeof(print_term_scalar),IOBuffer,QuTerm,Int,Bool})
    @warnpcfail Base.precompile(Tuple{typeof(print_term_scalar),IOBuffer,QuTerm,Rational{Int},Bool})
    @warnpcfail Base.precompile(Tuple{typeof(show),IOBuffer,MIME{Symbol("text/latex")},QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(simplify_number),Rational{Int}})
    @warnpcfail Base.precompile(Tuple{typeof(symmetric_index_nums),QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,NTuple{4, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,NTuple{4, Tuple{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,NTuple{5, Tuple{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,NTuple{6, Tuple{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,NTuple{7, Tuple{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,NTuple{8, Tuple{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,NTuple{9, Tuple{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{NTuple{4, Int}, NTuple{4, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{NTuple{4, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{NTuple{5, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{NTuple{6, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{NTuple{7, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{NTuple{8, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{NTuple{9, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int, Int, Int}, Tuple{Int, Int, Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int, Int, Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int, Int}, Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, NTuple{4, Int}, NTuple{4, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, NTuple{4, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, NTuple{5, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, NTuple{6, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, NTuple{7, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, NTuple{8, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int, Int, Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int, Int}, Tuple{Int, Int}, Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int, Int}, Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, NTuple{4, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, NTuple{5, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, NTuple{6, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, NTuple{7, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int, Int, Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int, Int}, Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, NTuple{4, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, NTuple{5, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, NTuple{6, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int, Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int}, Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, NTuple{4, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, NTuple{5, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, NTuple{4, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int}, Tuple{Int, Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}, Tuple{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}, Tuple{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(term2corr),QuTerm,Tuple{Tuple{Int}}})
    @warnpcfail Base.precompile(Tuple{typeof(use_σpm),Bool})
    @warnpcfail Base.precompile(Tuple{typeof(vacA),QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(vacExpVal),QuExpr,QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(vacExpVal),QuExpr})
    @warnpcfail Base.precompile(Tuple{typeof(∑),Symbol,QuExpr})
end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct VirtualMachineScaleSetUpdateProperties <: SwaggerModel
    upgradePolicy::Any # spec type: Union{ Nothing, UpgradePolicy } # spec name: upgradePolicy
    virtualMachineProfile::Any # spec type: Union{ Nothing, VirtualMachineScaleSetUpdateVMProfile } # spec name: virtualMachineProfile
    overprovision::Any # spec type: Union{ Nothing, Bool } # spec name: overprovision
    singlePlacementGroup::Any # spec type: Union{ Nothing, Bool } # spec name: singlePlacementGroup

    function VirtualMachineScaleSetUpdateProperties(;upgradePolicy=nothing, virtualMachineProfile=nothing, overprovision=nothing, singlePlacementGroup=nothing)
        o = new()
        validate_property(VirtualMachineScaleSetUpdateProperties, Symbol("upgradePolicy"), upgradePolicy)
        setfield!(o, Symbol("upgradePolicy"), upgradePolicy)
        validate_property(VirtualMachineScaleSetUpdateProperties, Symbol("virtualMachineProfile"), virtualMachineProfile)
        setfield!(o, Symbol("virtualMachineProfile"), virtualMachineProfile)
        validate_property(VirtualMachineScaleSetUpdateProperties, Symbol("overprovision"), overprovision)
        setfield!(o, Symbol("overprovision"), overprovision)
        validate_property(VirtualMachineScaleSetUpdateProperties, Symbol("singlePlacementGroup"), singlePlacementGroup)
        setfield!(o, Symbol("singlePlacementGroup"), singlePlacementGroup)
        o
    end
end # type VirtualMachineScaleSetUpdateProperties

const _property_map_VirtualMachineScaleSetUpdateProperties = Dict{Symbol,Symbol}(Symbol("upgradePolicy")=>Symbol("upgradePolicy"), Symbol("virtualMachineProfile")=>Symbol("virtualMachineProfile"), Symbol("overprovision")=>Symbol("overprovision"), Symbol("singlePlacementGroup")=>Symbol("singlePlacementGroup"))
const _property_types_VirtualMachineScaleSetUpdateProperties = Dict{Symbol,String}(Symbol("upgradePolicy")=>"UpgradePolicy", Symbol("virtualMachineProfile")=>"VirtualMachineScaleSetUpdateVMProfile", Symbol("overprovision")=>"Bool", Symbol("singlePlacementGroup")=>"Bool")
Base.propertynames(::Type{ VirtualMachineScaleSetUpdateProperties }) = collect(keys(_property_map_VirtualMachineScaleSetUpdateProperties))
Swagger.property_type(::Type{ VirtualMachineScaleSetUpdateProperties }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_VirtualMachineScaleSetUpdateProperties[name]))}
Swagger.field_name(::Type{ VirtualMachineScaleSetUpdateProperties }, property_name::Symbol) =  _property_map_VirtualMachineScaleSetUpdateProperties[property_name]

function check_required(o::VirtualMachineScaleSetUpdateProperties)
    true
end

function validate_property(::Type{ VirtualMachineScaleSetUpdateProperties }, name::Symbol, val)
end


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

name = "MiniFB"
version = v"0.1.1"

# Collection of sources required to complete build
sources = [
    GitSource("https://github.com/emoon/minifb.git", "dda1275bd741752d1b7cdc1ee4d9941887a1891a") #master as of 10Sep2020
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/minifb/
sed -i -e 's/add_library(minifb STATIC/add_library(minifb SHARED/' \
    -e 's/ -Wall/-I$ENV{includedir} -Wall/' \
    CMakeLists.txt
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
    -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
    -DCMAKE_BUILD_TYPE=Release \
    -DMINIFB_BUILD_EXAMPLES=OFF \
    ..
make -j${nproc}
mv libminifb* ${libdir}
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()

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

# Dependencies that must be installed before this package can be built
dependencies = [
    Dependency(PackageSpec(name="Xorg_libX11_jll", uuid="4f6342f7-b3d2-589e-9d20-edeb45f2b2bc"))
    BuildDependency(PackageSpec(name="Xorg_xorgproto_jll", uuid="c4d99508-4286-5418-9131-c86396af500b"))
]

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

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
"""
    is_leap_year(year)

Return `true` if `year` is a leap year in the gregorian calendar.
    on every year that is evenly divisible by 4
    except every year that is evenly divisible by 100
      unless the year is also evenly divisible by 400
"""
function is_leap_year(year)
    if year % 4 == 0 && year % 100 != 0
		return true
	elseif year % 4 == 0 && year % 400 == 0
        return true
	else
		return false
    end

end

max_stars_repo_name: tamireinhorn/exercism

max_issues_repo_name: tamireinhorn/exercism

max_forks_repo_name: tamireinhorn/Exercism


text:
"""
`SolutionODE`: Solution of an ordinary differential equation

Contains all fields necessary to store the solution of an ODE.

### Fields

* `nd`: dimension of the dynamical variable ``q``
* `nt`: number of time steps to store
* `ni`: number of initial conditions
* `t`:  time steps
* `q`:  solution `q[nd, nt+1, ni]` with `q[:,0,:]` the initial conditions
* `ntime`: number of time steps to compute
* `nsave`: store every nsave'th time step (default: 1)
* `nwrite`: save data to disk after every nwrite'th time step (default: ntime)
* `offset`: counter for file offset
* `counter`: counter for copied solution entries

### Constructors

```julia
SolutionODE(equation, Δt, ntimesteps; nsave=DEFAULT_NSAVE, nwrite=DEFAULT_NWRITE, filename=nothing)
SolutionODE(t::TimeSeries, q::DataSeries, ntimesteps)
SolutionODE(h5io::SolutionHDF5)
SolutionODE(file::String)
```

The usual way to initialise a `Solution` is by passing an equation, which for
`SolutionODE` has to be an [`ODE`](@ref) or [`SODE`](@ref), a time step `Δt`
and the number of time steps `ntimesteps`. The optional parameters `nsave` and
`nwrite` determine the intervals for storing the solution and writing to file,
i.e., if `nsave > 1` only every `nsave`'th solution is actually stored, and
every `nwrite`'th time step the solution is stored to disk.

The other constructors, either passing a `TimeSeries` and a `DataSeries` or a
filename are used to read data from previous simulations.

"""
mutable struct SolutionODE{dType,tType,N} <: DeterministicSolution{dType,tType,N}
    nd::Int
    nt::Int
    ni::Int
    t::TimeSeries{tType}
    q::DataSeries{dType,N}
    ntime::Int
    nsave::Int
    nwrite::Int
    offset::Int
    counter::Vector{Int}
    periodicity::dType

    function SolutionODE{dType,tType,N}(nd, nt, ni, t, q, ntime, nsave, nwrite, periodicity = zero(q[begin])) where {dType<:Union{Number,AbstractArray},tType<:Real,N}
        new(nd, nt, ni, t, q, ntime, nsave, nwrite, 0, zeros(Int, ni), periodicity)
    end
end

function SolutionODE(equation::Union{ODE{DT,TT1,AT},SODE{DT,TT1,AT}}, Δt::TT2, ntimesteps::Int;
    nsave::Int = DEFAULT_NSAVE, nwrite::Int = DEFAULT_NWRITE) where {DT,TT1,TT2,AT}
    @assert nsave > 0
    @assert ntimesteps == 0 || ntimesteps ≥ nsave
    @assert nwrite == 0 || nwrite ≥ nsave
    @assert mod(ntimesteps, nsave) == 0

    if nwrite > 0
        @assert mod(nwrite, nsave) == 0
        @assert mod(ntimesteps, nwrite) == 0
    end

    TT = promote_type(TT1, TT2)
    N = nsamples(equation) > 1 ? 2 : 1
    nd = ndims(equation)
    ni = nsamples(equation)
    nt = div(ntimesteps, nsave)
    nt = (nwrite == 0 ? nt : div(nwrite, nsave))
    nw = (nwrite == 0 ? ntimesteps : nwrite)

    @assert nd > 0
    @assert ni > 0
    @assert nt ≥ 0
    @assert nw ≥ 0

    t = TimeSeries{TT}(nt, Δt, nsave)
    q = DataSeries(equation.q₀, nt, ni)
    s = SolutionODE{AT,TT,N}(nd, nt, ni, t, q, ntimesteps, nsave, nw, periodicity(equation))
    set_initial_conditions!(s, equation)

    return s
end

function SolutionODE(t::TimeSeries{TT}, q::DataSeries{DT,N}, ntimesteps::Int) where {DT,TT,N}
    # extract parameters
    nd = length(q[begin])
    ni = nsamples(q)
    nt = t.n
    ns = div(ntimesteps, nt)

    @assert mod(ntimesteps, nt) == 0

    # create solution
    SolutionODE{DT,TT,N}(nd, nt, ni, t, q, ntimesteps, ns, 0)
end

function SolutionODE(h5io::SolutionHDF5)
    # get hdf5 file descriptor
    h5 = hdf5(h5io)

    # read attributes
    ntimesteps = read(attributes(h5)["ntime"])
    nsave = read(attributes(h5)["nsave"])
    nsamples = read(attributes(h5)["nsamples"])

    # reading data arrays
    t = TimeSeries(read(h5["t"]), nsave)
    q = fromarray(DataSeries, read(h5["q"]), nsamples)

    # create solution
    SolutionODE(t, q, ntimesteps)
end

function SolutionODE(file::String)
    load(file) do h5io
        SolutionODE(h5io::SolutionHDF5)
    end
end

Base.:(==)(sol1::SolutionODE{DT1,TT1,N1}, sol2::SolutionODE{DT2,TT2,N2}) where {DT1,TT1,N1,DT2,TT2,N2} = (
    DT1 == DT2
    && TT1 == TT2
    && N1 == N2
    && sol1.nd == sol2.nd
    && sol1.nt == sol2.nt
    && sol1.ni == sol2.ni
    && sol1.t == sol2.t
    && sol1.q == sol2.q
    && sol1.ntime == sol2.ntime
    && sol1.nsave == sol2.nsave
    && sol1.nwrite == sol2.nwrite
    && sol1.offset == sol2.offset
    && sol1.counter == sol2.counter
    && sol1.periodicity == sol2.periodicity)

@inline GeometricBase.counter(sol::SolutionODE) = sol.counter
@inline GeometricBase.offset(sol::SolutionODE) = sol.offset
@inline GeometricBase.lastentry(sol::SolutionODE) = sol.ni == 1 ? sol.counter[1] - 1 : sol.counter .- 1
@inline GeometricBase.nsamples(sol::SolutionODE) = sol.ni
@inline GeometricBase.nsave(sol::SolutionODE) = sol.nsave
@inline GeometricBase.ntime(sol::SolutionODE) = sol.ntime
@inline GeometricBase.timesteps(sol::SolutionODE) = sol.t
@inline GeometricBase.eachtimestep(sol::SolutionODE) = 1:sol.nt*sol.nsave
@inline GeometricBase.periodicity(sol::SolutionODE) = sol.periodicity

function set_initial_conditions!(sol::SolutionODE, equ::Union{ODE,SODE})
    set_initial_conditions!(sol, equ.t₀, equ.q₀)
end

function set_initial_conditions!(sol::SolutionODE{DT}, t₀::Real, q₀) where {DT}
    set_data!(sol.q, q₀, 0)
    compute_timeseries!(sol.t, t₀)
    sol.counter .= 1
end

function set_initial_conditions!(sol::SolutionODE{DT}, t₀::Real, q₀::AbstractVector{DT}) where {DT}
    for i in eachindex(q₀)
        set_data!(sol.q, q₀[i], 0, i)
    end
    compute_timeseries!(sol.t, t₀)
    sol.counter .= 1
end

function get_initial_conditions!(sol::SolutionODE{AT,TT}, asol::AtomicSolutionODE{DT,TT,AT}, k, n = 1) where {DT,TT,AT<:AbstractArray{DT}}
    get_solution!(sol, asol.q, n - 1, k)
    asol.t = sol.t[n-1]
    asol.q̃ .= 0
end

function get_initial_conditions!(sol::SolutionODE{DT}, q::DT, k, n = 1) where {DT}
    get_solution!(sol, q, n - 1, k)
end

function get_initial_conditions(sol::SolutionODE, k, n = 1)
    get_solution(sol, n - 1, k)
end

function set_solution!(sol::SolutionODE, t, q, n, k = 1)
    set_solution!(sol, q, n, k)
end

function set_solution!(sol::SolutionODE{AT,TT}, asol::AtomicSolutionODE{DT,TT,AT}, n, k = 1) where {DT,TT,AT<:AbstractArray{DT}}
    set_solution!(sol, asol.t, asol.q, n, k)
end

function set_solution!(sol::SolutionODE{AT}, q::AT, n, k = 1) where {AT}
    @assert n <= sol.ntime
    @assert k <= sol.ni
    if mod(n, sol.nsave) == 0
        if sol.counter[k] > sol.nt
            @error("Solution overflow. Call write_to_hdf5() and reset!() before continuing the simulation.")
        end
        set_data!(sol.q, q, sol.counter[k], k)
        sol.counter[k] += 1
    end
end

function get_solution!(sol::SolutionODE{AT}, q::AT, n, k = 1) where {AT}
    get_data!(sol.q, q, n, k)
end

function get_solution(sol::SolutionODE{AT,TT,1}, n, k = 1) where {AT,TT}
    @assert k == 1
    (sol.t[n], sol.q[n])
end

function get_solution(sol::SolutionODE{AT,TT,2}, n, k = 1) where {AT,TT}
    (sol.t[n], sol.q[n, k])
end

function GeometricBase.reset!(sol::SolutionODE)
    reset!(sol.q)
    compute_timeseries!(sol.t, sol.t[end])
    sol.counter .= 1
    sol.offset += sol.nt
end

function Base.close(solution::SolutionODE)
    close(solution.h5)
end


text:
#!/usr/bin/env julia

inp = ARGS[1] # example input /proj/tay6575/tcga_gbm/filtered_vcf/vep/chrY.ncv
lines = readlines(open(inp))

types = []
for ln in lines
	cols  = split(ln, "|")
	if ismatch(r"&", cols[2])
		names = split(cols[2], "\&")
		append!(types, names)
	else
		push!(types, cols[2])
	end
end

list = []

for name in (types)
	push!(list, chomp(name))
end
typecounts = Dict{ASCIIString,Int64}()

for word in list
	typecounts[word]=get(typecounts, word, 0) + 1
end

for ln in unique(list)
	println("$ln", "\t", typecounts["$ln"])
end


text:
function interior_dGx_pos(loc_globaldata, loc_ghost_holder, dist_length, idx, gamma, phi_i, phi_k, G_i, G_k, result, qtilde_i, qtilde_k, ∑_Δx_Δf, ∑_Δy_Δf, power, limiter_flag, vl_const, Gxp)

    ∑_Δx_sqr = zero(Float64)
    ∑_Δy_sqr = zero(Float64)
    ∑_Δx_Δy = zero(Float64)

    fill!(∑_Δx_Δf, zero(Float64))
    fill!(∑_Δy_Δf, zero(Float64))

    x_i = loc_globaldata[idx].x
    y_i = loc_globaldata[idx].y

    nx = loc_globaldata[idx].nx
    ny = loc_globaldata[idx].ny

    tx = ny
    ty = -nx

    for itm in loc_globaldata[idx].xpos_conn
        if itm <= dist_length
            globaldata_itm = loc_globaldata[itm]
        else
            globaldata_itm = loc_ghost_holder[1][itm]
        end
        x_k = globaldata_itm.x
        y_k = globaldata_itm.y

        delx = x_k - x_i
        dely = y_k - y_i

        dels = delx*tx + dely*ty
        deln = delx*nx + dely*ny

        dist = hypot(dels, deln)
        weights = dist^power

        dels_weights = dels*weights
        deln_weights = deln*weights

        ∑_Δx_sqr = ∑_Δx_sqr + dels*dels_weights
        ∑_Δy_sqr = ∑_Δy_sqr + deln*deln_weights

        ∑_Δx_Δy = ∑_Δx_Δy + dels*deln_weights

        for i in 1:4
            qtilde_i[i] = (loc_globaldata[idx].q[i]) - 0.5 * (delx*(loc_globaldata[idx].dq1[i]) + dely*(loc_globaldata[idx].dq2[i]))
            qtilde_k[i] = (globaldata_itm.q[i]) - 0.5 * (delx*(globaldata_itm.dq1[i]) + dely*(globaldata_itm.dq2[i]))
        end

        if limiter_flag == 1
            venkat_limiter(qtilde_i, loc_globaldata[idx], vl_const, phi_i)
            venkat_limiter(qtilde_k, globaldata_itm, vl_const, phi_k)
            for i in 1:4
                qtilde_i[i] = (loc_globaldata[idx].q[i]) - 0.5 * phi_i[i] * (delx*(loc_globaldata[idx].dq1[i]) + dely*(loc_globaldata[idx].dq2[i]))
                qtilde_k[i] = (globaldata_itm.q[i]) - 0.5 * phi_k[i] * (delx*(globaldata_itm.dq1[i]) + dely*(globaldata_itm.dq2[i]))
            end
        end

        qtilde_to_primitive(result, qtilde_i, gamma)
        flux_Gxp(G_i, nx, ny, result[1], result[2], result[3], result[4])

        qtilde_to_primitive(result, qtilde_k, gamma)
        flux_Gxp(G_k, nx, ny, result[1], result[2], result[3], result[4])

        for i in 1:4
            ∑_Δx_Δf[i] += (G_k[i] - G_i[i]) * dels_weights
            ∑_Δy_Δf[i] += (G_k[i] - G_i[i]) * deln_weights
        end
    end
    det = ∑_Δx_sqr*∑_Δy_sqr - ∑_Δx_Δy*∑_Δx_Δy
    one_by_det = one(Float64) / det
    for iter in 1:4
        Gxp[iter] = (∑_Δx_Δf[iter]*∑_Δy_sqr - ∑_Δy_Δf[iter]*∑_Δx_Δy)*one_by_det
    end
    return nothing
end

function interior_dGx_neg(loc_globaldata, loc_ghost_holder, dist_length, idx, gamma, phi_i, phi_k, G_i, G_k, result, qtilde_i, qtilde_k, ∑_Δx_Δf, ∑_Δy_Δf, power, limiter_flag, vl_const, Gxn)

    ∑_Δx_sqr = zero(Float64)
    ∑_Δy_sqr = zero(Float64)
    ∑_Δx_Δy = zero(Float64)

    fill!(∑_Δx_Δf, zero(Float64))
    fill!(∑_Δy_Δf, zero(Float64))

    x_i = loc_globaldata[idx].x
    y_i = loc_globaldata[idx].y

    nx = loc_globaldata[idx].nx
    ny = loc_globaldata[idx].ny

    tx = ny
    ty = -nx

    for itm in loc_globaldata[idx].xneg_conn

        if itm <= dist_length
            globaldata_itm = loc_globaldata[itm]
        else
            globaldata_itm = loc_ghost_holder[1][itm]
        end
        x_k = globaldata_itm.x
        y_k = globaldata_itm.y

        delx = x_k - x_i
        dely = y_k - y_i

        dels = delx*tx + dely*ty
        deln = delx*nx + dely*ny

        dist = hypot(dels, deln)
        weights = dist^power

        dels_weights = dels*weights
        deln_weights = deln*weights

        ∑_Δx_sqr = ∑_Δx_sqr + dels*dels_weights
        ∑_Δy_sqr = ∑_Δy_sqr + deln*deln_weights

        ∑_Δx_Δy = ∑_Δx_Δy + dels*deln_weights

        for i in 1:4
            qtilde_i[i] = (loc_globaldata[idx].q[i]) - 0.5 * (delx*(loc_globaldata[idx].dq1[i]) + dely*(loc_globaldata[idx].dq2[i]))
            qtilde_k[i] = (globaldata_itm.q[i]) - 0.5 * (delx*(globaldata_itm.dq1[i]) + dely*(globaldata_itm.dq2[i]))
        end

        if limiter_flag == 1
            venkat_limiter(qtilde_i, loc_globaldata[idx], vl_const, phi_i)
            venkat_limiter(qtilde_k, globaldata_itm, vl_const, phi_k)
            for i in 1:4
                qtilde_i[i] = (loc_globaldata[idx].q[i]) - 0.5 * phi_i[i] * (delx*(loc_globaldata[idx].dq1[i]) + dely*(loc_globaldata[idx].dq2[i]))
                qtilde_k[i] = (globaldata_itm.q[i]) - 0.5 * phi_k[i] * (delx*(globaldata_itm.dq1[i]) + dely*(globaldata_itm.dq2[i]))
            end
        end

        qtilde_to_primitive(result, qtilde_i, gamma)
        flux_Gxn(G_i, nx, ny, result[1], result[2], result[3], result[4])

        qtilde_to_primitive(result, qtilde_k, gamma)
        flux_Gxn(G_k, nx, ny, result[1], result[2], result[3], result[4])

        for i in 1:4
            ∑_Δx_Δf[i] += (G_k[i] - G_i[i]) * dels_weights
            ∑_Δy_Δf[i] += (G_k[i] - G_i[i]) * deln_weights
        end
    end
    det = ∑_Δx_sqr*∑_Δy_sqr - ∑_Δx_Δy*∑_Δx_Δy
    one_by_det = one(Float64) / det

    for iter in 1:4
        Gxn[iter] = (∑_Δx_Δf[iter] *∑_Δy_sqr - ∑_Δy_Δf[iter] *∑_Δx_Δy)*one_by_det
    end
    return nothing
end

function interior_dGy_pos(loc_globaldata, loc_ghost_holder, dist_length, idx, gamma, phi_i, phi_k, G_i, G_k, result, qtilde_i, qtilde_k, ∑_Δx_Δf, ∑_Δy_Δf, power, limiter_flag, vl_const, Gyp)

    ∑_Δx_sqr = zero(Float64)
    ∑_Δy_sqr = zero(Float64)
    ∑_Δx_Δy = zero(Float64)

    fill!(∑_Δx_Δf, zero(Float64))
    fill!(∑_Δy_Δf, zero(Float64))

    x_i = loc_globaldata[idx].x
    y_i = loc_globaldata[idx].y

    nx = loc_globaldata[idx].nx
    ny = loc_globaldata[idx].ny

    tx = ny
    ty = -nx

    for itm in loc_globaldata[idx].ypos_conn

        if itm <= dist_length
            globaldata_itm = loc_globaldata[itm]
        else
            globaldata_itm = loc_ghost_holder[1][itm]
        end
        x_k = globaldata_itm.x
        y_k = globaldata_itm.y

        delx = x_k - x_i
        dely = y_k - y_i

        dels = delx*tx + dely*ty
        deln = delx*nx + dely*ny

        dist = hypot(dels, deln)
        weights = dist^power

        dels_weights = dels*weights
        deln_weights = deln*weights

        ∑_Δx_sqr = ∑_Δx_sqr + dels*dels_weights
        ∑_Δy_sqr = ∑_Δy_sqr + deln*deln_weights

        ∑_Δx_Δy = ∑_Δx_Δy + dels*deln_weights

        for i in 1:4
            qtilde_i[i] = (loc_globaldata[idx].q[i]) - 0.5 * (delx*(loc_globaldata[idx].dq1[i]) + dely*(loc_globaldata[idx].dq2[i]))
            qtilde_k[i] = (globaldata_itm.q[i]) - 0.5 * (delx*(globaldata_itm.dq1[i]) + dely*(globaldata_itm.dq2[i]))
        end

        if limiter_flag == 1
            venkat_limiter(qtilde_i, loc_globaldata[idx], vl_const, phi_i)
            venkat_limiter(qtilde_k, globaldata_itm, vl_const, phi_k)
            for i in 1:4
                qtilde_i[i] = (loc_globaldata[idx].q[i]) - 0.5 * phi_i[i] * (delx*(loc_globaldata[idx].dq1[i]) + dely*(loc_globaldata[idx].dq2[i]))
                qtilde_k[i] = (globaldata_itm.q[i]) - 0.5 * phi_k[i] * (delx*(globaldata_itm.dq1[i]) + dely*(globaldata_itm.dq2[i]))
            end
        end

        qtilde_to_primitive(result, qtilde_i, gamma)
        flux_Gyp(G_i,nx, ny, result[1], result[2], result[3], result[4])

        qtilde_to_primitive(result, qtilde_k, gamma)
        flux_Gyp(G_k, nx, ny, result[1], result[2], result[3], result[4])

        for i in 1:4
            ∑_Δx_Δf[i] += (G_k[i] - G_i[i]) * dels_weights
            ∑_Δy_Δf[i] += (G_k[i] - G_i[i]) * deln_weights
        end

    end
    det = ∑_Δx_sqr*∑_Δy_sqr - ∑_Δx_Δy*∑_Δx_Δy
    one_by_det = one(Float64) / det
    for iter in 1:4
        Gyp[iter] = (∑_Δy_Δf[iter] *∑_Δx_sqr - ∑_Δx_Δf[iter] *∑_Δx_Δy)*one_by_det
    end
    return nothing

end

function interior_dGy_neg(loc_globaldata, loc_ghost_holder, dist_length, idx, gamma, phi_i, phi_k, G_i, G_k, result, qtilde_i, qtilde_k, ∑_Δx_Δf, ∑_Δy_Δf, power, limiter_flag, vl_const, Gyn)

    ∑_Δx_sqr = zero(Float64)
    ∑_Δy_sqr = zero(Float64)
    ∑_Δx_Δy = zero(Float64)

    fill!(∑_Δx_Δf, zero(Float64))
    fill!(∑_Δy_Δf, zero(Float64))

    x_i = loc_globaldata[idx].x
    y_i = loc_globaldata[idx].y

    nx = loc_globaldata[idx].nx
    ny = loc_globaldata[idx].ny

    tx = ny
    ty = -nx

    for itm in loc_globaldata[idx].yneg_conn

        if itm <= dist_length
            globaldata_itm = loc_globaldata[itm]
        else
            globaldata_itm = loc_ghost_holder[1][itm]
        end
        x_k = globaldata_itm.x
        y_k = globaldata_itm.y

        delx = x_k - x_i
        dely = y_k - y_i

        dels = delx*tx + dely*ty
        deln = delx*nx + dely*ny

        dist = hypot(dels, deln)
        weights = dist^power

        dels_weights = dels*weights
        deln_weights = deln*weights

        ∑_Δx_sqr = ∑_Δx_sqr + dels*dels_weights
        ∑_Δy_sqr = ∑_Δy_sqr + deln*deln_weights

        ∑_Δx_Δy = ∑_Δx_Δy + dels*deln_weights

        for i in 1:4
            qtilde_i[i] = (loc_globaldata[idx].q[i]) - 0.5 * (delx*(loc_globaldata[idx].dq1[i]) + dely*(loc_globaldata[idx].dq2[i]))
            qtilde_k[i] = (globaldata_itm.q[i]) - 0.5 * (delx*(globaldata_itm.dq1[i]) + dely*(globaldata_itm.dq2[i]))
        end

        if limiter_flag == 1
            venkat_limiter(qtilde_i, loc_globaldata[idx], vl_const, phi_i)
            venkat_limiter(qtilde_k, globaldata_itm, vl_const, phi_k)
            for i in 1:4
                qtilde_i[i] = (loc_globaldata[idx].q[i]) - 0.5 * phi_i[i] * (delx*(loc_globaldata[idx].dq1[i]) + dely*(loc_globaldata[idx].dq2[i]))
                qtilde_k[i] = (globaldata_itm.q[i]) - 0.5 * phi_k[i] * (delx*(globaldata_itm.dq1[i]) + dely*(globaldata_itm.dq2[i]))
            end
        end

        qtilde_to_primitive(result, qtilde_i, gamma)
        flux_Gyn(G_i, nx, ny, result[1], result[2], result[3], result[4])

        qtilde_to_primitive(result, qtilde_k, gamma)
        flux_Gyn(G_k, nx, ny, result[1], result[2], result[3], result[4])

        for i in 1:4
            ∑_Δx_Δf[i] += (G_k[i] - G_i[i]) * dels_weights
            ∑_Δy_Δf[i] += (G_k[i] - G_i[i]) * deln_weights
        end

    end
    det = ∑_Δx_sqr*∑_Δy_sqr - ∑_Δx_Δy*∑_Δx_Δy
    one_by_det = one(Float64) / det
    for iter in 1:4
        Gyn[iter] = (∑_Δy_Δf[iter]*∑_Δx_sqr - ∑_Δx_Δf[iter]*∑_Δx_Δy)*one_by_det
    end
    return nothing
end

max_stars_repo_name: TestSubjector/HybridMeshfreeSolver

max_issues_repo_name: TestSubjector/HybridMeshfreeSolver

max_forks_repo_name: TestSubjector/HybridMeshfreeSolver


text:
using JuMP
using DisjunctiveProgramming

m = Model()
@variable(m, -1<=x<=10)

@constraint(m, con1, x<=3)
@constraint(m, con2, 0<=x)
@constraint(m, con3, x<=9)
@constraint(m, con4, 5<=x)

M = 10
@disjunction(m,(con1,con2),con3,con4,
                reformulation=:BMR,M=M)


text:
using Distributions
export get_informed_insertion_dist

function get_informed_insertion_dist(
    posterior::Union{SisPosterior,SimPosterior},
    α::Float64
    )
    data = posterior.data
    V = posterior.V
    p = zeros(length(V))
    for S in data
        p .+= [i ∈ vcat(S...) for i in V]
    end
    p ./= sum(p)
    p .+= α
    p ./= sum(p)
    return Categorical(p)
end


text:
using Documenter, ProximalOperators

makedocs(
    modules = [ProximalOperators],
    sitename = "ProximalOperators.jl",
    pages = [
        "Home" => "index.md",
        "Functions" => "functions.md",
        "Calculus rules" => "calculus.md",
        "Prox and gradient" => "operators.md",
        "Demos" => "demos.md"
    ],
)

deploydocs(
    repo   = "github.com/JuliaFirstOrder/ProximalOperators.jl.git",
)


text:
module PlutoPkgTestD

import Pkg

include_dependency("../Project.toml")

project_relative_path(xs...) = normpath(joinpath(dirname(dirname(pathof(@__MODULE__))), xs...))
p = Pkg.TOML.parsefile(project_relative_path("Project.toml"))

const MY_VERSION = VersionNumber(p["version"])
const MY_NAME = p["name"]

end # module


text:
module Faulhaber

using LinearAlgebra

"""
    faulhaber(m, ::Val{p})

Compute the summation `sum(i->i^p, 1:m)` in ``O(p)`` time. When `m` is an
integer, the function returns an exact integer solution assuming integer
overflows don't occur. When `m` is a floating-point number, then it returns a
less accurate float solution.

Examples:
```julia
julia> using BenchmarkTools, Faulhaber

julia> @btime faulhaber(Ref(Int128(2000))[], Val(7))
  1.143 ns (0 allocations: 0 bytes)
32064037333328666667000000

julia> @btime sum(i->i^7, 1:Int128(2000))
  12.282 μs (0 allocations: 0 bytes)
32064037333328666667000000

julia> @btime faulhaber(Ref(2000.0)[], Val(7))
  1.134 ns (0 allocations: 0 bytes)
3.2064037333328662e25
```
"""
@generated function faulhaber(m, ::Val{p}) where p
    p >= 0 || throw(ArgumentError("The exponent must be non-negative! Got $p."))
    T = m
    IT = typeof(Integer(zero(m)))
    k = p + 1
    A = LowerTriangular(Rational{IT}[m > n ? zero(IT) : (-1)^(m+n) * binomial(IT(n), IT(m)-1)  for n in 1:k, m in 1:k])
    cc = A' \ [i==k for i in 1:k]
    zz = zero(T)
    if m <: Integer
        factor = lcm(denominator.(cc)...)
        coeffs = T.(factor * cc)
        :(@evalpoly(m, $zz, $(coeffs...)) ÷ $factor)
    else
        coeffs = T.(cc)
        :(@evalpoly(m, $zz, $(coeffs...)))
    end
end

export faulhaber

end


text:
using ClimaCore.Geometry: ⊗

function vertical_diffusion_boundary_layer_coupled_tendency!(Yₜ, Y, p, t)
    ᶜρ = Y.c.ρ
    (; ᶜp, ᶠv_a, ᶠz_a, ᶠK_E) = p # assume ᶜts and ᶜp have been updated
    (; dif_flux_energy, dif_flux_ρq_tot, dif_flux_uₕ) = p
    ᶠgradᵥ = Operators.GradientC2F() # apply BCs to ᶜdivᵥ, which wraps ᶠgradᵥ

    Fields.field_values(ᶠv_a) .= Fields.field_values(Spaces.level(Y.c.uₕ, 1)) .* one.(Fields.field_values(ᶠz_a)) # TODO: fix VIJFH copyto! to remove this
    @. ᶠK_E = eddy_diffusivity_coefficient(norm(ᶠv_a), ᶠz_a, ᶠinterp(ᶜp)) #* FT(0)

    # Total Energy
    if :ρe in propertynames(Y.c)
        ᶜdivᵥ = Operators.DivergenceF2C(
            top = Operators.SetValue(Geometry.WVector(FT(0))),
            bottom = Operators.SetValue(.-dif_flux_energy),
        )
        @. Yₜ.c.ρe += ᶜdivᵥ(ᶠK_E * ᶠinterp(ᶜρ) * ᶠgradᵥ((Y.c.ρe + ᶜp) / ᶜρ))
    end

    # Liquid Mass and Total Mass
    if :ρq_tot in propertynames(Y.c)
        ᶜdivᵥ = Operators.DivergenceF2C(
            top = Operators.SetValue(Geometry.WVector(FT(0))),
            bottom = Operators.SetValue(.-dif_flux_ρq_tot),
        )
        @. Yₜ.c.ρq_tot += ᶜdivᵥ(ᶠK_E * ᶠinterp(ᶜρ) * ᶠgradᵥ(Y.c.ρq_tot / ᶜρ))
        @. Yₜ.c.ρ += ᶜdivᵥ(ᶠK_E * ᶠinterp(ᶜρ) * ᶠgradᵥ(Y.c.ρq_tot / ᶜρ))
    end

    # Momentum
    if :uₕ in propertynames(Y.c)
        ᶜdivᵥ = Operators.DivergenceF2C(
            top = Operators.SetValue(Geometry.Contravariant3Vector(FT(0)) ⊗ Geometry.Covariant12Vector(FT(0), FT(0))),
            bottom = Operators.SetValue(.-dif_flux_uₕ),
        )

        @. Yₜ.c.uₕ += ᶜdivᵥ(ᶠK_E * ᶠgradᵥ(Y.c.uₕ))
    end

end

function vertical_diffusion_boundary_layer_coupled_cache(Y; Cd = FT(0.0044), Ch = FT(0.0044))
    ᶠz_a = similar(Y.f, FT)
    z_bottom = Spaces.level(Fields.coordinate_field(Y.c).z, 1)
    Fields.field_values(ᶠz_a) .= Fields.field_values(z_bottom) .* one.(Fields.field_values(ᶠz_a))
    # TODO: fix VIJFH copyto! to remove the one.(...)

    if :ρq_tot in propertynames(Y.c)
        dif_flux_ρq_tot = similar(z_bottom, Geometry.WVector{FT})
    else
        dif_flux_ρq_tot = Ref(Geometry.WVector(FT(0)))
    end

    #dif_flux_uₕ = similar(z_bottom, Geometry.Contravariant3Vector{FT}) .⊗ similar(z_bottom, Geometry.Covariant12Vector{FT}) # this breaks
    dif_flux_uₕ =
        Geometry.Contravariant3Vector.(zeros(axes(z_bottom))) .⊗
        Geometry.Covariant12Vector.(zeros(axes(z_bottom)), zeros(axes(z_bottom)))

    if (:ρq_liq in propertynames(Y.c) && :ρq_ice in propertynames(Y.c) && :ρq_tot in propertynames(Y.c))
        ts_type = TD.PhaseNonEquil{FT}
    elseif :ρq_tot in propertynames(Y.c)
        ts_type = TD.PhaseEquil{FT}
    else
        ts_type = TD.PhaseDry{FT}
    end
    coef_type = SF.Coefficients{
        FT,
        SF.InteriorValues{FT, Tuple{FT, FT}, ts_type},
        SF.SurfaceValues{FT, Tuple{FT, FT}, TD.PhaseEquil{FT}},
    }

    return (;
        ᶠv_a = similar(Y.f, eltype(Y.c.uₕ)),
        ᶠz_a,
        ᶠK_E = similar(Y.f, FT),
        flux_coefficients = similar(z_bottom, coef_type),
        dif_flux_energy = similar(z_bottom, Geometry.WVector{FT}),
        dif_flux_ρq_tot,
        dif_flux_uₕ,
        Cd,
        Ch,
    )
end

# TODO: flip order so that NamedTuple() is fallback.
additional_cache(Y, params, dt; use_tempest_mode = false) = merge(
    hyperdiffusion_cache(Y; κ₄ = FT(2e17), use_tempest_mode),
    sponge ? rayleigh_sponge_cache(Y, dt) : NamedTuple(),
    isnothing(microphy) ? NamedTuple() : zero_moment_microphysics_cache(Y),
    isnothing(forcing) ? NamedTuple() : held_suarez_cache(Y),
    isnothing(rad) ? NamedTuple() : rrtmgp_model_cache(Y, params; radiation_mode, idealized_h2o),
    vert_diff ? vertical_diffusion_boundary_layer_coupled_cache(Y) : NamedTuple(),
    (;
        tendency_knobs = (;
            hs_forcing = forcing == "held_suarez",
            microphy_0M = microphy == "0M",
            rad_flux = !isnothing(rad),
            vert_diff,
            hyperdiff,
        )
    ),
)

additional_tendency!(Yₜ, Y, p, t) = begin
    (; rad_flux, vert_diff, hs_forcing) = p.tendency_knobs
    (; microphy_0M, hyperdiff) = p.tendency_knobs
    hyperdiff && hyperdiffusion_tendency!(Yₜ, Y, p, t)
    sponge && rayleigh_sponge_tendency!(Yₜ, Y, p, t)
    hs_forcing && held_suarez_tendency!(Yₜ, Y, p, t)
    vert_diff && vertical_diffusion_boundary_layer_coupled_tendency!(Yₜ, Y, p, t)
    microphy_0M && zero_moment_microphysics_tendency!(Yₜ, Y, p, t)
    rad_flux && rrtmgp_model_tendency!(Yₜ, Y, p, t)
end

parsed_args["microphy"] = nothing
parsed_args["forcing"] = nothing
parsed_args["idealized_h2o"] = false
parsed_args["vert_diff"] = true
parsed_args["rad"] = nothing
parsed_args["hyperdiff"] = false
parsed_args["config"] = "sphere"
parsed_args["moist"] = "equil"

max_stars_repo_name: CliMA/ClimaCoupler


text:
# ---
# title: 1091. Shortest Path in Binary Matrix
# id: problem1091
# author: Indigo
# date: 2022-03-08
# difficulty: Medium
# categories: Breadth-first Search
# link: <https://leetcode.com/problems/shortest-path-in-binary-matrix/description/>
# hidden: true
# ---
#
# In an N by N square grid, each cell is either empty (0) or blocked (1).
#
# A  _clear  path from top-left to bottom-right_ has length `k` if and only if
# it is composed of cells `C_1, C_2, ..., C_k` such that:
#
#   * Adjacent cells `C_i` and `C_{i+1}` are connected 8-directionally (ie., they are different and share an edge or corner)
#   * `C_1` is at location `(0, 0)` (ie. has value `grid[0][0]`)
#   * `C_k` is at location `(N-1, N-1)` (ie. has value `grid[N-1][N-1]`)
#   * If `C_i` is located at `(r, c)`, then `grid[r][c]` is empty (ie. `grid[r][c] == 0`).
#
# Return the length of the shortest such clear path from top-left to bottom-
# right.  If such a path does not exist, return -1.
#
#
#
# **Example 1:**
#
#
#
#     Input: [[0,1],[1,0]]
#     ![](https://assets.leetcode.com/uploads/2019/08/04/example1_1.png)
#
#     Output: 2
#     ![](https://assets.leetcode.com/uploads/2019/08/04/example1_2.png)
#
#
# **Example 2:**
#
#
#
#     Input: [[0,0,0],[1,1,0],[1,1,0]]
#     ![](https://assets.leetcode.com/uploads/2019/08/04/example2_1.png)
#
#     Output: 4
#     ![](https://assets.leetcode.com/uploads/2019/08/04/example2_2.png)
#
#
#
#
# **Note:**
#
#   1. `1 <= grid.length == grid[0].length <= 100`
#   2. `grid[r][c]` is `0` or `1`
#
#
## @lc code=start
using LeetCode

function shortest_path_binary_matrix(mat::Matrix{Int})
    visited = fill(false, size(mat))
    q = [CartesianIndex(1, 1)]
    dist = [1]
    visited[1, 1] = true
    directions = [CartesianIndex(i, j) for i in -1:1, j in -1:1 if i != 0 || j != 0]
    res = 0
    while !visited[end, end]
        frt = popfirst!(q)
        dst = popfirst!(dist)
        for dir in directions
            next_coord = frt + dir
            next_coord ∉ CartesianIndices(mat) && continue
            visited[next_coord] && continue
            visited[next_coord] = true
            if mat[next_coord] == 0
                push!(q, next_coord)
                push!(dist, dst + 1)
                res = dst + 1
            end
        end
    end
    return res
end

## @lc code=end


text:
function evalcards{T<:Union{Char}}(ranks::T...; take = 5)
  return foldl( (x,y) -> 100*x + y, indexin([ranks...][1:min(end, take)], collect(RANKS)))
end

function evalcards() return 0 end

function orderhand!(hand::Hand)
  sort!(hand.cards
    , lt = (x,y) -> begin
      findlast(RANKS, first(x))*10 + findlast(SUITS, last(x)) <
      findlast(RANKS, first(y))*10 + findlast(SUITS, last(y))
    end)
  return hand
end

function findstraight(hand::Hand)
  @assert length(hand.cards) >= 5 """cannot evaluate straights with less than 5 cards"""

  # hands already have the cards ordered
  oranks = unique(map(first, hand.cards))
  last(oranks) == 'A' && unshift!(oranks, 'A') # create that wrap

  ind = 1:(length(oranks)-4)
  contigs = map(i -> string(oranks[i:i+4]...), ind)
  filter!(c -> contains(RANKS, c), contigs) # RANKS is already ordered
  length(contigs) == 0 && return nothing
  sort!(contigs
    , lt = (x,y) ->
      findlast(collect(RANKS), last(x)) < findlast(collect(RANKS), last(y))
    , rev=true)

  # return the cards that belong in the largest straight
  return Hand(filter(c -> in(first(c), first(contigs)), hand.cards))
end

function tally(arr::AbstractArray)
  d = countmap(arr)
  collect(zip(keys(d), values(d)))
end

function findflush(hand::Hand)
  ranks = map(first, hand.cards)
  suits = map(last, hand.cards)

  # there can be at most 3 unique suits for a flush
  # to be present
  length(unique(suits)) > 3 && return nothing

  tallied = sort(tally(suits), lt = (x,y) -> x[2] < y[2], rev=true)

  tallied[1][2] < 5 && return nothing

  flush_suit = tallied[1][1]
  return Hand(filter(c -> last(c) == flush_suit, hand.cards))
end

@memoize function evaluate(hand::Integer)
  return evaluate(Hand(hand))
end

function evaluate(hand::Hand)
  # @assert length(hand.cards) == 7 """hands must contain 2 hole cards and 5 community cards"""

  # 900-999 straight flush
  # 800-899 quads
  # 700-799 full house
  # 600-699 flush
  # 500-599 straights
  # 400-499 trips
  # 300-399 two pair
  # 200-299 one pair
  # 100-199 hi card

  # STRAIGHT FLUSH
  flush = findflush(hand)
  if flush != nothing
    straight = findstraight(flush)
  end

  if flush != nothing && straight != nothing
    return round(900 + evalcards(last(straight.cards)[1]), 8)
  end

  ranks = map(first, hand.cards)
  counts = tally(ranks)
  sort!(counts, lt = (x,y) -> x[2]*100 + evalcards(x[1]) < y[2]*100 + evalcards(y[1]), rev=true)

  # QUADS
  if counts[1][2] >= 4
    return round(800 + evalcards(map(first, counts[1:2])...) / 10.0^2, 8)
  end

  # FULL HOUSE
  if counts[1][2] == 3 && counts[2][2] >= 2
    return round(700 + evalcards(map(first, counts[1:2])...) / 10.0^2, 8)
  end

  # FLUSH
  flush != nothing && return round(600 + evalcards(last(flush.cards)[1]), 8)

  # STRAIGHT
  straight = findstraight(hand)
  straight != nothing && return round(500 + evalcards(last(straight.cards)[1]), 8)

  # TRIPS
  if counts[1][2] == 3
    return round(400 + evalcards(map(first, counts[1:3])...) / 10.0^4, 8)
  end

  # TWO PAIR
  if counts[1][2] == 2 && counts[2][2] == 2
    return round(300 + evalcards(map(first, counts[1:3])...) / 10.0^4, 8)
  end

  # PAIR
  if counts[1][2] == 2
    return round(200 + evalcards(map(first, counts[1:4])...) / 10.0^6, 8)
  end

  return round(100 + evalcards(map(first, counts[1:5])...) / 10.0^8, 8)
end