text:
using AxisAlgorithms, OffsetArrays

@testset "Unconventional axes" begin
    # At present, for a particular type of non-1 array you need to specialize this function
    function AxisAlgorithms.A_ldiv_B_md!(dest::OffsetArray, F, src::OffsetArray, dim::Integer, b::AbstractVector)
        indsdim = axes(parent(src), dim)
        indsF = axes(F)[2]
        if indsF == indsdim
            return A_ldiv_B_md!(parent(dest), F, parent(src), dim, b)
        end
        throw(DimensionMismatch("indices $(axes(parent(src))) do not match $(axes(F))"))
    end

    for (constructor, copier) in ((interpolate, x->x), (interpolate!, copy))
        isinplace = constructor == interpolate!
        f1(x) = sin((x-3)*2pi/9 - 1)
        inds = -3:6
        A1 = OffsetArray(Float64[f1(x) for x in inds], inds)

        f2(x,y) = sin(x/10)*cos(y/6) + 0.1
        xinds, yinds = -2:28,0:9
        A2 = OffsetArray(Float64[f2(x,y) for x in xinds, y in yinds], xinds, yinds)

        for O in (Constant, Linear)
            itp1 = @inferred(constructor(copier(A1), BSpline(O())))
            check_axes(itp1, A1, isinplace)
            check_inbounds_values(itp1, A1)
            check_oob(itp1)
            can_eval_near_boundaries(itp1)

            itp2 = @inferred(constructor(copier(A2), BSpline(O())))
            check_axes(itp2, A2, isinplace)
            check_inbounds_values(itp2, A2)
            check_oob(itp2)
            can_eval_near_boundaries(itp2)
        end

        for BC in (Flat,Line,Free,Periodic,Reflect,Natural), GT in (OnGrid, OnCell)
            itp1 = @inferred(constructor(copier(A1), BSpline(Quadratic(BC(GT())))))
            check_axes(itp1, A1, isinplace)
            check_inbounds_values(itp1, A1)
            check_oob(itp1)
            can_eval_near_boundaries(itp1)

            itp2 = @inferred(constructor(copier(A2), BSpline(Quadratic(BC(GT())))))
            check_axes(itp2, A2, isinplace)
            check_inbounds_values(itp2, A2)
            check_oob(itp2)
            can_eval_near_boundaries(itp2)
        end

        for BC in (Flat,Line,Free,Periodic), GT in (OnGrid, OnCell)
            itp1 = @inferred(constructor(copier(A1), BSpline(Cubic(BC(GT())))))
            check_axes(itp1, A1, isinplace)
            check_inbounds_values(itp1, A1)
            check_oob(itp1)
            can_eval_near_boundaries(itp1)

            itp2 = @inferred(constructor(copier(A2), BSpline(Cubic(BC(GT())))))
            check_axes(itp2, A2, isinplace)
            check_inbounds_values(itp2, A2)
            check_oob(itp2)
            can_eval_near_boundaries(itp2)
        end
    end

    let
        f(x) = sin((x-3)*2pi/9 - 1)
        inds = -7:2
        A = OffsetArray(Float64[f(x) for x in inds], inds)
        itp1 = interpolate!(copy(A), BSpline(Quadratic(InPlace(OnCell()))))
        check_axes(itp1, A)
        check_inbounds_values(itp1, A)
        check_oob(itp1)
        can_eval_near_boundaries(itp1)

        f(x,y) = sin(x/10)*cos(y/6) + 0.1
        xinds, yinds = -2:28,0:9
        A2 = OffsetArray(Float64[f(x,y) for x in xinds, y in yinds], xinds, yinds)
        itp2 = interpolate!(copy(A2), BSpline(Quadratic(InPlace(OnCell()))))
        check_axes(itp2, A2)
        check_inbounds_values(itp2, A2)
        check_oob(itp2)
        can_eval_near_boundaries(itp2)
    end
end


text:
import Random.shuffle!
@testset "fsm_loopback_win.jl" begin
    DEFAULT_CAPACITY = 65000
    TIMEOUT_DFLT = 1000
    NREPS = 32
    MAX_PAYLOAD_SIZE = 1460
    @testset "loop segments back in a different order" begin
        for i in 0:NREPS
            rx_offset = WrappingInt32(rand(UInt32))
            conn = fsm_in_established(rx_offset - 1, rx_offset - 1; cap=DEFAULT_CAPACITY)
            send_ack!(conn, rx_offset, rx_offset, 65000)
            d = rand(UInt8(1):UInt8(127), DEFAULT_CAPACITY) |> pointer |> unsafe_string
            sendoff = 0
            segs = TCPSegment[]
            sendoff = 0
            while sendoff < length(d)
                len = min(length(d) - sendoff, rand(UInt) % 8192)
                len == 0 && continue
                write!(conn, @view(d[sendoff+1:sendoff+len]))
                tick!(conn, 1)
                @test bytes_in_flight(conn) == sendoff + len
                @test conn.segments_out |> !isempty
                while conn.segments_out |> !isempty
                    push!(segs, expect_seg(conn))
                end
                sendoff += len
            end
            seg_idx = collect(1:length(segs))
            shuffle!(seg_idx)
            acks = TCPSegment[]
            for idx in seg_idx
                send_seg!(conn, segs[idx])
                tick!(conn, 1)
                s = expect_one_seg(conn; ack=true)
                push!(acks, s)
                expect_no_seg(conn)
            end
            send_seg!(conn, acks[end])
            expect_no_seg(conn)
            expect_data!(conn, d)
        end
    end
end

ext: jl

max_stars_repo_name: AquaIndigo/JLSponge

max_issues_repo_name: AquaIndigo/JLSponge

max_forks_repo_name: AquaIndigo/JLSponge


text:
struct Reader{S <: TranscodingStream} <: BioGenerics.IO.AbstractReader
    state::State{S}
end

function Reader(input::IO)
    if !(input isa TranscodingStream)
        stream = TranscodingStreams.NoopStream(input)
    end

    return Reader(State(stream, 1, 1, false))
end

function Base.eltype(::Type{<: Reader})
    return Record
end

function BioGenerics.IO.stream(reader::Reader)
    return reader.state.stream
end

function Base.read!(rdr::Reader, rec::Record)
    cs, ln, f = readrecord!(rdr.state.stream, rec, (rdr.state.state, rdr.state.linenum))
    rdr.state.state = cs
    rdr.state.linenum = ln
    rdr.state.filled = f
    if !f
        cs == 0 && throw(EOFError())
        throw(ArgumentError("malformed file"))
    end
    return rec
end

function Base.close(reader::Reader)
    if reader.state.stream isa IO
        close(reader.state.stream)
    end
    return nothing
end

function allspace(stream)
    while !eof(stream)
        if !isspace(read(stream, Char))
            return false
        end
    end
    return true
end


text:
@testset "Envelopes" begin
    @testset "Trapezoidal envelopes" begin
        @field(F) do
            I₀ = 1.0
            T = 2.0
            ramp_up = 1.0
            flat = 3.0
            ramp_down = 2.0
            env = :trapezoidal
        end

        env = envelope(F)
        @test env isa ElectricFields.TrapezoidalEnvelope

        @test env(-1.0) == 0.0
        @test env(0.0) == 0.0
        @test env(1.0) == 0.5
        @test env(2.5) == 1.0
        @test env(7.9) == 1.0
        @test env(10.0) == 0.5
        @test env(12.0) == 0.0
        @test env(13.0) == 0.0

        @test continuity(env) == 0
        @test span(env) == 0..12

        @test string(env) == "/1‾3‾2\\ cycles trapezoidal envelope"

        @field(F2) do
            I₀ = 1.0
            T = 2.0
            ramp = 1.0
            flat = 3.0
            env = :trapezoidal
        end

        env2 = envelope(F2)

        @test env2.ramp_up == env2.ramp_down == 1.0
        @test span(env2) == 0..10

        @test_throws ErrorException ElectricFields.TrapezoidalEnvelope(-1.0, 1.0, 1.0, 1.0)
        @test_throws ErrorException ElectricFields.TrapezoidalEnvelope(1.0, -1.0, 1.0, 1.0)
        @test_throws ErrorException ElectricFields.TrapezoidalEnvelope(1.0, 1.0, -1.0, 1.0)
        @test_throws ErrorException ElectricFields.TrapezoidalEnvelope(0.0, 0.0, 0.0, 1.0)
    end

    @testset "cos² envelopes" begin
        @field(F) do
            I₀ = 1.0
            T = 2.0
            cycles = 3.0
            env = :cos²
        end

        env = envelope(F)

        @test env(0.0) == 1.0
        @test env(6/4) ≈ 1/2
        @test env(3.0) == 0.0
        @test env(3.1) == 0.0

        @test string(env) == "3.00 cycles cos² envelope"

        @test continuity(env) == 0
        @test span(env) == -3..3
    end
end


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

module ExpressRouteCircuitClient

using Random
using Dates
using Swagger
import Swagger: field_name, property_type, hasproperty, validate_property, SwaggerApi, SwaggerModel
import Base: convert, propertynames

include("modelincludes.jl")

include("api_ExpressRouteCircuitArpTableApi.jl")
include("api_ExpressRouteCircuitAuthorizationsApi.jl")
include("api_ExpressRouteCircuitConnectionsApi.jl")
include("api_ExpressRouteCircuitPeeringsApi.jl")
include("api_ExpressRouteCircuitRoutesTableApi.jl")
include("api_ExpressRouteCircuitRoutesTableSummaryApi.jl")
include("api_ExpressRouteCircuitStatsApi.jl")
include("api_ExpressRouteCircuitsApi.jl")
include("api_ExpressRouteServiceProvidersApi.jl")
include("api_PeerExpressRouteCircuitConnectionsApi.jl")

# export models
export convert, AuthorizationListResult
export convert, AuthorizationPropertiesFormat
export convert, CircuitConnectionStatus
export convert, CloudError
export convert, CloudErrorBody
export convert, ExpressRouteCircuit
export convert, ExpressRouteCircuitArpTable
export convert, ExpressRouteCircuitAuthorization
export convert, ExpressRouteCircuitConnection
export convert, ExpressRouteCircuitConnectionListResult
export convert, ExpressRouteCircuitConnectionPropertiesFormat
export convert, ExpressRouteCircuitListResult
export convert, ExpressRouteCircuitPeering
export convert, ExpressRouteCircuitPeeringConfig
export convert, ExpressRouteCircuitPeeringListResult
export convert, ExpressRouteCircuitPeeringPropertiesFormat
export convert, ExpressRouteCircuitPropertiesFormat
export convert, ExpressRouteCircuitRoutesTable
export convert, ExpressRouteCircuitRoutesTableSummary
export convert, ExpressRouteCircuitServiceProviderProperties
export convert, ExpressRouteCircuitSku
export convert, ExpressRouteCircuitStats
export convert, ExpressRouteCircuitsArpTableListResult
export convert, ExpressRouteCircuitsRoutesTableListResult
export convert, ExpressRouteCircuitsRoutesTableSummaryListResult
export convert, ExpressRouteConnectionId
export convert, ExpressRoutePeeringState
export convert, ExpressRoutePeeringType
export convert, ExpressRouteServiceProvider
export convert, ExpressRouteServiceProviderBandwidthsOffered
export convert, ExpressRouteServiceProviderListResult
export convert, ExpressRouteServiceProviderPropertiesFormat
export convert, Ipv6CircuitConnectionConfig
export convert, Ipv6ExpressRouteCircuitPeeringConfig
export convert, PeerExpressRouteCircuitConnection
export convert, PeerExpressRouteCircuitConnectionListResult
export convert, PeerExpressRouteCircuitConnectionPropertiesFormat
export convert, ProvisioningState
export convert, Resource
export convert, ServiceProviderProvisioningState
export convert, SubResource
export convert, TagsObject

# export operations
export convert, ExpressRouteCircuitArpTableApi, ExpressRouteCircuitAuthorizationsApi, ExpressRouteCircuitConnectionsApi, ExpressRouteCircuitPeeringsApi, ExpressRouteCircuitRoutesTableApi, ExpressRouteCircuitRoutesTableSummaryApi, ExpressRouteCircuitStatsApi, ExpressRouteCircuitsApi, ExpressRouteServiceProvidersApi, PeerExpressRouteCircuitConnectionsApi

