text:
# Note: Functions surrounded by a comment blocks are there because `Vararg` is sitll allocating.
# When Vararg is fast enough, they can simply be removed

####################
# PseudoBlockArray #
####################

"""
    PseudoBlockArray{T, N, R} <: AbstractBlockArray{T, N}

A `PseudoBlockArray` is similar to a [`BlockArray`](@ref) except the full array is stored
contiguously instead of block by block. This means that is not possible to insert and retrieve
blocks without copying data. On the other hand `full` on a `PseudoBlockArray` is instead instant since
it just returns the wrapped array.

When iteratively solving a set of equations with a gradient method the Jacobian typically has a block structure. It can be convenient
to use a `PseudoBlockArray` to build up the Jacobian block by block and then pass the resulting matrix to
a direct solver using `full`.

```jlcon
julia> A = PseudoBlockArray(rand(2,3), [1,1], [2,1])
2×2-blocked 2×3 BlockArrays.PseudoBlockArray{Float64,2,Array{Float64,2}}:
 0.599925  0.288788  │  0.55428
 --------------------┼----------
 0.82342   0.394812  │  0.263454

julia> A = PseudoBlockArray(sprand(6, 0.5), [3,2,1])
3-blocked 6-element BlockArrays.PseudoBlockArray{Float64,1,SparseVector{Float64,Int64}}:
 0.542401
 0.542299
 0.0
 ---------
 0.682638
 0.0
 ---------
 0.0553841
```
"""
immutable PseudoBlockArray{T, N, R <: AbstractArray} <: AbstractBlockArray{T, N}
    blocks::R
    block_sizes::BlockSizes{N}
    function PseudoBlockArray(blocks::R, block_sizes::BlockSizes{N})
        for i in 1:N
            @assert sum(block_sizes[i]) == size(blocks, i)
        end
        @assert ndims(R) == N
        @assert eltype(T) == T
        new(blocks, block_sizes)
    end
end

typealias PseudoBlockMatrix{T, R} PseudoBlockArray{T, 2, R}
typealias PseudoBlockVector{T, R} PseudoBlockArray{T, 1, R}
typealias PseudoBlockVecOrMat{T, R} Union{PseudoBlockMatrix{T, R}, PseudoBlockVector{T, R}}

# Auxiliary outer constructor
PseudoBlockArray{N, R}(blocks::R, block_sizes::BlockSizes{N}) = PseudoBlockArray{eltype(R), N, R}(blocks, block_sizes)
PseudoBlockArray{N, R}(blocks::R, block_sizes::Vararg{Vector{Int}, N}) = PseudoBlockArray(blocks, BlockSizes(block_sizes))

###########################
# AbstractArray Interface #
###########################

function Base.similar{T,N,T2}(block_array::PseudoBlockArray{T,N}, ::Type{T2})
    PseudoBlockArray(similar(block_array.blocks, T2), copy(block_array.block_sizes))
end

Base.size(arr::PseudoBlockArray) = map(sum, arr.block_sizes.sizes)

# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv #
function Base.getindex{T, N}(block_arr::PseudoBlockArray{T, N}, i::Int)
    @boundscheck checkbounds(block_arr, )
    @inbounds v = block_arr.blocks[i]
    return v
end

function Base.getindex{T, N}(block_arr::PseudoBlockArray{T, N}, i::Int, j::Int)
    @boundscheck checkbounds(block_arr, i, j)
    @inbounds v = block_arr.blocks[i, j]
    return v
end
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #

function Base.getindex{T, N}(block_arr::PseudoBlockArray{T, N}, i::Vararg{Int, N})
    @boundscheck checkbounds(block_arr, i...)
    @inbounds v = block_arr.blocks[i...]
    return v
end

# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv #
function Base.setindex!{T, N}(block_arr::PseudoBlockArray{T, N}, v, i::Int)
    @boundscheck checkbounds(block_arr, i)
    @inbounds block_arr.blocks[i] = v
    return block_arr
end

function Base.setindex!{T, N}(block_arr::PseudoBlockArray{T, N}, v, i::Int, j::Int)
    @boundscheck checkbounds(block_arr, i, j)
    @inbounds block_arr.blocks[i, j] = v
    return block_arr
end
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #

function Base.setindex!{T, N}(block_arr::PseudoBlockArray{T, N}, v, i::Vararg{Int, N})
    @boundscheck checkbounds(block_arr, i...)
    @inbounds block_arr.blocks[i...] = v
    return block_arr
end

################################
# AbstractBlockArray Interface #
################################

nblocks(block_array::PseudoBlockArray) = nblocks(block_array.block_sizes)
blocksize{T, N}(block_array::PseudoBlockArray{T,N}, i::Vararg{Int, N}) = blocksize(block_array.block_sizes, i)

############
# Indexing #
############

# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv #
function getblock{T,N}(block_arr::PseudoBlockArray{T,N}, block_i::Int)
    range = globalrange(block_arr.block_sizes, (block_i,))
    return block_arr.blocks[range[1]]
end

function getblock{T,N}(block_arr::PseudoBlockArray{T,N}, block_i::Int, block_j::Int)
    range = globalrange(block_arr.block_sizes, (block_i, block_j))
    return block_arr.blocks[range[1], range[2]]
end
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #

function getblock{T,N}(block_arr::PseudoBlockArray{T,N}, block::Vararg{Int, N})
    range = globalrange(block_arr.block_sizes, block)
    return block_arr.blocks[range...]
end

function _check_getblock!{T, N}(blockrange, x, block_arr::PseudoBlockArray{T,N}, block::NTuple{N, Int})
    for i in 1:N
        if size(x, i) != length(blockrange[i])
            throw(DimensionMismatch(string("tried to assign ", blocksize(block_arr, block...), " block to $(size(x)) array")))
        end
    end
end

# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv #
@propagate_inbounds function getblock!{T}(x, block_arr::PseudoBlockArray{T,1}, block_i::Int)
    blockrange = globalrange(block_arr.block_sizes, (block_i,))
    @boundscheck _check_getblock!(blockrange, x, block_arr, (block_i,))

    arr = block_arr.blocks
    k_1 = 1
    @inbounds for i in blockrange[1]
        x[k_1] = arr[i]
        k_1 += 1
    end
    return x
end

@propagate_inbounds function getblock!{T}(x, block_arr::PseudoBlockArray{T,2}, block_i::Int, block_j::Int)
    blockrange = globalrange(block_arr.block_sizes, (block_i,block_j))
    @boundscheck _check_getblock!(blockrange, x, block_arr, (block_i, block_j))

    arr = block_arr.blocks
    k_2 = 1
    @inbounds for j in blockrange[2]
        k_1 = 1
        for i in blockrange[1]
            x[k_1, k_2] = arr[i, j]
            k_1 += 1
        end
        k_2 += 1
    end
    return x
end
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #

@generated function getblock!{T,N}(x, block_arr::PseudoBlockArray{T,N}, block::Vararg{Int, N})
    return quote
        blockrange = globalrange(block_arr.block_sizes, block)
        @boundscheck _check_getblock!(blockrange, x, block_arr, block)

        arr = block_arr.blocks
        @nexprs $N d -> k_d = 1
        @inbounds begin
            @nloops $N i (d->(blockrange[d])) (d-> k_{d-1}=1) (d-> k_d+=1) begin
                (@nref $N x k) = (@nref $N arr i)
            end
        end
        return x
    end
end

function _check_setblock!{T, N}(blockrange, x, block_arr::PseudoBlockArray{T,N}, block::NTuple{N, Int})
    for i in 1:N
        if size(x, i) != block_arr.block_sizes[i, block[i]]
            throw(DimensionMismatch(string("tried to assign $(size(x)) array to ", blocksize(block_arr, block...), " block")))
        end
    end
end

# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv #
@propagate_inbounds function setblock!{T}(block_arr::PseudoBlockArray{T,1}, x, block_i::Int)
    blockrange = globalrange(block_arr.block_sizes, (block_i,))
    @boundscheck _check_setblock!(blockrange, x, block_arr, (block_i,))

    arr = block_arr.blocks
    k_1 = 1
    @inbounds for i in blockrange[1]
        arr[i] = x[k_1]
        k_1 += 1
    end
    return x
end

@propagate_inbounds function setblock!{T}(block_arr::PseudoBlockArray{T,2}, x, block_i::Int, block_j::Int)
    blockrange = globalrange(block_arr.block_sizes, (block_i,block_j))
    @boundscheck _check_setblock!(blockrange, x, block_arr, (block_i, block_j))

    arr = block_arr.blocks
    k_2 = 1
    @inbounds for j in blockrange[2]
        k_1 = 1
        for i in blockrange[1]
            arr[i, j] = x[k_1, k_2]
            k_1 += 1
        end
        k_2 += 1
    end
    return x
end
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #

@generated function setblock!{T, N}(block_arr::PseudoBlockArray{T, N}, x, block::Vararg{Int, N})
    return quote
        blockrange = globalrange(block_arr.block_sizes, block)
        @boundscheck _check_setblock!(blockrange, x, block_arr, block)
        arr = block_arr.blocks
        @nexprs $N d -> k_d = 1
        @inbounds begin
            @nloops $N i (d->(blockrange[d])) (d-> k_{d-1}=1) (d-> k_d+=1) begin
                (@nref $N arr i) = (@nref $N x k)
            end
        end
    end
end

########
# Misc #
########

function Base.full(block_array::PseudoBlockArray)
    return block_array.blocks
end

function Base.copy!{T, N, R <: AbstractArray}(block_array::PseudoBlockArray{T, N, R}, arr::R)
    copy!(block_array.blocks, arr)
end

function Base.fill!(block_array::PseudoBlockArray, v)
    fill!(block_array.blocks, v)
end


text:
mutable struct SimpleArc{T<:Node,U<:Real,V<:Int}
    uuid                    ::UUID
    origin                  ::T
    destination             ::T
    assignment              ::V
    value                   ::U
end

Base.show(io::IO,arc::SimpleArc) = Base.print(
    io,
    "\n   Assignment: ", arc.assignment, "\n",
    "   Arc Value: ", arc.value, "\n"
)

#change hashing of nodes to use uuids
Base.hash(arc::SimpleArc) = hash(arc.uuid)
Base.:(==)(x::SimpleArc,y::SimpleArc) = x.uuid == y.uuid

#do UUIDs automatically
function SimpleArc(origin::T, destination::T, assignment::U, value::V)where{T<:Node, U<:Int, V<:Real}
    return SimpleArc(uuid4(), origin, destination, assignment, value)
end

"""
    deepCopy(arc::SimpleArc)

Deep copy an arc

# Arguments
- `arcs::SimpleArc`: the arc
"""
function deepCopy(arc::SimpleArc)
    return SimpleArc(arc.uuid, arc.origin,arc.destination,arc.assignment,arc.value)
end

"""
    deepCopy(arcs::Vector{SimpleArc})

Deep copy a list of arcs

# Arguments
- `arcs::Array{SimpleArc}`: a list of arcs
"""
function deepCopy(arcs::Vector{SimpleArc})
    newArcs = Vector{SimpleArc}()
    for arc in arcs
        push!(newArcs, deepCopy(arc))
    end
    return newArcs
end

"""
    shallowCopy(arc::SimpleArc)

Shallow copy an arc

# Arguments
- `arcs::SimpleArc`: the arc
"""
function shallowCopy(arc::SimpleArc)
    return SimpleArc(arc.origin,arc.destination,arc.assignment,arc.value)
end

"""
    shallowCopy(arcs::Vector{SimpleArc})

functionally the same as deepCopy a list of arcs, but with different uuids

# Arguments
- `arcs::Array{SimpleArc}`: a list of arcs
"""
function shallowCopy(arcs::Vector{SimpleArc})
    newArcs = Vector{SimpleArc}()
    for arc in arcs
        push!(newArcs, shallowCopy(arc))
    end
    return newArcs
end

"""
    findBestArc(model::SequencingModel, arcs::Vector{SimpleArc})

Find the best arc in a list, where best means containing the most optimal path

# Arguments
- `model::SequencingModel`: The Sequencing problem
- `arcs::Vector{SimpleArc}`: The list of arcs
"""
function findBestArc(model::SequencingModel, arcs::Vector{SimpleArc})
    bestArc = arcs[1]
    bestArcValue = bestArc.origin.lengthToRoot + bestArc.value
    for arc in arcs
        if isBetterSolutionValue(model, arc.origin.lengthToRoot + arc.value, bestArcValue)
            bestArc = arc
            bestArcValue = arc.origin.lengthToRoot + arc.value
        end
    end
    return bestArc, bestArcValue
end

"""
    getArcValue(model::SequencingModel, arc::SimpleArc)

Get the best arc value by checking the states it can be coming from, arc.origin.state must be a BitVector

# Arguments
- `model::SequencingModel`: The Sequencing problem
- `arc::SimpleArc`: The arc
"""
function getArcValue(model::SequencingModel, arc::SimpleArc)
    arcValue = nothing
    for (i, bit) in enumerate(arc.origin.state)
        if bit
            if hasKey(model.objective, i, arc.assignment)
                if isnothing(arcValue) || isBetterSolutionValue(model, evaluateDecision(model.objective, i, arc.assignment),arcValue)
                    arcValue = evaluateDecision(model.objective, i, arc.assignment)
                end
            end
        end
    end
    return arcValue