export check_required, field_name, property_type, hasproperty, propertynames, validate_property, convert

end


text:
int_rules_4_3_1_2 = @theory begin

    #= ::Subsection::Closed:: =#
    #= 4.3.1.2*(d*sec)^m*(a+b*tan)^n =#
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)), ~x) => (~b * (~d * sec(~e + ~f * ~x)) ^ ~m) / (~f * ~m) + ~a * Antiderivative((~d * sec(~e + ~f * ~x)) ^ ~m, ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m], ~x) && (IntegerQ(2 * ~m) || NeQ((~a) ^ 2 + (~b) ^ 2, 0))
    @apply_utils Antiderivative(sec(~(e') + ~(f') * ~x) ^ ~m * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (1 / ((~a) ^ (~m - 2) * ~b * ~f)) * Subst(Antiderivative((~a - ~x) ^ (~m / 2 - 1) * (~a + ~x) ^ ((~n + ~m / 2) - 1), ~x), ~x, ~b * tan(~e + ~f * ~x)) <-- FreeQ([~a, ~b, ~e, ~f, ~n], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && IntegerQ(~m / 2))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~b * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ ~n) / (~a * ~f * ~m) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && EqQ(Simplify(~m + ~n), 0))
    @apply_utils Antiderivative(sec(~(e') + ~(f') * ~x) / sqrt(~a + ~(b') * tan(~(e') + ~(f') * ~x)), ~x) => ((-2 * ~a) / (~b * ~f)) * Subst(Antiderivative(1 / (2 - ~a * (~x) ^ 2), ~x), ~x, sec(~e + ~f * ~x) / sqrt(~a + ~b * tan(~e + ~f * ~x))) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && EqQ((~a) ^ 2 + (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~b * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ ~n) / (~a * ~f * ~m) + (~a / (2 * (~d) ^ 2)) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ (~m + 2) * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (EqQ(~m / 2 + ~n, 0) && GtQ(~n, 0)))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (2 * (~d) ^ 2 * (~d * sec(~e + ~f * ~x)) ^ (~m - 2) * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n + 1)) / (~b * ~f * (~m - 2)) + ((2 * (~d) ^ 2) / ~a) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ (~m - 2) * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n + 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (EqQ(~m / 2 + ~n, 0) && LtQ(~n, -1)))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~m * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (((~a / ~d) ^ (2 * IntPart(~n)) * (~a + ~b * tan(~e + ~f * ~x)) ^ FracPart(~n) * (~a - ~b * tan(~e + ~f * ~x)) ^ FracPart(~n)) / (~d * sec(~e + ~f * ~x)) ^ (2 * FracPart(~n))) * Antiderivative(1 / (~a - ~b * tan(~e + ~f * ~x)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && EqQ(Simplify(~m / 2 + ~n), 0))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (2 * ~b * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 1)) / (~f * ~m) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && EqQ(Simplify((~m / 2 + ~n) - 1), 0))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~b * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 1)) / (~f * ((~m + ~n) - 1)) + ((~a * ((~m + 2 * ~n) - 2)) / ((~m + ~n) - 1)) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (IGtQ(Simplify((~m / 2 + ~n) - 1), 0) && Not(IntegerQ(~n))))
    @apply_utils Antiderivative(sqrt(~(d') * sec(~(e') + ~(f') * ~x)) * sqrt(~a + ~(b') * tan(~(e') + ~(f') * ~x)), ~x) => ((-4 * ~b * (~d) ^ 2) / ~f) * Subst(Antiderivative((~x) ^ 2 / ((~a) ^ 2 + (~d) ^ 2 * (~x) ^ 4), ~x), ~x, sqrt(~a + ~b * tan(~e + ~f * ~x)) / sqrt(~d * sec(~e + ~f * ~x))) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && EqQ((~a) ^ 2 + (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~m * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (2 * ~b * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 1)) / (~f * ~m) - (((~b) ^ 2 * ((~m + 2 * ~n) - 2)) / ((~d) ^ 2 * ~m)) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ (~m + 2) * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 2), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (GtQ(~n, 1) && ((IGtQ(~n / 2, 0) && ILtQ(~m - 1 / 2, 0) || (EqQ(~n, 2) && LtQ(~m, 0) || (LeQ(~m, -1) && GtQ(~m + ~n, 0) || (ILtQ(~m, 0) && (LtQ((~m / 2 + ~n) - 1, 0) && IntegerQ(~n)) || EqQ(~n, 3 / 2) && EqQ(~m, -1 / 2))))) && IntegerQ(2 * ~m))))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~m * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~b * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ ~n) / (~a * ~f * ~m) + ((~a * (~m + ~n)) / (~m * (~d) ^ 2)) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ (~m + 2) * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (GtQ(~n, 0) && (LtQ(~m, -1) && IntegersQ(2 * ~m, 2 * ~n))))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~b * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 1)) / (~f * ((~m + ~n) - 1)) + ((~a * ((~m + 2 * ~n) - 2)) / ((~m + ~n) - 1)) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (GtQ(~n, 0) && (NeQ((~m + ~n) - 1, 0) && IntegersQ(2 * ~m, 2 * ~n))))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ (3 / 2) / sqrt(~a + ~(b') * tan(~(e') + ~(f') * ~x)), ~x) => ((~d * sec(~e + ~f * ~x)) / (sqrt(~a - ~b * tan(~e + ~f * ~x)) * sqrt(~a + ~b * tan(~e + ~f * ~x)))) * Antiderivative(sqrt(~d * sec(~e + ~f * ~x)) * sqrt(~a - ~b * tan(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && EqQ((~a) ^ 2 + (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~m * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (2 * (~d) ^ 2 * (~d * sec(~e + ~f * ~x)) ^ (~m - 2) * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n + 1)) / (~b * ~f * (~m + 2 * ~n)) - (((~d) ^ 2 * (~m - 2)) / ((~b) ^ 2 * (~m + 2 * ~n))) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ (~m - 2) * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n + 2), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (LtQ(~n, -1) && ((ILtQ(~n / 2, 0) && IGtQ(~m - 1 / 2, 0) || (EqQ(~n, -2) || (IGtQ(~m + ~n, 0) || IntegersQ(~n, ~m + 1 / 2) && GtQ(2 * ~m + ~n + 1, 0)))) && IntegerQ(2 * ~m))))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => ((~d) ^ 2 * (~d * sec(~e + ~f * ~x)) ^ (~m - 2) * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n + 1)) / (~b * ~f * ((~m + ~n) - 1)) + (((~d) ^ 2 * (~m - 2)) / (~a * ((~m + ~n) - 1))) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ (~m - 2) * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n + 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (LtQ(~n, 0) && (GtQ(~m, 1) && (Not(ILtQ(~m + ~n, 0)) && (NeQ((~m + ~n) - 1, 0) && IntegersQ(2 * ~m, 2 * ~n))))))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~a * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ ~n) / (~b * ~f * (~m + 2 * ~n)) + (Simplify(~m + ~n) / (~a * (~m + 2 * ~n))) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n + 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (LtQ(~n, 0) && (NeQ(~m + 2 * ~n, 0) && IntegersQ(2 * ~m, 2 * ~n))))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~b * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 1)) / (~f * Simplify((~m + ~n) - 1)) + ((~a * ((~m + 2 * ~n) - 2)) / Simplify((~m + ~n) - 1)) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n - 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (IGtQ(Simplify((~m + ~n) - 1), 0) && RationalQ(~n)))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~a * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ ~n) / (~b * ~f * (~m + 2 * ~n)) + (Simplify(~m + ~n) / (~a * (~m + 2 * ~n))) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x)) ^ (~n + 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 + (~b) ^ 2, 0) && (ILtQ(Simplify(~m + ~n), 0) && NeQ(~m + 2 * ~n, 0)))
    #= Antiderivative(((~d')*sec((~e')+(~f')*(~x)))^(~m')*((~a)+(~b')*tan((~e')+(~f')*(~x)))^(~n),~x)  := a^n*(d*sec(e+f*x))^m/(b*f*(sec(e+f*x)^2)^(m/2))*Subst(Antiderivative((1+x/ a)^(n+m/2-1)*(1-x/a)^(m/2-1),x),x,b*tan(e+f*x)) <--  FreeQ([a,b,d,e,f,m],x) && EqQ(a^2+b^2,0) && IntegerQ(n) =#
    #= Antiderivative(((~d')*sec((~e')+(~f')*(~x)))^(~m')*((~a)+(~b')*tan((~e')+(~f')*(~x)))^(~n),~x)  := (d*sec(e+f*x))^m/(b*f*(sec(e+f*x)^2)^(m/2))*Subst(Antiderivative((a+x)^n*( 1+x^2/b^2)^(m/2-1),x),x,b*tan(e+f*x)) <-- FreeQ([a,b,d,e,f,m,n],x) &&  EqQ(a^2+b^2,0) =#
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~(n'), ~x) => ((~d * sec(~e + ~f * ~x)) ^ ~m / ((~a + ~b * tan(~e + ~f * ~x)) ^ (~m / 2) * (~a - ~b * tan(~e + ~f * ~x)) ^ (~m / 2))) * Antiderivative((~a + ~b * tan(~e + ~f * ~x)) ^ (~m / 2 + ~n) * (~a - ~b * tan(~e + ~f * ~x)) ^ (~m / 2), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && EqQ((~a) ^ 2 + (~b) ^ 2, 0)
    @apply_utils Antiderivative(sec(~(e') + ~(f') * ~x) ^ ~m * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (1 / (~b * ~f)) * Subst(Antiderivative((~a + ~x) ^ ~n * (1 + (~x) ^ 2 / (~b) ^ 2) ^ (~m / 2 - 1), ~x), ~x, ~b * tan(~e + ~f * ~x)) <-- FreeQ([~a, ~b, ~e, ~f, ~n], ~x) && (NeQ((~a) ^ 2 + (~b) ^ 2, 0) && IntegerQ(~m / 2))
    @apply_utils Antiderivative((~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ 2 / sec(~(e') + ~(f') * ~x), ~x) => (((~b) ^ 2 * atanh(sin(~e + ~f * ~x))) / ~f - (2 * ~a * ~b * cos(~e + ~f * ~x)) / ~f) + (((~a) ^ 2 - (~b) ^ 2) * sin(~e + ~f * ~x)) / ~f <-- FreeQ([~a, ~b, ~e, ~f], ~x) && NeQ((~a) ^ 2 + (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ 2, ~x) => (~b * (~d * sec(~e + ~f * ~x)) ^ ~m * (~a + ~b * tan(~e + ~f * ~x))) / (~f * (~m + 1)) + (1 / (~m + 1)) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ ~m * (((~a) ^ 2 * (~m + 1) - (~b) ^ 2) + ~a * ~b * (~m + 2) * tan(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m], ~x) && (NeQ((~a) ^ 2 + (~b) ^ 2, 0) && NeQ(~m, -1))
    @apply_utils Antiderivative(sec(~(e') + ~(f') * ~x) / (~a + ~(b') * tan(~(e') + ~(f') * ~x)), ~x) => (-1 / ~f) * Subst(Antiderivative(1 / (((~a) ^ 2 + (~b) ^ 2) - (~x) ^ 2), ~x), ~x, (~b - ~a * tan(~e + ~f * ~x)) / sec(~e + ~f * ~x)) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && NeQ((~a) ^ 2 + (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~m / (~a + ~(b') * tan(~(e') + ~(f') * ~x)), ~x) => (-((~d) ^ 2) / (~b) ^ 2) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ (~m - 2) * (~a - ~b * tan(~e + ~f * ~x)), ~x) + (((~d) ^ 2 * ((~a) ^ 2 + (~b) ^ 2)) / (~b) ^ 2) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ (~m - 2) / (~a + ~b * tan(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 + (~b) ^ 2, 0) && IGtQ(~m, 1))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~m / (~a + ~(b') * tan(~(e') + ~(f') * ~x)), ~x) => (1 / ((~a) ^ 2 + (~b) ^ 2)) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ ~m * (~a - ~b * tan(~e + ~f * ~x)), ~x) + ((~b) ^ 2 / ((~d) ^ 2 * ((~a) ^ 2 + (~b) ^ 2))) * Antiderivative((~d * sec(~e + ~f * ~x)) ^ (~m + 2) / (~a + ~b * tan(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 + (~b) ^ 2, 0) && ILtQ(~m, 0))
    @apply_utils Antiderivative((~(d') * sec(~(e') + ~(f') * ~x)) ^ ~(m') * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (((~d) ^ (2 * IntPart(~m / 2)) * (~d * sec(~e + ~f * ~x)) ^ (2 * FracPart(~m / 2))) / (~b * ~f * (sec(~e + ~f * ~x) ^ 2) ^ FracPart(~m / 2))) * Subst(Antiderivative((~a + ~x) ^ ~n * (1 + (~x) ^ 2 / (~b) ^ 2) ^ (~m / 2 - 1), ~x), ~x, ~b * tan(~e + ~f * ~x)) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (NeQ((~a) ^ 2 + (~b) ^ 2, 0) && Not(IntegerQ(~m / 2)))
    @apply_utils Antiderivative(sqrt(~a + ~(b') * tan(~(e') + ~(f') * ~x)) / sqrt(~(d') * cos(~(e') + ~(f') * ~x)), ~x) => ((-4 * ~b) / ~f) * Subst(Antiderivative((~x) ^ 2 / ((~a) ^ 2 * (~d) ^ 2 + (~x) ^ 4), ~x), ~x, sqrt(~d * cos(~e + ~f * ~x)) * sqrt(~a + ~b * tan(~e + ~f * ~x))) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && EqQ((~a) ^ 2 + (~b) ^ 2, 0)
    @apply_utils Antiderivative(1 / ((~(d') * cos(~(e') + ~(f') * ~x)) ^ (3 / 2) * sqrt(~a + ~(b') * tan(~(e') + ~(f') * ~x))), ~x) => (1 / (~d * cos(~e + ~f * ~x) * sqrt(~a - ~b * tan(~e + ~f * ~x)) * sqrt(~a + ~b * tan(~e + ~f * ~x)))) * Antiderivative(sqrt(~a - ~b * tan(~e + ~f * ~x)) / sqrt(~d * cos(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && EqQ((~a) ^ 2 + (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * cos(~(e') + ~(f') * ~x)) ^ ~m * (~a + ~(b') * tan(~(e') + ~(f') * ~x)) ^ ~(n'), ~x) => (~d * cos(~e + ~f * ~x)) ^ ~m * (~d * sec(~e + ~f * ~x)) ^ ~m * Antiderivative((~a + ~b * tan(~e + ~f * ~x)) ^ ~n / (~d * sec(~e + ~f * ~x)) ^ ~m, ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && Not(IntegerQ(~m))
end

max_stars_repo_path: src/rules/4 Trig functions/4.3 Tangent/4.3.1.2 (d sec)^m (a+b tan)^n.jl


text:
struct Benchmark{T<:Union{BenchmarkTools.Trial, BenchmarkTools.BenchmarkGroup}}

    env::Base.EnvHash
    time::DateTime
    commit::String
    trial::T
end

function Benchmark(trial::BenchmarkTools.Trial)
    Benchmark(ENV, now(), readstring(`git log --pretty=format:'%h' -n 1`), trial)
end

"""
    Use: updatehistory!(history::String, trial::BenchmarkTools.Trial, funcName::String; pkg::Module = Meganet)

Appends `hist` in the JLD file `history` with the latest trial and metadata contained
in a `Benchmark` instance.
"""
function updatehistory!(history::String, trial::BenchmarkTools.Trial, funcName::String; pkg::Module = Meganet)

    cd(Pkg.dir("$pkg"))
    if isfile(history)
        println("Appending trial history: "*history)

        hist = JLD.load(history)
        if haskey(hist, funcName)
            histFunc = hist[funcName]
        else
            histFunc = Vector{Meganet.Benchmark}()
        end

        push!(histFunc, Meganet.Benchmark(trial))

        JLD.jldopen(history, "w") do file
            write(file, funcName, histFunc)
        end
    else
        println("Creating trial history: "*history)
        hist = Vector{Meganet.Benchmark}()
        push!(hist, Meganet.Benchmark(trial))

        JLD.jldopen(history, "w") do file
            write(file, funcName, hist)
        end
    end
end

function Base.show(io::IO, b::Meganet.Benchmark)
    println()
    println(b.time)
    println(b.trial)
end

function Base.show(io::IO, bv::Array{Meganet.Benchmark,1})
    show(io, bv[1])
    println("""
                ...
                    """)
    show(io, bv[end - 1])
    show(io, bv[end])
end

"""
    Use: judge(hist::Vector{Meganet.Benchmark}, i::Int, j::Int;
                                    estimator::Function = BenchmarkTools.median)

Judge between benchmark `i` and `j` in `hist` using `estimator`.
"""
function BenchmarkTools.judge(hist::Vector{Meganet.Benchmark}, i::Int, j::Int;
                                    estimator::Function = BenchmarkTools.median)
    length(hist) <= 1 && error("Only one benchmark in history")
    a, b = hist[i].trial, hist[j].trial
    j = BenchmarkTools.judge(estimator(a), estimator(b))

    return j
end

"""
    Use: judge(hist::Vector{Meganet.Benchmark}
                                    estimator::Function = BenchmarkTools.median)

Judge between the two most recent benchmarks in `hist` using `estimator`.
"""
function BenchmarkTools.judge(hist::Vector{Meganet.Benchmark};
                                    estimator::Function = BenchmarkTools.median)
    n = length(hist)
    n <= 1 && error("Only one benchmark in history")
    j = BenchmarkTools.judge(hist, n, n - 1)

    return j
end


text:
using Fastfood
using Gadfly
using LinearAlgebra

# generate training dataset (two spirals)
data = zeros(2, 97)
for i in 0:96
    angle = i * pi / 16.0
    radius = 6.5 * (104.0 - i) / 104.0
    data[:, i+1] = radius * [sin(angle), cos(angle)]
end
X_train = hcat(data, -data)
Y_train = hcat(ones(1,size(data,2)), -ones(1,size(data,2)))

# train
sgm = 3.0
N = 1000
param = FastfoodParam(N, size(X_train,1))
Kern = FastfoodKernel(X_train, param, sgm=sgm)
W = Y_train * pinv(Kern)  # least squares method

# generate test dataset
xrange = yrange = -6:0.1:6.0
X = repeat(xrange', length(yrange), 1)
Y = repeat(yrange, 1, length(xrange))
X_test = collect(hcat(X[:], Y[:])')

# test
Y_test = W * FastfoodKernel(X_test, param, sgm=sgm)
Y_test = collect(reshape(Y_test, length(xrange), length(yrange))')

# visualize
p = plot(
         layer(x=xrange, y=yrange, z=Y_test, Geom.contour(levels=[0.0])),
         layer(x=data[1, :], y=data[2,:], Geom.point, Theme(default_color=colorant"skyblue")),
         layer(x=-data[1, :], y=-data[2,:], Geom.point, Theme(default_color=colorant"salmon")),
         Coord.cartesian(xmin=-6, xmax=6, ymin=-6, ymax=6),
)
draw(SVG("out.svg", 4inch, 4inch), p)


text:
using Shapes
using Test
using StaticArrays
using Shapes: concrete_eltype, ShapedView

@testset "Shapes.jl" begin

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

    @testset "StaticArrays support" begin
        svec = SVector(1, 2, 3)
        mvec = MVector(1, 2, 3)
        sizedvec = SizedVector{3}(1, 2, 3)

        @test @inferred(Shape(svec)) === Shape{Tuple{3},Int,1,3}()
        @test @inferred(Shape(mvec)) === Shape{Tuple{3},Int,1,3}()
        @test @inferred(Shape(sizedvec)) === Shape{Tuple{3},Int,1,3}()

        s1 = Shape(svec)
        s2 = Shape{Tuple{3},Integer,1,3}()
        @test @inferred(similar_type(s1)) === @inferred(similar_type(s2)) === typeof(svec)
        @test @inferred(similar_type(MArray, s1)) ===
              @inferred(similar_type(MArray, s2)) === typeof(mvec)

    end

    @testset "Array constructors" begin
        let s = VectorShape{5,Real}()
            @test @inferred(Array(undef, s)) isa Vector{Float64}
            @test @inferred(Array{Float64}(undef, s)) isa Vector{Float64}
            @test size(Array{Float64}(undef, s)) == (5,)
            @test size(allocate(s)) == (5,)

            @test @inferred(Array(undef, s, 10)) isa Matrix{Float64}
            @test @inferred(Array{Float64}(undef, s, 10)) isa Matrix{Float64}
            @test size(Array{Float64}(undef, s, 10)) == (5, 10)
            @test size(allocate(s, 10)) == (5, 10)

            @test @inferred(zeros(s)) == zeros(Float64, 5)
            @test @inferred(zeros(s, 10)) == zeros(Float64, 5, 10)
        end

        let s = MatrixShape{5,10,Real}()
            @test @inferred(Array(undef, s)) isa Matrix{Float64}
            @test @inferred(Array{Float64}(undef, s)) isa Matrix{Float64}
            @test size(Array{Float64}(undef, s)) == (5, 10)
            @test size(allocate(s)) == (5, 10)

            @test @inferred(Array(undef, s, 15)) isa Array{Float64,3}
            @test @inferred(Array{Float64}(undef, s, 15)) isa Array{Float64,3}
            @test size(Array{Float64}(undef, s, 15)) == (5, 10, 15)
            @test size(allocate(s, 15)) == (5, 10, 15)

            @test @inferred(zeros(s)) == zeros(Float64, 5, 10)
            @test @inferred(zeros(s, 15)) == zeros(Float64, 5, 10, 15)
        end
    end

    @testset "default_datatype" begin
        @test @inferred(Shapes.default_datatype(Integer)) == Int
        @test @inferred(Shapes.default_datatype(Int32)) == Int32
        @test @inferred(Shapes.default_datatype(AbstractFloat)) == Float64
        @test @inferred(Shapes.default_datatype(Real)) == Float64
        @test @inferred(Shapes.default_datatype(Float32)) == Float32
        @test @inferred(Shapes.default_datatype(Real)) == Float64
        @test_throws ArgumentError Shapes.default_datatype(Complex)
    end

end


text:
module TestCore

using Test
using ContextManagers.++

function test_ignoreerror()
    @with(_ = IgnoreError()) do
        error("error")
    end
    @test true
end

function test_onexit()
    calledwith = []
    @with(
        int = onexit(111) do x
            push!(calledwith, x)
        end,
        io = closing(IOBuffer()),
    ) do
        @test int == 111
        @test io isa IOBuffer
    end
    @test calledwith == [111]
end

function test_onexit_noarg()
    calledwith = []
    @with(
        onexit() do
            push!(calledwith, 111)
        end,
        io = closing(IOBuffer()),
    ) do
        @test io isa IOBuffer
    end
    @test calledwith == [111]
end

function test_non_assignment()
    calledwith = []
    xs = [
        onexit(111) do x
            push!(calledwith, x)
        end,
        onexit(222) do x
            push!(calledwith, x)
        end,
    ]
    @with(xs[2], xs[1]) do
    end
    @test calledwith == [111, 222]
end

function check_onfail(witherror)
    calledwith = []
    thrown = try
        @with(
            int = onfail(111) do x
                push!(calledwith, x)
            end,
            onfail() do
                push!(calledwith, 222)
            end,
            io = closing(IOBuffer()),
        ) do
            @test int == 111
            @test io isa IOBuffer
            witherror && error("error")
        end
        false
    catch
        true
    end
    return calledwith, thrown
end

function test_onfail()
    @test check_onfail(false) == ([], false)
    @test check_onfail(true) == ([222, 111], true)
end

function test_many()
    l1 = ReentrantLock()
    l2 = ReentrantLock()
    @with(l1, l2, ch1 = Channel(1), ch2 = Channel(1)) do
        @test l1 isa ReentrantLock
        @test l2 isa ReentrantLock
        @test ch1 isa Channel
        @test ch2 isa Channel
    end
end

function test_many_function()
    l1 = ReentrantLock()
    l2 = ReentrantLock()
    ContextManagers.with(l1, l2, Channel(1), Channel(1)) do l1, l2, ch1, ch2
        @test l1 isa ReentrantLock
        @test l2 isa ReentrantLock
        @test ch1 isa Channel
        @test ch2 isa Channel
    end
end

function test_error_in_exit()
    calledwith = []
    @with(
        IgnoreError(),
        int = onexit(111) do x
            push!(calledwith, x)
        end,
        onexit(nothing) do _
            error("error")
        end,
    ) do
        @test int == 111
    end
    @test calledwith == [111]
end

end  # module


text:
# julia -i transfer_image.jl

import PushInterface: LIBUSB, DisplayInterface
import .LIBUSB: libusb_init, libusb_set_debug, libusb_open_device_with_vid_pid, libusb_get_device, libusb_get_device_descriptor, libusb_kernel_driver_active, libusb_detach_kernel_driver, libusb_claim_interface, libusb_error_name, libusb_alloc_transfer, libusb_fill_bulk_transfer, libusb_submit_transfer, libusb_cancel_transfer, libusb_handle_events_completed, libusb_handle_events_timeout_completed, libusb_free_transfer, libusb_release_interface, libusb_close, libusb_exit, libusb_reset_device
import .LIBUSB: LibusbContext, LibusbDeviceDescriptor, LibusbTransfer, Ctimeval # Ptr
import .LIBUSB: LIBUSB_LOG_LEVEL_DEBUG, LIBUSB_SUCCESS, LIBUSB_TRANSFER_COMPLETED

const ABLETON_VENDOR_ID = 0x2982
const PUSH2_PRODUCT_ID  = 0x1967

ctx = Ptr{LibusbContext}(C_NULL)
init_result = libusb_init(Ptr{Ptr{LibusbContext}}(ctx))
# libusb_set_debug(ctx, LIBUSB_LOG_LEVEL_DEBUG)
device_handle = libusb_open_device_with_vid_pid(ctx, ABLETON_VENDOR_ID, PUSH2_PRODUCT_ID)
if C_NULL == device_handle
    @error :libusb_open_device_with_vid_pid "could not found ableton push 2"
    exit(1)
end
device = libusb_get_device(device_handle)
descriptor = Ref{Ptr{LibusbDeviceDescriptor}}()
libusb_get_device_descriptor(device, descriptor)
# @info :descriptor_bDeviceClass descriptor[].bDeviceClass # 0 LIBUSB_CLASS_PER_INTERFACE
# @info :descriptor_idVendor     descriptor[].idVendor
# @info :descriptor_idProduct    descriptor[].idProduct

interface_number = Cint(0)

# 0 no kernel driver is active
# 1 if a kernel driver is active
kernel_driver_is_active = libusb_kernel_driver_active(device_handle, interface_number) == 1
if kernel_driver_is_active
    detach_result = libusb_detach_kernel_driver(device_handle, interface_number)
    @info :detach_result detach_result
end

claim_result = libusb_claim_interface(device_handle, interface_number)
if claim_result != LIBUSB_SUCCESS
    @info :claim_result libusb_error_name(claim_result)
end

frame_header = [
  0xff, 0xcc, 0xaa, 0x88,
  0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00]

const PUSH2_BULK_EP_OUT = Cuchar(0x01)
const TRANSFER_TIMEOUT  = Cuint(1000) # milliseconds

function libusb_frame_header_transfer_cb(transfer::Ptr{LibusbTransfer})
end
libusb_frame_header_transfer_callback = @cfunction libusb_frame_header_transfer_cb Cvoid (Ptr{LibusbTransfer},)

function on_transfer_finished
end

function libusb_pixel_data_transfer_cb(transfer::Ptr{LibusbTransfer})
    t = unsafe_load(transfer)
    if t.status != LIBUSB_TRANSFER_COMPLETED
    elseif t.length != t.actual_length
    else
        # @info :libusb_pixel_data_transfer_cb transfer
        on_transfer_finished(transfer)
    end
    nothing
end
libusb_pixel_data_transfer_callback = @cfunction libusb_pixel_data_transfer_cb Cvoid (Ptr{LibusbTransfer},)

iso_packets = Cint(0)
frame_header_transfer = libusb_alloc_transfer(iso_packets)
    libusb_fill_bulk_transfer(
        frame_header_transfer,
        device_handle,
        PUSH2_BULK_EP_OUT,
        pointer(frame_header),
        length(frame_header),
        libusb_frame_header_transfer_callback,
        C_NULL,
        TRANSFER_TIMEOUT)

    iso_packets = Cint(0)
    pixel_data_transfer = libusb_alloc_transfer(iso_packets)

function submit_buffers(row_idx, buffer)
    if 1 == row_idx
        frame_header_transfer_result = libusb_submit_transfer(frame_header_transfer)
        if frame_header_transfer_result != LIBUSB_SUCCESS
            @info :frame_header_transfer_result frame_header_transfer_result
        end
    end

    libusb_fill_bulk_transfer(
        pixel_data_transfer,
        device_handle,
        PUSH2_BULK_EP_OUT,
        pointer(buffer),
        length(buffer),
        libusb_pixel_data_transfer_callback,
        C_NULL,
        TRANSFER_TIMEOUT);
    pixel_data_transfer_result = libusb_submit_transfer(pixel_data_transfer)
    if pixel_data_transfer_result != LIBUSB_SUCCESS
        @info :pixel_data_transfer_result pixel_data_transfer_result
    end
end

function close_device()
    libusb_cancel_transfer(frame_header_transfer)
    libusb_cancel_transfer(pixel_data_transfer)
    libusb_free_transfer(frame_header_transfer)
    libusb_free_transfer(pixel_data_transfer)
    libusb_release_interface(device_handle, interface_number)
    libusb_reset_device(device_handle)
    C_NULL != ctx && libusb_close(device_handle)
    libusb_exit(ctx)
end

const counting_the_callback_to_close = true
const callback_count_limit = 5
callback_count = 1
function periodic_callback(timer)
    completed = Ptr{Cint}(C_NULL)
    tv = Ref(Ctimeval(0, 500000))
    events_completed_result = libusb_handle_events_timeout_completed(ctx, tv, completed)
    if events_completed_result != LIBUSB_SUCCESS
        @info :events_completed_result events_completed_result completed
    end
    if counting_the_callback_to_close
        global callback_count
        if callback_count_limit < callback_count
            # @info :close_timer
            close(timer)
            close_device()
        end
        callback_count += 1
    end
end

import .DisplayInterface: Canvas, fill!, draw!
import .DisplayInterface: framebuffer
import .DisplayInterface: DisplayPixelHeight, LineCountPerSendBuffer, SendBufferSize
import Colors: @colorant_str
using Pkg

path = joinpath(Pkg.dir("PushInterface"), "examples/pushinterface/usb", "logo.png")

canvas = Canvas()
fill!(canvas, colorant"white") # @colorant_str
draw!(canvas, path)

const buf = framebuffer(canvas)
row_idx = 1

const line_count = Int(DisplayPixelHeight/LineCountPerSendBuffer)
function on_transfer_finished(transfer)
    global row_idx
    buffer = buf[SendBufferSize*(row_idx-1)+1:SendBufferSize*row_idx]
    submit_buffers(row_idx, buffer)
    if row_idx == line_count
        row_idx = 1
    else
        row_idx +=1
    end
end

on_transfer_finished(nothing)

t = Timer(periodic_callback, 0, interval = 0.5) # Timer(callback::Function, delay; interval)
finalizer(t) do timer
end


text:
using Revise

using MeshCat
using RigidBodyDynamics
const rbd = RigidBodyDynamics

using Colors: @colorant_str
using MeshCatMechanisms: MechanismVisualizer, URDFVisuals
using LearningMPC: mechanism, environment, LQRSolution, MPCParams
using LearningMPC.Models: BoxAtlas
using LCMCore: LCM, subscribe, handle, set_queue_capacity, publish
using BotCoreLCMTypes: robot_state_t
using DrakeLCMTypes: whole_body_data_t, piecewise_polynomial_t, qp_controller_input_t
using LCMPolynomials: cubic_spline
using BoxAtlasControl: BoxAtlasStateTranslator, OneStepSimulator, LIPM_zmp_data, body_motion_data, foot_support_data
using StaticArrays: SVector
using MAT: matopen
using AtlasRobot

draw_velocity!(mvis::MechanismVisualizer, state::MechanismState, name::AbstractString) =
    draw_velocity!(mvis, state, findbody(state.mechanism, name))

function draw_velocity!(mvis::MechanismVisualizer, state::MechanismState, body::RigidBody)
    vis = mvis.visualizer["velocities"][string(body)]
    pose = transform_to_root(state, body)
    twist = twist_wrt_world(state, body)
    setobject!(vis, LineSegments(PointCloud([translation(pose), translation(pose) + linear(twist)]),
                                 MeshCat.LineBasicMaterial(color=colorant"red")))
end

robot = BoxAtlas()
translator = BoxAtlasStateTranslator(robot)

vis = Visualizer()
mvis = MechanismVisualizer(robot, vis[:boxatlas])
open(mvis)
wait(mvis)

mpc_params = LearningMPC.MPCParams(robot)
mpc_params.horizon = 1
mpc_params.Δt = 0.01
lqrsol = LearningMPC.LQRSolution(robot, mpc_params)

vis_handler = function(state)
    set_configuration!(mvis, configuration(state))
    for body in values(translator.bodies)
        draw_velocity!.(mvis, state, body)
    end
    state
end

sim = OneStepSimulator(translator, lqrsol, mpc_params.Δt, mpc_params.lcp_solver)

function qp_input_generator(state, splines, timestamp=0)
    msg = qp_controller_input_t()
    msg.timestamp = timestamp
    msg.be_silent = false
    msg.zmp_data = LIPM_zmp_data(SVector(0., 0, 0, 0), SVector(0., 0))
    msg.num_support_data = 2
    msg.support_data = [
        foot_support_data("r_foot"),
        foot_support_data("l_foot")
    ]

    now = timestamp / 1e6

    msg.num_tracked_bodies = length(splines)
    msg.body_motion_data = [body_motion_data(string(body), spline) for (body, spline) in splines]

    msg.num_external_wrenches = 0

    fname = joinpath(@__DIR__, "data", "atlas_fp.mat")
    fp_file = matopen(fname)
    xstar = try
        read(fp_file, "xstar")
    finally
        close(fp_file)
    end
    qstar = xstar[1:36]
    q_spline = [cubic_spline(SVector(now, now + 1), SVector(qi, qi), SVector(0., 0)) for qi in qstar]
    msg.whole_body_data = whole_body_data_t(
        timestamp,
        36,
        qstar,
        piecewise_polynomial_t(q_spline),
        17,
        [10, 17, 18, 19, 20, 21, 22, 23, 30, 31, 32, 33, 34, 35, 36, 8, 7]
    )

    msg.num_joint_pd_overrides = 0
    msg.param_set_name = "standing"
    msg.torque_alpha_filter = 0
    msg
end

lcm = LCM()

function handle_box_atlas_state(channel, msg::robot_state_t)
    state = translator(msg)
    vis_handler(state)
    splines = sim(state)
    qp_input_msg = qp_input_generator(state, splines, msg.utime)
    publish(lcm, "QP_CONTROLLER_INPUT", qp_input_msg)
end

sub = subscribe(lcm, "BOX_ATLAS_STATE", handle_box_atlas_state, robot_state_t)
set_queue_capacity(sub, 1)

atlas = AtlasRobot.mechanism()
atlas_vis = MechanismVisualizer(atlas, URDFVisuals(AtlasRobot.urdfpath(), package_path=[AtlasRobot.packagepath()]), vis[:atlas])

using HumanoidLCMSim.AtlasSim: atlasrobotinfo
using HumanoidLCMSim: set!

atlas_info = atlasrobotinfo(atlas)
atlas_state = MechanismState(atlas)

function handle_atlas_state(channel, msg::robot_state_t)
    set!(atlas_state, msg, atlas_info)
    set_configuration!(atlas_vis, configuration(atlas_state))
end

sub = subscribe(lcm, "EST_ROBOT_STATE", handle_atlas_state, robot_state_t)
set_queue_capacity(sub, 1)

finished = Ref(false)

@async begin
    while !finished[]
        handle(lcm)
    end
end


text:
include("grammartests.jl")
include("productiontests.jl")
include("transitiontests.jl")
include("automatontests.jl")
include("itemtests.jl")
include("derivationtests.jl")

rungrammartests()
runproductiontests()
runautomatontests()
runtransitiontests()
runderivationtests()
runitemtests()


text:
# automatically generated by the FlatBuffers compiler, do not modify

UnionVector.eval(quote

FlatBuffers.@with_kw mutable struct Movie
    main_character_type::UInt8 = 0
    main_character::Character = nothing
    characters_type::Vector{UInt8} = []
    characters::Vector{Character} = []
end
FlatBuffers.@ALIGN(Movie, 1)
FlatBuffers.slot_offsets(::Type{T}) where {T<:Movie} = [
    0x00000004, 0x00000006, 0x00000008, 0x0000000A
]
FlatBuffers.root_type(::Type{T}) where {T<:Movie} = true
FlatBuffers.file_identifier(::Type{T}) where {T<:Movie} = "MOVI"

Movie(buf::AbstractVector{UInt8}) = FlatBuffers.read(Movie, buf)
Movie(io::IO) = FlatBuffers.deserialize(io, Movie)

end)

max_stars_repo_name: rjkat/flatbuffers-julia

max_issues_repo_name: rjkat/flatbuffers-julia

max_forks_repo_name: rjkat/flatbuffers-julia


text:
function isalphabet(c)
    return 'a' <= c <= 'z' || 'A' <= c <= 'Z'
end
counts = Dict(zip('a':'z', zeros(Int, 26)))

strs = readlines()
for str in strs
    for c in str
        if isalphabet(c)
            counts[lowercase(c)] += 1
        end
    end
end

for c in 'a':'z'
    println(c, " : ", counts[c])
end


text:
"""
    Mesh

Struct containing frequency meshes for the self energy, vertices and correlations.
* `num_σ :: Int64`           : total number of frequencies in the self energy mesh
* `num_Ω :: Int64`           : total number of frequencies in the bosonic meshes
* `num_ν :: Int64`           : total number of frequencies in the fermionic meshes
* `num_χ :: Int64`           : total number of frequencies in the correlation mesh
* `σ     :: Vector{Float64}` : self energy mesh
* `Ωs    :: Vector{Float64}` : bosonic mesh for the s (u) channel
* `νs    :: Vector{Float64}` : fermionic mesh for the s (u) channel
* `Ωt    :: Vector{Float64}` : bosonic mesh for the t channel
* `νt    :: Vector{Float64}` : fermionic mesh for the t channel
* `χ     :: Vector{Float64}` : correlation mesh
"""
struct Mesh
    num_σ :: Int64
    num_Ω :: Int64
    num_ν :: Int64
    num_χ :: Int64
    σ     :: Vector{Float64}
    Ωs    :: Vector{Float64}
    νs    :: Vector{Float64}
    Ωt    :: Vector{Float64}
    νt    :: Vector{Float64}
    χ     :: Vector{Float64}
end

# auxiliary function to fetch frequency arguments for a specific channel and kernel
function get_kernel_args(
    ch     :: Int64,
    kernel :: Int64,
    w1     :: Int64,
    w2     :: Int64,
    w3     :: Int64,
    m      :: Mesh
    )      :: NTuple{3, Float64}

    # fetch arguments for s channel
    if ch == 1
        if kernel == 1
            return m.Ωs[w1], Inf, Inf
        elseif kernel == 2
            return m.Ωs[w1], m.νs[w2], Inf
        elseif kernel == 3
            return m.Ωs[w1], Inf, m.νs[w3]
        else
            return m.Ωs[w1], m.νs[w2], m.νs[w3]
        end
    # fetch arguments for t channel
    elseif ch == 2
        if kernel == 1
            return m.Ωt[w1], Inf, Inf
        elseif kernel == 2
            return m.Ωt[w1], m.νt[w2], Inf
        elseif kernel == 3
            return m.Ωt[w1], Inf, m.νt[w3]
        else
            return m.Ωt[w1], m.νt[w2], m.νt[w3]
        end
    # fetch arguments for u channel
    else
        if kernel == 1
            return m.Ωs[w1], Inf, Inf
        elseif kernel == 2
            return m.Ωs[w1], m.νs[w2], Inf
        elseif kernel == 3
            return m.Ωs[w1], Inf, m.νs[w3]
        else
            return m.Ωs[w1], m.νs[w2], m.νs[w3]
        end
    end
end

"""
    get_mesh(
        linear :: Float64,
        upper  :: Float64,
        num    :: Int64,
        p      :: Float64
        )      :: Vector{Float64}

Generate a mesh of (num + 1) linearly (0.0 to linear) and logarithmically (linear to upper) spaced frequencies.
Thereby linear and upper are explicitly included and p * num frequencies of the grid are devoted to the linear part.
"""
function get_mesh(
    linear :: Float64,
    upper  :: Float64,
    num    :: Int64,
    p      :: Float64
    )      :: Vector{Float64}

    # sanity checks
    @assert linear > 0.0 "Linear bound must be larger than zero."
    @assert upper > 0.0 "Upper bound must be larger than zero."
    @assert linear < upper "Linear bound must be smaller than upper bound."

    # compute number of linear and logarithmic points
    num_lin = ceil(Int64, p * num)
    num_log = num - num_lin

    # sanity check
    @assert num_log > 0 "Number of frequencies is too small."

    # determine linear width and logarithmic factor
    h = linear / num_lin
    ξ = (upper / linear)^(1.0 / num_log)

    # allocate list
    mesh = zeros(Float64, num + 1)

    # compute frequencies
    for i in 1 : num_lin
        mesh[i + 1] = i * h
    end

    for i in 1 : num_log
        mesh[num_lin + 1 + i] = ξ^i * linear
    end

    return mesh
end


text:
include("Packages.jl") #import the packages
##################################################
include("Args.jl") # Parsing the command-line
##################################################
# General parameters
##################################################
"""
    PARALLEL

Determining if the code is run in parallel.
"""
const PARALLEL = parsed_args["parallel"]
if ((PARALLEL != "yes") && (PARALLEL != "no"))
    error("ERROR: UNKNOWN PARALLEL") # Unknown parallel procedure
end

"""
    lmax

Maximum harmonic number used in the multipole expansion of DRRjj.
"""
const lmax = parsed_args["lmax"]

"""
    nbK

Number of sampling points for geometric factor Klnnp.
"""
const nbK = parsed_args["nbK"]

"""
    nbResPoints

Number of points on the resonance lines.
"""
const nbResPoints = parsed_args["nbResPoints"]

"""
    mBH

Mass of the central BH, in solar masses (MSun).
"""
const mBH = parsed_args["mBH"]

"""
    rh

Influence radius of the BH, in milliparsecs (mpc).
We do not compute any resonance lines beyond that point.
"""
const rh = parsed_args["rh"]

"""
    INPUTBATH

Name of the input file for the bath.
"""
const INPUTBATH = parsed_args["inputBath"]

"""
    INPUTCLUSTER

Name of the input file for the S-Cluster.
"""
const INPUTCLUSTER = parsed_args["inputCluster"]

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

include("Constants.jl") # Physical constants
include("Bath.jl") # Definition of the background bath
include("Mean.jl") # Mean quantities of the model
include("Cluster.jl") # Definition of the cluster stars
include("IntTable.jl") # Definition of the structure used for the computation of integrals K, dK
include("Klnnp.jl") # Computation of the Klnnp coefficients
include("ResonanceLines.jl") # Construction of the resonant lines
include("SRR.jl") # Computation of the SRR diffusion coefficients
include("NR.jl") # Computation of the NR diffusion coefficients
include("DJ.jl") # Computation of diffusion coefficient DRR_j (and DRR_jj in parallel)


text:
using SnoopCompile
using Test

push!(LOAD_PATH, joinpath(@__DIR__, "testmodules"))
using A
using E
using FuncKinds
using Reachable.ModuleA
using Reachable.ModuleB
using Reachable2
pop!(LOAD_PATH)

@testset "topmodule" begin
    # topmod is called on moduleroots but nevertheless this is a useful test
    @test SnoopCompile.topmodule([A, A.B]) === A
    @test SnoopCompile.topmodule([A, A.B.C]) === A
    @test SnoopCompile.topmodule([A.B, A]) === A
    @test SnoopCompile.topmodule([A.B.C, A]) === A
    @test SnoopCompile.topmodule([A.B.C, A.B.D]) === nothing
    @test SnoopCompile.topmodule([A, Base]) === A
    @test SnoopCompile.topmodule([Base, A]) === A
end

module Lookup
f1(x, y; a=1) = error("oops")
f2(f::Function, args...; kwargs...) = f1(args...; kwargs...)
end

@testset "lookup bodyfunction" begin
    Core.eval(Lookup, SnoopCompile.lookup_kwbody_ex)
    m = first(methods(Lookup.f1))
    f = Lookup.__lookup_kwbody__(m)
    @test occursin("f1#", String(nameof(f)))
    m = first(methods(Lookup.f2))
    f = Lookup.__lookup_kwbody__(m)
    isdefined(Core, :_apply_iterate) && @test f !== Core._apply_iterate
    @test f !== Core._apply
    @test occursin("f2#", String(nameof(f)))
end

uncompiled(x) = x + 1

@testset "snoopi" begin
    tinf = @snoopi uncompiled(2)
    @test any(td->td[2].def.name == :uncompiled, tinf)
    # Ensure older methods can be tested
    a = rand(Float16, 5)
    tinf = @snoopi sum(a)
    @test any(td->td[2].def.name == :sum, tinf)

    a = [E.ET(1)]
    c = [A.B.C.CT(1)]
    tinf = @snoopi (A.f(a); A.f(c))
    @test length(tinf) == 2

    pc = SnoopCompile.parcel(tinf)
    @test isa(pc, Dict)
    @test length(pc) == 1
    @test length(pc[:A]) == 1
    directive = pc[:A][1]
    @test occursin("C.CT", directive)
    @test !occursin("E.ET", directive)

    # Identify kwfuncs, whose naming depends on the Julia version (issue #46)
    # Also check for kw body functions (also tested below)
    tinf = @snoopi sortperm(rand(5); rev=true)
    pc = SnoopCompile.parcel(tinf)
    FK = pc[:Base]
    @test any(str->occursin("kwftype", str), FK)
    if VERSION >= v"1.4.0-DEV.215"
        @test any(str->occursin("__lookup_kwbody__", str), FK)
    else
        @test any(str->occursin("isdefined", str), FK)
    end

    # Keyword body functions
    tinf = @snoopi FuncKinds.callhaskw()
    pc = SnoopCompile.parcel(tinf)
    FK = pc[:FuncKinds]
    @test any(str->occursin("kwftype", str), FK)
    @test any(str->occursin("precompile(Tuple{typeof(FuncKinds.haskw),", str), FK)
    if VERSION >= v"1.4.0-DEV.215"
        @test any(str->occursin("let", str), FK)
        @test !any(str->occursin("isdefined", str), FK)
    else
        @test any(str->occursin("isdefined", str), FK)
    end

    # Wrap anonymous functions in an `if isdefined`
    list = Any["xbar7", "yfoo8"]
    tinf = @snoopi FuncKinds.hasfoo(list)
    pc = SnoopCompile.parcel(tinf)
    @test any(str->occursin("isdefined", str), pc[:FuncKinds])

    # Extract the generator in a name-independent manner
    tinf = @snoopi begin
        FuncKinds.gen(1.0f0)
        FuncKinds.gen2(3, 1.1)
        FuncKinds.genkw1()
        FuncKinds.genkw2(; b="hello")
    end
    pc = SnoopCompile.parcel(tinf)
    FK = pc[:FuncKinds]
    @test any(str->occursin("precompile(Tuple{typeof(FuncKinds.gen),Float32})", str), FK)
    @test any(str->occursin("precompile(Tuple{typeof(FuncKinds.gen2),$Int,Float64})", str), FK)
    @test any(str->occursin("typeof(which(FuncKinds.gen2,($Int,Any,)).generator.gen)", str), FK)
    @test any(str->occursin("precompile(Tuple{typeof(FuncKinds.genkw1)})", str), FK)
    @test !any(str->occursin("precompile(Tuple{typeof(FuncKinds.genkw2)})", str), FK)
    @test any(str->occursin("Tuple{Core.kwftype(typeof(FuncKinds.genkw2)),NamedTuple{(:b,),Tuple{String}},typeof(FuncKinds.genkw2)}", str), FK)
    if VERSION >=  v"1.4.0-DEV.215"
        @test any(str->occursin("__lookup_kwbody__(which(FuncKinds.genkw1, ()))", str), FK)
        @test any(str->occursin("__lookup_kwbody__(which(FuncKinds.genkw2, ()))", str), FK)
    else
        @test any(str->occursin("isdefined", str), FK)
    end

    # Inner functions
    tinf = @snoopi FuncKinds.hasinner(1, 2)
    pc = SnoopCompile.parcel(tinf)
    FK = pc[:FuncKinds]
    @test any(str->match(r"isdefined.*#inner#", str) !== nothing, FK)

    # blacklist_remover
    blacklist = ["hi", "bye"]
    pcI = ["good", "bad", "hi", "bye", "no"]
    @test SnoopCompile.blacklist_remover!(pcI, blacklist) == ["good", "bad", "no"]
end

@testset "Lots of methods" begin
    # Tests functions from JuliaInterpreter/test/toplevel_script.jl and LoweredCodeUtils
    tinf = @snoopi begin
        FuncKinds.f1(0)
        FuncKinds.f1(0.0)
        FuncKinds.f1(0.0f0)
        FuncKinds.f2("hi")
        FuncKinds.f2(UInt16(1))
        FuncKinds.f2(3.2)
        FuncKinds.f2(view([1,2], 1:1))
        FuncKinds.f2([1,2])
        FuncKinds.f2(reshape(view([1,2], 1:2), 2, 1))
        FuncKinds.f3(1, 1)
        FuncKinds.f3(1, :hi)
        FuncKinds.f3(UInt16(1), :hi)
        FuncKinds.f3(rand(2, 2), :hi, :there)
        FuncKinds.f4(1, 1)
        FuncKinds.f4(1)
        FuncKinds.f4(UInt(1), "hey", 2)
        FuncKinds.f4(rand(2,2))
        FuncKinds.f5(Int8(1); y=22)
        FuncKinds.f5(Int16(1))
        FuncKinds.f5(Int32(1))
        FuncKinds.f5(rand(2,2); y=7)
        FuncKinds.f6(1; z=8)
    end
    pc = SnoopCompile.parcel(tinf)
    FK = pc[:FuncKinds]
    @test any(str->occursin("typeof(FuncKinds.f1),Int", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f1),Float64", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f1),Float32", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f2),String", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f2),UInt16", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f2),Float64", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f2),$(typeof(view([1,2], 1:1)))", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f2),Array{$Int,1}", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f2),$(typeof(reshape(view([1,2], 1:2), 2, 1)))", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f3),$Int,$Int", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f3),$Int,Symbol", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f3),UInt16,Symbol", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f3),Array{Float64,2},Symbol,Symbol", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f4),$Int,$Int", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f4),$UInt,String", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f4),Array{Float64,2}", str), FK)
    @test any(str->occursin(r"kwftype\(typeof\(FuncKinds.f5.*:y.*Int8", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f5),Int16", str), FK)
    @test any(str->occursin("typeof(FuncKinds.f5),Int32", str), FK)
    @test any(str->occursin(r"kwftype\(typeof\(FuncKinds.f5.*:y.*Array\{Float64,2\}", str), FK)
    # @test any(str->occursin("typeof(FuncKinds.f6),(1, "hi"; z=8) == 1
    # @test any(str->occursin("typeof(FuncKinds.f7),(1, (1, :hi)) == 1
    # @test any(str->occursin("typeof(FuncKinds.f8),(0) == 1
    # @test any(str->occursin("typeof(FuncKinds.f9),(3) == 9
    # @test any(str->occursin("typeof(FuncKinds.f9),(3.0) == 3.0

end

# Issue https://github.com/timholy/SnoopCompile.jl/issues/40#issuecomment-570560584
@testset "Reachable" begin
    tinf = @snoopi begin
        include("snoopreachable.jl")
    end
    pc = SnoopCompile.parcel(tinf)
    pcd = pc[:Reachable]
    @test length(pcd) == 2
    @test sum(str->occursin("RchA", str), pcd) == 2
    # Make sure that two modues that know about each other only via Main do not allow precompilation
    @test !any(str->occursin("ModuleB.f", str), pcd)
    pcd = pc[:Reachable2]
    @test length(pcd) == 1
end

@testset "@snoopi docs" begin
    # docstring is present (weird Docs bug)
    dct = Docs.meta(SnoopCompile)
    @test haskey(dct, Docs.Binding(SnoopCompile, Symbol("@snoopi")))
end

@testset "Duplicates (#70)" begin
    tinf = @snoopi begin
        function eval_local_function(i)
            @eval generated() = $i
            return Base.invokelatest(generated)
        end
        eval_local_function(1)
        eval_local_function(2)
        eval_local_function(3)
    end
    pc = SnoopCompile.parcel(tinf)
    @test count(isequal("precompile(Tuple{typeof(generated)})"), pc[:Main]) == 1
end


text:
struct GPUCodeGen
    buf_var_name::Symbol
end

function gpu_buffer_expr(var, buffer_var, sz_ex)
    gpu_sz_ex = matchingex(:(zeros(_...)), sz_ex) ? :(GPUArray($sz_ex)) : sz_ex
    return :($var = @get_or_create $buffer_var $(Expr(:quote, var)) $gpu_sz_ex)
end


text:
using KMLPolynetTools
using Meshes
using Test

@testset "KMLPolynetTools.jl" begin
    @test KMLPolynetTools.remove_repeats([1,2,3,4,4,4,5,6,6,7,8,8,1]) == [1,2,3,4,5,6,7,8,1]
    @test sort(KMLPolynetTools.split_at_intersections([1,2,3,4,5,6,7,2,8,1]), lt=(a,b)->length(a)<length(b)) == [[1,2,8,1],[2,3,4,5,6,7,2]]
    @test sort(KMLPolynetTools.split_at_intersections([1,2,3,4,5,13,6,7,4,8,9,10,4,11,12,1]), lt=(a,b)->length(a)<length(b)) == [[4,8,9,10,4], [4,5,13,6,7,4], [1,2,3,4,11,12,1]]
    @test KMLPolynetTools.txtPoint2("1.2,3.2") == Point(1.2, 3.2)
end


text:
# Parameters:
#	N::Int
#	- the problem size
#	PA::Array{Array{Int, 1}, 1}
#	- PA[i] is a Permutation of N
#	VA::Array{Float64, 1}
#	- VA[i] is the Value associated with PA[i]
# Return Values:
#	SNF::Array{Float64, 1}
#	- SNF[i] is the value associated with the permutation that permutation_index() maps to i
#	- this is the format for the SNF parameter of sn_fft()
# Notes:
#	- any permutation of N not represented in PA will be assigned a value of zero
function snf(N::Int, PA::Array{Array{Int, 1}, 1}, VA::Array{Float64, 1})
	SNF = zeros(Float64, factorial(N))
	for i = 1:length(PA)
		Permutation = PA[i]
		Index = permutation_index(Permutation)
		SNF[Index] = VA[i]
	end
	return SNF
end

# Parameters:
#	N::Int
#	- the problem size
#	K::Int
#	- the problem is homogenous at N-K
#	PA::Array{Array{Int, 1}, 1}
#	- PA[i] is a Permutation of N
#	VA::Array{Float64, 1}
#	- VA[i] is the Value associated with PA[i]
# Return Values:
#	SNF::Array{Float64, 1}
#	- SNF[i] is the value associated with all of the permutations that permutation_index() maps to any value in the range ((i - 1) * factorial(N - K) + 1):(i * factorial(N - K))
#	- this is the format for the SNF parameter of sn_fft_bl()
# Notes:
#	- any homogenous coset that doesn't have a representative permutation in PA will be assigned a value of zero
function snf_bl(N::Int, K::Int, PA::Array{Array{Int, 1}, 1}, VA::Array{Float64, 1})
	N_F = factorial(N)
	BS = factorial(N - K)
	SNF = zeros(Float64, round(Int, N_F / BS))
	for i = 1:length(PA)
		Permutation = PA[i]
		Index = permutation_index(P)
		Index = ceil(Index / BS)
		SNF[Index] = VA[i]
	end
	return SNF
end

# Parameters:
#	N::Int
#	- the problem size
#	PA::Array{Array{Int, 1}, 1}
#	- PA[i] is a Permutation of N
#	VA::Array{Float64, 1}
#	- VA[i] is the Value associated with PA[i]
# Return Values:
#	SNF::Array{Float64, 1}
#	- SNF[i] is the value associated with the permutation that permutation_index() maps to NZL[i]
#	- this is the format for the SNF parameter of sn_fft_sp()
#	NZL::Array{Int, 1}
#	- NZL must in increasing order
#	- this is the format for the NZL parameter of sn_fft_sp()
# Notes:
#	- the values in VA should be non-zero
function snf_sp(N::Int, PA::Array{Array{Int, 1}, 1}, VA::Array{Float64, 1})
	L = length(PA)
	SNF = Array(Float64, L)
	NZL = Array(Int, L)
	SNF[1] = VA[1]
	NZL[1] = permutation_index(PA[1])
	for i = 2:L
		val = VA[i]
		index = permutation_index(PA[i])
		j = 1
		while j <= (i - 1)
			if index < NZL[j]
				break
			end
			j += 1
		end
		for k = i:-1:(j + 1)
			SNF[k] = SNF[k - 1]
			NZL[k] = NZL[k - 1]
		end
		SNF[j] = val
		NZL[j] = index
	end
	return SNF, NZL
end


text:
#######################################################################

# print to stderr, since that is where Pkg prints its messages
eprintln(x...) = println(STDERR, x...)

# creating `GeoEfficiency` folder at the home directory.
println("INFO: Creating 'GeoEfficiency' folder at '$(homedir())'.....")
try
	cp(joinpath(Pkg.dir("GeoEfficiency"),".batch"), joinpath(homedir(),"GeoEfficiency"))

catch
	if isdir(joinpath(homedir(),"GeoEfficiency"))
		warn("'GeoEfficiency' folder allready exist.")
	else
		warn("'GeoEfficiency' folder: could not be created.")
	end
end


text:
function FNA2_kappa_lambda(platform, N, M, threshold; options...)
    # Computation of the Gram matrix may be expensive: check if it was passed as an argument
    if haskey(options, :G_N)
        G_N = options[:G_N]
    else
        G_N = matrix(discretization(platform, N, samplingstyle=GramStyle(); options...))
    end

    G_MN = solver(platform, N, samplingstyle=OversamplingStyle(), M=M, solverstyle=DirectStyle(), directsolver=:svd, options...)
    U = G_MN.solver.U
    S = G_MN.solver.S
    V = collect(G_MN.solver.V)
    I = findlast(S .>= threshold)
    U_reg = U[:,1:I]
    V_reg = V[:,1:I]
    S_reg = S[1:I]

    # Computation of kappa
    B_MN = V_reg * inv(Diagonal(S_reg)) * U_reg'
    Q = svdvals(B_MN' * G_N * B_MN)
    kappa = sqrt(Q[1])

    # Computation of lambda
    V_eps = V[:,I+1:end]
    C_MN = V_eps * V_eps'
    Q2 = svdvals(C_MN' * G_N * C_MN)
    lambda = sqrt(Q2[1])/threshold

    kappa, lambda
end


text:
#
# Mapping with integer indexes.
#

MappingQuery(idom, oty, col::Column) =
    Query(
        MappingSig(col),
        Input(convert(Domain, idom)),
        convert(Output, oty))

MappingQuery(idom, oty, offs::AbstractVector{Int}, vals::AbstractVector) =
    MappingQuery(idom, oty, Column(offs, vals))

MappingQuery{T}(idom, oty, data::AbstractVector{Vector{T}}) =
    MappingQuery(idom, convert(Output, oty) |> setoptional() |> setplural(), Column(data))

MappingQuery{T}(idom, oty, data::AbstractVector{Nullable{T}}) =
    MappingQuery(idom, convert(Output, oty) |> setoptional, Column(data))

MappingQuery(idom, oty, data::AbstractVector) =
    MappingQuery(idom, oty, Column(data))

MappingQuery{T}(idom, data::AbstractVector{Vector{T}}) =
    MappingQuery(idom, T, data)

MappingQuery{T}(idom, data::AbstractVector{Nullable{T}}) =
    MappingQuery(idom, T, data)

MappingQuery{T}(idom, data::AbstractVector{T}) =
    MappingQuery(idom, T, data)

MappingQuery(data::AbstractVector) =
    MappingQuery(Int, data)

immutable MappingSig <: AbstractPrimitive
    col::Column
end

ev(sig::MappingSig, idxs::AbstractVector) =
    sig.col[idxs]

max_stars_repo_name: rbt-lang/rbt-proto

max_issues_repo_name: rbt-lang/rbt-proto

max_forks_repo_name: rbt-lang/rbt-proto


text:
# Copyright (c) 2018: Matthew Wilhelm & Matthew Stuber.
# This code is licensed under MIT license (see LICENSE.md for full details)
#############################################################################
# ReverseMcCormick.jl
# A Reverse McCormick operator library in Julia
# See https://github.com/PSORLab/ReverseMcCormick.jl
#############################################################################
# src/reverse_operators/hyperbolic.jl
# Contains definitions of reverse McCormick operators of sinh, cosh, tanh,
# sech, csch, coth
#############################################################################

"""
$(SIGNATURES)

Reverse McCormick operator for `sinh`.
"""
function sinh_rev(y::MC, x::MC)
    isempty(y) && (return y, y)
    x = x ∩ asinh(y)
    y, x
end

"""
$(SIGNATURES)

Reverse McCormick operator for `cosh`.
"""
function cosh_rev(y::MC, x::MC)
    isempty(y) && (return y, y)
    y = y ∩ Interval{Float64}(1.0, Inf)
    x = x ∩ acosh(y)
    y, x
end

"""
$(SIGNATURES)

Reverse McCormick operator for `tanh`.
"""
function tanh_rev(y::MC, x::MC)
    isempty(y) && (return y, y)
    y = y ∩ Interval{Float64}(-1.0, 1.0)
    x = x ∩ atanh(y)
    y, x
end

"""
$(SIGNATURES)

Reverse McCormick operator for `sech`.
"""
function sech_rev(y::MC, x::MC)
    isempty(y) && (return y, y)
    y = y ∩ Interval{Float64}(0.0, 1.0)
    x = x ∩ asech(y)
    y, x
end

"""
$(SIGNATURES)

Reverse McCormick operator for `csch`.
"""
function csch_rev(y::MC, x::MC)
    isempty(y) && (return y, y)
    x = x ∩ acsch(y)
    y, x
end

"""
$(SIGNATURES)

Reverse McCormick operator for `coth`.
"""
function coth_rev(y::MC, x::MC)
    isempty(y) && (return y, y)
    x = x ∩ coth(y)
    y, x
end


text:
# need better dispatch in arg

function ss2float(ss::Array{Any})

    # the rows is simply the length of the array of arrays
    # the cols are elements in each array

    b = zeros(length(ss),length(ss[1]))

    for r in 1:size(b,1)
        for c in 1:size(b,2)
            if ~isempty(ss[r][c])
                b[r,c] = parsefloat(ss[r][c])
            else
                b[r,c] = NaN
            end
        end
    end

    return b
end


text:
using MyPkg
using Test

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


text:
# implementation/recursive.jl
#
# Implements a recursive divide and conquer approach to divide the problem into
# smaller subproblems by dividing those dimensions that lead to the largest
# jumps in memory. When the total length of the subproblem fits into BASELENGTH,
# the subproblem is handled by the kernels.

const BASELENGTH=2048

@generated function add_rec!{N}(α, A::StridedData{N}, β, C::StridedData{N}, dims::NTuple{N, Int}, offsetA::Int, offsetC::Int, minstrides::NTuple{N, Int})
    quote
        if 2*prod(dims) <= BASELENGTH
            add_micro!(α, A, β, C, dims, offsetA, offsetC)
        else
            dmax = _indmax(_memjumps(dims, minstrides))
            @dividebody $N dmax dims offsetA A offsetC C begin
                add_rec!(α, A, β, C, dims, offsetA, offsetC, minstrides)
            end begin
                add_rec!(α, A, β, C, dims, offsetA, offsetC, minstrides)
            end
        end
        return C
    end
end

@generated function trace_rec!{N}(α, A::StridedData{N}, β, C::StridedData{N}, dims::NTuple{N, Int}, offsetA::Int, offsetC::Int, minstrides::NTuple{N, Int})
    quote
        if prod(dims) + prod(_filterdims(dims,C)) <= BASELENGTH
            trace_micro!(α, A, β, C, dims, offsetA, offsetC)
        else
            dmax = _indmax(_memjumps(dims, minstrides))
            @dividebody $N dmax dims offsetA A offsetC C begin
                trace_rec!(α, A, β, C, dims, offsetA, offsetC, minstrides)
            end begin
                if C.strides[dmax] == 0
                    trace_rec!(α, A, _one, C, dims, offsetA, offsetC, minstrides)
                else
                    trace_rec!(α, A, β, C, dims, offsetA, offsetC, minstrides)
                end
            end
        end
        return C
    end
end

@generated function contract_rec!{N}(α, A::StridedData{N}, B::StridedData{N}, β, C::StridedData{N},
    dims::NTuple{N, Int}, offsetA::Int, offsetB::Int, offsetC::Int, minstrides::NTuple{N, Int})

    quote
        odimsA = _filterdims(_filterdims(dims, A), C)
        odimsB = _filterdims(_filterdims(dims, B), C)
        cdims = _filterdims(_filterdims(dims, A), B)
        oAlength = prod(odimsA)
        oBlength = prod(odimsB)
        clength = prod(cdims)

        if oAlength*oBlength + clength*(oAlength+oBlength) <= BASELENGTH
            contract_micro!(α, A, B, β, C, dims, offsetA, offsetB, offsetC)
        else
            if clength > oAlength && clength > oBlength
                dmax = _indmax(_memjumps(cdims, minstrides))
            elseif oAlength > oBlength
                dmax = _indmax(_memjumps(odimsA, minstrides))
            else
                dmax = _indmax(_memjumps(odimsB, minstrides))
            end
            @dividebody $N dmax dims offsetA A offsetB B offsetC C begin
                    contract_rec!(α, A, B, β, C, dims, offsetA, offsetB, offsetC, minstrides)
                end begin
                if C.strides[dmax] == 0 # dmax is contraction dimension: β -> 1
                    contract_rec!(α, A, B, _one, C, dims, offsetA, offsetB, offsetC, minstrides)
                else
                    contract_rec!(α, A, B, β, C, dims, offsetA, offsetB, offsetC, minstrides)
                end
            end
        end
        return C
    end
end


text:
@testset "Streaming reading" begin
    str = loadstreaming_wav(reference_wav)
    @test nframes(str) == 100
    @test position(str) == 1
    @test mse(read(str, 50), reference_buf[1:50, :]) < 1e-10
    @test mse(read(str, 50), reference_buf[51:100, :]) < 1e-10
    close(str)
    # now with do syntax
    loadstreaming_wav(reference_wav) do str
        @test mse(read(str, 50), reference_buf[1:50, :]) < 1e-10
        @test mse(read(str, 50), reference_buf[51:100, :]) < 1e-10
    end
    # now try reading all at once
    loadstreaming_wav(reference_wav) do str
        @test mse(read(str), reference_buf) < 1e-10
    end

    # seeking
    loadstreaming_wav(reference_wav) do str
        seek(str, 22)
        @test mse(read(str), reference_buf[22:end, :]) < 1e-10
    end

    # skipping
    loadstreaming_wav(reference_wav) do str
        seek(str, 22)
        skip(str, 10)
        @test mse(read(str), reference_buf[32:end, :]) < 1e-10
    end

end

@testset "Reading from IO Stream" begin
    open(reference_wav) do io
        loadstreaming_wav(io) do str
            @test nframes(str) == 100
            @test mse(read(str), reference_buf) < 1e-10
        end
    end
    open(reference_wav) do io
        buf = load_wav(io)
        @test samplerate(buf) == srate
        @test nchannels(buf) == 2
        @test nframes(buf) == 100
        @test isapprox(domain(buf), collect(0:99)/(srate))
        @test mse(buf, reference_buf) < 1e-10
    end
end

@testset "Writing to IO Streams" begin
    fname = string(tempname(), ".wav")
    testbuf = SampleBuf(rand(Float32, 100, 2) .- 0.5, srate)
    open(fname, "w") do io
        savestreaming_wav(io, 2, srate, Float32) do str
            write(str, testbuf[1:50, :])
            write(str, testbuf[51:100, :])
        end
    end
    @test load_wav(fname) == testbuf
    fname = string(tempname(), ".wav")
    open(fname, "w") do io
        save_wav(io, testbuf)
    end
    @test load_wav(fname) == testbuf
end

@testset "Supports IOBuffer" begin
    io = IOBuffer()
    testbuf = SampleBuf(rand(100, 2) .- 0.5, srate)
    save_wav(io, testbuf)
    seek(io, 0)
    @test load_wav(io) == testbuf
end


text:
# script to add EarthEngine REST API types
# attempt to replicated API types in Julia structs

"""
`EESession` type used for authenticating request to the API

$(TYPEDFIELDS)
"""
struct EESession
    "GCP project name used for REST API requests"
    project::AbstractString
    "authenticated Python requests session for making requests"
    auth::PyObject

    EESession(project::AbstractString, auth::PyObject) = new(project, auth)

    function EESession(args...; kwargs...)
        try
            copy!(serviceaccount, pyimport("google.oauth2.service_account"))
        catch err
            error(
                "The `google.oauth2` package could not be imported. You must install the Python earthengine-api before using this package. The error was $err",
            )
        end

        try
            copy!(gauth, pyimport("google.auth.transport.requests"))
        catch err
            error(
                "The `google.auth` package could not be imported. You must install the Python earthengine-api before using this package. The error was $err",
            )
        end

        credentials = serviceaccount.Credentials.from_service_account_file(
            args...;
            kwargs...,
        )
        scoped_credentials = credentials.with_scopes([
            "https://www.googleapis.com/auth/cloud-platform",
        ])
        auth = gauth.AuthorizedSession(scoped_credentials)
        project = credentials.project_id
        new(project, auth)
    end
end

"""
Type used for defining the number of rows and columns for image requests
See https://developers.google.com/earth-engine/reference/rest/v1beta/PixelGrid#GridDimensions

$(TYPEDFIELDS)
"""
struct GridDimensions
    "width of the grid, in pixels"
    width::Integer
    "height of the grid, in pixels"
    height::Integer

    GridDimensions(width::Integer, height::Integer) = new(width, height)
end

"""
Type for defining the affine transform of image requests. The six values form a 2x3 matrix:

See https://developers.google.com/earth-engine/reference/rest/v1beta/PixelGrid#affinetransform

"""
struct AffineTransform
    "horizontal scale factor. w-e pixel resolution / pixel width"
    scaleX::Real
    "horizontal shear factor. row rotation typically set to 0 for north-up images"
    shearX::Real
    "horizontal offset. x-coordinate of the upper-left corner of the upper-left pixel "
    translateX::Real
    "vertical shear factor. column rotation typically set to 0 for north-up images"
    shearY::Real
    "vertical scale factor. n-s pixel resolution / pixel height (negative for north-up images)"
    scaleY::Real
    "vertical offset. y-coordinate of the upper-left corner of the upper-left pixel "
    translateY::Real

    AffineTransform(
        scaleX::Real,
        shearX::Real,
        translateX::Real,
        shearY::Real,
        scaleY::Real,
        translateY::Real,
    ) = new(scaleX, shearX, translateX, shearY, scaleY, translateY)

end

"""
Type used for defining a pixel grid on the surface of the Earth, via a map projection
See https://developers.google.com/earth-engine/reference/rest/v1beta/PixelGrid

$(TYPEDFIELDS)
"""
struct PixelGrid
    "dimensions of the pixel grid"
    dimensions::GridDimensions
    "affine transform of pixel grid"
    affineTransform::AffineTransform
    "standard coordinate reference system code (e.g. 'EPSG:4326')"
    crsCode::AbstractString

    PixelGrid(
        dimensions::GridDimensions,
        affinetransform::AffineTransform,
        crsCode::AbstractString,
    ) = new(dimensions, affinetransform, crsCode)
end

"""
    PixelGrid(bbox::AbstractVector, resolution::Real, crsCode::String)

PixelGrid constructor based on bounding box, resolution, and crs code
"""
function PixelGrid(bbox::AbstractVector, resolution::Real, crsCode::String)
    minx, miny, maxx, maxy = bbox
    y_coords = collect(range(miny + resolution, maxy, step = resolution))
    x_coords = collect(range(minx, maxx - resolution, step = resolution))
    xdim = length(x_coords)
    ydim = length(y_coords)

    dimensions = GridDimensions(xdim, ydim)

    affinetransform = AffineTransform(resolution, 0, minx, 0, -resolution, maxy)

    PixelGrid(dimensions, affinetransform, crsCode)
end

"""
    PixelGrid(bbox::AbstractVector, shape::AbstractVector{Integer}, crsCode::String)

PixelGrid constructor based on bounding box, image dimensions, and crs code
"""
function PixelGrid(
    bbox::AbstractVector{Real},
    shape::AbstractVector{Integer},
    crsCode::AbstractString,
)
    minx, miny, maxx, maxy = bbox
    xdim, ydim = shape
    xres = (maxx - minx) / xdim
    yres = (maxy - miny) / ydim

    griddims = GridDimension(xdim, ydim)

    transform = AffineTransform(xres, 0, minx, 0, -yres, maxy)

    PixelGrid(griddims, transform, crsCode)
end

"""
    PixelGrid(session::EESession,geom::EE.AbstractEEObject,resolution::Real,crsCode::String)

PixelGrid constructor based on an EarthEngine feature collection bounds, needs resolution and crs defined
"""
function PixelGrid(
    session::EESession,
    geom::EE.AbstractEEObject,
    resolution::Real,
    crsCode::String,
)
    coords = computevalue(session, coordinates(bounds(geom)))
    minx = min(coords[1, :, 1]...)
    maxx = max(coords[1, :, 1]...)
    miny = min(coords[1, :, 2]...)
    maxy = max(coords[1, :, 2]...)

    PixelGrid([minx, miny, maxx, maxy], resolution, crsCode)
end

struct CloudStorageDestination
    bucket::AbstractString
    filenamePrefix::AbstractString
    permissions::AbstractString
    bucketCorsUris::Vector{AbstractString}

    CloudStorageDestination(
        bucket::AbstractString,
        filenamePrefix::AbstractString,
        permissions::AbstractString,
        bucketCorsUris::Vector{AbstractString},
    ) = new(bucket, filenamePrefix, permissions, bucketCorsUris)
end

struct DoubleRange
    min::Real
    max::Real

    DoubleRange(min::Real, max::Real) = new(min, max)
end

struct DriveDestination
    folder::AbstractString
    filenamePrefix::AbstractString

    DriveDestination(folder::AbstractString, filenamePrefix::AbstractString) =
        new(folder, filenamePrefix)
end

struct EarthEngineDestination
    name::AbstractString

    EarthEngineDestination(name::AbstractString) = new(name)
end

struct Expression
    values::AbstractDict{Union{String,Symbol},Any}
    result::AbstractString

    Expression(
        values::AbstractDict{Union{AbstractString,Symbol},Any},
        result::AbstractString,
    ) = new(values, result)
end

struct Feature
    type::AbstractString
    geometry::AbstractDict{Union{AbstractString,Symbol},Any}
    properties::AbstractDict{Union{AbstractString,Symbol},Any}
end

struct VisualizationOptions
    ranges::AbstractVector{DoubleRange}
    paletteColors::AbstractVector{String}
    gamma::Real
    opacity::Real

    VisualizationOptions(
        ranges::AbstractVector{DoubleRange},
        paletteColors::AbstractVector{String},
        gamma::Real,
        opacity::Real,
    ) = new(ranges, paletteColors, gamma, opacity)

    function VisualizationOptions(
        range::DoubleRange,
        paletteColors::AbstractVector{String},
        gamma::Real,
        opacity::Real,
    )
        ranges = [range]
        new(ranges, paletteColors, gamma, opacity)
    end

end

struct ZoomSubset
    startof::Real
    endof::Real

    ZoomSubset(startof::Real, endof::Real) = new(startof, endof)
end

struct TileOptions
    startZoom::Integer
    skipEmpty::Bool
    mapsApiKey::String
    dimensions::GridDimensions
    stride::Integer
    zoomSubset::ZoomSubset
    endZoom::Integer
    scale::Real

    TileOptions(
        startZoom::Integer,
        skipEmpty::Bool,
        mapsApiKey::String,
        dimensions::GridDimensions,
        stride::Integer,
        zoomSubset::ZoomSubset,
        endZoom::Integer,
        scale::Real,
    ) = new(
        startZoom,
        skipEmpty,
        mapsApiKey,
        dimensions,
        stride,
        zoomSubset,
        endZoom,
        scale,
    )
end


text:
"""
Subroutine ddot

This subroutine forms the dot product of two vectors.
It uses unrolled loops for increments equal to one.
Jack Dongarra, LINPACK, 3/11/78.
"""
function tron_ddot(n,dx,incx,dy,incy)
    dtemp = 0.0

    if n <= 0
        return
    end
    if (incx == 1 && incy == 1)
        # Code for both increments equal to 1
        m = mod(n,5)
        if m != 0
            for i=1:m
                dtemp = dtemp + dx[i]*dy[i]
            end
        end
        if n >= 5
            mp1 = m + 1
            for i=mp1:5:n
                dtemp = dtemp + dx[i]*dy[i] + dx[i+1]*dy[i+1] +
                    dx[i+2]*dy[i+2] + dx[i+3]*dy[i+3] + dx[i+4]*dy[i+4]
            end
        end
    else
        ix = 1
        iy = 1
        if incx < 0
            ix = (-n+1)*incx + 1
        end
        if incy < 0
            iy = (-n+1)*incy + 1
        end
        for i=1:n
            dtemp += dx[ix]*dy[iy]
            ix += incx
            iy += incy
        end
    end

    return dtemp
end

if isequal(BLAS_LIBRARY, :OpenBlas)
    ddot(n,dx,incx,dy,incy) = BLAS.dot(n,dx,incx,dy,incy)
    ddot(n, dx::CuArray, incx, dy::CuArray, incy) = CUBLAS.dot(n, dx, dy)
else
    ddot(n,dx,incx,dy,incy) = tron_ddot(n,dx,incx,dy,incy)
end

@inline function ddot(n::Int,dx::CuDeviceArray{Float64,1},incx::Int,
                      dy::CuDeviceArray{Float64,1},incy::Int)
    # Currently, all threads compute the same dot product,
    # hence, no sync_threads() is needed.
    # For very small n, we may want to gauge how much gains
    # we could get by run it in parallel.

    v = 0
    @inbounds for i=1:n
        v += dx[i]*dy[i]
    end
    CUDA.sync_threads()
    return v
end


text:
using LightGraphs
using LightGraphs.Parallel
using Base.Threads: @threads, Atomic
@test length(description()) > 1

tests = [
    "centrality/betweenness",
    "centrality/closeness",
    "centrality/pagerank",
    "centrality/radiality",
    "centrality/stress",
    "distance",
    "shortestpaths/bellman-ford",
    "shortestpaths/dijkstra",
    "shortestpaths/floyd-warshall",
    "shortestpaths/johnson",
    "traversals/bfs",
    "traversals/gdistances",
    "traversals/greedy_color",
    "dominatingset/minimal_dom_set",
    "independentset/maximal_ind_set",
    "vertexcover/random_vertex_cover",
    "utils"
]

@testset "LightGraphs.Parallel" begin
    for t in tests
        tp = joinpath(testdir, "parallel", "$(t).jl")
        include(tp)
    end
end


text:
abstract type AbstractMesh end

include("rectilinear_grid.jl")
include("volume_mesh.jl")
include("polytope_vertex_mesh.jl")
include("materialize.jl")
include("submesh.jl")
include("mesh_partition_tree.jl")
include("io_abaqus.jl")
include("io_xdmf.jl")
include("io.jl")
#include("statistics.jl")

max_stars_repo_name: khurrumsaleem/MOCNeutronTransport

max_issues_repo_name: khurrumsaleem/MOCNeutronTransport

max_forks_repo_name: khurrumsaleem/MOCNeutronTransport


text:
### samplingSolver
include("revampedLinkedListFloatStorage.jl")
export llsInit
export llsAdd
export llsPurge

include("sqLinOpWrapper.jl")
export SqLinOp

#=
include("samplingSolver.jl")
export samplingSDDMSolver
export samplingLapSolver
export samplingParams
=#

### KMP
# included in Laplacians.jl

### hybridSolver -- has been removed from master, and now lives in own branch

### useful misc
include("condNumber.jl")
export condNumber

include("powerIteration.jl")
export powerIteration

"""A list containing SDDM linear system solvers. They take in a SDDM matrix plus tol, maxits and maxtime parameters."""
SDDMSolvers = [augTreeSddm, KMPSDDMSolver, approxchol_sddm]

"""A list containing Laplacian linear system solvers. They take in an adjacency matrix plus tol, maxits and maxtime parameters."""
LapSolvers = [approxchol_lap, augTreeLap, KMPLapSolver, cgLapSolver]


text:
function set_parameter_lower_bound!(
    p::Problem,
    block::Vector{Float64},
    index::Union{Int32, Int64},
    bound::Float64
)
    ceres_set_parameter_lower_bound_c(
        p.c_ptr,
        Base.unsafe_convert(Ptr{Cdouble}, block),
        index,
        bound
    )
end

function set_parameter_upper_bound!(
    p::Problem,
    block::Vector{Float64},
    index::Union{Int32, Int64},
    bound::Float64
)
    ceres_set_parameter_upper_bound_c(
        p.c_ptr,
        Base.unsafe_convert(Ptr{Cdouble}, block),
        index,
        bound
    )
end

function SetParameterBlockConstant!(problem::Problem,
                                    params::Vector{Float64})
    param_ptr = Base.unsafe_convert(Ptr{Cdouble}, params)
    ceres_set_parameter_block_constant_c(problem.c_ptr, param_ptr)
end

function SetParameterBlockVariable!(problem::Problem,
                                    params::Vector{Float64})
    param_ptr = Base.unsafe_convert(Ptr{Cdouble}, params)
    ceres_set_parameter_block_variable_c(problem.c_ptr, param_ptr)
end


text:
function AmpereStep!(d, h, J, cb, nx, ny, nz)
    @turbo for k = 2:nz-1
        for j = 2:ny-1
            for i = 2:nx-1
                d[i, j, k, 1] = d[i, j, k, 1] +
                                cb[i, j, k, 1] * (h[i, j, k, 3] - h[i, j-1, k, 3] - h[i, j, k, 2] + h[i, j, k-1, 2]) - J[i, j, k, 1]
                d[i, j, k, 2] = d[i, j, k, 2] +
                                cb[i, j, k, 2] * (h[i, j, k, 1] - h[i, j, k-1, 1] - h[i, j, k, 3] + h[i-1, j, k, 3]) - J[i, j, k, 2]
                d[i, j, k, 3] = d[i, j, k, 3] +
                                cb[i, j, k, 3] * (h[i, j, k, 2] - h[i-1, j, k, 2] - h[i, j, k, 1] + h[i, j-1, k, 1]) - J[i, j, k, 3]
            end
        end
    end
    @turbo for k = 2:nz-1
        for j = 2:ny-1
            for i = 1:1
                d[i, j, k, 1] = d[i, j, k, 1] +
                                cb[i, j, k, 1] * (h[i, j, k, 3] - h[i, j-1, k, 3] - h[i, j, k, 2] + h[i, j, k-1, 2]) - J[i, j, k, 1]
            end
        end
    end
    @turbo for k = 2:nz-1
        for j = 1:1
            for i = 2:nx-1
                d[i, j, k, 2] = d[i, j, k, 2] + cb[i, j, k, 2] * (h[i, j, k, 1] - h[i, j, k-1, 1] - h[i, j, k, 3] + h[i-1, j, k, 3]) - J[i, j, k, 2]
            end
        end
    end
    @turbo for k = 1:1
        for j = 2:ny-1
            for i = 2:nx-1
                d[i, j, k, 3] = d[i, j, k, 3] +
                                cb[i, j, k, 3] * (h[i, j, k, 2] - h[i-1, j, k, 2] - h[i, j, k, 1] + h[i, j-1, k, 1]) - J[i, j, k, 3]
            end
        end
    end
end