end

"""
    deleteArc!(arc::SimpleArc)
Remove an arc from both relevant nodes

# Arguments
- `arc::SimpleArc`: the arc to remove
"""
function deleteArc!(arc::SimpleArc)
    filter!(x->x!=arc, arc.origin.arcsOut)
    filter!(x->x!=arc, arc.destination.arcsIn)
end

"""
    deleteArcs!(arcsToRemove::Vector{SimpleArc})
Delete a list of arcs

# Arguments
- `arcsToRemove::Vector{SimpleArc}`: the arcs to remove
"""
function deleteArcs!(arcsToRemove::Vector{SimpleArc})
    toRemove = Vector{SimpleArc}()
    for arc in arcsToRemove
        push!(toRemove, arc)
    end
    for arc in toRemove
        deleteArc!(arc)
    end
end

ext: jl


text:
using DiffEqBase, Test

f_op = (u,p,t) -> u
f_ip = (du,u,p,t) -> du .= u
DE_f = ODEFunction{false}(f_op)
DE_f_ip = ODEFunction{true}(f_ip)
DI_f = DiscreteFunction{false}(f_op)
DI_f_ip = DiscreteFunction{true}(f_ip)
du = zeros(3); u = [1.0,2.0,3.0]; p = nothing; t = 0.0
@test DE_f(u,p,t) == u
DE_f_ip(du,u,p,t)
@test du == u
@test DI_f(u,p,t) == u
DI_f_ip(du,u,p,t)
@test du == u

f(u,p,t) = u
jac = (u,p,t) -> 1
@inferred ODEFunction{false}(f_op,jac=jac)
@inferred DiscreteFunction{false}(f_op,analytic=f)

f(du,u,p,t) = u


text:
using Test, OpenStreetMapX
using Random, StableRNGs
import LightGraphs

@testset "$ext" for ext in ["osm", "pbf"]
    pth = joinpath(dirname(pathof(OpenStreetMapX)),"..","test","data","reno_east3.$ext")
    m =  OpenStreetMapX.get_map_data(pth,use_cache = false);

    @testset "maps" begin
        @test length(m.nodes) == 9032
        rng = StableRNGs.StableRNG(1234)
        pA = generate_point_in_bounds(rng, m)
        @test all(isapprox.(pA,(39.52679926947162, -119.7400090256387)))
        pB = generate_point_in_bounds(rng, m)
        @test all(isapprox.(pB,(39.53417080390912, -119.73955700911934)))
        pointA = point_to_nodes(pA, m)
        pointB = point_to_nodes(pB, m)

        @test pointA == 3625693684
        @test pointB == 140115165

        sr1, shortest_distance1, shortest_time1 = shortest_route(m, pointA, pointB)
        @test (sr1[1], sr1[end]) == (pointA, pointB)

        @test shortest_route(m, pointA, pointB; routing = :astar) == shortest_route(m, pointA, pointB; routing = :dijkstra)
        @test fastest_route(m, pointA, pointB; routing = :astar) == fastest_route(m, pointA, pointB; routing = :dijkstra)

        #######################################################
        ### nodes.jl ###
        #nodes.jl/nearest_node
        @test nearest_node(m.nodes, ENU(3300,1500,-1)) == 3052967130

        #nodes.jl/centroid
        node_list = [pointA,pointB]
        @test centroid(m.nodes,node_list) ≈ ENU(1264.3091688577153, 982.9015092571676, -0.2152924371073368)

        #nodes.jl/nodes_within_range
        @test Set(nodes_within_range(m.nodes, ENU(3300,1500,-1), 100.0)) == Set([3052967037, 3052967180, 3052967130, 6050217400, 3052966904, 3052967140, 6050217409, 3052967199])

        #nodes.jl/add_new_node!
        @test haskey(m.nodes,-1) == false
        OpenStreetMapX.add_new_node!(m.nodes,ENU(3300,1500,-1),-1)
        @test length(m.nodes) == 9033
        @test nearest_node(m.nodes,ENU(3300,1500,-1)) == -1

        ### intersections.jl ###
        #intersections.jl/oneway
        @test OpenStreetMapX.oneway(m.roadways[1]) == true

        #intersections.jl/distance
        @test distance(m.nodes,sr1) ≈ 1720.2462568078658

        #intersections.jl/find_intersections
        @test OpenStreetMapX.find_intersections(m.roadways[1:2]) == Dict(139988738=>Set([14370413]),2975020216=>Set([14370407]),2441017888=>Set([14370407]),385046328=>Set([14370413]))

        ### routing.jl ###
        #routing.jl/get_edges
        @test Dict(zip(OpenStreetMapX.get_edges(m.nodes,m.roadways[1:2])...)) == Dict((139988738, 385046327) => 1, (2441017870, 2975020216) => 4, (385046327, 385046328) => 1, (2441017888, 2441017878) => 4, (2441017878, 2441017870) => 4)

        #parseMap.jl/get_vertices_and_graph_nodes
        vertices, graph_nodes = OpenStreetMapX.get_vertices_and_graph_nodes(OpenStreetMapX.get_edges(m.nodes,m.roadways[1:2])[1])
        @test sort(graph_nodes) == sort([2441017878,139988738,2975020216,2441017870,385046328,2441017888,385046327])
        @test vertices == Dict(zip(graph_nodes, 1:length(graph_nodes)))

        #routing.jl/distance
        #Returns seem to be equal yet returning false (?)
        @test sort(distance(m.nodes,OpenStreetMapX.get_edges(m.nodes,m.roadways[1:2])[1])) ≈ sort([30.2013937293296, 7.243941886194111, 35.492758006997796, 12.29992029473937, 11.290063259013777])

        conn_components = sort!(LightGraphs.strongly_connected_components(m.g),
                lt=(x,y)->length(x)<length(y), rev=true)
        @test length(conn_components)>1
        @test length(conn_components[1])==1799

        m2 =  OpenStreetMapX.get_map_data(pth,use_cache = false, trim_to_connected_graph=true);
        conn_components2 = sort!(LightGraphs.strongly_connected_components(m2.g),
                lt=(x,y)->length(x)<length(y), rev=true)
        @test length(conn_components2)==1
        @test length(conn_components[1])==length(conn_components2[1])

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

        function perftest()
            sr_len=length(shortest_route(m, pointA, pointB; routing = :astar)[1])
            fr_len=length(fastest_route(m, pointA, pointB; routing = :astar)[1])
            shortest_route(m, pointA, pointB; routing = :dijkstra)
            fastest_route(m, pointA, pointB; routing = :dijkstra)

            shortest_route(m, pointA, pointB; routing = :astar)
            shortest_route(m, pointA, pointB; routing = :dijkstra)
            fastest_route(m, pointA, pointB; routing = :astar)
            fastest_route(m, pointA, pointB; routing = :dijkstra)
            nothing

        end

        @test perftest() == nothing

    end

    @testset "converters" begin
        node = m.nodes[140376307]
        lla = LLA(node, m.bounds)
        @test all((lla.lat, lla.lon, lla.alt) .≈ (39.5173324, -119.8005402, 0.0))
        e = ECEF(lla)
        #test with data from https://www.oc.nps.edu/oc2902w/coord/llhxyz.htm?source=post_page---------------------------
        @test all( abs.((e.x, e.y, e.z)./1000 .- (-2448.622, -4275.441, 4036.788)) .< 0.001)
        llawarsaw = LLA(52.22977,21.01178)
        # http://www.apsalin.com/convert-geodetic-to-cartesian.aspx
        ewaw = ECEF(llawarsaw)
        @test ewaw ≈ ECEF(3654475.66587739, 1403683.91652118, 5018503.15478704)
        llawarsaw2 = LLA(ewaw)
        @test llawarsaw2 ≈ llawarsaw
    end
end


text:
@discord_object struct PruneCount
    pruned::Int
end


text:
using HTTP, Base.Test

# TODO
  # docs:
    # manual page
  # server.jl
    # docs
    # tests
  # proxy stuff, multi-part files, digest auth

@testset "HTTP" begin
    include("utils.jl");
    include("fifobuffer.jl");
    include("sniff.jl");
    include("uri.jl");
    include("cookies.jl");
    include("parser.jl");
    include("types.jl");
    include("client.jl");
    include("server.jl")
end;

# server_task = @async HTTP.serve()
#
# client = connect("127.0.0.1", 8081)
# write(client, "OPTIONS * HTTP/1.1\r\n\r\n")
# sleep(1)
# resp = String(readavailable(client))

# reject invalid HTTP versions

# test a variety of invalid requests (see http_parser error codes?)
  # invalid METHOD (501 not implemented status)
  # URI too long (414 status)
  # invalid HTTP versions
  # whitespace where there shouldn't be
  # reject message w/ space between header field & colon (400) # https://tools.ietf.org/html/rfc7230#section-3.2.4
  # non-encoded target resource w/ spaces (return 400)
  # duplicate headers
  # no space between header field name and colon
  # reject obs-fold multi-line header field values (400 bad request)

# limit on overall header size # https://tools.ietf.org/html/rfc7230#section-3.2.5

# no response body
 # HEAD requests
 # 1xx and 2xx responses
 # CONNECT requests
 # 204, 304

# no transfer-encoding header in response to:
 # 1xx or 204 response statuses
 # CONNECT request

# https://tools.ietf.org/html/rfc7230#section-3.3.1
# unsupported transfer-endcoding => 501 not implemented

# bad request 400 on multiple Content-Length headers

# timeout and close connection when bytes received don't match Content-Length from client

# https://tools.ietf.org/html/rfc7230#section-3.5
# ignore preceeding CRLF to request-line

# https://tools.ietf.org/html/rfc7230#section-4.1.1
# ignore unsupported chunk-extensions

# https://tools.ietf.org/html/rfc7230#section-4.1.2
# chunk trailer headers are handled appropriately

# https://tools.ietf.org/html/rfc7230#section-4.2
# transfer-encodings supported: compress, deflate, gzip, x-gzip

# https://tools.ietf.org/html/rfc7230#section-5.4
# 400 for no Host or multiple Host headers

# https://tools.ietf.org/html/rfc7230#section-6.1
# test keep-alive support

# https://tools.ietf.org/html/rfc7230#section-6.5
# test an inactive client (i.e. sent keep-alive, but didn't send anything else)

# https://tools.ietf.org/html/rfc7230#section-3
# The normal procedure for parsing an HTTP message is to read the
#   start-line into a structure, read each header field into a hash table
#   by field name until the empty line, and then use the parsed data to
#   determine if a message body is expected.  If a message body has been
#   indicated, then it is read as a stream until an amount of octets
#   equal to the message body length is read or the connection is closed.

# A sender MUST NOT send whitespace between the start-line and the
#    first header field.  A recipient that receives whitespace between the
#    start-line and the first header field MUST either reject the message
#    as invalid or consume each whitespace-preceded line without further
#    processing of it (i.e., ignore the entire line, along with any
#    subsequent lines preceded by whitespace, until a properly formed
#    header field is received or the header section is terminated).

# reject a received request: https://tools.ietf.org/html/rfc7230#section-3.1
# restrict uri length to 8000 by default: https://tools.ietf.org/html/rfc7230#section-3.1.1

# https://tools.ietf.org/html/rfc7230#section-3.2.2
# handle response w/ multiple "Set-Cookie" header fields

# https://tools.ietf.org/html/rfc7230#section-3.3
# never a repsonse body in HEAD/CONNECT requests
# 1xx, 204, 304 don't include bodies


text:
mutable struct SparseMatrixCOO{T}
    # simple coordinate form
    # maybe to do for later: try to implement a compressed column scheme
    data::Vector{T}
    row_index::Vector{<:Integer}
    col_index::Vector{<:Integer}
    function SparseMatrixCOO{T}(data, row_index, col_index) where {T}
        # last index must specify the length of the full array
        Ld = length(data)
        Lci = length(col_index)
        Lri = length(row_index)
        if Lci != Lri
            error("The two index arrays must have the same length")
        end

        if (Ld + 1) != Lci
            error(
                "Data array must have one element less then index array,
                last index must contain the number of elements in the full array")
        end
        if Lci[end] * Lri[end] < Ld
            error("The last index element must contain the col and row dimensions")
        end
        vec = new(data, row_index, col_index);
    end
end

function SparseMatrixCOO(data::Vector{T}, col_index, row_index) where {T}
    vec = SparseMatrixCOO{T}(data, col_index, row_index);
end

function Base.length(spmat::SparseMatrixCOO{T}) where {T}
    return length(spmat.data)
end

function n_nonzero(spmat::SparseMatrixCOO{T}) where {T}
    return length(spmat)
end

function sparse_length(spmat::SparseMatrixCOO{T}) where {T}
    return length(spmat)
end

function full_length(spmat::SparseMatrixCOO{T}) where {T}
    return spmat.col_index[end] * spmat.row_index[end]
end

function Base.size(spmat::SparseMatrixCOO{T}) where {T}
    return ( spmat.row_index[end], spmat.col_index[end] )
end

function Base.size(spmat::SparseMatrixCOO{T}, dim) where {T}
    if dim == 1
        return spmat.row_index[end]
    elseif dim == 2
        return spmat.col_index[end]
    else
        return 1
    end
end

function Base.show(io::IO, spmat::SparseMatrixCOO{T}) where {T}
    n = length(spmat)
    (n_row_full, n_col_full) = size(spmat)
    println("$(n)-sparse element (full size: $(n_row_full)x$(n_col_full)) SparseMatrixCOO{$(T)}:")
    println("\tindex\tdata")
    for kk = 1:n
        ii = spmat.row_index[kk]
        jj = spmat.col_index[kk]
        dd = spmat.data[kk]
        println("\t($(ii), $(jj))\t$(dd)")
    end
end

function create_full(spmat::SparseMatrixCOO{T}) where {T}
    (n_row_full, n_col_full) = size(spmat)
    Ls = sparse_length(spmat)
    mat = zeros(T, n_row_full, n_col_full)
    for ii = 1:Ls
        mat[ spmat.row_index[ii], spmat.col_index[ii] ] = spmat.data[ii]
    end
    return mat
end

function create_sparse_coo(data::Matrix, tolerance = 1e-10)
    # for now: create a temporary array with the size of data
    L = length(data)
    tmp_data = similar(data)
    tmp_col_index = Vector{Int64}(undef, L+1)
    tmp_row_index = Vector{Int64}(undef, L+1)

    (n_row, n_col) = size(data)

    kk = 0
    for jj = 1:n_col
        for ii = 1:n_row
            if abs(data[ii, jj]) >= tolerance
                kk += 1
                tmp_data[kk] = data[ii, jj]
                tmp_col_index[kk] = jj
                tmp_row_index[kk] = ii
            end
        end
    end

    data = tmp_data[1:kk]

    kk += 1
    tmp_col_index[kk] = n_col
    tmp_row_index[kk] = n_row

    col_index = tmp_col_index[1:kk]
    row_index = tmp_row_index[1:kk]

    spmat = SparseMatrixCOO(data, row_index, col_index)
    return spmat
end

function sort_indicies_with_data!(data, row_idx, col_idx)
    # radix sort algo

    i1 = sortperm(row_idx; alg = MergeSort)
    row_idx = row_idx[i1]
    col_idx = col_idx[i1]

    i2 = sortperm(col_idx; alg = MergeSort)
    row_idx = row_idx[i2]
    col_idx = col_idx[i2]

    data = data[i1]
    data = data[i2]

    return (data, row_idx, col_idx)
end

struct SparseMatrixCSC{T}
    n_row::Int
    n_col::Int
    data::Vector{T}
    row_index::Vector{Int} # has the same length as data
    col_begins_index::Vector{Int} # same length as number of columns

    function SparseMatrixCSC(n_row::Int, n_col::Int, data_in::Vector, row_idx_in::Vector, col_idx_in::Vector)
        data    = copy(data_in)
        row_idx = copy(row_idx_in)
        col_idx = copy(col_idx_in)

        (data, row_idx, col_idx) = sort_indicies_with_data!(data, row_idx, col_idx)

        L = length(data)
        col_begins = zeros(Int, n_col+1)

        kk = 1
        for cc = 1:n_col

            # if the data only at later columns comes , then move the column index to this
            if col_idx[kk] > cc
                continue
            end

            # if
            while true
                if kk <= L && col_idx[kk] < cc
                    kk += 1
                else
                    break
                end
            end
            if kk > L
                 break
            end
            if col_idx[kk] == cc
                col_begins[cc] = kk
            end
        end
        # ii = n_col
        # while col_begins[ii] == 0
        #     col_begins[ii] = -1
        #     ii -= 1
        # end
        col_begins[n_col+1] = length(data)+1

        T = eltype(data)
        obj = new{T}(n_row, n_col, data, row_idx, col_begins)
        return obj
    end
end

function create_sparse_csc(data::Matrix, tolerance = 1e-10)
    # for now: create a temporary array with the size of data
    L = length(data)
    tmp_data = similar(data)
    tmp_col_index = Vector{Int64}(undef, L+1)
    tmp_row_index = Vector{Int64}(undef, L+1)

    (n_row, n_col) = size(data)

    kk = 0
    for jj = 1:n_col
        for ii = 1:n_row
            if abs(data[ii, jj]) >= tolerance
                kk += 1
                tmp_data[kk] = data[ii, jj]
                tmp_col_index[kk] = jj
                tmp_row_index[kk] = ii
            end
        end
    end

    data = tmp_data[1:kk]
    col_index = tmp_col_index[1:kk]
    row_index = tmp_row_index[1:kk]

    spmat = SparseMatrixCSC(n_row, n_col, data, row_index, col_index)
    return spmat
end

function create_full(spmat::SparseMatrixCSC)
    A = zeros(eltype(spmat.data), spmat.n_row, spmat.n_col)
    L = length(spmat)

    for cc = 1:spmat.n_col

        idx_start = spmat.col_begins_index[cc]
        if idx_start <= 0
            continue
        end
        (idx_end, flag_end_reached) = find_next_nonempty_col_begin(spmat, cc)

        for rr = idx_start:(idx_end-1)
            if rr < 0
                println("")
            end
            a_ij = spmat.data[rr]
            ii = spmat.row_index[rr]
            jj = cc
            A[ii, jj] = a_ij
        end

    end

    return A
end

# function Base.show(io::IO, spmat::SparseMatrixCSC)

#     n = length(spmat)
#     (n_row_full, n_col_full) = size(spmat)
#     T = eltype(spmat.data)
#     println("$(n)-sparse element (full size: $(n_row_full)x$(n_col_full)) SparseMatrixCSC{$(T)}:")
#     println("\tindex\tdata")

#     for cc = 1:n_col_full

#     end

#     for kk = 1:n
#         ii = spmat.row_index[kk]
#         jj = spmat.col_index[kk]
#         dd = spmat.data[kk]
#         println("\t($(ii), $(jj))\t$(dd)")
#     end

# end

function Base.length(spmat::SparseMatrixCSC)
    return length(spmat.data)
end

function n_nonzero(spmat::SparseMatrixCSC)
    return length(spmat)
end

function sparse_length(spmat::SparseMatrixCSC)
    return length(spmat)
end

function full_length(spmat::SparseMatrixCSC)
    return spmat.n_row * spmat.n_col
end

function Base.size(spmat::SparseMatrixCSC)
    return ( spmat.n_row, spmat.n_col )
end

function Base.size(spmat::SparseMatrixCSC, dim)
    if dim == 1
        return spmat.n_row
    elseif dim == 2
        return spmat.n_col
    else
        return 1
    end
end

function find_next_nonempty_col_begin(spmat::SparseMatrixCSC, col::Int)
    kk::Int = 1
    idx_end::Int = 0
    while true
        idx_end = spmat.col_begins_index[col + kk]
        if idx_end <= 0
            kk += 1
        else
            break
        end
    end
    flag_end_reached = idx_end == spmat.col_begins_index[end]
    return (idx_end, flag_end_reached)
end

function Base.getindex(spmat::SparseMatrixCSC, idx::Int)

    n_row = spmat.n_row
    n_col = spmat.n_col
    dims = (n_row, n_col)
    ci = CartesianIndices(dims)
    (rr, cc) = ci[idx].I

    col_begin = spmat.col_begins_index[cc]
    if col_begin <= 0
        return zero(eltype(spmat.data))
    end

    (col_end, flag_end_reached) = find_next_nonempty_col_begin(spmat, cc)
    if flag_end_reached
        return zero(eltype(spmat.data))
    end

    for ii = col_begin:(col_end-1)
        if spmat.row_index[ii] == rr
            return spmat.data[ii]
        end
    end

    return zero(eltype(spmat.data))
end

function Base.getindex(spmat::SparseMatrixCSC, I...)

    rr = I[1]
    cc = I[2]

    col_begin = spmat.col_begins_index[cc]
    if col_begin == 0
        return zero(eltype(spmat.data))
    end

    (col_end, flag_end_reached) = find_next_nonempty_col_begin(spmat, cc)

    if flag_end_reached
        return zero(eltype(spmat.data))
    end

    for ii = col_begin:(col_end-1)
        if spmat.row_index[ii] == rr
            return spmat.data[ii]
        end
    end

    return zero(eltype(spmat.data))

end

function matrix_split(spmat::SparseMatrixCSC)

    n_row = spmat.n_row
    n_col = spmat.n_col

    L = length(spmat)

    n_square = min(n_row, n_col)
    T = eltype(spmat.data)
    d = zeros(T, n_square)

    # for now: every newly created temporary array will have the same length as the original
    L_data      = zeros(T, L)
    L_row_idx   = zeros(Int, L)
    L_col_idx   = zeros(Int, L)

    U_data      = zeros(T, L)
    U_row_idx   = zeros(Int, L)
    U_col_idx   = zeros(Int, L)

    # main loop
    lastidx_l = 0
    lastidx_u = 0
    lastidx_d = 0

    for cc = 1:n_col

        col_begin = spmat.col_begins_index[cc]
        if col_begin <= 0
            continue
        end
        (col_end, flag_end_reached) = find_next_nonempty_col_begin(spmat, cc)

        for ii = col_begin:(col_end-1)

            dd = spmat.data[ii]
            rr = spmat.row_index[ii]

            if rr > cc # rr < cc # upper half

                lastidx_l += 1
                L_data[lastidx_l] = dd
                L_row_idx[lastidx_l] = rr
                L_col_idx[lastidx_l] = cc

            elseif rr == cc # diagonal

                lastidx_d += 1
                d[lastidx_d] = dd

            else # rr > cc # lower half

                lastidx_u += 1
                U_data[lastidx_u] = dd
                U_row_idx[lastidx_u] = rr
                U_col_idx[lastidx_u] = cc

            end

        end

    end

    # selection
    L_data      = L_data[1:lastidx_l]
    L_row_idx   = L_row_idx[1:lastidx_l]
    L_col_idx   = L_col_idx[1:lastidx_l]
    U_data      = U_data[1:lastidx_u]
    U_row_idx   = U_row_idx[1:lastidx_u]
    U_col_idx   = U_col_idx[1:lastidx_u]

    L = SparseMatrixCSC(n_row, n_col, L_data, L_row_idx, L_col_idx)
    U = SparseMatrixCSC(n_row, n_col, U_data, U_row_idx, U_col_idx)

    return (L, d, U)
end

max_stars_repo_name: HomoModelicus/julia

max_issues_repo_name: HomoModelicus/julia

max_forks_repo_name: HomoModelicus/julia


text:
f = 4

include("file2.jl")

b = 4

d = 3

function f1(x, y)
  n = 3 * x
  m = 2 * y
  return n + m
end

k = f2(a, d)

k = f1(a, d)

println(k) # should be 33

max_stars_repo_name: judy-vscode/judy

max_issues_repo_name: judy-vscode/judy

max_forks_repo_name: judy-vscode/judy


text:
using Yao.EasyBuild, YaoPlots, Yao
using Compose, Cairo

_save(str) = PNG(joinpath(@__DIR__, str))

lighttheme!()
YaoPlots.CircuitStyles.gate_bgcolor[] = "white"  # default is transparent
# qft circuit
vizcircuit(qft_circuit(5)) |> _save("qft.png")

# labeled and time evolution
vizcircuit(chain(control(5, 3, (2,4)=>matblock(rand_unitary(4); tag="label")),
    put(5, (2,4)=>matblock(rand_unitary(4); tag="label")), time_evolve(put(5, 2=>X), 0.2))) |> _save("labelled.png")

# variational circuit
vizcircuit(variational_circuit(5)) |> _save("variational.png")
# vizcircuit(variational_circuit(5; mode=:Merged))

# general U4 gate
vizcircuit(general_U4()) |> _save("u4.png")

# quantum supremacy circuit
vizcircuit(rand_supremacy2d(2, 2, 8)) |> _save("supremacy2d.png")

# google 52 qubit
vizcircuit(rand_google53(5); scale=0.5) |> _save("google53.png")

# control blocks
vizcircuit(chain(control(5, (2,-3), 4=>X), control(5, (-4, -2), 1=>Z))) |> _save("controls.png")

# controlled kron
control(4, 2, (1, 3)=>kron(X, X)) |> vizcircuit |> _save("cxx.png")

control(4, -collect(1:4-1), 4=>-Z) |> vizcircuit |> _save("reflect.png")

chain(5, [put(5, 2=>X), Yao.Measure(5; locs=(2,3)), Yao.Measure(5;locs=(2,)), Yao.Measure(5; resetto=bit"00110")]) |> vizcircuit |> _save("measure.png")

chain(5, [put(5, 2=>ConstGate.Sdag), put(5, 3=>ConstGate.Tdag),
    put(5, (2,3)=>ConstGate.CNOT), put(5, (1,4)=>ConstGate.CZ), put(5, (1,2,5)=>ConstGate.Toffoli),
    put(5, (2,3)=>ConstGate.SWAP), put(5, (1,)=>ConstGate.P0), put(5, (1,)=>ConstGate.I2),
    put(5, (2,)=>ConstGate.P1), put(5, (1,)=>ConstGate.Pu), put(5, (1,)=>ConstGate.Pd),
    put(5, (2,)=>ConstGate.T),
    put(5, (2,)=>phase(0.4π)),
    put(5, (2,)=>shift(0.4π)),
    ]) |> vizcircuit |> _save("constgates.png")

chain(5, [put(5, (2,3)=>matblock(Matrix(SWAP), tag="SWAP")'), put(5, 2=>matblock(mat(I2), tag="id")), put(5, 2=>label(X, "X")), control(5, (5,3), (2,4,1)=>put(3, (1,3)=>label(SWAP, "SWAP")))]) |> vizcircuit |>  _save("multiqubit.png")

YaoPlots.darktheme!()
YaoPlots.CircuitStyles.gate_bgcolor[] = "transparent"  # default is transparent
# qft circuit
vizcircuit(qft_circuit(5)) |> _save("qft-white.png")


text:
# syntax: proto3
using ProtoBuf
import ProtoBuf.meta

const TreeEnsemblePostEvaluationTransform = (;[
    Symbol("NoTransform") => Int32(0),
    Symbol("Classification_SoftMax") => Int32(1),
    Symbol("Regression_Logistic") => Int32(2),
    Symbol("Classification_SoftMaxWithZeroClassReference") => Int32(3),
]...)

const TreeEnsembleParameters_TreeNode_TreeNodeBehavior = (;[
    Symbol("BranchOnValueLessThanEqual") => Int32(0),
    Symbol("BranchOnValueLessThan") => Int32(1),
    Symbol("BranchOnValueGreaterThanEqual") => Int32(2),
    Symbol("BranchOnValueGreaterThan") => Int32(3),
    Symbol("BranchOnValueEqual") => Int32(4),
    Symbol("BranchOnValueNotEqual") => Int32(5),
    Symbol("LeafNode") => Int32(6),
]...)

mutable struct TreeEnsembleParameters_TreeNode_EvaluationInfo <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function TreeEnsembleParameters_TreeNode_EvaluationInfo(; kwargs...)
        obj = new(meta(TreeEnsembleParameters_TreeNode_EvaluationInfo), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct TreeEnsembleParameters_TreeNode_EvaluationInfo
const __meta_TreeEnsembleParameters_TreeNode_EvaluationInfo = Ref{ProtoMeta}()
function meta(::Type{TreeEnsembleParameters_TreeNode_EvaluationInfo})
    ProtoBuf.metalock() do
        if !isassigned(__meta_TreeEnsembleParameters_TreeNode_EvaluationInfo)
            __meta_TreeEnsembleParameters_TreeNode_EvaluationInfo[] = target = ProtoMeta(TreeEnsembleParameters_TreeNode_EvaluationInfo)
            allflds = Pair{Symbol,Union{Type,String}}[:evaluationIndex => UInt64, :evaluationValue => Float64]
            meta(target, TreeEnsembleParameters_TreeNode_EvaluationInfo, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_TreeEnsembleParameters_TreeNode_EvaluationInfo[]
    end
end
function Base.getproperty(obj::TreeEnsembleParameters_TreeNode_EvaluationInfo, name::Symbol)
    if name === :evaluationIndex
        return (obj.__protobuf_jl_internal_values[name])::UInt64
    elseif name === :evaluationValue
        return (obj.__protobuf_jl_internal_values[name])::Float64
    else
        getfield(obj, name)
    end
end

mutable struct TreeEnsembleParameters_TreeNode <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function TreeEnsembleParameters_TreeNode(; kwargs...)
        obj = new(meta(TreeEnsembleParameters_TreeNode), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct TreeEnsembleParameters_TreeNode
const __meta_TreeEnsembleParameters_TreeNode = Ref{ProtoMeta}()
function meta(::Type{TreeEnsembleParameters_TreeNode})
    ProtoBuf.metalock() do
        if !isassigned(__meta_TreeEnsembleParameters_TreeNode)
            __meta_TreeEnsembleParameters_TreeNode[] = target = ProtoMeta(TreeEnsembleParameters_TreeNode)
            fnum = Int[1,2,3,10,11,12,13,14,20,30]
            allflds = Pair{Symbol,Union{Type,String}}[:treeId => UInt64, :nodeId => UInt64, :nodeBehavior => Int32, :branchFeatureIndex => UInt64, :branchFeatureValue => Float64, :trueChildNodeId => UInt64, :falseChildNodeId => UInt64, :missingValueTracksTrueChild => Bool, :evaluationInfo => Base.Vector{TreeEnsembleParameters_TreeNode_EvaluationInfo}, :relativeHitRate => Float64]
            meta(target, TreeEnsembleParameters_TreeNode, allflds, ProtoBuf.DEF_REQ, fnum, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_TreeEnsembleParameters_TreeNode[]
    end
end
function Base.getproperty(obj::TreeEnsembleParameters_TreeNode, name::Symbol)
    if name === :treeId
        return (obj.__protobuf_jl_internal_values[name])::UInt64
    elseif name === :nodeId
        return (obj.__protobuf_jl_internal_values[name])::UInt64
    elseif name === :nodeBehavior
        return (obj.__protobuf_jl_internal_values[name])::Int32
    elseif name === :branchFeatureIndex
        return (obj.__protobuf_jl_internal_values[name])::UInt64
    elseif name === :branchFeatureValue
        return (obj.__protobuf_jl_internal_values[name])::Float64
    elseif name === :trueChildNodeId
        return (obj.__protobuf_jl_internal_values[name])::UInt64
    elseif name === :falseChildNodeId
        return (obj.__protobuf_jl_internal_values[name])::UInt64
    elseif name === :missingValueTracksTrueChild
        return (obj.__protobuf_jl_internal_values[name])::Bool
    elseif name === :evaluationInfo
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{TreeEnsembleParameters_TreeNode_EvaluationInfo}
    elseif name === :relativeHitRate
        return (obj.__protobuf_jl_internal_values[name])::Float64
    else
        getfield(obj, name)
    end
end

mutable struct TreeEnsembleParameters <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function TreeEnsembleParameters(; kwargs...)
        obj = new(meta(TreeEnsembleParameters), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct TreeEnsembleParameters
const __meta_TreeEnsembleParameters = Ref{ProtoMeta}()
function meta(::Type{TreeEnsembleParameters})
    ProtoBuf.metalock() do
        if !isassigned(__meta_TreeEnsembleParameters)
            __meta_TreeEnsembleParameters[] = target = ProtoMeta(TreeEnsembleParameters)
            pack = Symbol[:basePredictionValue]
            allflds = Pair{Symbol,Union{Type,String}}[:nodes => Base.Vector{TreeEnsembleParameters_TreeNode}, :numPredictionDimensions => UInt64, :basePredictionValue => Base.Vector{Float64}]
            meta(target, TreeEnsembleParameters, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, pack, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_TreeEnsembleParameters[]
    end
end
function Base.getproperty(obj::TreeEnsembleParameters, name::Symbol)
    if name === :nodes
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{TreeEnsembleParameters_TreeNode}
    elseif name === :numPredictionDimensions
        return (obj.__protobuf_jl_internal_values[name])::UInt64
    elseif name === :basePredictionValue
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{Float64}
    else
        getfield(obj, name)
    end
end

mutable struct TreeEnsembleClassifier <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function TreeEnsembleClassifier(; kwargs...)
        obj = new(meta(TreeEnsembleClassifier), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct TreeEnsembleClassifier
const __meta_TreeEnsembleClassifier = Ref{ProtoMeta}()
function meta(::Type{TreeEnsembleClassifier})
    ProtoBuf.metalock() do
        if !isassigned(__meta_TreeEnsembleClassifier)
            __meta_TreeEnsembleClassifier[] = target = ProtoMeta(TreeEnsembleClassifier)
            fnum = Int[1,2,100,101]
            allflds = Pair{Symbol,Union{Type,String}}[:treeEnsemble => TreeEnsembleParameters, :postEvaluationTransform => Int32, :stringClassLabels => StringVector, :int64ClassLabels => Int64Vector]
            oneofs = Int[0,0,1,1]
            oneof_names = Symbol[Symbol("ClassLabels")]
            meta(target, TreeEnsembleClassifier, allflds, ProtoBuf.DEF_REQ, fnum, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, oneofs, oneof_names)
        end
        __meta_TreeEnsembleClassifier[]
    end
end
function Base.getproperty(obj::TreeEnsembleClassifier, name::Symbol)
    if name === :treeEnsemble
        return (obj.__protobuf_jl_internal_values[name])::TreeEnsembleParameters
    elseif name === :postEvaluationTransform
        return (obj.__protobuf_jl_internal_values[name])::Int32
    elseif name === :stringClassLabels
        return (obj.__protobuf_jl_internal_values[name])::StringVector
    elseif name === :int64ClassLabels
        return (obj.__protobuf_jl_internal_values[name])::Int64Vector
    else
        getfield(obj, name)
    end
end

mutable struct TreeEnsembleRegressor <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function TreeEnsembleRegressor(; kwargs...)
        obj = new(meta(TreeEnsembleRegressor), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            if fldval !== nothing
                values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
            end
        end
        obj
    end
end # mutable struct TreeEnsembleRegressor
const __meta_TreeEnsembleRegressor = Ref{ProtoMeta}()
function meta(::Type{TreeEnsembleRegressor})
    ProtoBuf.metalock() do
        if !isassigned(__meta_TreeEnsembleRegressor)
            __meta_TreeEnsembleRegressor[] = target = ProtoMeta(TreeEnsembleRegressor)
            allflds = Pair{Symbol,Union{Type,String}}[:treeEnsemble => TreeEnsembleParameters, :postEvaluationTransform => Int32]
            meta(target, TreeEnsembleRegressor, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_TreeEnsembleRegressor[]
    end
end
function Base.getproperty(obj::TreeEnsembleRegressor, name::Symbol)
    if name === :treeEnsemble
        return (obj.__protobuf_jl_internal_values[name])::TreeEnsembleParameters
    elseif name === :postEvaluationTransform
        return (obj.__protobuf_jl_internal_values[name])::Int32
    else
        getfield(obj, name)
    end
end

export TreeEnsemblePostEvaluationTransform, TreeEnsembleParameters_TreeNode_TreeNodeBehavior, TreeEnsembleParameters_TreeNode_EvaluationInfo, TreeEnsembleParameters_TreeNode, TreeEnsembleParameters, TreeEnsembleClassifier, TreeEnsembleRegressor


text:
#=
# 2D Poisson, Dirichlet bc
# Uses Matlab imported as a custom gen target
=#

### If the Finch package has already been added, use this line #########
using Finch # Note: to add the package, first do: ]add "https://github.com/paralab/Finch.git"

### If not, use these four lines (working from the examples directory) ###
# if !@isdefined(Finch)
#     include("../Finch.jl");
#     using .Finch
# end
##########################################################################

init_finch("poisson2dmatlab");

# Try making an optional log
useLog("poisson2dmatlablog")

# Generate for the target in customtarget.jl
generateFor(MATLAB)

# Set up the configuration (order doesn't matter)
domain(2)
functionSpace(order=3)

# Specify the problem
mesh(QUADMESH, elsperdim=30)

u = variable("u")

testSymbol("v")

boundary(u, 1, DIRICHLET, 0)

# Write the weak form
coefficient("f", "-10*pi*pi*sin(pi*x)*sin(3*pi*y)")
weakForm(u, "-dot(grad(u),grad(v)) - f*v")

solve(u);

finalize_finch()

max_stars_repo_name: paralab/Finch

max_issues_repo_name: paralab/Finch

max_forks_repo_name: paralab/Finch


text:
function get_events_detectors(obj::ManeuverTriggers)
    return jcall(obj, "getEventsDetectors", Stream, ())
end

function get_field_events_detectors(obj::ManeuverTriggers, arg0::Field)
    return jcall(obj, "getFieldEventsDetectors", Stream, (Field,), arg0)
end

function init(obj::ManeuverTriggers, arg0::SpacecraftState, arg1::AbsoluteDate)
    return jcall(obj, "init", void, (SpacecraftState, AbsoluteDate), arg0, arg1)
end

function is_firing(obj::ManeuverTriggers, arg0::AbsoluteDate, arg1::Vector{jdouble})
    return jcall(obj, "isFiring", jboolean, (AbsoluteDate, Vector{jdouble}), arg0, arg1)
end

function is_firing(obj::ManeuverTriggers, arg0::FieldAbsoluteDate, arg1::Vector{RealFieldElement})
    return jcall(obj, "isFiring", jboolean, (FieldAbsoluteDate, Vector{RealFieldElement}), arg0, arg1)
end


text:
import Base.reshape, Base.vec
export reshape, vec

reshape(x::Constant, m::Int64, n::Int64) = Constant(reshape(x.value, m, n))

function reshape(x::AffineExpr, m::Int64, n::Int64)
  if x.size[1] * x.size[2] != m * n
    error("Cannot reshape expression of size $(x.size[1]) by $(x.size[2]) to $m by $n")
  end
  this = AffineExpr(:reshape, (x,), x.vars_to_coeffs_map, x.constant, (m, n))
  this.evaluate = ()->reshape(x.evaluate(), m, n)
  return this
end

vec(x::AffineOrConstant) = reshape(x, x.size[1] * x.size[2], 1)


text:
import LinearAlgebra: size, mul!
import Base: *

struct ImplicitProd{T<:Number,TQ<:AbstractMatrix{T},TU<:AbstractMatrix{T}} <:AbstractMatrix{T}
    p1::AbstractVector{Int}
    Q::TQ
    p2::AbstractVector{Int}
    U::TU

    function ImplicitProd(p1::AbstractVector{Int}, Q::AbstractMatrix{T},
                          p2::AbstractVector{Int}, U::AbstractMatrix{T}) where T<:Number

        @assert isempty(p1) || length(p1) == size(Q, 1) && isperm(p1)
        @assert isempty(p2) || length(p2) == size(Q, 2) && isperm(p2)
        @assert size(U, 2) <= size(U, 1) <= size(Q, 2)
        p1 = p1 == 1:length(p1) ? NOPERM : p1
        p2 = p2 == 1:length(p2) ? NOPERM : p2
        new{T, typeof(Q), typeof(U)}(p1, Q, p2, U)
    end
end

const NOPERM = Base.OneTo(0)

ImplicitProd(Q::AbstractMatrix{T}, U::AbstractMatrix{T}) where T =
    ImplicitProd(1:0, Q, 1:0, U)

ImplicitProd(p1::AbstractVector{Int}, Q::AbstractMatrix{T}, U::AbstractMatrix{T}) where T =
    ImplicitProd(p1, Q, 1:0, U)

ImplicitProd(Q::AbstractMatrix{T}, p2::AbstractVector{Int}, U::AbstractMatrix{T}) where T =
    ImplicitProd(1:0, Q, p2, U)

Base.show(io::IO, A::ImplicitProd) = show(io, MIME("text/plain"), A)
Base.show(io::IO, ::MIME"text/plain", A::ImplicitProd) = Base.show_default(io, A)
Base.show(io::IO, A::Adjoint{<:Any,<:ImplicitProd}) = show(io, MIME("text/plain"), A)
Base.show(io::IO, ::MIME"text/plain", A::Adjoint{<:Any,<:ImplicitProd}) = Base.show_default(io, A)

#convert named tuple to explicit matrix
function Base.Matrix(A::ImplicitProd{T}) where T<:Number
    m, n, rk, nullity = sizes(A)
    X = zeros(T, m, n)
    X[1:rk,1:nullity] .= A.U
    for i = 1:m-rk
        X[rk+i,nullity+i] = T(1)
    end
    if ! isempty(A.p2)
        X = X[A.p2,:]
    end
    X = A.Q * X
    if ! isempty(A.p1)
        X = X[A.p1,:]
    end
    X
end

Base.Matrix(aA::Adjoint{<:Any,<:ImplicitProd}) = Matrix(Matrix(aA.parent)')

"""
    `m, n, rk, nullity = sizes(A::ImplicitProd)`

m is the column count of A.Q
n is the column count of A.X
rk is the row count of U
nullity is the column count of U
"""
@inline function sizes(A::ImplicitProd)
    rk, nullity = size(A.U)
    m = size(A.Q, 2)
    n = m - rk + nullity
    m, n, rk, nullity
end

size(A::ImplicitProd) = (size(A.Q, 1), size(A.U, 2) + size(A.Q, 2) - size(A.U, 1))

## *(A::ImplicitProd, B::AbstractVector) = mul!(similar(B, size(A, 1)), A, B)

function mul!(C::AbstractVector, A::ImplicitProd, B::AbstractVector)
    checkdims(C, A, B)
    m, n, rk, nullity = sizes(A)
    @inbounds C[1:rk] .= A.U * B[1:nullity]
    @inbounds C[rk+1:end] .= B[nullity+1:end]
    if ! isempty(A.p2)
        C[:] .= C[A.p2]
    end
    lmul!(A.Q, C)
    if ! isempty(A.p1)
        @inbounds C[:] .= C[A.p1]
    end
    C
end

## *(A::ImplicitProd, B::AbstractMatrix) = mul!(similar(B, size(A, 1), size(B, 2)), A, B)

function mul!(C::AbstractMatrix, A::ImplicitProd, B::AbstractMatrix)
    checkdims(C, A, B)
    m, n, rk, nullity = sizes(A)
    @inbounds C[1:rk,:] .= A.U * B[1:nullity,:]
    @inbounds C[rk+1:end,:] .= B[nullity+1:end,:]
    if ! isempty(A.p2)
        @inbounds C[:,:] .= C[A.p2,:]
    end
    lmul!(A.Q, C)
    if ! isempty(A.p1)
        @inbounds C[:,:] .= C[A.p1,:]
    end
    C
end

## *(A::Adjoint{<:Any,<:ImplicitProd}, B::AbstractVector) = mul!(similar(B, size(A, 1)), A, B)

function mul!(C::AbstractVector, aA::Adjoint{<:Any,<:ImplicitProd}, B::AbstractVector)
    checkdims(C, aA, B)
    A = aA.parent
    m, n, rk, nullity = sizes(A)
    if ! isempty(A.p1)
        D = similar(B)
        @inbounds D[A.p1] .= B
    else
        D = B
    end
    lmul!(A.Q', D)
    if ! isempty(A.p2)
        @inbounds D[A.p2] .= D
    end
    @inbounds C[1:nullity] = A.U' * D[1:rk]
    @inbounds C[nullity+1:end] = D[rk+1:end]
    C
end

## *(A::Adjoint{<:Any,<:ImplicitProd}, B::AbstractMatrix) = mul!(similar(B, size(A, 1), size(B, 2)), A, B)

function mul!(C::AbstractMatrix, aA::Adjoint{<:Any,<:ImplicitProd}, B::AbstractMatrix)
    checkdims(C, aA, B)
    A = aA.parent
    m, n, rk, nullity = sizes(A)
    if ! isempty(A.p1)
        D = similar(B)
        D[A.p1,:] .= B
    else
        D = B
    end
    E = A.Q' * D # mul! not defined for adjoints of Q mul!(similar(D), A.Q', D)
    if ! isempty(A.p2)
        E[A.p2,:] .= E
    end
    C[1:nullity,:] .= A.U' * E[1:rk,:]
    C[nullity+1:end,:] .= E[rk+1:end,:]
    C
end

function mul!(C::AbstractMatrix, aA::Adjoint{<:Any,<:ImplicitProd}, aB::Adjoint{<:Any,<:AbstractMatrix})

    mul!(C, aA, copy(aB))
end

mul!(C::AbstractArray, A::UniformScaling, B::AbstractArray) = ( C .= B; C .*= A[1,1]; C )

function checkdims(C, A, B)
    m, n = size(A, 2), size(B, 1)
    if m != n
        text = "second dimension of A, $m, does not match first dimension of B, $n"
        throw(DimensionMismatch(text))
    end
    if size(C, 1) != size(A, 1) || size(C, 2) != size(B, 2)
        text = "destination dimensions $(size(C)) do not match result dimensions ($(size(A, 1)),$(size(B, 2)))"
        throw(DimensionMismatch(text))
    end
end


text:
using Elly
using Test
using Random

function test_hdfs(host="localhost", port=9000)
    limitedtestenv = (get(ENV, "CI", "false") == "true")

    hdfsclnt = HDFSClient(host, port)

    exists(hdfsclnt, "/tmp") || mkdir(hdfsclnt, "/tmp")

    println("listing files in root folder...")
    dirtree = readdir(hdfsclnt, "/")
    println(dirtree)
    @test "tmp" in dirtree

    println("getting server defaults...")
    defs = hdfs_server_defaults(hdfsclnt)
    for k in keys(defs)
        println("\t$k => $(defs[k])")
    end
    @test hdfs_default_block_size(hdfsclnt) > 0
    @test hdfs_default_replication(hdfsclnt) > 0

    println("getting file system status...")
    fs_status = hdfs_status(hdfsclnt)
    for k in keys(fs_status)
        println("\t$k => $(fs_status[k])")
    end
    @test hdfs_capacity(hdfsclnt) > 0

    println("/tmp should be a directory")
    @test isdir(hdfsclnt, "/tmp")

    println("du should be >= 0")
    @test du(hdfsclnt, "/") >= 0

    println("stat /tmp")
    st = stat(hdfsclnt, "/tmp")
    println(st)
    @test st.name == "/tmp"

    println("create a temporary dir...")
    cd(hdfsclnt, "/tmp")
    foo_dir = HDFSFile(hdfsclnt, "foo")
    mkdir(foo_dir, Elly.DEFAULT_FOLDER_MODE)

    println("create a temporary file...")
    cd(hdfsclnt, "foo")
    bar_file = HDFSFile(hdfsclnt, "bar")
    teststr = "hello world\n"
    nloops = 1000
    t1 = time()
    open(bar_file, "w") do f
        for idx in 1:nloops
            write(f, teststr)
        end
    end
    println("...done in $(time() - t1) secs")
    println("verify file size to be $(length(teststr)*nloops)...")
    @test filesize(bar_file) == length(teststr) * nloops

    println("touch, move and delete file...")
    touch(bar_file)
    @test isfile(bar_file)
    st = stat(bar_file)
    println(st)
    @test st.name == "bar"
    mv(bar_file, "/tmp/foo/bar2")
    bar2_file = HDFSFile("hdfs://$(host):$(port)/tmp/foo/bar2")
    @test isfile(bar2_file)
    rm(bar2_file)

    println("touch and delete a new file...")
    touch(bar_file)
    @test exists(bar_file)
    @test isfile(bar_file)
    rm(bar_file)

    println("create a large file...")
    size_bytes = limitedtestenv ? (128 * 10 * 1000) : (128 * 1000 * 1000)
    nloops = limitedtestenv ? 2 : 5
    A = rand(UInt8, size_bytes)
    open(bar_file, "w"; blocksz=UInt64(size_bytes)) do f
        for idx in 1:nloops
            t1 = time()
            write(f, A)
            println("...block written in $(time() - t1) secs")
        end
    end
    println("verify file size to be $(sizeof(A) * nloops)...")
    @test filesize(bar_file) == sizeof(A) * nloops

    println("read and verify...")
    B = Array{UInt8}(undef, size_bytes)
    open(bar_file, "r") do f
        for idx in 1:nloops
            t1 = time()
            read!(f, B)
            println("...block read in $(time() - t1) secs")
            @test A == B
        end
    end

    println("read and verify with crc...")
    B = Array{UInt8}(undef, size_bytes)
    open(bar_file, "r"; crc=true) do f
        for idx in 1:nloops
            t1 = time()
            read!(f, B)
            println("...block read in $(time() - t1) secs")
            @test A == B
        end
    end

    println("blocks for $bar_file")
    blocks = hdfs_blocks(bar_file)
    println(blocks)

    println("setting replication factor for $bar_file")
    @test hdfs_set_replication(bar_file, 2)

    cd(hdfsclnt, "/tmp/foo")
    NFILES = limitedtestenv ? 10 : 1000
    println("create many ($NFILES) files...")
    for fidx in 1:NFILES
        bar_file = HDFSFile(hdfsclnt, "bar$fidx")
        open(bar_file, "w") do f
            for idx in 1:nloops
                write(f, teststr)
            end
        end
        ((fidx % 10) == 0) && println("...created file #$fidx")
    end
    println("reading directory...")
    allfiles = readdir(hdfsclnt, "/tmp/foo")
    println("delete many ($NFILES) files...")
    for idx in 1:NFILES
        bar_file = HDFSFile(hdfsclnt, "bar$idx")
        rm(bar_file)
        ((idx % 10) == 0) && println("...deleted file #$idx")
    end
    @test length(allfiles) >= NFILES

    println("test renew lease")
    hdfs_renewlease(hdfsclnt)
    iob = IOBuffer()
    show(iob, hdfsclnt)
    @test !isempty(take!(iob))

    nothing
end


text:
using Printf
using Statistics

using Oceananigans: short_show

struct StateChecker{T, F} <: AbstractDiagnostic
    schedule :: T
      fields :: F
end

"""
    StateChecker(; schedule, fields)

Returns a `StateChecker` that logs field information (minimum, maximum, mean)
for each field in a named tuple of `fields` when `schedule` actuates.
"""
StateChecker(model; schedule, fields=fields(model)) = StateChecker(schedule, fields)

function run_diagnostic!(sc::StateChecker, model)
    pad = keys(sc.fields) .|> string .|> length |> maximum

    @info "State check @ $(short_show(model.clock))"

    for (name, field) in pairs(sc.fields)
        state_check(field, name, pad)
    end

    return nothing
end

function state_check(field, name, pad)
    min_val = minimum(field)
    max_val = maximum(field)
    mean_val = mean(field)

    name = lpad(name, pad)

    @info @sprintf("%s | min = %+.15e | max = %+.15e | mean = %+.15e", name, min_val, max_val, mean_val)
    return nothing
end

(sc::StateChecker)(model) = run_diagnostic!(sc, model)

Base.show(io::IO, sc::StateChecker) =
    print(io, "StateChecker checking $(length(sc.fields)) fields: $(keys(sc.fields))")


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

using Test, Libdl, OpenBLAS_jll

if Base.USE_BLAS64
    macro blasfunc(x)
        return Expr(:quote, Symbol(x, "64_"))
    end
else
    macro blasfunc(x)
        return Expr(:quote, x)
    end
end

@testset "OpenBLAS_jll" begin
    @test dlsym(OpenBLAS_jll.libopenblas_handle, @blasfunc(openblas_set_num_threads); throw_error=false) != nothing
end

max_stars_repo_name: jonas-schulze/julia

max_issues_repo_name: jonas-schulze/julia

max_forks_repo_name: jonas-schulze/julia


text:
using IEX
using Test

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


text:
immutable CellRange{T}
  box::Box{T}
  datael_id::Int
  style_id::Int
end
size(rng::CellRange)  = size(rng.box)

_data_id(r::CellRange) = r.datael_id
_style_id(r::CellRange) = r.style_id
_box(r::CellRange) = r.box

function shatterinto{T <: Number}(r1::CellRange{T}, r2::CellRange{T})
  box = _box(r2)
  dataid  = _data_id(r2)
  styleid = _style_id(r2)
  ibox = intersect(_box(r1), box)

  if isnull(ibox)
    return [r2]
  else
    ibox = get(ibox)
  end

  hastopspace    = ymax(box) > ymax(ibox)
  hasbottomspace = ymin(box) < ymin(ibox)

  hasrightspace  = xmax(box) > xmax(ibox)
  hasleftspace   = xmin(box) < xmin(ibox)

  res = CellRange{T}[]
  # place top
  if hastopspace
#     print("top")
    p1, p2 = Point(xmin(box), ymax(ibox)), Point(xmax(box), ymax(box))
    push!(res, Range(Box{T}(p1, p2), dataid, styleid))
  end
  # place bottom
  if hasbottomspace
#     print("bottom")
    p1, p2 = Point(xmin(box), ymin(box)), Point(xmax(box), ymin(ibox))
    push!(res, Range(Box{T}(p1, p2), dataid, styleid))
  end
  # place right
  if hasrightspace
#     print("right")
    p1, p2 = Point(xmax(ibox), ymin(ibox)), Point(xmax(box), ymax(ibox))
    push!(res, Range(Box{T}(p1, p2), dataid, styleid))
  end
  # place left
  if hasleftspace
#     print("left")
    p1, p2 = Point(xmin(box), ymin(ibox)), Point(xmin(ibox), ymax(ibox))
    push!(res, Range(Box{T}(p1, p2), dataid, styleid))
  end
  return res
end


text:
function generate(args::Dict)
  file_type = args["<generator>"]
  file_name = args["<name>"]
  file_params = args["<field>"]

  generate(file_type, file_name, file_params...)
end

function generate(file_type, file_name, file_params...)

  if file_type == "init"
    touch("$(pwd())/config/initializers/$file_name.jl")
    return
  end

  if file_type == "task"
    file_abs_path = "$(pwd())/lib/tasks/$file_name.jl"

    template_file = generate_file_template("src", "function", file_name, file_params)

    open(file_abs_path, "w") do file
      write(file, template_file)
    end

    return
  end

  parent_folders = [
    "src",
    "test"
  ]

  for parent_folder in parent_folders
    suffix = ( parent_folder == "test" ) ? "_test" : ""
    file_rel_path = "$(pluralize(file_type))/$file_name$suffix.jl"
    file_abs_path = "$(pwd())/$parent_folder/$file_rel_path"

    if isfile(file_abs_path)
      answer = user_input("Do you want to overwrite $file_rel_path? [y/n] ");
      if strip(lowercase(answer)) != "y" ; continue ; end
    end

    nested_path, parsed_file_name = contains(file_name, "/") ?
      rsplit(file_name, "/"; limit=2) : ("", file_name)

    parsed_file_name = String(parsed_file_name)

    current_nested_path = ""
    for nested_ancestor in split(nested_path, "/")
      current_nested_path = "$current_nested_path/$nested_ancestor"
      folder_path = "$(pwd())/$parent_folder/$(pluralize(file_type))$current_nested_path"

      if isdir(folder_path) ; continue ; end
      mkdir(folder_path)
    end

    template_file = generate_file_template(parent_folder, file_type, parsed_file_name, file_params)

    open(file_abs_path, "w") do file
      write(file, template_file)
    end
  end

end


text:
@testset "utils" begin
    @test radians_to_length(1, "radians") == 1
    @test radians_to_length(1, "kilometers") == earth_radius / 1000
    @test radians_to_length(1, "miles") == earth_radius / 1609.344

    @test length_to_radians(1, "radians") == 1
    @test length_to_radians(earth_radius / 1000, "kilometers") == 1
    @test length_to_radians(earth_radius / 1609.344, "miles") == 1

    @test length_to_degrees(1, "radians") ≈ 57.29 atol=0.01
    @test length_to_degrees(100, "kilometers") ≈ 0.89 atol=0.01
    @test length_to_degrees(10, "miles") ≈ 0.14 atol=0.01

    @test convert_length(1000, "meters") == 1
    @test convert_length(1, "kilometers", "miles") ≈ 0.62 atol=0.01
    @test convert_length(1, "nauticalmiles") == 1.852
    @test convert_length(1, "miles", "kilometers") == 1.609344

    @test convert_area(1000) == 0.001
    @test convert_area(1, "kilometers", "miles") == 0.386
    @test convert_area(1, "metres", "centimeters") == 10000
    @test convert_area(100, "meters", "feet") ≈ 1076.39 atol=0.01

    @test_throws ErrorException convert_area(-5, "meters", "feet")

    poly = Polygon([[[125, -15],[113, -22],[117, -37],[130, -33],[148, -39],[154, -27],[144, -15],[125, -15]]])
    @test area(poly) ≈ 7766240997209

    line = LineString([
	[
		0,
		0
	],
	[
		0,
		2
	],
	[
		0,
		5
	],
	[
		0,
		8
	],
	[
		0,
		10
	],
	[
		0,
		10
		]])

	poly = Polygon([
			[
				[
					0,
					0
				],
				[
					0,
					5
				],
				[
					0,
					10
				],
				[
					10,
					10
				],
				[
					10,
					0
				],
				[
					5,
					0
				],
				[
					0,
					0
				],
				[
					0,
					0
				]
			]
		])

	ml = MultiLineString([
			[
				[
					0,
					0
				],
				[
					0,
					2
				],
				[
					0,
					5
				],
				[
					0,
					8
				],
				[
					0,
					10
				],
				[
					0,
					10
				]
			],
			[
				[
					1,
					1
				],
				[
					2,
					2
				],
				[
					3,
					3
				],
				[
					4,
					4
				],
				[
					5,
					5
				],
				[
					6,
					6
				]
			]
		])

	mp = MultiPolygon([
			[
				[
					[
						0,
						0
					],
					[
						5,
						0
					],
					[
						5,
						0
					],
					[
						10,
						0
					],
					[
						10,
						10
					],
					[
						0,
						10
					],
					[
						0,
						5
					],
					[
						0,
						0
					]
				],
				[
					[
						1,
						5
					],
					[
						1,
						7
					],
					[
						1,
						8.5
					],
					[
						4.5,
						8.5
					],
					[
						4.5,
						7
					],
					[
						4.5,
						5
					],
					[
						1,
						5
					]
				]
			],
			[
				[
					[
						11,
						11
					],
					[
						11.5,
						11.5
					],
					[
						12,
						12
					],
					[
						12,
						11
					],
					[
						11.5,
						11
					],
					[
						11,
						11
					],
					[
						11,
						11
					]
				]
			]
		])

	mpo = MultiPoint([
			[
				14.765625,
				26.194876675795218
			],
			[
				8.61328125,
				23.483400654325642
			],
			[
				17.75390625,
				24.926294766395593
			]
		])
    @test clean(line).coordinates == [[0, 0], [0, 10]]
	@test clean(poly).coordinates == [
			[
				[
					0,
					0
				],
				[
					0,
					10
				],
				[
					10,
					10
				],
				[
					10,
					0
				],
				[
					0,
					0
				]
			]
		]

	@test clean(ml).coordinates == [
			[
				[
					0,
					0
				],
				[
					0,
					10
				]
			],
			[
				[
					1,
					1
				],
				[
					6,
					6
				]
			]
		]
	@test clean(mp).coordinates == [
			[
				[
					[
						0,
						0
					],
					[
						10,
						0
					],
					[
						10,
						10
					],
					[
						0,
						10
					],
					[
						0,
						0
					]
				],
				[
					[
						1,
						5
					],
					[
						1,
						8.5
					],
					[
						4.5,
						8.5
					],
					[
						4.5,
						5
					],
					[
						1,
						5
					]
			],
			[
					[
						11,
						11
					],
					[
						12,
						12
					],
					[
						12,
						11
					],
					[
						11,
						11
					]
			]
		]
	]

	@test clean(mpo).coordinates == mpo.coordinates
	@test clean(Feature(mpo)).coordinates == clean(mpo).coordinates
end


text:
using Plots
pyplot()

taskNr = 2;

function coinFlips(n,p)
    # Generate a random vector from the uniform distribution
    r = rand(n);
    heads = zeros(Float64,n);

    # Turney operator, make head or tail (1,0)
    heads = map(x -> x >= p ? 1 : 0, r)

    # Calculate the cumulative ratio of heads along the series
    headsNr = cumsum(heads)
    flipnr = collect(1:n)
    headsRatio = headsNr ./ flipnr

    return heads, headsRatio
end

if taskNr == 1
    N = 1000;
    P = 0.5;    # ratio of tails
    (h, hRatio) = coinFlips(N,P);

    # Plot it
    plot(hRatio,
         xlabel = "Flips",
         xscale = :log10,
         xlims  = (1,N),
         ylabel = "Frequency Heads",
         yticks = 0:.1:1,
         marker = :d,
         label  = "")
    # for holding the plot
    plot!([1,N],[P,P],     # start @ 1 to make log work
          linestyle = :dash,
          label = "",
          w = 2)
    annotate!(N/10, abs(hRatio[1] - (P-0.2)), # located either above or below the 0.5 line
             text(string("Final ratio = ", hRatio[end])))

    savefig("TaskA-1-a.eps")
    savefig("TaskA-1-a.png")

elseif taskNr == 2
    for i = 1:3
        N = 100 * 10^(i-1);
        P = 0.75;   # ratio of tails

        (h, hRatio) = coinFlips(N,P);
        histogram(h,
            label = string(N, " flips"),
            bar_width = 1,
            normalize = :probability)
        plot!([0, 0],[0, P],
            label = "PMF",
            linestyle = :solid,
            c = :red,
            w = 3)
        plot!([1, 1],[0, 1-P],
            label = "",
            linestyle = :solid,
            c = :red,
            w = 3)
        scatter!([0, 1],[P, 1-P],
            label = "",
            marker = (0,20,:red))

        savefig(string("TaskA-1-c-", i, ".eps"))
        savefig(string("TaskA-1-c-", i, ".png"))
    end
end


text:
"""
Formulate and solve the Beasley and Christofides benchmarks using JuMP
(solved using Gurobi in this case, which seems faster than CPLEX)
"""

using LightGraphs
using JuMP
using Gurobi
using BenchmarkTools # For timing

import Base.parse

"""
Parse a Beasley-Christofides benchmark file and returns
- g - SimpleDiGraph with problem
- min_res - Vector of float with lower bounds
- max_res - Vector of float with upper bounds
- costs - Vector of float with upper bounds
"""
function parse_benchmark(
  filename::String
)::Tuple{
  SimpleDiGraph,Vector{Float64},Vector{Float64},Vector{Float64},AbstractMatrix{Float64}
}
  f = open(filename)
  arc_count = Int(1)
  number_nodes = Int(0)
  number_edges = Int(0)
  number_resources = Int(0)

  for line in eachline(f)
    line = split(line, " ")
    number_nodes, number_edges, number_resources = parse(Int, line[2]),
    parse(Int, line[3]),
    parse(Int, line[4])
    break
  end

  g = SimpleDiGraph(number_nodes)

  min_res = []
  for line in eachline(f)
    line = split(line, " ")
    for r in 1:number_resources
      r = parse(Float64, line[1 + r])
      push!(min_res, r)
    end
    break
  end
  max_res = []
  for line in eachline(f)
    line = split(line, " ")
    for r in 1:number_resources
      r = parse(Float64, line[1 + r])
      push!(max_res, r)
    end
    break
  end
  count = 1
  for line in eachline(f)
    if count == number_nodes
      break
    end
    count += 1
  end
  # Parse edges
  res_costs = zeros(Float64, number_edges, number_resources)
  costs = []
  count = 1
  for line in eachline(f)
    line = split(line, " ")
    i, j, cost = parse(Int, line[2]), parse(Int, line[3]), parse(Float64, line[4])
    if j != 1 || i != number_nodes
      add_edge!(g, i, j)
    end
    push!(costs, cost)
    for r in 1:number_resources
      res = parse(Float64, line[4 + r])
      res_costs[count, r] = res
    end
    count += 1
  end
  close(f)
  return g, min_res, max_res, costs, res_costs
end

function get_result(folder::String, instance_number::Int)::Float64
  f = open("$folder/results.txt")
  count = 1
  result = 0.0
  for line in eachline(f)
    line = split(line, " ")
    if count == instance_number + 1
      result = parse(Int, line[2])
      break
    end
    count += 1
  end
  close(f)
  return result
end

function formulate(
  g::SimpleDiGraph,
  min_res::Vector{Float64},
  max_res::Vector{Float64},
  costs::Vector{Float64},
  res_costs::AbstractMatrix{Float64},
)::Float64
  N = nv(g)
  M = ne(g)
  R = length(max_res)

  model = Model(Gurobi.Optimizer)
  set_silent(model)
  @variable(model, x[e=edges(g)], Bin)
  @constraint(
    model,
    [i = 2:(N - 1)],
    sum(x[Edge(i, j)] for j in outneighbors(g, i)) -
    sum(x[Edge(j, i)] for j in inneighbors(g, i)) == 0
  )
  @constraint(model, sum(x[Edge(1, j)] for j in outneighbors(g, 1)) == 1)
  @constraint(model, -sum(x[Edge(i, N)] for i in inneighbors(g, N)) == -1)
  @constraint(
    model,
    [r = 1:R],
    min_res[r] <=
    sum(res_costs[e_idx, r] * x[e] for (e_idx, e) in enumerate(edges(g))) <=
    max_res[r]
  )

  @objective(model, Min, sum(costs[e_idx] * x[e] for (e_idx, e) in enumerate(edges(g))))
  t = @elapsed optimize!(model)
  @info "$(t*1000)"
  if termination_status(model) == MOI.OPTIMAL
    return objective_value(model)
  end
  return 0.0
end

for i in 1:24
  @info "$i"
  g, min_res, max_res, costs, res_costs = parse_benchmark(
    "../beasley_christofides_1989/rcsp$i.txt"
  )
  obj = formulate(g, min_res, max_res, costs, res_costs)
  opt = get_result("../beasley_christofides_1989/", i)
  if obj != opt
    @error "Failed for instance $i"
  end
end

max_stars_repo_name: dvbuntu/cspy

max_issues_repo_name: dvbuntu/cspy

max_forks_repo_name: dvbuntu/cspy


text:
struct InterfaceQuadratures
    quads::Any
    normals::Any
    tangents::Any
    scaleareas::Any
    celltoquad::Any
    ncells::Any
    totalnumqps::Any
    function InterfaceQuadratures(
        quads,
        normals,
        tangents,
        scaleareas,
        celltoquad,
    )
        ncells = length(celltoquad)
        nphase, nquads = size(quads)

        interfacenumqps = length.(quads)
        interfacenumqps = nquads == 0 ? [0, 0] : sum(interfacenumqps, dims = 2)
        @assert interfacenumqps[1] == interfacenumqps[2]
        totalnumqps = interfacenumqps[1]

        @assert nphase == 2
        @assert length(normals) == nquads
        @assert length(tangents) == nquads
        @assert length(scaleareas) == nquads
        @assert all(celltoquad .>= 0)
        @assert all(celltoquad .<= nquads)

        new(
            quads,
            normals,
            tangents,
            scaleareas,
            celltoquad,
            ncells,
            totalnumqps,
        )
    end
end

function InterfaceQuadratures(cutmesh, levelset, numqp)
    polyorder = order(levelset)
    dim = dimension(cutmesh)
    interpgrad = InterpolatingPolynomial(dim, dim, polyorder)
    numcells = number_of_cells(cutmesh)

    xL, xR = [-1.0, -1.0], [1.0, 1.0]
    invjac = inverse_jacobian(cutmesh)

    hasinterface = [cell_sign(cutmesh, cellid) == 0 for cellid = 1:numcells]
    numinterfaces = count(hasinterface)
    quads = Matrix(undef, 2, numinterfaces)
    normals = Vector(undef, numinterfaces)
    tangents = Vector(undef, numinterfaces)
    scaleareas = Vector(undef, numinterfaces)
    celltoquad = zeros(Int, numcells)
    invjac = inverse_jacobian(cutmesh)

    interfacecellids = findall(hasinterface)
    counter = 1
    for cellid in interfacecellids
        load_coefficients!(levelset, cellid)
        update_interpolating_gradient!(interpgrad,interpolater(levelset))
        cellmap = cell_map(cutmesh, cellid)

        try
            update_interface_quadrature!(
                quads,
                normals,
                tangents,
                scaleareas,
                counter,
                interpolater(levelset),
                interpgrad,
                xL,
                xR,
                numqp,
                invjac,
                2,
            )
        catch e
            update_interface_quadrature!(
                quads,
                normals,
                tangents,
                scaleareas,
                counter,
                interpolater(levelset),
                interpgrad,
                xL,
                xR,
                numqp,
                invjac,
                3,
            )
        end

        celltoquad[cellid] = counter
        counter += 1
    end
    return InterfaceQuadratures(
        quads,
        normals,
        tangents,
        scaleareas,
        celltoquad,
    )
end

function total_number_of_quadrature_points(interfacequads::InterfaceQuadratures)
    return interfacequads.totalnumqps
end

function update_interface_quadrature!(
    quads,
    normals,
    tangents,
    scaleareas,
    counter,
    levelset,
    levelsetgrad,
    xL,
    xR,
    numqp,
    invjac,
    numsplits,
)
    squad = surface_quadrature(
        levelset,
        levelsetgrad,
        xL,
        xR,
        numqp,
        numsplits = numsplits,
    )
    n = levelset_normals(levelset, points(squad), invjac)
    t = rotate_90(n)
    s = scale_area(t, invjac)

    quads[1, counter] = squad
    quads[2, counter] = squad
    normals[counter] = n
    tangents[counter] = t
    scaleareas[counter] = s
end

function Base.getindex(iquads::InterfaceQuadratures, s, cellid)
    row = cell_sign_to_row(s)
    idx = iquads.celltoquad[cellid]
    idx > 0 || error("Cell $cellid does not have an interface quadrature rule")
    return iquads.quads[row, idx]
end

function Base.show(io::IO, interfacequads::InterfaceQuadratures)
    ncells = interfacequads.ncells
    numinterfaces = length(interfacequads.normals)
    str = "InterfaceQuadratures\n\tNum. Cells: $ncells\n\tNum. Interfaces: $numinterfaces"
    print(io, str)
end

function interface_normals(iquads::InterfaceQuadratures, cellid)
    idx = iquads.celltoquad[cellid]
    idx > 0 || error("Cell $cellid does not have an interface quadrature rule")
    return iquads.normals[idx]
end

function interface_scale_areas(iquads::InterfaceQuadratures, cellid)
    idx = iquads.celltoquad[cellid]
    idx > 0 || error("Cell $cellid does not have an interface quadrature rule")
    return iquads.scaleareas[idx]
end

function interface_tangents(iquads::InterfaceQuadratures, cellid)
    idx = iquads.celltoquad[cellid]
    idx > 0 || error("Cell $cellid does not have an interface quadrature rule")
    return iquads.tangents[idx]
end

function update_interface_quadrature!(
    interfacequads::InterfaceQuadratures,
    s,
    cellid,
    quad,
)
    row = cell_sign_to_row(s)
    idx = interfacequads.celltoquad[cellid]
    interfacequads.quads[row, idx] = quad
end

function collect_interface_normals(interfacequads, mesh)

    ncells = number_of_cells(mesh)
    cellsign = [cell_sign(mesh, cellid) for cellid = 1:ncells]
    cellids = findall(cellsign .== 0)

    return collect_interface_normals(interfacequads, mesh, cellids)
end

function collect_interface_normals(interfacequads, mesh, cellids)

    totalnumqps = sum([length(interfacequads[1, cellid]) for cellid in cellids])
    interfacenormals = zeros(2, totalnumqps)
    start = 1

    for cellid in cellids
        normals = interface_normals(interfacequads, cellid)
        numqps = size(normals)[2]

        stop = start + numqps - 1

        interfacenormals[:, start:stop] = normals
        start = stop + 1
    end
    return interfacenormals
end

function collect_interface_quadrature_points(
    interfacequads,
    cellsign,
    mesh,
    cellids,
)
    totalnumqps = sum([length(interfacequads[1, cellid]) for cellid in cellids])
    quadraturepoints = zeros(2, totalnumqps)
    quadraturecellids = zeros(Int, totalnumqps)
    start = 1

    for cellid in cellids
        quad = interfacequads[cellsign, cellid]
        qps = points(quad)
        numqps = size(qps)[2]

        stop = start + numqps - 1

        quadraturepoints[:, start:stop] = qps
        quadraturecellids[start:stop] = repeat([cellid], numqps)
        start = stop + 1
    end
    return quadraturepoints, quadraturecellids
end

function collect_interface_quadrature_points(interfacequads, levelsetsign, mesh)

    ncells = number_of_cells(mesh)
    cellsign = [cell_sign(mesh, cellid) for cellid = 1:ncells]
    cellids = findall(cellsign .== 0)
    qps, qpcellids = collect_interface_quadrature_points(
        interfacequads,
        levelsetsign,
        mesh,
        cellids,
    )

    return qps, qpcellids
end


text:
using GAIO
using ForwardDiff

# domain (-40,40)^n, 3^n roots in domain
g(x) = 100*x + x .^ 2 - x .^ 3 .- sum(x)
Dg = x -> ForwardDiff.jacobian(g, x)

dim = 3
center, radius = zeros(dim), 40*ones(dim)
P = BoxPartition(Box(center, radius))

R = cover_roots(g, Dg, P[:], steps=dim*8)

plot(R)


text:
module BCs

using DocStringExtensions
using Adapt

export LwBCs, SwBCs

"""
    LwBCs{FT,FTA1D,FTA2DN}

Longwave boundary conditions

# Fields
$(DocStringExtensions.FIELDS)
"""
struct LwBCs{FT, FTA2D, FTA2DN}
    "Surface emissivity `[W/m²]` `(nbnd, ncol)`"
    sfc_emis::FTA2D
    "incident flux at top of atmosphere `[W/m²]` `(ncol, ngpt)`"
    inc_flux::FTA2DN
end
LwBCs(sfc_emis, inc_flux) = LwBCs{eltype(sfc_emis), typeof(sfc_emis), typeof(inc_flux)}(sfc_emis, inc_flux)
Adapt.@adapt_structure LwBCs

"""
    SwBCs{FT,FTA1D}
Shortwave boundary conditions
# Fields
$(DocStringExtensions.FIELDS)
"""
struct SwBCs{FT, FTA1D, FTA1DN, FTA2D}
    "zenith angle `(ncol)`"
    zenith::FTA1D
    "top of atmosphere flux `(ncol)`"
    toa_flux::FTA1D
    "surface albedo for specular (direct) radiation `(nbnd, ncol)`"
    sfc_alb_direct::FTA2D
    "incident diffuse flux at top of domain `[W/m2]` `(ncol, ngpt)`"
    inc_flux_diffuse::FTA1DN
    "surface albedo for diffuse radiation `(nbnd, ncol)`"
    sfc_alb_diffuse::FTA2D
end
SwBCs(zenith, toa_flux, sfc_alb_direct, inc_flux_diffuse, sfc_alb_diffuse) =
    SwBCs{eltype(zenith), typeof(zenith), typeof(inc_flux_diffuse), typeof(sfc_alb_direct)}(
        zenith,
        toa_flux,
        sfc_alb_direct,
        inc_flux_diffuse,
        sfc_alb_diffuse,
    )
Adapt.@adapt_structure SwBCs

end

max_stars_repo_name: climate-machine/JRRTMGP

max_issues_repo_name: climate-machine/JRRTMGP

max_forks_repo_name: climate-machine/JRRTMGP


text:
using Documenter
using UrlDownload

makedocs(;
    modules=[UrlDownload],
    authors="Andrey Oskin",
    repo="https://github.com/Arkoniak/UrlDownload.jl/blob/{commit}{path}#L{line}",
    sitename="UrlDownload.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://Arkoniak.github.io/UrlDownload.jl",
        siteurl="https://github.com/Arkoniak/UrlDownload.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
        "Basic usage" => "basic.md",
        "Additional functionality" => "advanced.md"
    ],
)

deploydocs(;
    repo="github.com/Arkoniak/UrlDownload.jl",
)


text:
function [X,J,dXdx]=JacobiDG1(DG,F,Topo,Param)
ksi=DG.xwX;
eta=DG.xwY;
nX=DG.OrdPolyX+1;
nY=DG.OrdPolyY+1;
XE1=Topo(DG,F.P(:,1),F.P(:,2),Param.Grid.Edges(F.E(1)).Type,Param);
Topo(X(i,j,1),X(i,j,2),z,Param)
XE2=Topo(DG,F.P(:,2),F.P(:,3),Param.Grid.Edges(F.E(2)).Type,Param);
XE3=Topo(DG,F.P(:,4),F.P(:,3),Param.Grid.Edges(F.E(3)).Type,Param);
XE4=Topo(DG,F.P(:,1),F.P(:,4),Param.Grid.Edges(F.E(4)).Type,Param);
X=zeros(nX,nY,3);
for j=1:nY
  for i=1:nX
    X(i,j,1:2)=0.5*((1-ksi(i))*XE4(j,:)+(1+ksi(i))*XE2(j,:)+(1-eta(j))*XE1(i,:)+(1+eta(j))*XE3(i,:))-...
      0.25*((1-ksi(i))*((1-eta(j))*F.P(1:2,1)'+(1+eta(j))*F.P(1:2,4)')+...
      (1+ksi(i))*((1-eta(j))'*F.P(1:2,2)'+(1+eta(j))*F.P(1:2,3)'));
  end
end
dXdx=zeros(nX,nY,2,2);
dXdx(:,:,1,1)=DG.DSX*X(:,:,1);
dXdx(:,:,2,1)=DG.DSX*X(:,:,2);
dXdx(:,:,1,2)=X(:,:,1)*(DG.DSY');
dXdx(:,:,2,2)=X(:,:,2)*(DG.DSY');
J=dXdx(:,:,1,1).*dXdx(:,:,2,2)-dXdx(:,:,1,2).*dXdx(:,:,2,1);
end


text:
function MidpointFieldIntegrator(arg0::Field, arg1::RealFieldElement)
    return MidpointFieldIntegrator((Field, RealFieldElement), arg0, arg1)
end

function get_a(obj::MidpointFieldIntegrator)
    return jcall(obj, "getA", Vector{Vector{RealFieldElement}}, ())
end

function get_b(obj::MidpointFieldIntegrator)
    return jcall(obj, "getB", Vector{RealFieldElement}, ())
end

function get_c(obj::MidpointFieldIntegrator)
    return jcall(obj, "getC", Vector{RealFieldElement}, ())
end


text:
poisson(T, n) = sparse(Tridiagonal(fill(T(-1), n-1),
                        fill(T(2), n), fill(T(-1), n-1)))
poisson(n) = poisson(Float64, n)

function stencil_grid(T,stencil,sz)
    # upper-bound for storage
    n = prod(sz) * sum(.!iszero,stencil)

    # indices and value of nonzero elements
    Si = zeros(Int,n)
    Sj = zeros(Int,n)
    Ss = zeros(T,n)

    linindices = LinearIndices(sz)
    nnz = 0

    stencil_sz = size(stencil)
    offset = CartesianIndex((stencil_sz .+ 1) .÷ 2)

    for i in CartesianIndices(sz)
        for k in CartesianIndices(stencil_sz)
            if stencil[k] != 0
                j = i + k - offset
                if checkbounds(Bool,linindices,j)
                    nnz = nnz + 1
                    Si[nnz] = linindices[i]
                    Sj[nnz] = linindices[j]
                    Ss[nnz] = stencil[k]
                end
            end
        end
    end

    sparse((@view Si[1:nnz]),
           (@view Sj[1:nnz]),
           (@view Ss[1:nnz]),
           prod(sz),prod(sz))
end

function poisson(T,sz::NTuple{N,Int}) where N
    #=
    In 2D stencil has the value:
    stencil = [0  -1   0;
               -1  4  -1;
               0  -1   0]

    =#
    stencil = zeros(T,ntuple(i -> 3,Val(N)))
    for i = 0:N-1
        Ipre = CartesianIndex(ntuple(l -> 2,i))
        Ipost = CartesianIndex(ntuple(l -> 2,N-i-1))
        stencil[Ipre, 1, Ipost] = -1
        stencil[Ipre, 3, Ipost] = -1
    end
    Icenter = CartesianIndex(ntuple(l -> 2,Val(N)))
    stencil[Icenter] = 2*N

    stencil_grid(T,stencil,sz)
end

poisson(sz::NTuple{N,Int}) where N = poisson(Float64,sz)


text:
include(joinpath(BASE_DIR, "test", "data_5bus_pu.jl"))
include(joinpath(BASE_DIR, "test", "data_14bus_pu.jl"))

checksys = false

@testset "Test System constructors from .jl files" begin
    tPowerSystem = System(nothing)
    nodes_5 = nodes5()
    nodes_14 = nodes14()

    for i in nodes_5
        nodes_5[i].angle = deg2rad(nodes_5[i].angle)
    end

    # Components with forecasts cannot be added to multiple systems, so clear them on each
    # test.

    sys5 = System(
        nodes_5,
        thermal_generators5(nodes_5),
        loads5(nodes_5),
        nothing,
        nothing,
        100.0,
        nothing,
        nothing;
        runchecks = checksys,
    )
    clear_components!(sys5)

    sys5b = System(
        nodes_5,
        thermal_generators5(nodes_5),
        loads5(nodes_5),
        nothing,
        battery5(nodes_5),
        100.0,
        nothing,
        nothing;
        runchecks = checksys,
    )
    clear_components!(sys5b)

    # GitHub issue #234 - fix forecasts5 in data file, use new format
    #_sys5b = PowerSystems._System(nodes_5, thermal_generators5(nodes_5), loads5(nodes_5), nothing, battery5(nodes_5),
    #                              100.0, forecasts5, nothing, nothing)
    #sys5b = System(_sys5b)

    sys5bh = System(
        nodes_5,
        vcat(thermal_generators5(nodes_5), hydro_generators5(nodes_5)),
        loads5(nodes_5),
        branches5(nodes_5),
        battery5(nodes_5),
        100.0,
        nothing,
        nothing;
        runchecks = checksys,
    )
    clear_components!(sys5bh)

    sys5bh = System(;
        buses = nodes_5,
        generators = vcat(thermal_generators5(nodes_5), hydro_generators5(nodes_5)),
        loads = loads5(nodes_5),
        branches = branches5(nodes_5),
        storage = battery5(nodes_5),
        basepower = 100.0,
        services = nothing,
        annex = nothing,
        runchecks = checksys,
    )
    clear_components!(sys5bh)

    # Test Data for 14 Bus

    # GitHub issue #234 - fix forecasts5 in data file, use new format
    #_sys14 = PowerSystems._System(nodes_14, thermal_generators14, loads14, nothing, nothing,
    #                            100.0, Dict{Symbol,Vector{<:Forecast}}(),nothing,nothing)
    #sys14 = System(_sys14)

    for i in nodes_14
        nodes_14[i].angle = deg2rad(nodes_14[i].angle)
    end

    sys14b = PowerSystems.System(
        nodes_14,
        thermal_generators14(nodes_14),
        loads14(nodes_14),
        nothing,
        battery14(nodes_14),
        100.0,
        nothing,
        nothing;
        runchecks = checksys,
    )
    clear_components!(sys14b)
    sys14b = PowerSystems.System(
        nodes_14,
        thermal_generators14(nodes_14),
        loads14(nodes_14),
        branches14(nodes_14),
        battery14(nodes_14),
        100.0,
        nothing,
        nothing;
        runchecks = checksys,
    )
    clear_components!(sys14b)
end

@testset "Test System constructor from Matpower" begin
    sys = System(PowerSystems.PowerModelsData(joinpath(MATPOWER_DIR, "case5_re.m")))
end

@testset "Test accessor functions of PowerSystems auto-generated types" begin
    # If this test fails because a type doesn't have a constructor that takes nothing,
    # it's because not all fields in that type are defined in power_system_structs.json
    # with nullable values. Consider adding them so that this "demo-constructor" works.
    # If that isn't appropriate for this type, add it to types_to_skip below.

    types_to_skip = (System,)
    for ps_type in IS.get_all_concrete_subtypes(PowerSystemType)
        ps_type in types_to_skip && continue
        obj = ps_type(nothing)
        for (field_name, field_type) in zip(fieldnames(ps_type), fieldtypes(ps_type))
            if field_name == :name || field_name == :forecasts
                func = getfield(InfrastructureSystems, Symbol("get_" * string(field_name)))
            else
                func = getfield(PowerSystems, Symbol("get_" * string(field_name)))
            end
            val = func(obj)
            @test val isa field_type
        end
    end
end

@testset "Test component conversion" begin
    sys = System(PowerSystems.PowerModelsData(joinpath(MATPOWER_DIR, "case5_re.m")))
    l = get_component(Line, sys, "4")
    PSY.convert_component!(MonitoredLine, l, sys)
    @test isnothing(get_component(Line, sys, "4"))
    @test get_name(get_component(MonitoredLine, sys, "4")) == "4"
    @test_throws ErrorException convert_component!(
        Line,
        get_component(MonitoredLine, sys, "4"),
        sys,
    )
    convert_component!(Line, get_component(MonitoredLine, sys, "4"), sys, force = true)
    @test isnothing(get_component(MonitoredLine, sys, "4"))
end


text:
using Network_ADER
using Test

include("Polynomial_reconstruction_coefficients_tests.jl")


text:
module NVTX

const ext = joinpath(dirname(@__DIR__), "deps", "ext.jl")
isfile(ext) || error("NVTX.jl has not been built, please run Pkg.build(\"NVTX\").")
include(ext)
if !configured
    # default (non-functional) values for critical variables,
    # making it possible to _load_ the package at all times.
    const libnvtx = nothing
end

const active = Ref{Bool}(false)

"""
    start()
    stop()

Controls whether calls to NVTX.jl effectively generate profiling data (disabled by default).
This is a feature of NVTX.jl, useful in combination with nvprof's `--profile-from-start off`
to narrow down the region where profiling data is collected.

See also: [`@activate`](@ref)
"""
start() = (active[] = true)

stop()  = (active[] = false)
@doc (@doc start) stop

"""
    @activate ex

Runs the expressions with the NVTX API activated.
"""
macro activate(ex)
    quote
        start()
        local ret = $(esc(ex))
        stop()
        ret
    end
end

include("domains.jl")
include("markers.jl")
include("ranges.jl")
# TODO: CUDA API

end


text:
@testset "CPLayer Representation" begin
    include("types.jl")
    include("accessors.jl")
end


text:
module MyExample

import Random
using ForwardDiff

greet() = print("Hello World!")
greet_alien() = print("Hello ", Random.randstring(8))

include("extra_file.jl")

export my_f, derivative_of_my_f

end # module


text:
using ITensors
using LinearAlgebra
using Random

include(joinpath(ITensors.examples_dir(), "src", "electronk.jl"))
include(joinpath(ITensors.examples_dir(), "src", "hubbard.jl"))

function main(;
  Nx::Int=6,
  Ny::Int=3,
  U::Float64=4.0,
  t::Float64=1.0,
  maxdim::Int=3000,
  conserve_ky=true,
  use_splitblocks=true,
  nsweeps=10,
  blas_num_threads=1,
  strided_num_threads=1,
  use_threaded_blocksparse=true,
  outputlevel=1,
  seed=1234,
)
  Random.seed!(seed)
  ITensors.Strided.set_num_threads(strided_num_threads)
  BLAS.set_num_threads(blas_num_threads)
  if use_threaded_blocksparse
    ITensors.enable_threaded_blocksparse()
  else
    ITensors.disable_threaded_blocksparse()
  end

  if outputlevel > 0
    @show Threads.nthreads()
    @show Sys.CPU_THREADS
    @show ITensors.blas_get_num_threads()
    @show ITensors.Strided.get_num_threads()
    @show ITensors.using_threaded_blocksparse()
    println()
  end

  N = Nx * Ny

  sweeps = Sweeps(nsweeps)
  maxdims = min.([100, 200, 400, 800, 2000, 3000, maxdim], maxdim)
  maxdim!(sweeps, maxdims...)
  cutoff!(sweeps, 1e-6)
  noise!(sweeps, 1e-6, 1e-7, 1e-8, 0.0)

  if outputlevel > 0
    @show sweeps
  end

  sites = siteinds("ElecK", N; conserve_qns=true, conserve_ky=conserve_ky, modulus_ky=Ny)

  ampo = hubbard(; Nx=Nx, Ny=Ny, t=t, U=U, ky=true)
  H = MPO(ampo, sites)

  if outputlevel > 0
    @show use_splitblocks
  end

  # This step makes the MPO more sparse but also
  # introduces more blocks.
  # It generally improves DMRG performance
  # at large bond dimensions.
  if use_splitblocks
    H = splitblocks(linkinds, H)
  end

  # Number of structural nonzero elements in a bulk
  # Hamiltonian MPO tensor
  if outputlevel > 0
    @show nnz(H[end ÷ 2])
    @show nnzblocks(H[end ÷ 2])
  end

  # Create start state
  state = Vector{String}(undef, N)
  for i in 1:N
    x = (i - 1) ÷ Ny
    y = (i - 1) % Ny
    if x % 2 == 0
      if y % 2 == 0
        state[i] = "Up"
      else
        state[i] = "Dn"
      end
    else
      if y % 2 == 0
        state[i] = "Dn"
      else
        state[i] = "Up"
      end
    end
  end

  psi0 = randomMPS(sites, state, 10)

  energy, psi = @time dmrg(H, psi0, sweeps; outputlevel=outputlevel)

  if outputlevel > 0
    @show Nx, Ny
    @show t, U
    @show flux(psi)
    @show maxlinkdim(psi)
    @show energy
  end
  return nothing
end

println("################################")
println("Compilation")
println("################################")
println("Without threaded block sparse:\n")
main(; nsweeps=2, use_threaded_blocksparse=false, outputlevel=0)
println()
println("With threaded block sparse:\n")
main(; nsweeps=2, use_threaded_blocksparse=true, outputlevel=0)
println()

println("################################")
println("Runtime")
println("################################")
println()
println("Without threaded block sparse:\n")
main(; nsweeps=10, use_threaded_blocksparse=false)
println()
println("With threaded block sparse:\n")
main(; nsweeps=10, use_threaded_blocksparse=true)
println()


text:
using PyCall
@pyimport importlib.machinery as mach

function pyimp(file)
	mach.SourceFileLoader("module", abspath(joinpath(dirname(@__FILE__), file)))[:load_module]("module")
end