text:
using Base: concatenate_setindex!

g = TypeDBClient

@given("put attribute type: username, with value type: string") do context
    _put_attribute_to_db(context, "username", g.Proto.AttributeType_ValueType.STRING)
end

@given("entity(person) set owns key type: username") do context
    g.con.entity_set_owns("person", "username", context[:transaction], true)
end

# Scenario: Entity can be created
@when("\$a = entity(person) create new instance with key(username): alice") do context

    username_type = g.get(context[:cm], AttributeType, "username")
    username_alice = g.put(g.as_remote(username_type, context[:transaction]), "alice")

    ent_type = g.get(context[:cm], EntityType, "person")
    ent_instance = g.create(g.as_remote(ent_type, context[:transaction]))

    g.set_has(context[:transaction], ent_instance, username_alice)

    context[:a] = ent_instance
end

@then("entity \$a is null: false") do context
    @expect context[:a] !== nothing
end

@then("entity \$a has type: person") do context
    erg = context[:a]
    @expect erg.type.label.name == "person"
end

@then("entity(person) get instances contain: \$a") do context
    attr = g.get(context[:cm], EntityType, "person")
    res = g.get_instances(g.as_remote(attr, context[:transaction]))
    @expect in(context[:a], res)
end

@when("\$a = entity(person) get instance with key(username): alice") do context
    attr_type = g.get(context[:cm], AttributeType, "username")
    res_attr = g.get(g.as_remote(attr_type, context[:transaction]), "alice")
    context[:a] = g.get_owners(context[:transaction], res_attr, nothing)[1]
end

# Scenario: Entity cannot be created when it misses a key
@when("\$a = entity(person) create new instance") do context
    ent_type = g.get(context[:cm], EntityType, "person")
    context[:a] = g.create(g.as_remote(ent_type, context[:transaction]))
end

# Scenario: Entity can be deleted
@when("delete entity: \$a") do context
    g.delete(g.as_remote(context[:a], context[:transaction]))
end

@then("entity \$a is deleted: true") do context
    res = g.is_deleted(g.as_remote(context[:a], context[:transaction]))
    @expect res
end

@then("entity(person) get instances is empty") do context
    attr = g.get(context[:cm], EntityType, "person")
    res_ent = g.get_instances(g.as_remote(attr, context[:transaction]))
    @expect isempty(res_ent)
end

# Scenario: Entity can have keys
@when("\$alice = attribute(username) as(string) put: alice") do context
    attr_type = g.get(context[:cm], AttributeType, "username")
    res = g.put(g.as_remote(attr_type, context[:transaction]), "alice")
    context[:alice] = res
end

@when("entity \$a set has: \$alice") do context
    set_has(context[:transaction], context[:a], context[:alice])
end

@then("entity \$a get attributes(username) as(string) contain: \$alice") do context
    attr = get(ConceptManager(context[:transaction]), AttributeType, "username")
    inst_usernames = get_has(context[:transaction], context[:a], attr)
    @expect in(context[:alice], inst_usernames)
end

@then("entity \$a get keys contain: \$alice") do context
    inst_keys = get_has(context[:transaction], context[:a] , nothing, nothing, true)
    @expect in(context[:alice], inst_keys)
end

@then("attribute \$alice get owners contain: \$a") do context
    owners = get_owners(context[:transaction], context[:alice])
    @expect in(context[:a], owners)
end

@when("\$alice = attribute(username) as(string) get: alice") do context
    attr = get(ConceptManager(context[:transaction]), AttributeType, "username")
    res = g.get_instances(g.as_remote(attr, context[:transaction]))
    context[:alice] = res[1]
end

# Scenario: Entity can unset keys
@when("entity \$a unset has: \$alice") do context
    g.unset_has(context[:transaction], context[:a], context[:alice])
end

@then("entity \$a get attributes(username) as(string) do not contain: \$alice") do context
    attr = get(ConceptManager(context[:transaction]), AttributeType, "username")
    inst_usernames = get_has(context[:transaction], context[:a], attr)
    @expect !in(context[:alice], inst_usernames)
end

@then("entity \$a get keys do not contain: \$alice") do context
    inst_keys = get_has(context[:transaction], context[:a] , nothing, nothing, true)
    @expect !in(context[:alice], inst_keys)
end

@then("attribute \$alice get owners do not contain: \$a") do context
    owners = get_owners(context[:transaction], context[:alice])
    @expect !in(context[:a], owners)
end

# Scenario: Entity cannot have more than one key for a given key type
@when("\$bob = attribute(username) as(string) put: bob") do context
    attr_type = g.get(context[:cm], AttributeType, "username")
    res = g.put(g.as_remote(attr_type, context[:transaction]), "bob")
    context[:bob] = res
end

@then("entity \$a set has: \$bob; throws exception") do context
    try
        set_has(context[:transaction], context[:a], context[:bob])
    catch ex
        @expect ex !== nothing
    end
end

@when("\$bob = attribute(username) as(string) get: bob") do context
    attr = get(ConceptManager(context[:transaction]), AttributeType, "username")
    inst_usernames = get_has(context[:transaction], context[:a], attr)
    @expect !in(context[:bob], inst_usernames)
end

# Scenario: Entity cannot have a key that has been taken
@when("\$b = entity(person) create new instance") do context
    ent_type = g.get(context[:cm], EntityType, "person")
    res = g.create(g.as_remote(ent_type, context[:transaction]))
    context[:b] = res
    @expect res !== nothing
end

@then("entity \$b set has: \$alice; throws exception") do context
    try
        g.set_has(context[:transaction], context[:b], context[:alice])
    catch ex
        @expect ex !== nothing
    end
end

# Scenario: Entity can have attribute
@when("\$email = attribute(email) as(string) put: alice@email.com") do context
    attr = g.get(context[:cm], AttributeType, "email")
    context[:email] = g.put(g.as_remote(attr, context[:transaction]), "alice@email.com")
end

@when("entity \$a set has: \$email") do context
    set_has(context[:transaction], context[:a], context[:email])
end

@then("entity \$a get attributes(email) as(string) contain: \$email") do context
    email_type = g.get(g.ConceptManager(context[:transaction]), AttributeType, "email")
    res_email = get_has(context[:transaction], context[:a], email_type)
    @expect in(context[:email], res_email)
end

@then("entity \$a get attributes contain: \$email") do context
    res_email = get_has(context[:transaction], context[:a])
    @expect in(context[:email], res_email)
end

@then("attribute \$email get owners contain: \$a") do context
    res_owns = get_owners(context[:transaction], context[:email])
    @expect in(context[:a], res_owns)
end

@when("\$email = attribute(email) as(string) get: alice@email.com") do context
    @expect context[:email].value == "alice@email.com"
end

# Scenario: Entity can unset attribute
@when("entity \$a unset has: \$email") do context
    g.unset_has(context[:transaction], context[:a], context[:email])
end

@then("entity \$a get attributes(email) as(string) do not contain: \$email") do context
    res_email = get_has(context[:transaction], context[:a])
    @expect in(context[:email], res_email) === false
end

@then("entity \$a get attributes do not contain: \$email") do context
    res_email = get_has(context[:transaction], context[:a])
    @expect in(context[:email], res_email) === false
end

@then("attribute \$email get owners do not contain: \$a") do context
    res_owns = get_owners(context[:transaction], context[:email])
    @expect in(context[:a], res_owns) === false
end

# Scenario: Entity cannot be given an attribute after deletion
@when("entity \$a set has: \$email; throws exception") do context
    try
        set_has(context[:transaction], context[:a], context[:email])
    catch ex
        @expect ex !== nothing
    end
end


text:
mutable struct ByteStream
    buf::CircularBuffer{UInt8}
    str_arr::Vector{UInt8}
    bytes_written_count::Int
    bytes_read_count::Int
    has_eof::Bool
    error::Bool
    function ByteStream(cap::Int)
        return new(CircularBuffer{UInt8}(cap), zeros(UInt8, cap), 0, 0, false, false)
    end
end

mutable struct StreamReassembler
    output::ByteStream
    unassembled_strings::SortedDict{Int,String}
    capacity::Int
    unassembled_bytes::Int
    cur_idx::Int
    eof_idx::Int
    StreamReassembler(cap::Int) = return new(ByteStream(cap), OrderedDict{Int,String}(), cap, 0, 0, 0)
end

mutable struct TCPReceiver
    reassembler::StreamReassembler
    capacity::Int
    abs_seqno::Int
    isn::WrappingInt32
    has_syn::Bool
    # has_fin::Bool
    TCPReceiver(cap::Int) = new(StreamReassembler(cap), cap, 0, WrappingInt32(0), false)
end

mutable struct TCPSender
    capacity::Int
    isn::WrappingInt32

    segments_out::Queue{TCPSegment}
    outstanding_segs::Vector{TCPSegment}

    initial_retransmission_timeout::Int
    RTO::Int
    ticks::Int
    consecutive_retransmissions::Int

    timer_on::Bool
    fin_flg::Bool

    stream::ByteStream

    next_seqno::Int
    last_acked::Int
    bytes_in_flight::Int
    win_size::Int

    TCPSender(;cap::Int=64000, retx_timeout::UInt16=UInt16(1000), fixed_isn=nothing) =
        new(cap, fixed_isn === nothing ? WrappingInt32(rand(1:typemax(UInt32))) : fixed_isn,
        Queue{TCPSegment}(), TCPSegment[], retx_timeout, retx_timeout, 0, 0,
        false, false, ByteStream(cap), 0, 0, 0, 0)
end

mutable struct TCPConnection
    receiver::TCPReceiver
    sender::TCPSender
    segments_out::Queue{TCPSegment}
    linger_after_streams_finish::Bool
    active::Bool
    rt_timeout::UInt16
    time_since_last_segment_received::Int
    function TCPConnection(;cap::Int=64000, retx_timeout::UInt16=UInt16(1000), fixed_isn=nothing)
        conn = new(TCPReceiver(cap),
            TCPSender(;cap, retx_timeout, fixed_isn),
            Queue{TCPSegment}(), true, true, UInt16(retx_timeout), 0)
        # function f(conn::TCPConnection)
        #     try
        #         if conn.active
        #             println(stderr, "Warning: Unclean shutdown of TCPConnection")
        #             send_empty_segment!(conn)
        #             unclean_shutdown!(conn)
        #         end
        #     catch e
        #         println(stderr, "Exception destructing TCP FSM: ", e)
        #     end
        # end
        # finalizer(f, conn)
    end
end

ext: jl

max_stars_repo_name: AquaIndigo/JLSponge

max_issues_repo_name: AquaIndigo/JLSponge

max_forks_repo_name: AquaIndigo/JLSponge


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

@testset "prefix" begin
    @test MB.prefix(["a", "b", "c", "d"], 0) == []
    @test MB.prefix(["a", "b", "c", "d"], 1) == ["a"]
    @test MB.prefix(["a", "b", "c", "d"], 2) == ["a","b"]

    # mut
    data = [1,2,3]
    p = MB.prefix(data, 1)
    p[1] = 42
    @test data == [42,2,3]
end

@testset "move_to_front!" begin
    pts_initial = ["a", "b", "c", "d"]

    pts = deepcopy(pts_initial)
    MB.move_to_front!(pts, 1)
    @test pts == pts_initial

    pts = deepcopy(pts_initial)
    MB.move_to_front!(pts, 2)
    @test pts == ["b", "a", "c", "d"]

    pts = deepcopy(pts_initial)
    MB.move_to_front!(pts, 4)
    @test pts == ["d", "a", "b", "c"]
end

@testset "isinside" begin
    @test MB.isinside([0.], MB.SqBall([0.], 0.))
    @test !MB.isinside([0.], MB.SqBall([NaN], 0.))
    @test !MB.isinside([0.], MB.SqBall([0.], NaN))

end


text:
#= udemy.com code challenge
from Prof. Mike X Cohen's course in Linear Algebra
https://www.udemy.com/course/linear-algebra-theory-and-implementation

# Is the dot product commutative?
# A*B' == B*A' ?
=#

using LinearAlgebra

# generate two 100-element random row vectors, transposed from default column layout.
a = randn(100)'
b = randn(100)'

# display vectors (in truncated form)
println("Vector a with 100 elements:")
display(a)
println("\n")

println("Vector b of the same size:")
display(b)
println("\n")

# calculate dot products
dp1 = dot(a, b) # a * b' also works
dp2 = dot(b, a) # b * a'

# display them
println("Dot product of a and b is $(dp1)")
println("Dot product of b and a is $(dp2)\n")

# are they equal?
if dp1 == dp2
  println("The dot product of the 100-element vector is commutative.\n")
else
  println("Dot product is not commutative.\n")
end

# generate 1 row, 2 column array with random integers from -10:10
c = rand(-10:10, 1, 2)

d = rand(-10:10, 1, 2)

println("Array c = $c")
println("Array d = $d\n")

dp3 = c * d'
dp4 = d * c'

println("Dot product of c and d is $(dp3)")
println("Dot product of d and c is $(dp4)")

if dp3 == dp4
  println("Thus, the dot product of the 2-element vector is commutative.")
else
  println("Dot product is not commutative")
end

max_stars_repo_name: jawuku/julia

max_issues_repo_name: jawuku/julia

max_forks_repo_name: jawuku/julia


text:
function start_game()

end

function move(board::Boardstate, you_index::Int, simulation_time::Float64)
    # time stuff
    simulation_time -= 0.05

    if length(board.snakes) > 2

        snek = board.snakes[you_index]

        possible_as = [possible_actions(snake) for snake in board.snakes]
        dead_counts = Dict{Direction, Int}(a => 0 for a in possible_actions(snek))

        for actions in Iterators.product(possible_as...)
            new_board = deepcopy(board)
            for (i, dir) in enumerate(actions)
                move_snake!(new_board.snakes[i], new_board.food, dir)
            end
            dead = check_dead(new_board.snakes, new_board.height, new_board.width)
            if you_index in dead
                dead_counts[actions[you_index]] += 1
            end
        end
        food_action = nothing
        if snek.health < 50

            min_dist = nothing
            min_path = nothing

            for f in board.food.positions
                our_distance, our_path = a_star_search(get_head(snek), f, deepcopy(board))
                if our_distance === nothing
                    continue
                end
                opponent_distances = Vector{Int}()
                for (i, snake) in enumerate(board.snakes)
                    if i == you_index
                        continue
                    end
                    d = a_star_search(get_head(snake), f, deepcopy(board))[1]
                    if d === nothing
                        d = 2000
                    end
                    push!(opponent_distances, d)
                end
                if all([d === nothing for d in opponent_distances]) || all([our_distance < d for d in opponent_distances])
                    if min_dist === nothing || our_distance < min_dist
                        min_dist = our_distance
                        min_path = our_path
                    end
                elseif any([our_distance == d for d in opponent_distances]) && our_distance == minimum(opponent_distances)
                    opponent_idx = findfirst(d -> d == our_distance, opponent_distances)
                    if length(snek.body) > length(board.snakes[opponent_idx].body)
                        if min_dist === nothing || our_distance < min_dist
                            min_dist = our_distance
                            min_path = our_path
                        end
                    end
                end
            end

            if min_path !== nothing
                food_action = last(min_path)[1]
                return food_action
            else
                food_action = nothing
            end

        end
        if food_action !== nothing && dead_counts[food_action] == 0
            return food_action
        end
        flood_values = Vector{Tuple{Direction, Int}}()
        for action in possible_actions(snek)
            new_board = deepcopy(board)
            move_snake!(new_board.snakes[you_index], new_board.food, action)

            floods = maxN_floodfill(new_board.snakes, board.width, board.height)
            push!(flood_values, (action, floods[you_index]))
        end
        flood_action = sort(flood_values, by=di -> di[2], rev=true)[1][1]
        if dead_counts[flood_action] != 0

            dead_list = sort(collect(pairs(dead_counts)), by=di -> di[2])
            return dead_list[1][1]

        end
        return flood_action

    else
        minimax_action = iterative_deepening(board, simulation_time, board.height, board.width, you_index)
    end
    return minimax_action
end

function end_game()

end

max_stars_repo_name: rhotertj/solide-schlange

max_issues_repo_name: rhotertj/solide-schlange

max_forks_repo_name: rhotertj/solide-schlange


text:
println("Dq) Test of the RadiativeAuger module with ASF from an internally generated initial- and final-state multiplet.")
#
wa = Atomic.Computation("xx",  Nuclear.Model(26.),
                        initialConfigs=[Configuration("1s^2 2s"), Configuration("1s^2 2p")],
                        finalConfigs  =[Configuration("1s^2 2s^2"), Configuration("1s^2 2s 2p") ],
                        process = JAC.RAuger,
                        processSettings=RadiativeAuger.Settings([E1, M1], [JAC.UseCoulomb, JAC.UseBabushkin], 6, true, false,
                                                                Tuple{Int64,Int64}[], 0., 1.0e6, 2)  )

wb = perform(wa)


text:
using DelimitedFiles

function read_input(filename)
  open(filename, "r") do f
    draw = parse.(Int, split(readline(f), ","))
    boards = split(replace(read(f, String), "\n" => " ", "\r\n" => " "), " ", keepempty = false)
    boards = reshape(parse.(Int, boards), 5, 5, :)
    (draw, boards)
  end
end

function main()
    (nums, cards) = read_input("data_4.dat")
    j = 0
    num_count_old = 1000
    board_count = 0
    num_save = 0
    for ii in 1:Int((length(cards)/5)/5 )
        cards_select = view(cards, :, :, ii)
        num_count = 0
        kk = 0
        for n in nums
            cards_select[cards_select.==n] .= -1
            winner = any(all(==(-1), cards_select, dims = 1)) || any(all(==(-1), cards_select, dims = 2))

            if winner
                if kk < 1
                    kk += 1
                    if num_count < num_count_old
                        board_count = sum(cards_select[cards_select.!==-1])
                        num_count_old = num_count
                        num_save = n

                    end
                end
            end
            num_count += 1
        end
        j += 1
    end
    println(board_count * num_save)
end

@time main()


text:
using Documenter, MLJBase, NearestNeighborModels

makedocs(;
    authors = """
        Anthony D. Blaom <anthony.blaom@gmail.com>,
        Sebastian Vollmer <s.vollmer.4@warwick.ac.uk>,
        Thibaut Lienart <thibaut.lienart@gmail.com> and
        Okon Samuel <okonsamuel50@gmail.com>
        """,
    format = Documenter.HTML(;
        prettyurls= get(ENV, "CI", "false") == "true"
    ),
    modules = [NearestNeighborModels],
    pages=[
        "Home" => "index.md",
        "API" => "api.md"
    ],
    doctest = false,
    repo = "https://github.com/JuliaAI/NearestNeighborModels.jl/blob/{commit}{path}#L{line}",
    sitename = "NearestNeighborModels.jl",
)

# By default Documenter does not deploy docs just for PR
# this causes issues with how we're doing things and ends
# up choking the deployment of the docs, so  here we
# force the environment to ignore this so that Documenter
# does indeed deploy the docs
#ENV["GITHUB_EVENT_NAME"] = "pull_request"

deploydocs(;
    deploy_config = Documenter.GitHubActions(),
    repo="github.com/JuliaAI/NearestNeighborModels.jl.git",
    push_preview=true
)


text:
optim_value(::ComponentData) = nothing

@component @with_kw struct Spin
    ϕ::Float64
    magnitude::Float64 = 1.0
    v::Vec3 = magnitude*polar2vec(ϕ, 0.0)
end

optim_value(s::Spin) = s.ϕ
optimizable(::Spin) = true
optim_length(::Spin) = 1
Spin(::Spin, optim_val) = Spin(ϕ=optim_val[1])

@component @with_kw struct L
    ϕ::Float64
    magnitude::Float64 = 1.0
    v::Vec3 = magnitude*polar2vec(ϕ, 0.0)
end
optim_value(s::L) = s.ϕ
optimizable(::L) = true
optim_length(::L) = 1
L(l1::L, optim_val) = L(ϕ=optim_val[1])

@component @with_kw struct Pb
    pb::Float64=0.15
end
optim_value(s::Pb) = s.pb
optimizable(::Pb) = true
optim_length(::Pb) = 1
Pb(l1::Pb, optim_val) = Pb(optim_val[1])

@component @with_kw struct EasyAxis
    ϕ::Float64
    v::Vec3 = polar2vec(ϕ, 0.0)
end

@component struct Optimize end

@component struct Position
    p::Vec3
end

# optim_value(s::Position) = [s.p[1], s.p[2]]

@component @with_kw mutable struct H
    ϕ::Float64
    magnitude::Float64 = 1.0
    v::Vec3 = magnitude*polar2vec(ϕ, 0.0)
end

@component @with_kw mutable struct E_field
    e::Float64 = 0.0
end

LinearAlgebra.:(⋅)(v1::Union{H, L, Spin, EasyAxis}, v2::Union{H, L, Spin, EasyAxis}) = v1.v ⋅ v2.v

@component @with_kw mutable struct Model @deftype Float64
    J1 = 0.40
    J2 = 1.25
    χ_Gd = ustrip(uconvert(eV/Unitful.T,7*μB*1000)) #in meV
    χ_L  = 0.01
    K_L = 0.45
    K_Gd =0.11
    K_Gd_4th =0.0
    Gd_easy_ϕ = deg2rad(12)
    L1_easy_ϕ = deg2rad(23.4)
    L2_easy_ϕ = deg2rad(-23.4)
    Gd_easy::Vector{Float64} = -[Gd_easy_ϕ, -Gd_easy_ϕ, -Gd_easy_ϕ, Gd_easy_ϕ]
    dipole_cutoff = 4.6
    l2h2_strength = 1.0
    dipole_strength = ustrip(uconvert(eV, 7^2 * μ0 * μB^2 / (4π*(1Å)^3))*1000) #in meV, 4 is wrong
    γ = 0.1753596
    α = 0.06
    β = 0.04
    g = 0.06
end

Model(dr::DataFrameRow) = Model(;[n => v for (n, v) in zip(names(dr), dr) if n in fieldnames(Model)]...)
J_parallel(m::Model)      = 2/m.χ_L
J_perpendicular(m::Model) = sqrt(J_parallel(m) * m.γ)

#Different models
@export zero_dipole_model(;kwargs...) = Model(J2 =  0.95,
                                   K_L = 1.03,
                                   J1  = 17.0,
                                   γ   = -0.43,
                                   χ_L = 0.0,
                                   K_Gd= 0.0,
                                   χ_Gd = 0.59,
                                   K_Gd_4th= 0.0,
                                   dipole_strength=0;kwargs...)

@export best_model(;kwargs...) = Model(J2       = 0.14666667,
                                       K_L      = 5.266666666666667,
                                       J1       = 3.3333333333333335,
                                       γ        = 0.13333333333333333,
                                       K_Gd     = 0.19999999999999998,
                                       χ_L      = 0.075,
                                       χ_Gd     = 0.4,
                                       K_Gd_4th = 0.0,
                                       dipole_strength=14,
                                       l2h2_strength=0.05;kwargs...)

@export physical_model(;kwargs...) = Model(J2       = 0.2,
                                           K_L      = 1.1,
                                           J1       = 7.9,
                                           γ        = 0.05,
                                           K_Gd     = 0.09,
                                           χ_L      = 0.01,
                                           χ_Gd     = 0.405,
                                           K_Gd_4th = 0.0,
                                           l2h2_strength=0.05;kwargs...)

@export minimal_model(;kwargs...) = Model(J2 =  0.0,
                               K_L = 7.9,
                               J1  = 5.0,
                               γ   = 0.0,
                               K_Gd= 0.0,
                               χ_L = 0.00,
                               χ_Gd = 0.4,
                               K_Gd_4th= 0.0,
                               dipole_strength=10.5,
                               l2h2_strength=0.05; kwargs...)

@component @with_kw mutable struct Etot
    e::Float64 = 0.0
end

Base.:(+)(e::Etot, v::Number) = e.e + v
Base.:(-)(e::Etot, v::Number) = e.e - v
Base.:(+)(e::Etot, v::Etot) = Etot(e.e + v.e)
Base.:(-)(e::Etot, v::Etot) = Etot(e.e - v.e)

@component @with_kw struct Bond
    e1::Entity #Index in Spin component of first spin
    e2::Entity #Index in Spin component of second spin
    r::Vec3
    nr2::Float64 = norm(r)^2
    inv_nr5::Float64 = 1/norm(r)^5
end

Bond(x,y,z; kwargs...) = Bond(;e1=x, e2=y, r=z, kwargs...)

@component @with_kw struct JBond
    e1::Entity #Index in Spin component of first spin
    e2::Entity #Index in Spin component of second spin
    J::Float64
end

@component struct Gd end

@component struct Mn
    Lid::Int
    Ssign::Int
end

@component struct Child
    parent::Entity
end

@component struct StateLedger
    l::Ledger
end

@export L_components() = (L, EasyAxis)
@export Gd_components() = (Spin, EasyAxis, Position)


text:
##############################################################################
#
# Inverse Wishart Distribution
#
#  Parameterized such that E(X) = Psi / (nu - p - 1)
#  See the riwish and diwish function of R's MCMCpack
#
##############################################################################

immutable InverseWishart <: ContinuousMatrixDistribution
    nu::Float64
    Psichol::Cholesky{Float64}
    function InverseWishart(n::Real, Pc::Cholesky{Float64})
        if n > size(Pc, 1) - 1
            new(float64(n), Pc)
        else
            error("Inverse Wishart parameters must be df > p - 1")
        end
    end
end

function InverseWishart(nu::Real, Psi::Matrix{Float64})
    InverseWishart(float64(nu), cholfact(Psi))
end

function insupport(IW::InverseWishart, X::Matrix{Float64})
    return size(X, 1) == size(X, 2) && isApproxSymmmetric(X) &&
           size(X, 1) == size(IW.Psichol, 1) && hasCholesky(X)
end

function mean(IW::InverseWishart)
    if IW.nu > size(IW.Psichol, 1) + 1
        return 1.0 / (IW.nu - size(IW.Psichol, 1) - 1.0) *
               IW.Psichol[:U]' * IW.Psichol[:U]
    else
        error("mean only defined for nu > p + 1")
    end
end

pdf(IW::InverseWishart, X::Matrix{Float64}) = exp(logpdf(IW, X))

function logpdf(IW::InverseWishart, X::Matrix{Float64})
    if !insupport(IW, X)
        return -Inf
    else
        p = size(X, 1)
        logd::Float64 = IW.nu * p / 2.0 * log(2.0)
        logd += lpgamma(p, IW.nu / 2.0)
        logd -= IW.nu / 2.0 * logdet(IW.Psichol)
        logd = -logd
        logd -= 0.5 * (IW.nu + p + 1.0) * logdet(X)
        logd -= 0.5 * trace(X \ (IW.Psichol[:U]' * IW.Psichol[:U]))
        return logd
    end
end

# rand(Wishart(nu, Psi^-1))^-1 is an sample from an
#  inverse wishart(nu, Psi). there is actually some wacky
#  behavior here where inv of the Cholesky returns the
#  inverse of the original matrix, in this case we're getting
#  Psi^-1 like we want
rand(IW::InverseWishart) = inv(rand(Wishart(IW.nu, inv(IW.Psichol))))

function rand!(IW::InverseWishart, X::Array{Matrix{Float64}})
    Psiinv = inv(IW.Psichol)
    W = Wishart(IW.nu, Psiinv)
    X = rand!(W, X)
    for i in 1:length(X)
        X[i] = inv(X[i])
    end
    return X
end

var(IW::InverseWishart) = error("Not yet implemented")

# because X == X' keeps failing due to floating point nonsense
function isApproxSymmmetric(a::Matrix{Float64})
    tmp = true
    for j in 2:size(a, 1)
        for i in 1:(j - 1)
            tmp &= abs(a[i, j] - a[j, i]) < 1e-8
        end
    end
    return tmp
end

# because isposdef keeps giving the wrong answer for samples
# from Wishart and InverseWisharts
function hasCholesky(a::Matrix{Float64})
    try achol = cholfact(a)
    catch e
        return false
    end
    return true
end


text:
module SimpleCaching

using SHA
using Dates
using Serialization
using JLD2

import Base: esc

# export caching macros
export @scache, @scachejld
export @scache_if, @scachejld_if

# export deprecated macros
export @scachefast

include("settings.jl")
include("utils.jl")
include("caching.jl")
include("deprecated.jl")
include("init.jl")

end # module


text:
export RewardOverriddenEnv

"""
    RewardOverriddenEnv(env, f)

Apply `f` on `env` to generate a custom reward.
"""
struct RewardOverriddenEnv{F,E<:AbstractEnv} <: AbstractEnvWrapper
    env::E
    f::F
end

RLBase.reward(env::RewardOverriddenEnv, args...; kwargs...) =
    env.f(env.env, args...; kwargs...)


text:
# Copyright 2017, Iain Dunning, Joey Huchette, Miles Lubin, and contributors    #src
# This Source Code Form is subject to the terms of the Mozilla Public License   #src
# v.2.0. If a copy of the MPL was not distributed with this file, You can       #src
# obtain one at https://mozilla.org/MPL/2.0/.                                   #src

# # Maximum likelihood estimation

# Use nonlinear optimization to compute the maximum likelihood estimate (MLE) of
# the parameters of a normal distribution, a.k.a., the sample mean and variance.

using JuMP
import Ipopt
import Random
import Statistics
import Test

function example_mle(; verbose = true)
    n = 1_000
    Random.seed!(1234)
    data = randn(n)
    model = Model(Ipopt.Optimizer)
    set_silent(model)
    @variable(model, μ, start = 0.0)
    @variable(model, σ >= 0.0, start = 1.0)
    @NLobjective(
        model,
        Max,
        n / 2 * log(1 / (2 * π * σ^2)) - sum((data[i] - μ)^2 for i = 1:n) / (2 * σ^2)
    )
    optimize!(model)
    if verbose
        println("μ             = ", value(μ))
        println("mean(data)    = ", Statistics.mean(data))
        println("σ^2           = ", value(σ)^2)
        println("var(data)     = ", Statistics.var(data))
        println("MLE objective = ", objective_value(model))
    end
    Test.@test value(μ) ≈ Statistics.mean(data) atol = 1e-3
    Test.@test value(σ)^2 ≈ Statistics.var(data) atol = 1e-2
    ## You can even do constrained MLE!
    @NLconstraint(model, μ == σ^2)
    optimize!(model)
    Test.@test value(μ) ≈ value(σ)^2
    if verbose
        println()
        println("With constraint μ == σ^2:")
        println("μ                         = ", value(μ))
        println("σ^2                       = ", value(σ)^2)
        println("Constrained MLE objective = ", objective_value(model))
    end
    return
end

example_mle()

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
using Genie
using Genie.Router, Genie.Requests, Genie.Renderer.Json
using HTTP

include("./MiniMax.jl")
using .MiniMax: play_bot_turn!, State, MARK_P1, MARK_P2, MARK_TIE, MARK_EMPTY

Genie.config.cors_headers["Access-Control-Allow-Origin"] = "http://localhost:3000"
Genie.config.cors_headers["Access-Control-Allow-Headers"] = "Content-Type"
Genie.config.cors_headers["Access-Control-Allow-Methods"] = "GET, POST"

const TransformIndex = Int8[1 2 3; 4 5 6; 7 8 9];
const TransformWinner =
    Dict{Int8,String}(MARK_P1 => "player_1", MARK_P2 => "player_2", MARK_TIE => "tie")

route("/api/game/v1", method = POST) do
    game_type::String = getpayload(:type, "normal")
    payload::Dict{String,Any} = jsonpayload()

    if length(get(payload, "board", [])) == 9
        raw_array::Array{Int,1} = payload["board"]
        # need to take transpose of the board now and before returning the updated version
        game_board::Array{Int8,2} = reshape(convert(Array{Int8,1}, raw_array), (3, 3))'

        game_state::State = play_bot_turn!(game_board, game_type)

        winner::String = get(TransformWinner, game_state.winner, "open")
        last_entry::Int =
            (game_state.last_entry > 0) ? Int(TransformIndex[game_state.last_entry]) :
            Int(0)
        board::Array{Int,1} = convert(Array{Int,1}, reshape(game_state.board', (9,)))

        response::Dict{String,Union{String,Int,Array{Int,1}}} =
            Dict{String,Union{String,Int,Array{Int,1}}}(
                "winner" => winner,
                "bot_last_entry" => last_entry,
                "board" => board,
            )

        json(response)
    else
        "Payload must contain an array of length nine with key `board`."
    end
end

route("/api/game/v1", method = GET) do
    """Hello from game backend!

    Play bot's turn by making a POST request with status of the current game board as payload.
    This payload must be an one-dimensional array, length of nine, and provided by key `board`.
    Mark your moves in the board by -1, bot will use 1 to mark its latest move."""
end

function force_compile()
    sleep(5) # allow the server to start before running the following
    println("run test requests...")

    base_url::String = "http://localhost:8000"
    endpoint::String = "/api/game/v1"

    HTTP.request("GET", "$(base_url)$(endpoint)")

    HTTP.request(
        "POST",
        "$(base_url)$(endpoint)?type=normal",
        [("Content-Type", "application/json")],
        """{"board":[0,0,0,0,0,0,0,0,0]}""",
    )
    HTTP.request(
        "POST",
        "$(base_url)$(endpoint)?type=normal",
        [("Content-Type", "application/json")],
        """{"board":[0,0,0,0,-1,0,0,0,0]}""",
    )
    HTTP.request(
        "POST",
        "$(base_url)$(endpoint)?type=easy",
        [("Content-Type", "application/json")],
        """{"board":[0,0,0,0,-1,0,0,0,0]}""",
    )

    println("test requests completed")
end

function main()
    println("running the server...")

    @async force_compile()

    up(8000, "0.0.0.0", async = false)
end

if abspath(PROGRAM_FILE) == @__FILE__
    println("running main...")
    main()
else
    println("not running main...")
end

max_stars_repo_name: elmomoilanen/Tic-tac-toe

max_issues_repo_name: elmomoilanen/Tic-tac-toe

max_forks_repo_name: elmomoilanen/Tic-tac-toe


text:
### A Pluto.jl notebook ###
# v0.14.0

using Markdown
using InteractiveUtils

# ╔═╡ c27879d8-9702-11eb-3050-f1c4477273fe
using PlotlyLight

# ╔═╡ e2dedee2-9702-11eb-1364-118bcaff2607
Plot(Config(x=1:10,y=randn(10), type="bar"), src=:cdn)

# ╔═╡ Cell order:
# ╠═c27879d8-9702-11eb-3050-f1c4477273fe
# ╠═e2dedee2-9702-11eb-1364-118bcaff2607


text:
module PDFToc
struct Heading
    title::String
    page::Int
    children::Vector{Heading}
end
Heading(title, page) = Heading(title, page, Vector{Heading}())

function Base.show(io::IO, ::MIME"text/plain", h::Heading)
    write(io, "$(h.title) ... $(h.page)")
    buf = IOBuffer()
    for c in h.children
        write(buf, "\n")
        show(buf, MIME"text/plain"(), c)
    end
    for l in split(String(take!(buf)), "\n")
        write(io, "    $(l)\n")
    end
end

function Base.show(io::IO, ::MIME"text/plain", hs::Vector{Heading})
    foreach(h -> show(io, MIME"text/plain"(), h), hs)
end

function clean_hierarchy!(headings)
    nh = length(headings)
    i = 1
    while i < nh
        li = headings[i][end]
        j = i+1
        lj = headings[j][end]
        if lj-li > 1
            k = something(findfirst(h -> h[end]≠lj, view(headings, j:nh)), nh-j) + j - 1
            for l in j:k-1
                title, page = headings[l]
                headings[l] = (title, page, li+1)
            end
            i = k
        end
        i += 1
    end
end

function readtoc(filename, patterns...)
    headings = open(filename, "r") do file
        map(eachline(file)) do line
            for (p,f) in patterns
                m = match(p, line)
                isnothing(m) && continue
                return f(m)
            end
            println("No pattern matching: ", line)
        end
    end
    clean_hierarchy!(headings)
    s = [Vector{Heading}()]
    for h in headings
        title,page,level = h[1], h[2], h[3]
        level > length(s) && push!(s, s[end][end].children)
        while level < length(s)
            pop!(s)
        end
        push!(s[end], Heading(title, page))
    end

    first(s)
end

function psescape(s)
    if isascii(s)
        "("*replace(replace(s, "(" => "\\("), ")" => "\\)")*")"
    else
        cus = vcat(0xfeff, transcode(UInt16, s))
        "<"*join(map(c -> string(c, base=16, pad=4), cus), " ")*">"
    end
end

function pdfmarks(io::IO, h::Heading; offset=0, kwargs...)
    write(io, "[")
    c = length(h.children)
    c > 0 && write(io, "/Count $(c) ")
    write(io, "/Title $(psescape(h.title)) /Page $(h.page+offset)")
    write(io, " /OUT pdfmark\n")
    foreach(hc -> pdfmarks(io, hc; offset=offset), h.children)
end

function pdfmarks(io::IO, hs::Vector{Heading};
                  title=nothing, author=nothing, year=nothing,
                  kwargs...)
    foreach(h -> pdfmarks(io, h; kwargs...), hs)
    metadata = String[]
    !isnothing(title) && push!(metadata, "/Title $(psescape(title))")
    !isnothing(author) && push!(metadata, "/Author $(psescape(author))")
    !isnothing(year) && push!(metadata, "/Year ($(year))")
    if !isempty(metadata)
        push!(metadata, "/DOCINFO pdfmark")
        write(io, "[ "*join(metadata, "\n  "))
    end
end

pdfmarks(h; kwargs...) = pdfmarks(stdout, h; kwargs...)

# https://tex.stackexchange.com/a/390337
function pdfpages(io::IO; pages=[], kwargs...)
    isempty(pages) && return
    spec = join(["$i << $s >>" for (i,s) in pages], "\n        ")
    s = """

[
  {Catalog} <<
    /PageLabels <<
      /Nums [
        $spec
      ]
    >>
  >>
/PUT pdfmark
"""
    write(io, s)
end

page_common(style, n=1; prefix=nothing) =
    (isnothing(prefix) ?
     "" : "/P $(prefix) ")*"/S /$(style) /St $(n)"

arabic(args...;kwargs...) = page_common("D", args...; kwargs...)
Roman(args...;kwargs...) = page_common("R", args...; kwargs...)
roman(args...;kwargs...) = page_common("r", args...; kwargs...)
Alph(args...;kwargs...) = page_common("A", args...; kwargs...)
alph(args...;kwargs...) = page_common("a", args...; kwargs...)

function addtoc(pdffile, tocfile, patterns...; debug=false, kwargs...)
    toc = readtoc(tocfile, patterns...)
    filename = first(splitext(pdffile))
    open("$(filename).pdfmarks", "w") do file
        pdfmarks(file, toc; kwargs...)
        pdfpages(file; kwargs...)
    end
    debug || run(`gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=$(filename)-out.pdf $(pdffile) $(filename).pdfmarks`)
end

export readtoc, pdfmarks, addtoc,
    arabic, Roman, roman, Alph, alph

end # module


text:
#!/usr/bin/julia

# Julia Lang

# Written by Katrina Siegfried
# 2018-09-15
# CSCI3412_Algorithms

# BubbleSort algorithm written from notes from DataStructures
function bubbleSort(list)
	numberOfSwaps = 0
	numberOfComparisons = 0
	len = length(list)
	for i = 1:len-1
		for j = 2:len
			numberOfComparisons += 1
			if list[j-1] > list[j]
				tmp = list[j-1]
				list[j-1] = list[j]
				list[j] = tmp
				numberOfSwaps += 1
			end
		end
	end
	println("Number of swaps: ", numberOfSwaps)
	println("Number of comparisons: ", numberOfComparisons)
end

# UNCOMMENT CODE BELOW TO PRINT UNSORTED LIST
for i = 1:length(listToSort)
	# println(listToSort[i])
end

# CALL BUBBLE SORT AND BENCHMARK IT
println("Bubble Sort")
@time bubbleSort(listToSort)
writedlm("sortResults.txt", listToSort)

# UNCOMMENT CODE BELOW TO PRINT SORTED LIST
for i = 1:length(listToSort)
	println(listToSort[i])
end

max_stars_repo_name: siegfrkn/JuliaDemoScripts

max_issues_repo_name: siegfrkn/JuliaDemoScripts

max_forks_repo_name: siegfrkn/JuliaDemoScripts


text:
using Test
using MPIClusterManagers
using Distributed

using MPIClusterManagers: mpiexec
import MPI

# Start workers via `mpiexec` that communicate among themselves via MPI;
# communicate with the workers via TCP
if !Sys.iswindows() && occursin( "OpenRTE", open(f->read(f, String),`$mpiexec --version`))
    mgr = MPIManager(np=4, mpirun_cmd=`$mpiexec --oversubscribe -n 4`)
else
    mgr = MPIManager(np=4)
end
addprocs(mgr)

refs = []
for w in workers()
    push!(refs, @spawnat w MPI.Comm_rank(MPI.COMM_WORLD))
end
ids = falses(nworkers())
for r in refs
    id = fetch(r)
    @test !ids[id+1]
    ids[id+1] = true
end
for id in ids
    @test id
end

s = @distributed (+) for i in 1:10
    i^2
end
@test s == 385

@mpi_do mgr n = 2
@mpi_do mgr n + 2


text:
module TestLoggerParams

using Log4jl
using FactCheck

cmname = string(current_module())

macro logger(params...)
    parser_type = Nullable{Symbol}()
    name, msgfactory, config_file, config_eval = Log4jl.parseargs(params, cmname)
    quote
        $name, $msgfactory, $config_file, $config_eval
    end
end

macro rootlogger(params...)
    :(@logger $(Log4jl.ROOT_LOGGER_NAME) $(params...))
end

facts("Parameter parser of `logger` macro") do
    context("no parameters") do
        res = @logger
        @fact res[1] --> cmname
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_MESSAGE
        @fact isnull(res[3]) --> true
        @fact isnull(res[4]) --> true
    end
    context("logger name") do
        res = @logger "AAA"
        @fact res[1] --> "AAA"
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_MESSAGE
        @fact isnull(res[3]) --> true
        @fact isnull(res[4]) --> true
    end
    context("root name") do
        res = @rootlogger
        @fact isempty(res[1]) --> true
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_MESSAGE
        @fact isnull(res[3]) --> true
        @fact isnull(res[4]) --> true
    end
    context("massage factory") do
        res = @logger MSG=Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact res[1] --> cmname
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact isnull(res[3]) --> true
        @fact isnull(res[4]) --> true
    end
    context("configuration uri") do
        res = @logger URI="log4jl.yml"
        @fact res[1] --> cmname
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_MESSAGE
        @fact get(res[3]) --> "log4jl.yml"
        @fact isnull(res[4]) --> true
    end
    context("programmable configuration") do
        res = @logger begin 1 end
        @fact res[1] --> cmname
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_MESSAGE
        @fact isnull(res[3]) --> true
        @fact isnull(res[4]) --> false
    end
    context("logger name and massage factory") do
        res = @logger "AAA" MSG=Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact res[1] --> "AAA"
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact isnull(res[3]) --> true
        @fact isnull(res[4]) --> true
    end
    context("logger name and configuration uri") do
        res = @logger "AAA" URI="log4jl.yml"
        @fact res[1] --> "AAA"
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_MESSAGE
        @fact get(res[3]) --> "log4jl.yml"
        @fact isnull(res[4]) --> true
    end
    context("logger name and programmable configuration") do
        res = @logger "AAA" begin 1 end
        @fact res[1] --> "AAA"
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_MESSAGE
        @fact isnull(res[3]) --> true
        @fact isnull(res[4]) --> false
    end
    context("massage factory and configuration uri") do
        res = @logger MSG=Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL URI="log4jl.yml"
        @fact res[1] --> cmname
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact get(res[3]) --> "log4jl.yml"
        @fact isnull(res[4]) --> true
    end
    context("configuration uri and massage factory") do
        res = @logger URI="log4jl.yml" MSG=Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact res[1] --> cmname
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact get(res[3]) --> "log4jl.yml"
        @fact isnull(res[4]) --> true
    end
    context("massage factory and programmable configuration") do
        res = @logger MSG=Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL begin 1 end
        @fact res[1] --> cmname
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact isnull(res[3]) --> true
        @fact isnull(res[4]) --> false
    end
    context("name, massage factory and programmable configuration") do
        res = @logger "AAA" MSG=Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL begin 1 end
        @fact res[1] --> "AAA"
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact isnull(res[3]) --> true
        @fact isnull(res[4]) --> false
    end
    context("name, configuration uri and massage factory") do
        res = @logger "AAA" URI="log4jl.yml" MSG=Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact res[1] --> "AAA"
        @fact res[2] --> Log4jl.LOG4JL_DEFAULT_STATUS_LEVEL
        @fact get(res[3]) --> "log4jl.yml"
        @fact isnull(res[4]) --> true
    end

end

end


text:
using Test
using LibCURL_jll

@testset "LibCURL_jll" begin
    v = unsafe_string(ccall((:curl_version, libcurl), Cstring, ()))
    @test startswith(v, "libcurl/")
end


text:
using ..Utils.AllocatorModel

#####
##### Numa Optimizer Type
#####
struct Numa{T} <: AbstractOptimizer{T}
    ratio::T

    Numa{T}(x::T) where {T <: OPTIM_TYPES} = new{T}(x)
    Numa(x::T) where {T <: OPTIM_TYPES} = new{T}(x)
end

name(::Numa) = "numa"
function (M::Numa{Rational{Int64}})(data, backend::nGraph.Backend)
    bounds = Profiler.allocation_bounds(data)

    # Special case the all DRAM case - give a little more DRAM for fudge-factor sake
    if M.ratio == 0 // 1
        x = round(Int, 1.1 * bounds.upper_bound)
    else
        x = round(Int, (bounds.upper_bound / (M.ratio + 1)))
    end
    println("Trying to use $(x) MB of memory")

    # Return the result as Bytes without scaling to MB
    return x
end

function (M::Numa{Int64})(data, backend::nGraph.Backend)
    x = getlimit(M)
    println("Trying to use $(x) MB of memory")

    # Return the result as Bytes without scaling to MB
    return x
end

#####
##### NUMA First-touch Implementation
######

_ignore(t::String) = any(startswith.(Ref(t), ("Parameter", "Result", "Constant")))
_ignore(t::XTensor) = _ignore(nGraph.name(t))

mutable struct NumaTensorMeta
    tensor::XTensor
    location::TensorLocation
    offset::Int64
end

function numa(backend::nGraph.Backend, f::nGraph.NFunction, opt::Numa, cache)
    data = profile(f, backend; cache = cache)
    limit = opt(data, backend)
    @show limit
    pool = MemoryAllocator(limit, 4096)

    meta = Dict(
        # Default tensors to starting in PMEM
        t => NumaTensorMeta(t, DRAM, -1) for t in tensors(data)
    )

    for (index, node) in enumerate(nodes(data))
        # Try to allocate the outputs in the pool. If we can allocate, these tensors
        # belong in DRAM.
        #
        # Otherwise, they belong in PMEM. Simple as that.
        for tensor in filter(!_ignore, node.newlist)
            offset = allocate(pool, sizeof(tensor))
            if !isnothing(offset)
                meta[tensor].location = DRAM
                meta[tensor].offset = offset
            else
                meta[tensor].location = PMEM
            end
        end

        for tensor in filter(!_ignore, node.freelist)
            # Free this tensor from DRAM
            if meta[tensor].location == DRAM
                free(pool, meta[tensor].offset)
            end
        end
    end

    # Create a schedule and configure the graph
    schedule = Dict(t.tensor => (t.location, MoveAction[]) for t in values(meta))
    return data, schedule, limit
end

function run_numa(backend, f, opt::Numa; cache = nothing, kw...)
    limit_ref = Ref{Any}()
    function cb(f::nGraph.NFunction)
        data, schedule, limit = numa(backend, f, opt, cache)
        configure!(f, schedule, data)
        limit_ref[] = limit

        return nothing
    end

    callbacks = CallbackChain()
    callback!(callbacks, cb)

    A = f()::Actualizer
    fex = nGraph.compile(
        backend,
        A.f,
        A.args...;
        callback = callbacks,
        emit_timing = true,
        A.kw...
    )

    return fex, limit_ref[]
end

#####
##### _compare!
#####

function Profiler._compare!(
        stats,
        f,
        opt::Numa{<:Rational},
        backend::nGraph.Backend{nGraph.CPU};
        skip_run = false,
        cache = nothing,
        kw...,
    )

    fex, limit = ratiosearch(run_numa, backend, f, opt; cache = cache, kw...)

    # Get the predicted run time and then the actual run time
    nt = Dict(
        :dram_limit => limit,
        :ratio => getratio(opt),
        :actual_runtime => gettime(fex),
        :predicted_runtime => 0,
    )

    push!(stats.runs, nt)
    return nothing
end

max_stars_repo_name: darchr/AutoTM

max_issues_repo_name: darchr/AutoTM

max_forks_repo_name: darchr/AutoTM


text:
# Autogenerated wrapper script for tmux_jll for aarch64-linux-gnu
export tmux

using libevent_jll
using Ncurses_jll
using utf8proc_jll
JLLWrappers.@generate_wrapper_header("tmux")
JLLWrappers.@declare_executable_product(tmux)
function __init__()
    JLLWrappers.@generate_init_header(libevent_jll, Ncurses_jll, utf8proc_jll)
    JLLWrappers.@init_executable_product(
        tmux,
        "bin/tmux",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
#=
Basic thermodynamic properties
=#
using LinearAlgebra

@inline ncomponents(mix::MBWREoSMixture) = length(mix.components)
@inline Base.length(mix::MBWREoSMixture) = length(mix.components)

function __θ__(Tr, acentric)
    a, b = 0.05202976, -0.7498189
    return 1 + (acentric - C3_OMEGA) * (a + b * log(Tr))
end

function __ϕ__(Tr, Zc, acentric)
    a, b = 0.1435971, -0.2821562
    return (1 - (acentric - C3_OMEGA) * (a + b * log(Tr))) * C3_ZC / Zc
end

function scaling_coeffs(chx::MBWREoSComponent, T)
    acentric = acentric_factor(chx)
    Pc, RTc, Zc = chx.Pc, chx.RTc, chx.Zc
    Vc = Zc * RTc / Pc
    Tc = RTc / GAS_CONSTANT_SI
    Tr = T / Tc
    fx = (Tc / C3_TC) * __θ__(Tr, acentric)
    hx = (Vc / C3_VC) * __ϕ__(Tr, Zc, acentric)
    return (; fx, hx)
end

function __shape_factors!__(mix::MBWREoSMixture, T, fs, hs)
    comps = components(mix)
    @inbounds for i in eachindex(comps, fs, hs)
        subst = comps[i]
        Tc = subst.RTc / GAS_CONSTANT_SI
        Zc = subst.Zc
        Vc = Zc * subst.RTc / subst.Pc
        acentric = acentric_factor(subst)
        fs[i] = (Tc / C3_TC) .* __θ__(T / Tc, acentric)
        hs[i] = (Vc / C3_VC) .* __ϕ__(T / Tc, Zc, acentric)
    end
    return (f = fs, h = hs)
end

function __shape_matrices!__(fs, hs, fmatr, hmatr)
    fmatr .= sqrt.(fs .* fs')
    hmatr .= 0.125 .* (cbrt.(hs) .+ cbrt.(hs')).^3
    return (fm = fmatr, hm = hmatr)
end

"""
    scaling_coeffs(mixture::MBWREoSMixture, nmol, T[; buf])

Return scaling coefficients `fx`, `hx` and `Mx` for the TRAPP EoS for `mixture` with
composition `nmol` and thermal energy `RT`. Allocations may be avoided by passing `buf`.

# Arguments
- `nmol::AbstractVector`: Vector of composition
- `RT::Real`: Thermal energy (J mol⁻¹)

# Keywords
- `buf`: see ?pressure(mixture)
"""
function scaling_coeffs(
    mix::MBWREoSMixture, nmol::AbstractVector, T;
    buf::MBWRThermoBuffer=thermo_buffer(mix, nmol)
)
    fs, hs = __shape_factors!__(mix, T, buf.vec1, buf.vec2)
    fm, hm = __shape_matrices!__(fs, hs, buf.fij, buf.hij)
    comp = components(mix)
    # mws = map!(molar_mass, buf.vec1, comp)
    total_mol = sum(nmol)
    x = map!(x -> x / total_mol, buf.vec2, nmol)
    hx = sum(x[i] * x[j] * hm[i,j] for i in eachindex(comp) for j in eachindex(comp))
    fx = sum(x[i] * x[j] * hm[i,j] * fm[i,j]
        for i in eachindex(comp) for j in eachindex(comp)) / hx
    # mw = sum(x[i] * x[j] * cbrt(hm[i,j])^4 * sqrt(fm[i,j]) *
    #     sqrt(2 * mws[i] * mws[j] / (mws[i] + mws[j]))
    #     for i in eachindex(comp) for j in eachindex(comp))^2 / (fx * cbrt(hx)^8)
    return (; fx, hx)
end

function __ref_pressure__(ρ, T)
    ρmoll = ρ * 1e-3
    G1, G2, G3, G4, G5 = (
        -0.2804337729e-3,
        0.1180666107,
        -0.3756325860e+1,
        0.5624374521e3,
        -0.9354759605e5,
    )
    G6, G7, G8, G9 = (
        -0.4557405505e-4,
        0.1530044332,
        -0.1078107476e+3,
        0.2218072099e+5,
    )
    G10, G11, G12 = (
        0.6629473971e-5,
        -0.6199354447e-2,
        0.6754207966e+1,
    )
    G13 = 0.6472837570e-3
    G14, G15 = -0.6804325262e-1, -0.9726162355e+1
    G16 = 0.5097956459e-2
    G17, G18 = -0.1004655900e-3, 0.4363693352e-1
    G19 = -0.1249351947e-2
    G20, G21 = 0.2644755879e+5, -0.7944237270e+7
    G22, G23 = -0.7299920845e+3, 0.5381095003e+8
    G24, G25 = 0.3450217377e+1, 0.9936666689e+3
    G26, G27 = -0.2166699036, -0.1612103424e+5
    G28, G29 = -0.3633126990e-3, 0.1108612343e+1
    G30, G31, G32 = -0.1330932838e-4, -0.3157701101e-2, 0.1423083811
    iTsq = inv(T^2)
    iT = inv(T)
    a1 = GAS_CONSTANT_SI * T * 1e-3
    a2 = G1 * T + G2 * sqrt(T) + G3 + (G4 * T + G5) * iTsq
    a3 = G6 * T + G7 + (G8 * T + G9) * iTsq
    a4 = G10 * T + G11 + G12 * iT
    a5 = G13
    a6 = (G14 * T + G15) * iTsq
    a7 = G16 * iT
    a8 = (G17 * T + G18) * iTsq
    a9 = G19 * iTsq

    b3 = (G20 * T + G21) * iT * iTsq
    b5 = (G22 * T^2 + G23) * iTsq^2
    b7 = (G24 * T + G25) * iT * iTsq
    b9 = (G26 * T^2 + G27) * iTsq^2
    b11 = (G28 * T + G29) * iT * iTsq
    b13 = (G32 + T * (G31 + T * G30)) * iTsq^2

    a = (a1, a2, a3, a4, a5, a6, a7, a8, a9)
    b = (b3, b5, b7, b9, b11, b13)
    p_MPa = evalpoly(ρmoll, a) * ρmoll + evalpoly(ρmoll^2, b) * ρmoll^3 * exp(-(C3_VC * ρ)^2)
    return p_MPa * 1e6
end

"""
    pressure(substance, υ, RT)

Compute pressure (Pa) of `substance` at given molar volume `υ` (m³ mol⁻¹) and
thermal energy `RT` (J mol⁻¹).
"""
function pressure(substance::MBWREoSComponent, υ::Real, RT::Real)
    T = RT / GAS_CONSTANT_SI
    fx, hx = scaling_coeffs(substance, T)
    T_ref, v_ref = T / fx, υ / hx
    ρ_ref = inv(v_ref)
    p_ref = __ref_pressure__(ρ_ref, T_ref)

    return p_ref * fx / hx
end

"""
    pressure(substance, nmol, V, RT)

Compute pressure (Pa) of `substance` at given number of moles `nmol` (mol),
total volume `V` (m³) and thermal energy `RT` (J mol⁻¹).
"""
function pressure(substance::MBWREoSComponent, nmol::Real, V::Real, RT::Real)
    return pressure(substance, V / nmol, RT)
end

"""
    pressure(substance; nmol = 1, volume, temperature)

Compute pressure (Pa) of `substance` at given number of moles `nmol` (mol),
total volume (m³) and temperature (K).
"""
function pressure(
    substance::MBWREoSComponent;
    nmol::Real = 1,
    volume::Real,
    temperature::Real,
)
    RT = GAS_CONSTANT_SI * temperature
    return pressure(substance, nmol, volume, RT)
end

"""
    wilson_saturation_pressure(substance, RT)

Return approximate saturation pressure of `substance` at `RT` (J mol⁻¹).

Reference: Brusilovsky2002 [p 272, eq 5.4]
"""
function wilson_saturation_pressure(substance::MBWREoSComponent, RT::Real)
    return wilson_saturation_pressure(
        substance.Pc, substance.RTc, substance.acentric_factor, RT
    )
end

"""
    wilson_saturation_pressure(Pc::Real, RTc::Real, acentric_factor::Real, RT::Real)

Approximate saturation pressure at `RT` using Wilson correlation.

# Arguments
- `Pc::Real` - critical pressure
- `RTc::Real` - gas constant * critical temperature
- `acentric_factor::Real` - acentric factor
- `RT::Real` - gas constant * temperature

Reference: Brusilovsky2002 [p 272, eq 5.4], Mikyska2010 DOI 10.1002/aic.12387 [Algorithm step 1]
"""
function wilson_saturation_pressure(Pc::Real, RTc::Real, acentric_factor::Real, RT::Real)
    return Pc * exp(5.373 * (1.0 + acentric_factor) * (1.0 - RTc / RT))
end

"""
    pressure(mixture, nmol, volume, RT[; buf])

Return pressure (Pa) of `mixture` at given

- `nmol::AbstractVector`: composition (molar parts) or number of moles (mol)
- `volume::Real`: molar volume (m³ mol⁻¹) or volume (m³)
- `RT::Real`: thermal energy (J mol⁻¹)

Allocations may be avoided by passing `buf`.

# Keywords
- `buf::Union{BrusilovskyThermoBuffer,NamedTuple,AbstractDict}`: Buffer for intermediate
    calculations. In case of `NamedTuple` and `AbstractDict` `buf` should contain `buf[:ai]`
    `NC = ncomponents(mixture)` vector and `buf[:aij]` NCxNC matrix.

See also: [`thermo_buffer`](@ref)
"""
function pressure(
    mixture::MBWREoSMixture,
    nmol::AbstractVector,
    volume::Real,
    RT::Real;
    buf=thermo_buffer(mixture, nmol),
)
    T = RT / GAS_CONSTANT_SI
    fx, hx = scaling_coeffs(mixture, nmol, T; buf)
    T_ref, v_ref = T / fx, volume / (sum(nmol) * hx)
    ρ_ref = inv(v_ref)
    p_ref = __ref_pressure__(ρ_ref, T_ref)

    return p_ref * fx / hx
end


text:
using BenchmarkTools, LazySets
using LinearAlgebra, SparseArrays, Random

SUITE = BenchmarkGroup()  # parent BenchmarkGroup to contain our suite

include("supports.jl")
include("linear_map.jl")


text:
# Julia wrapper for header: /usr/include/libavcodec/avdct.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

export
    avcodec_dct_alloc,
    avcodec_dct_init,
    avcodec_dct_get_class

function avcodec_dct_alloc()
    ccall((:avcodec_dct_alloc, libavcodec), Ptr{AVDCT}, ())
end

function avcodec_dct_init(arg1)
    ccall((:avcodec_dct_init, libavcodec), Cint, (Ptr{AVDCT},), arg1)
end

function avcodec_dct_get_class()
    ccall((:avcodec_dct_get_class, libavcodec), Ptr{AVClass}, ())
end


text:
#########
# Trial #
#########

mutable struct Trial
    params::Parameters
    times::Vector{Float64}
    gctimes::Vector{Float64}
    memory::Int
    allocs::Int
end

Trial(params::Parameters) = Trial(params, Float64[], Float64[], typemax(Int), typemax(Int))

@compat function Base.:(==)(a::Trial, b::Trial)
    return a.params == b.params &&
           a.times == b.times &&
           a.gctimes == b.gctimes &&
           a.memory == b.memory &&
           a.allocs == b.allocs
end

Base.copy(t::Trial) = Trial(copy(t.params), copy(t.times), copy(t.gctimes), t.memory, t.allocs)

function Base.push!(t::Trial, time, gctime, memory, allocs)
    push!(t.times, time)
    push!(t.gctimes, gctime)
    memory < t.memory && (t.memory = memory)
    allocs < t.allocs && (t.allocs = allocs)
    return t
end

function Base.deleteat!(t::Trial, i)
    deleteat!(t.times, i)
    deleteat!(t.gctimes, i)
    return t
end

Base.length(t::Trial) = length(t.times)
Base.getindex(t::Trial, i::Number) = push!(Trial(t.params), t.times[i], t.gctimes[i], t.memory, t.allocs)
Base.getindex(t::Trial, i) = Trial(t.params, t.times[i], t.gctimes[i], t.memory, t.allocs)
Base.endof(t::Trial) = length(t)

function Base.sort!(t::Trial)
    inds = sortperm(t.times)
    t.times = t.times[inds]
    t.gctimes = t.gctimes[inds]
    return t
end

Base.sort(t::Trial) = sort!(copy(t))

Base.time(t::Trial) = time(minimum(t))
gctime(t::Trial) = gctime(minimum(t))
memory(t::Trial) = t.memory
allocs(t::Trial) = t.allocs
params(t::Trial) = t.params

# returns the index of the first outlier in `values`, if any outliers are detected.
# `values` is assumed to be sorted from least to greatest, and assumed to be right-skewed.
function skewcutoff(values)
    current_values = copy(values)
    while mean(current_values) > median(current_values)
        deleteat!(current_values, length(current_values))
    end
    return length(current_values) + 1
end

skewcutoff(t::Trial) = skewcutoff(t.times)

function rmskew!(t::Trial)
    sort!(t)
    i = skewcutoff(t)
    i <= length(t) && deleteat!(t, i:length(t))
    return t
end

function rmskew(t::Trial)
    st = sort(t)
    return st[1:(skewcutoff(st) - 1)]
end

trim(t::Trial, percentage = 0.1) = t[1:max(1, floor(Int, length(t) - (length(t) * percentage)))]

#################
# TrialEstimate #
#################

mutable struct TrialEstimate
    params::Parameters
    time::Float64
    gctime::Float64
    memory::Int
    allocs::Int
end

function TrialEstimate(trial::Trial, t, gct)
    return TrialEstimate(params(trial), t, gct, memory(trial), allocs(trial))
end

@compat function Base.:(==)(a::TrialEstimate, b::TrialEstimate)
    return a.params == b.params &&
           a.time == b.time &&
           a.gctime == b.gctime &&
           a.memory == b.memory &&
           a.allocs == b.allocs
end

Base.copy(t::TrialEstimate) = TrialEstimate(copy(t.params), t.time, t.gctime, t.memory, t.allocs)

function Base.minimum(trial::Trial)
    i = indmin(trial.times)
    return TrialEstimate(trial, trial.times[i], trial.gctimes[i])
end

function Base.maximum(trial::Trial)
    i = indmax(trial.times)
    return TrialEstimate(trial, trial.times[i], trial.gctimes[i])
end

Base.median(trial::Trial) = TrialEstimate(trial, median(trial.times), median(trial.gctimes))
Base.mean(trial::Trial) = TrialEstimate(trial, mean(trial.times), mean(trial.gctimes))

Base.isless(a::TrialEstimate, b::TrialEstimate) = isless(time(a), time(b))

Base.time(t::TrialEstimate) = t.time
gctime(t::TrialEstimate) = t.gctime
memory(t::TrialEstimate) = t.memory
allocs(t::TrialEstimate) = t.allocs
params(t::TrialEstimate) = t.params

##############
# TrialRatio #
##############

mutable struct TrialRatio
    params::Parameters
    time::Float64
    gctime::Float64
    memory::Float64
    allocs::Float64
end

@compat function Base.:(==)(a::TrialRatio, b::TrialRatio)
    return a.params == b.params &&
           a.time == b.time &&
           a.gctime == b.gctime &&
           a.memory == b.memory &&
           a.allocs == b.allocs
end

Base.copy(t::TrialRatio) = TrialRatio(copy(t.params), t.time, t.gctime, t.memory, t.allocs)

Base.time(t::TrialRatio) = t.time
gctime(t::TrialRatio) = t.gctime
memory(t::TrialRatio) = t.memory
allocs(t::TrialRatio) = t.allocs
params(t::TrialRatio) = t.params

function ratio(a::Real, b::Real)
    if a == b # so that ratio(0.0, 0.0) returns 1.0
        return one(Float64)
    end
    return Float64(a / b)
end

function ratio(a::TrialEstimate, b::TrialEstimate)
    ttol = max(params(a).time_tolerance, params(b).time_tolerance)
    mtol = max(params(a).memory_tolerance, params(b).memory_tolerance)
    p = Parameters(params(a); time_tolerance = ttol, memory_tolerance = mtol)
    return TrialRatio(p, ratio(time(a), time(b)), ratio(gctime(a), gctime(b)),
                      ratio(memory(a), memory(b)), ratio(allocs(a), allocs(b)))
end

gcratio(t::TrialEstimate) =  ratio(gctime(t), time(t))

##################
# TrialJudgement #
##################

struct TrialJudgement
    ratio::TrialRatio
    time::Symbol
    memory::Symbol
end

function TrialJudgement(r::TrialRatio)
    ttol = params(r).time_tolerance
    mtol = params(r).memory_tolerance
    return TrialJudgement(r, judge(time(r), ttol), judge(memory(r), mtol))
end

@compat function Base.:(==)(a::TrialJudgement, b::TrialJudgement)
    return a.ratio == b.ratio &&
           a.time == b.time &&
           a.memory == b.memory
end

Base.copy(t::TrialJudgement) = TrialJudgement(copy(t.params), t.time, t.memory)

Base.time(t::TrialJudgement) = t.time
memory(t::TrialJudgement) = t.memory
ratio(t::TrialJudgement) = t.ratio
params(t::TrialJudgement) = params(ratio(t))

judge(a::TrialEstimate, b::TrialEstimate; kwargs...) = judge(ratio(a, b); kwargs...)

function judge(r::TrialRatio; kwargs...)
    newr = copy(r)
    newr.params = Parameters(params(r); kwargs...)
    return TrialJudgement(newr)
end

function judge(ratio::Real, tolerance::Float64)
    if isnan(ratio) || (ratio - tolerance) > 1.0
        return :regression
    elseif (ratio + tolerance) < 1.0
        return :improvement
    else
        return :invariant
    end
end

isimprovement(t::TrialJudgement) = time(t) == :improvement || memory(t) == :improvement
isregression(t::TrialJudgement) = time(t) == :regression || memory(t) == :regression
isinvariant(t::TrialJudgement) = time(t) == :invariant && memory(t) == :invariant

###################
# Pretty Printing #
###################

prettypercent(p) = string(@sprintf("%.2f", p * 100), "%")

function prettydiff(p)
    diff = p - 1.0
    return string(diff >= 0.0 ? "+" : "", @sprintf("%.2f", diff * 100), "%")
end

function prettytime(t)
    if t < 1e3
        value, units = t, "ns"
    elseif t < 1e6
        value, units = t / 1e3, "μs"
    elseif t < 1e9
        value, units = t / 1e6, "ms"
    else
        value, units = t / 1e9, "s"
    end
    return string(@sprintf("%.3f", value), " ", units)
end

function prettymemory(b)
    if b < 1024
        return string(b, " bytes")
    elseif b < 1024^2
        value, units = b / 1024, "KiB"
    elseif b < 1024^3
        value, units = b / 1024^2, "MiB"
    else
        value, units = b / 1024^3, "GiB"
    end
    return string(@sprintf("%.2f", value), " ", units)
end

Base.show(io::IO, t::Trial) = print(io, "Trial(", prettytime(time(t)), ")")
Base.show(io::IO, t::TrialEstimate) = print(io, "TrialEstimate(", prettytime(time(t)), ")")
Base.show(io::IO, t::TrialRatio) = print(io, "TrialRatio(", prettypercent(time(t)), ")")
Base.show(io::IO, t::TrialJudgement) = print(io, "TrialJudgement(", prettydiff(time(ratio(t))), " => ", time(t), ")")

@compat function Base.show(io::IO, ::MIME"text/plain", t::Trial)
    if length(t) > 0
        min = minimum(t)
        max = maximum(t)
        med = median(t)
        avg = mean(t)
        memorystr = string(prettymemory(memory(min)))
        allocsstr = string(allocs(min))
        minstr = string(prettytime(time(min)), " (", prettypercent(gcratio(min)), " GC)")
        maxstr = string(prettytime(time(med)), " (", prettypercent(gcratio(med)), " GC)")
        medstr = string(prettytime(time(avg)), " (", prettypercent(gcratio(avg)), " GC)")
        meanstr = string(prettytime(time(max)), " (", prettypercent(gcratio(max)), " GC)")
    else
        memorystr = "N/A"
        allocsstr = "N/A"
        minstr = "N/A"
        maxstr = "N/A"
        medstr = "N/A"
        meanstr = "N/A"
    end
    println(io, "BenchmarkTools.Trial: ")
    println(io, "  memory estimate:  ", memorystr)
    println(io, "  allocs estimate:  ", allocsstr)
    println(io, "  --------------")
    println(io, "  minimum time:     ", minstr)
    println(io, "  median time:      ", maxstr)
    println(io, "  mean time:        ", medstr)
    println(io, "  maximum time:     ", meanstr)
    println(io, "  --------------")
    println(io, "  samples:          ", length(t))
    print(io,   "  evals/sample:     ", t.params.evals)
end

@compat function Base.show(io::IO, ::MIME"text/plain", t::TrialEstimate)
    println(io, "BenchmarkTools.TrialEstimate: ")
    println(io, "  time:             ", prettytime(time(t)))
    println(io, "  gctime:           ", prettytime(gctime(t)), " (", prettypercent(gctime(t) / time(t)),")")
    println(io, "  memory:           ", prettymemory(memory(t)))
    print(io,   "  allocs:           ", allocs(t))
end

@compat function Base.show(io::IO, ::MIME"text/plain", t::TrialRatio)
    println(io, "BenchmarkTools.TrialRatio: ")
    println(io, "  time:             ", time(t))
    println(io, "  gctime:           ", gctime(t))
    println(io, "  memory:           ", memory(t))
    print(io,   "  allocs:           ", allocs(t))
end

@compat function Base.show(io::IO, ::MIME"text/plain", t::TrialJudgement)
    println(io, "BenchmarkTools.TrialJudgement: ")
    println(io, "  time:   ", prettydiff(time(ratio(t))), " => ", time(t), " (", prettypercent(params(t).time_tolerance), " tolerance)")
    print(io,   "  memory: ", prettydiff(memory(ratio(t))), " => ", memory(t), " (", prettypercent(params(t).memory_tolerance), " tolerance)")
end


text:
"""
Handles Http server related functionality, manages requests and responses and their logging.
"""
module AppServer

using Revise, HTTP, HTTP.IOExtras, HTTP.Sockets, Millboard, MbedTLS, URIParser, Sockets, Distributed
using Genie, Genie.Configuration, Genie.Loggers, Genie.Sessions, Genie.Flax, Genie.Router, Genie.WebChannels

### PRIVATE ###

"""
    startup(port::Int = Genie.config.server_port, host::String = Genie.config.server_host;
        ws_port::Int = Genie.config.websocket_port, async::Bool = ! Genie.config.run_as_server) :: Nothing

Starts the web server.

# Arguments
- `port::Int`: the port used by the web server
- `host::String`: the host used by the web server
- `ws_port::Int`: the port used by the Web Sockets server
- `async::Bool`: run the web server task asynchronously

# Examples
```julia-repl
julia> startup(8000, "0.0.0.0", async = false)
[ Info: Ready!
Web Server starting at http://0.0.0.0:8000
```
"""
function startup(port::Int = Genie.config.server_port, host::String = Genie.config.server_host;
                  ws_port::Int = Genie.config.websocket_port, async::Bool = ! Genie.config.run_as_server,
                  verbose::Bool = false, ratelimit::Union{Rational{Int},Nothing} = nothing) :: Nothing

  # Create log directory and log file
  Genie.config.log_to_file && Loggers.initlogfile()

  # Create build folders
  Genie.config.flax_compile_templates && Flax.create_build_folders()

  if Genie.config.websocket_server
    @async HTTP.listen(host, ws_port) do req
      if HTTP.WebSockets.is_upgrade(req.message)
        HTTP.WebSockets.upgrade(req) do ws
          setup_ws_handler(req.message, ws)
        end
      end
    end

    log("Web Sockets server running at $host:$ws_port")
  end

  command = () -> begin
    HTTP.serve(parse(IPAddr, host), port, verbose = verbose, rate_limit = ratelimit) do req::HTTP.Request
      setup_http_handler(req)
    end
  end

  @info "Ready!\n"
  log("Web Server starting at http://$host:$port")

  if async
    @async command()
    log("Web Server running at http://$host:$port")
  else
    command()
    log("Web Server stopped")
  end

  nothing
end

"""
    setup_http_handler(req::HTTP.Request, res::HTTP.Response = HTTP.Response()) :: HTTP.Response

Configures the handler for the HTTP Request and handles errors.
"""
@inline function setup_http_handler(req::HTTP.Request, res::HTTP.Response = HTTP.Response()) :: HTTP.Response
  try
    @fetch handle_request(req, res)
  catch ex
    error_message = string(sprint(showerror, ex), "\n\n")

    log(error_message, :critical)

    message = Genie.Configuration.isprod() ?
                "The error has been logged and we'll look into it ASAP." :
                string(error_message, " in $(@__FILE__):$(@__LINE__)", "\n\n")

    Genie.Router.error_500(message, req)
  end
end

"""
    setup_ws_handler(req::HTTP.Request, ws_client) :: Nothing

Configures the handler for WebSockets requests.
"""
@inline function setup_ws_handler(req::HTTP.Request, ws_client) :: Nothing
  while ! eof(ws_client)
    write(ws_client, String(@fetch handle_ws_request(req, String(readavailable(ws_client)), ws_client)))
  end

  nothing
end

"""
    handle_request(req::HTTP.Request, res::HTTP.Response, ip::IPv4 = IPv4(Genie.config.server_host)) :: HTTP.Response

Http server handler function - invoked when the server gets a request.
"""
@inline function handle_request(req::HTTP.Request, res::HTTP.Response, ip::IPv4 = IPv4(Genie.config.server_host)) :: HTTP.Response
  isempty(Genie.config.server_signature) && sign_response!(res)
  set_headers!(req, res, Genie.Router.route_request(req, res, ip))
end

"""
    handle_ws_request(req::HTTP.Request, msg::String, ws_client, ip::IPv4 = IPv4(Genie.config.server_host)) :: String

Http server handler function - invoked when the server gets a request.
"""
function handle_ws_request(req::HTTP.Request, msg::String, ws_client, ip::IPv4 = IPv4(Genie.config.server_host)) :: String
  msg == "" && return "" # keep alive
  Genie.Router.route_ws_request(req, msg, ws_client, ip)
end

"""
    set_headers!(req::HTTP.Request, res::HTTP.Response, app_response::HTTP.Response) :: HTTP.Response

Configures the response headers.
"""
function set_headers!(req::HTTP.Request, res::HTTP.Response, app_response::HTTP.Response) :: HTTP.Response
  if req.method == Genie.Router.OPTIONS || req.method == Genie.Router.GET

    request_origin = Dict(req.headers)["Origin"]

    allowed_origin_dict = Dict("Access-Control-Allow-Origin" =>
      in(request_origin, Genie.config.cors_allowed_origins)
      ? request_origin
      : strip(Genie.config.cors_headers["Access-Control-Allow-Origin"])
    )

    #=
    Combine headers. If different values for the same keys,
    use the following order of precedence:
    app_response > res > allowed_origin > Genie.config

    The app_response likely has an automatically-determined
    response type header that we want to keep.
    =#
    app_response.headers = [d for d in merge(Genie.config.cors_headers, allowed_origin_dict, Dict(res.headers), Dict(app_response.headers))]
  end

  #=
  Combine headers. If different values for the same keys,
  use the following order of precedence:
  app_response > res
  =#
  app_response.headers = [d for d in merge(Dict(res.headers), Dict(app_response.headers))]

  app_response
end

"""
    sign_response!(res::HTTP.Response) :: HTTP.Response

Adds a signature header to the response using the value in `Genie.config.server_signature`.
If `Genie.config.server_signature` is empty, the header is not added.
"""
@inline function sign_response!(res::HTTP.Response) :: HTTP.Response
  headers = Dict(res.headers)
  isempty(Genie.config.server_signature) || (headers["Server"] = Genie.config.server_signature)

  res.headers = [k for k in headers]
  res
end

end


text:
@testset "consistency.jl" begin
    @testset "ECE" begin
        ce = ECE(UniformBinning(10))
        N = 1_000

        for nclasses in (2, 5, 10)
            println("Consistency test with ECE ($nclasses classes)")

            # sample predictions and targets
            Random.seed!(1234)
            dist = Dirichlet(nclasses, 1)
            predictions = [rand(dist) for _ in 1:10]
            targets_consistent = [
                rand(Categorical(prediction)) for prediction in predictions
            ]
            targets_onlyone = ones(Int, length(predictions))

            # define consistency resampling tests
            test_consistent = ConsistencyTest(ce, predictions, targets_consistent)
            test_onlyone = ConsistencyTest(ce, predictions, targets_onlyone)

            # compute pvalues with both resampling methods
            Random.seed!(1234)
            pvalues = [pvalue(Random.GLOBAL_RNG, test_consistent) for _ in 1:N]

            if nclasses == 2
                @test mean(pvalues) ≈ 0.35 atol = 1e-2
            elseif nclasses == 5
                @test mean(pvalues) ≈ 0.02 atol = 1e-2
            elseif nclasses == 10
                @test mean(pvalues) ≈ 0.02 atol = 1e-2
            end

            Random.seed!(1234)
            pvalues = [pvalue(Random.GLOBAL_RNG, test_onlyone) for _ in 1:N]
            @test mean(pvalues) < 1e-3
        end
    end

    @testset "Block SKCE" begin
        nsamples = 10
        N = 1_000

        for blocksize in (2, 5)
            ce = BlockUnbiasedSKCE(
                (ExponentialKernel() ∘ ScaleTransform(0.1)) ⊗ WhiteKernel(), blocksize
            )

            for nclasses in (2, 5, 10)
                println(
                    "Consistency test with the linear SKCE estimator ($nclasses classes)"
                )

                # sample predictions and targets
                Random.seed!(1234)
                dist = Dirichlet(nclasses, 1)
                predictions = [rand(dist) for _ in 1:10]
                targets_consistent = [
                    rand(Categorical(prediction)) for prediction in predictions
                ]
                targets_onlyone = ones(Int, length(predictions))

                # define consistency resampling tests
                test_consistent = ConsistencyTest(ce, predictions, targets_consistent)
                test_onlyone = ConsistencyTest(ce, predictions, targets_onlyone)

                # compute pvalues with both resampling methods
                Random.seed!(1234)
                pvalues = [pvalue(Random.GLOBAL_RNG, test_consistent) for _ in 1:N]

                if blocksize == 2
                    if nclasses == 2
                        @test mean(pvalues) ≈ 0.12 atol = 1e-2
                    elseif nclasses == 5
                        @test mean(pvalues) ≈ 0.62 atol = 1e-2
                    elseif nclasses == 10
                        @test mean(pvalues) ≈ 0.44 atol = 1e-2
                    end
                else
                    if nclasses == 2
                        @test mean(pvalues) ≈ 0.01 atol = 1e-2
                    elseif nclasses == 5
                        @test mean(pvalues) ≈ 0.63 atol = 1e-2
                    elseif nclasses == 10
                        @test mean(pvalues) ≈ 0.21 atol = 1e-2
                    end
                end

                Random.seed!(1234)
                pvalues = [pvalue(Random.GLOBAL_RNG, test_onlyone) for _ in 1:N]
                @test mean(pvalues) < 1e-2
            end
        end
    end
end


text:
module test_51_OneScalarMonteCarloMeasurementsSignal

using ModiaResult
using OrderedCollections
using Unitful
using MonteCarloMeasurements
ModiaResult.@usingModiaPlot

t = range(0.0, stop=10.0, length=100)
c = ones(size(t,1))

result = OrderedDict{String,Any}()

result["time"] = t*u"s"
result["phi"]  = [sin(t[i]) ± 0.1*c[i]  for i in eachindex(t)]*u"rad"

println("\n... test_51_OneScalarMonteCarloMeasurementsSignal:")
ModiaResult.printResultInfo(result)

plot(result, "phi", MonteCarloAsArea=true, heading="Sine(time) with MonteCarloMeasurements")

end

max_stars_repo_name: ModiaSim/ModiaResult

max_issues_repo_name: ModiaSim/ModiaResult

max_forks_repo_name: ModiaSim/ModiaResult


text:
module UTFDetect

utf8_lead_1(b::UInt8) = leading_ones(b) == 0
utf8_lead_2(b::UInt8) = leading_ones(b) == 2
utf8_lead_3(b::UInt8) = leading_ones(b) == 3
utf8_lead_4(b::UInt8) = leading_ones(b) == 4
utf8_cont(b::UInt8)   = leading_ones(b) == 1

utf16_lone(b::UInt8)  = (b >> 3) != 0b11011
utf16_lead(b::UInt8)  = (b >> 2) == 0b110110
utf16_trail(b::UInt8) = (b >> 2) == 0b110111

utf32_byte_4(b::UInt8) = b == 0x00
utf32_byte_3(b::UInt8) = b <= 0x10

false_p(b::UInt8) = false
true_p(b::UInt8)  = true

const predicates = [
    utf8_lead_1, utf8_lead_2, utf8_lead_3, utf8_lead_4, utf8_cont,
    utf16_lone, utf16_lead, utf16_trail,
    utf32_byte_4, utf32_byte_3,
    false_p, true_p,
]

p_mask(byte::UInt8) =
    sum(pred(byte) << (i-1) for (i, pred) in enumerate(predicates))
p_mask(p::Vector{<:Function}) =
    sum((pred in p) << (i-1) for (i, pred) in enumerate(predicates))

p_masks = sort!(unique(p_mask(byte) for byte = 0x0:0xff))
# 10 total predicate masks < 4 bits
@assert length(p_masks) == 10

# construct a predicate lookup table indexing into p_masks
p_table = UInt8[findfirst(==(p_mask(UInt8(b))), p_masks)-1 for b=0x00:0xff]
@assert all(p_mask(b) == p_masks[p_table[b+1]+1] for b = 0x00:0xff)

# UTF-8 state: counter of remaining trailing bytes from 3 down to 0 (bits: 2)
# UTF-16 state: hi/lo alternator, trail indicator (bits: 3, one shared with UTF-32)
# UTF-32 state: byte counter for 0-3 (bits: 2, one shared with UTF-16)
# total state: 6 bits (3 data-dependent, 3 data-independent)

# preds: value from p_table, index into p_masks
# represents a possible set of true predicates

function ⋲(p::Function, preds::UInt8)
    mask = p_masks[preds+1]
    for (i, p′) in enumerate(predicates)
        p′ == p && return !iszero(mask & (1 << (i-1)))
    end
    error("predicate not found: $p")
end

# u8_next: u8_trail must be 0 at start of a character
# set to the number of trailing continuation characters
# decremented after each continuation character

function u8_next(preds::UInt8, u8_trail::UInt8)::UInt8
    utf8_cont   ⋲ preds ? max(0, u8_trail-1) :
    utf8_lead_4 ⋲ preds ? 3 :
    utf8_lead_3 ⋲ preds ? 2 :
    utf8_lead_2 ⋲ preds ? 1 : 0
end

function u8_valid(u8_trail::UInt8)
    u8_trail == 0 ?
        p_mask([utf8_lead_1, utf8_lead_2, utf8_lead_3, utf8_lead_4]) :
        p_mask([utf8_cont])
end

# u16_next: only called on high bytes, for little-endian & big-endian
# there's a separate state bit for each one that's passed through as-is
# for bytes that aren't the high byte for that endianness

function u16_next(preds::UInt8)::UInt8
    utf16_lead ⋲ preds
end

function u16_valid(u16_trail::UInt8, count::UInt8, be::Bool)
    hi = be ⊻ isodd(count) # count is zero-based
    hi && u16_trail == 0 ? p_mask([utf16_lone, utf16_lead]) :
    hi && u16_trail == 1 ? p_mask([utf16_trail]) :
                           p_mask([true_p])
end

# u32_next: doesn't exist since UTF-32 has no data-dependent state

function u32_valid(count::UInt8, be::Bool)
    (count & 3) == (be ? 0 : 3) ? p_mask([utf32_byte_4]) :
    (count & 3) == (be ? 1 : 2) ? p_mask([utf32_byte_3]) :
                                  p_mask([true_p])
end

# build the transition table

t_table = zeros(UInt8, 2^4*2^2*10)
indices = Int[]
for u8_trail = 0b00:0b11, u16l_trail = 0b0:0b1, u16b_trail = 0b0:0b1
    state = u8_trail | (u16l_trail << 2) | (u16b_trail << 3)
    for count = 0b00:0b11
        mask_u8   = u8_valid(u8_trail)
        mask_u16l = u16_valid(u16l_trail, count, false)
        mask_u16b = u16_valid(u16b_trail, count, true)
        mask_u32l = u32_valid(count, false)
        mask_u32b = u32_valid(count, true)
        for preds in 0x0:0x9
            index = state | (count << 4) | (UInt16(preds) << 6)
            # compute the valid mask
            mask  = p_masks[preds+1]
            u8    = UInt8(!iszero(mask & mask_u8))
            u16l  = UInt8(!iszero(mask & mask_u16l))
            u16b  = UInt8(!iszero(mask & mask_u16b))
            u32l  = UInt8(!iszero(mask & mask_u32l))
            u32b  = UInt8(!iszero(mask & mask_u32b))
            valid = u8 | (u16l << 1) | (u16b << 2) | (u32l << 3) | (u32b << 4)
            # compute the next state
            u8_trail′ = u8_next(preds, u8_trail)
            if iseven(count)
                u16l_trail′ = u16l_trail
                u16b_trail′ = u16_next(preds)
            else
                u16l_trail′ = u16_next(preds)
                u16b_trail′ = u16b_trail
            end
            state′ = u8_trail′ | (u16l_trail′ << 2) | (u16b_trail′ << 3)
            # populate the table
            t_table[index + 1] = valid | (state′ << 5)
            push!(indices, index)
        end
    end
end
@assert sort!(indices) == 0:length(t_table)-1

const table = Tuple([p_table; t_table])

function detect(bytes::Union{AbstractVector{UInt8}, IO})
    valid = 0b11111
    state = 0b000
    count = 0b00
    @inbounds for byte in bytes
        preds = table[byte + 1]
        index = state | (count << 4) | (UInt16(preds) << 6)
        state = table[index + 1 + 256]
        valid &= state
        state >>= 5
        count = (count + 0x1) & 0x3
    end
    return valid, state, count
end

end # module

max_stars_repo_name: StefanKarpinski/UTFDetect

max_issues_repo_name: StefanKarpinski/UTFDetect

max_forks_repo_name: StefanKarpinski/UTFDetect


text:
### A Pluto.jl notebook ###
# v0.12.20

using Markdown
using InteractiveUtils

# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
    quote
        local el = $(esc(element))
        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
        el
    end
end

# ╔═╡ 635e5ebc-6567-11eb-1d9d-f98bfca7ec27
@bind x html"<input type=range>"

# ╔═╡ ad853ac9-a8a0-44ef-8d41-c8cea165ad57
@bind y html"<input type=range>"

# ╔═╡ 26025270-9b5e-4841-b295-0c47437bc7db
x + y

# ╔═╡ 1352da54-e567-4f59-a3da-19ed3f4bb7c7

# ╔═╡ 09ae27fa-525a-4211-b252-960cdbaf1c1e
b = @bind s html"<input>"

# ╔═╡ ed78a6f1-d282-4d80-8f42-40701aeadb52
b

# ╔═╡ cca2f726-0c25-43c6-85e4-c16ec192d464
s

# ╔═╡ c4f51980-3c30-4d3f-a76a-fc0f0fe16944

# ╔═╡ 8f0bd329-36b8-45ed-b80d-24661242129a
b2 = @bind s2 html"<input>"

# ╔═╡ c55a107f-5d7d-4396-b597-8c1ae07c35be
b2

# ╔═╡ a524ff27-a6a3-4f14-8ed4-f55700647bc4
sleep(1); s2

# ╔═╡ Cell order:
# ╠═635e5ebc-6567-11eb-1d9d-f98bfca7ec27
# ╠═ad853ac9-a8a0-44ef-8d41-c8cea165ad57
# ╠═26025270-9b5e-4841-b295-0c47437bc7db
# ╟─1352da54-e567-4f59-a3da-19ed3f4bb7c7
# ╠═09ae27fa-525a-4211-b252-960cdbaf1c1e
# ╠═ed78a6f1-d282-4d80-8f42-40701aeadb52
# ╠═cca2f726-0c25-43c6-85e4-c16ec192d464
# ╟─c4f51980-3c30-4d3f-a76a-fc0f0fe16944
# ╠═8f0bd329-36b8-45ed-b80d-24661242129a
# ╠═c55a107f-5d7d-4396-b597-8c1ae07c35be
# ╠═a524ff27-a6a3-4f14-8ed4-f55700647bc4


text:
function plotunicode_points(p)
    show(UnicodePlots.scatterplot(p[:, 1], p[:, 2],
                                  marker = :diamond))
    return
end
function plotunicode(U;
                     colormap::Symbol = :viridis, title::String = "")
    np = length(U)
    snp = ceil(Int64, sqrt(np))
    u = reshape(U, snp, snp)
    show(UnicodePlots.heatmap(real.(u), xfact = 2 / (snp - 1),
                              yfact = 2 / (snp - 1),
                              xoffset = -1., yoffset = -1.,
                              colormap = colormap, title = title,
                              #, colormap = :inferno,
                              width = 30, height = 30))
    print("\n")
    return nothing
end
#-------------------------------------------------------------------------------
"""

   plotmesh(filename::String = "Lpolmesh", nc::Int64 = 1_00;
            dimplot::Bool = true, alphac::Float64 = 0.9,
            visible::Bool = false, cut::Int64 = 0)
"""
function plotmesh(filename::String = "Lpolmesh", nc::Int64 = 1_00;
                  dimplot::Bool = true, alphac::Float64 = 0.9,
                  visible::Bool = true, cut::Int64 = 0,
                  randomcolors::Bool = !dimplot)
    mesh_filename = "$(@__DIR__)/../test/data/$(filename)_$(nc).jld2"
    println("read file $(mesh_filename)")
    JLD2.@load(mesh_filename, ps, pv, elem, bbelem, Iv, pb, tb)
    u = if dimplot
        pv'[:]
    else
        pv[:, end]
    end
    dim = size(ps, 2)
    cells = dim == 2 ? bbelem : elem
    bcells = bbelem
    if !visible
        Iv = 1:size(ps, 1)
    end
    if cut > 0
        Iv = intersect(Iv, findall((ps .- mean(pv, dims = 1))[:, cut] .> 0))
    end
    plotsolution(u, pv, cells, bcells, Iv, ps, wireframe = true,
                 visible = visible,
                 alphac = alphac, randomcolors = randomcolors)
    nothing
end
#-------------------------------------------------------------------------------
function plotsolution3D(uin, pv, cells, bcells, Iv, ps;
                        wireframe::Bool = false, randomcolors::Bool = false,
                        alphac::Float64 = 0.9, visible::Bool = false,
                        resolution::Int64 = 400, mesh_filename::String = "")
    np, m = length(cells), GeometryBasics.Mesh[]
    GLMakie.destroy!(GLMakie.global_gl_screen())
    colS = range(Colors.HSV(0, 1, 1), stop = Colors.HSV(330, 1, 1),
                 length = 64)
    colmapS = [convert(Colors.RGB{Float32}, colS[k]) for  k = 1:length(colS)]
    dim = length(uin) ÷ size(pv, 1)
    fig = GLMakie.Figure(resolution = (dim * resolution, resolution))
    println("build meshes in plotsolution3D")
    pts_wire = Vector{Vector{Float64}}()
    for k ∈ Iv #1:np
        Ik = unique(cells[k][:])
        pk = pv[Ik, :]
        t = convexhull(pk)[1]
        if wireframe
            fG = bcells[k]
            #fG = convexhull_3Dfaces(pk)[1]
            for l = 1:length(fG)
                for m = 1:length(fG[l])
                    if m == 1
                        push!(pts_wire, pk[fG[l][1], :])
                        push!(pts_wire, pk[fG[l][end], :])
                    else
                        push!(pts_wire, pk[fG[l][m - 1], :])
                        push!(pts_wire, pk[fG[l][m], :])
                    end
                end
            end
        end
        tG = [TriangleFace{Int32}(t[l, 1], t[l, 2], t[l, 3])
                                                          for l = 1:size(t, 1)]
        pG =  [Point3f0(pk[l, 1], pk[l, 2], pk[l, 3]) for l = 1:size(pk, 1)]
        push!(m, normal_mesh(copy(pG), copy(tG)))
    end
    if wireframe  # add edges of polygons
        npw = length(pts_wire)
        x = [pts_wire[k][1] for k = 1:npw]
        y = [pts_wire[k][2] for k = 1:npw]
        z = [pts_wire[k][3] for k = 1:npw]
    end
    # plot
    axlist = Any[]
    for k = 1:dim
        ax = L = GLMakie.Axis3(fig[1, 2 * k - 1])
        push!(axlist, ax)
        u, title = if dim == 1
            uin, ""
        elseif k == 1
            uin[1:3:end], "ux"
        elseif k == 2
            uin[2:3:end], "uy"
        elseif k == 3
            uin[3:3:end], "uz"
        end
        if length(title) > 0
            ax.title = title
        end
        xu = range(minimum(u), stop = maximum(u), length = length(colS))
        il = LinearInterpolation(xu, colmapS)
        colors = randomcolors ? [RGBA(rand(3)..., alphac) for _ ∈ Iv] : [il(mean(u[cells[l]])) for l ∈ Iv]
        Makie.mesh!(L, m, color = colors, shading = false)
        #Makie.scatter!(L, p[Ipv, 1], p[Ipv, 2], p[Ipv, 3], markersize = 5_000)
        #Makie.scatter!(L, p[Iv, 1], p[Iv, 2], p[Iv, 3], markersize = 5_000)
        ax.aspect = :data
        if wireframe  # add edges of polygons
            Makie.linesegments!(L, x, y, z, color = :black)
        end
        Colorbar(fig[1, 2 * k], limits = (minimum(u), maximum(u)),
                 colormap = :hsv,
                 size = 10,  height = Relative(3/4))
    end
    if dim > 1
    #    Main.Makie.linkaxes!(axlist...)
    end
    display(fig)
    return
end
#-------------------------------------------------------------------------------
function plotsolution(uin, pv, cells, bcells, Iv, ps;
                      alphac::Float64 = 0.9, visible::Bool = false,
                      resolution::Int64 = 400,  wireframe::Bool = false,
                      randomcolors::Bool = false,
                      mesh_filename::String = "")
    if size(pv, 2) == 3
        if !scipy
            error("3D plots only available if scipy is installed in conda..")
        end
        plotsolution3D(uin, pv, cells, bcells, Iv, ps, resolution = resolution,
                       alphac = alphac, mesh_filename = mesh_filename,
                       wireframe = wireframe, visible = visible,
                       randomcolors = randomcolors)
        return
    end
    GLMakie.destroy!(GLMakie.global_gl_screen())
    dim = length(uin) ÷ size(pv, 1)
    fig = GLMakie.Figure(resolution = (dim * resolution, resolution))
    P = Polygon[]
    for k ∈ Iv
        cc = [cells[k]..., cells[k][1]]
        push!(P, Polygon([Point2(pv[m, 1],
                                 pv[m, 2]) for m ∈ cc])) # u[m]
    end
    colS = range(Colors.HSV(0, 1, 1), stop = Colors.HSV(330, 1, 1),
                 length = 64)
    colmapS = [convert(Colors.RGB{Float32}, colS[k]) for  k = 1:length(colS)]
    dim = length(uin) ÷ size(pv, 1)
    axlist = Any[]
    for k = 1:dim
        ax = L = GLMakie.Axis(fig[1, 2 * k - 1])
        push!(axlist, ax)
        ax.aspect = GLMakie.DataAspect()
        u, title = if dim == 1
            uin, ""
        elseif k == 1
            uin[1:2:end], "ux"
        elseif k == 2
            uin[2:2:end], "uy"
        end
        if length(title) > 0
            ax.title = title
        end
        xu = range(minimum(u), stop = maximum(u), length = length(colS))
        il = LinearInterpolation(xu, colmapS)
        colors = randomcolors ? [RGBA(rand(3)..., alphac) for _ ∈ Iv] : [il(mean(u[cells[l]])) for l ∈ Iv]
        Makie.poly!(ax, P,
                    strokecolor = :black, strokewidth = 2.,
                    color = colors)
        Colorbar(fig[1, 2 * k], limits = (minimum(u), maximum(u)),
                 colormap = :hsv,
                 size = 10,  height = Relative(3/4))
        #Makie.scatter!(L, ps[Iv, 1], ps[Iv, 2], markersize = 10)
        if occursin("square", mesh_filename)
            xlims!(ax, (0, 1.))
            ylims!(ax, (0, 1.))
        elseif occursin("L", mesh_filename)
            xlims!(ax, (-1, 1.))
            ylims!(ax, (-1, 1.))
        end
    end
    if dim > 1
        Main.Makie.linkaxes!(axlist...)
    end
    display(Makie.current_figure())
    return
end


text:
module psmp

export weibel_streaming
using Sobol

function uniform_6d(Np::Int, nskip=0,T=Float64)
  x1n=Array{T}(Np)
  x2n=Array{T}(Np)
  x3n=Array{T}(Np)
  v1n=Array{T}(Np)
  v2n=Array{T}(Np)
  v3n=Array{T}(Np)

  sob = Sobol.SobolSeq(6)
  Sobol.skip(sob, 4+nskip) # Skip some entries
  for i=1:Np
    x1n[i],x2n[i],x3n[i],v1n[i],v2n[i],v3n[i]=Sobol.next(sob)
  end

  return x1n,x2n,x3n,v1n,v2n,v3n
end

import SpecialFunctions: erfinv
# Sampling

function maxwellian_6d{T}(Np::Int, nskip::Int=0,  L::Array{T,1}=ones(T,3),
            sigma::Array{T,1}=ones(T,3),
            mu::Array{T,1}=zeros(T,3) )

            x1n,x2n,x3n,v1n,v2n,v3n=uniform_6d(Np,nskip)

            p=maxwellian_6d(x1n,x2n,x3n,v1n,v2n,v3n,
                            L, sigma,mu)
            return x1n,x2n,x3n,v1n,v2n,v3n,p
end

function maxwellian_6d{T}(x1n,x2n,x3n,v1n,v2n,v3n,
               L::Array{T,1}=ones(T,3),
              sigma::Array{T,1}=ones(T,3),
              mu::Array{T,1}=zeros(T,3) )
              x1n.*=L[1]
              x2n.*=L[2]
              x3n.*=L[3]

              norminv=p->sqrt(2.).*erfinv.(2.*p - 1.0)

              v1n.=norminv(v1n).*sigma[1].+mu[1]
              v2n.=norminv(v2n).*sigma[2].+mu[2]
              v3n.=norminv(v3n).*sigma[3].+mu[3]

  #Probability density
  p(x1,x2,x3,v1,v2,v3)=exp.(- (v1.-mu[1]).^2./sigma[1]^2/2.
                        .-(v2.-mu[2]).^2./sigma[2]^2/2.
                       .-(v3.-mu[3]).^2./sigma[3]^2/2.  ).*
                   (2*pi)^(-1.5)/(prod(sigma)*prod(L))

  return p
end

# Rotation of initial density for testing
# function rotate3d
#
# end

# input uniformly distributed
function maxwellian_stream_3d{T}(v1n,v2n,v3n, alpha::Array{T,1},
                  sigma::Array{T,2},mu::Array{T,2})
  Ns::Int=length(alpha) # number of streams
  Np::Int=length(v1n)
  norminv=p->sqrt(2.).*erfinv.(2.*p - 1.0)
  v1n.=norminv(v1n)
  v2n.=norminv(v2n)
  v3n.=norminv(v3n)

  nidx=Array{Int}(Ns+1)
  nidx.=[1;ceil(Int,alpha[1:Ns-1]*Np);Np]

  for ndx=1:Ns
    # use fused multiply add fma
    v1n[nidx[ndx]:nidx[ndx+1]].=fma.(v1n[nidx[ndx]:nidx[ndx+1]],sigma[1,ndx],mu[1,ndx])
    v2n[nidx[ndx]:nidx[ndx+1]].=fma.(v2n[nidx[ndx]:nidx[ndx+1]],sigma[2,ndx],mu[2,ndx])
    v3n[nidx[ndx]:nidx[ndx+1]].=fma.(v3n[nidx[ndx]:nidx[ndx+1]],sigma[3,ndx],mu[3,ndx])
  end

  function p(v1,v2,v3)

    fun=similar(v1)
    fun.=0
     for ndx=1:Ns
       fun+=exp.(- (v1-mu[1,ndx]).^2./sigma[1,ndx]^2/2.
      -(v2-mu[2,ndx]).^2./sigma[2,ndx]^2/2.
     -(v3-mu[3,ndx]).^2./sigma[3,ndx]^2/2.  )*
         (2*pi)^(-1.5)/prod(sigma[:,ndx])
     end
    return fun
  end

  return p
end

d = Dict("a"=>1, "b"=>2, "c"=>3);

"""
Linear Landau Damping (Langmuir Wave)
# Arguments
- epsilon: default 0.5 for strong landau damping, set 0.05 for weak (linear)
"""
function landau{T}(x1n::Array{T,1},x2n,x3n,v1n,v2n,v3n; epsilon=0.5,
                   sigma=ones(T,3),
                   k::Array{T,1}=[0.5,0.5,0.5], q=-1., m=1.)

    L=ones(T,3)*2*pi./k;
    g=maxwellian_6d(x1n,x2n,x3n,v1n,v2n,v3n,L,sigma, zeros(T,3))

    f(x1,x2,x3,v1,v2,v3)=(1. + epsilon*cos.(k[1]*x1)).*
                          g(x1,x2,x3,v1,v2,v3)*prod(L)

    # Default parameters
    params=Dict("dt"=>0.1,"tmax"=>25, "q"=>q, "m"=>m, "c"=>1.,
                 "sigma"=>sigma, "k"=>k, "epsilon"=>epsilon,"L"=>L,
                  "f0"=>f, "g0"=>g)
    return params
end

"""
Jeans instability
"""
function jeans{T}(x1n::Array{T,1},x2n,x3n,v1n,v2n,v3n; epsilon=0.1,
                   sigma=ones(T,3),
                   k::Array{T,1}=[0.5,0.5,0.5], q=-1.,m=-1.)
    @assert m<0
    landau(x1n,x2n,x3n,v1n,v2n,v3n, epsilon=epsilon,sigma=sigma,k=k,q=q,m=m)
end

"Weibel instability in six dimensions"
function weibel{T}(x1n,x2n,x3n,v1n,v2n,v3n;
                   epsilon=1e-3, beta=-1e-3 ,
                   sigma= [ 0.02/sqrt(2), 0.02*sqrt(12/2),0.02*sqrt(12/2)],
                   k::Array{T,1}=[1.25,1.25,1.25])
  L=ones(T,3)*2*pi./k;

  g=maxwellian_6d(x1n,x2n,x3n,v1n,v2n,v3n,L,sigma, zeros(T,3))

  f(x1,x2,x3,v1,v2,v3)=(1. + epsilon*sin.(k[1]*x1)).*g(x1,x2,x3,v1,v2,v3)*prod(L)

  B3(x1,x2,x3)=real(beta)*cos.(k[1]*x1)+imag(beta)*sin.(k[1]*x1);

  # Default parameters
  params=Dict("dt"=>0.2,"tmax"=>150, "q"=>-1., "m"=>1., "c"=>1.,
               "sigma"=>sigma, "k"=>k, "epsilon"=>epsilon,"L"=>L,
                "B"=>(nothing,nothing,B3 ),
                "f0"=>f, "g0"=>g)

  return params
end

"Weibel streaming instability in six dimensions"
function weibel_streaming{T}(x1n::Array{T,1},x2n,x3n,v1n,v2n,v3n;
                   epsilon::T=T(0), beta=-im*1e-3,
                   sigma::Array{T,1}= 0.1./sqrt(2).*ones(T,3),
                   k::Array{T,1}=[0.2;0.2;0.2],
                   delta::T=(1./6.0) )
  L=ones(T,3)*2*pi./k;
  x1n.*=L[1]
  x2n.*=L[2]
  x3n.*=L[3]

  v01=0.5;
  v02=-0.1;

  gv=maxwellian_stream_3d(v1n,v2n,v3n, [delta;1.-delta],
                       sigma.*ones(1,2),
                        [ [0. 0.]; [v01 v02]; [0. 0.]  ]  )

  g(x1,x2,x3,v1,v2,v3)=(1. .+ epsilon*sin.(k[1]*x1)).*gv(v1,v2,v3)./prod(L)
  f(x1,x2,x3,v1,v2,v3)=(1. .+ epsilon*sin.(k[1]*x1)).*gv(v1,v2,v3)

  B3(x1,x2,x3)=real(beta)*cos.(k[1]*x1)+imag(beta)*sin.(k[1]*x1);

  # Default parameters
  params=Dict("dt"=>0.1,"tmax"=>200, "q"=>-1., "m"=>1., "c"=>1.,
               "sigma"=>sigma, "k"=>k, "epsilon"=>epsilon,"L"=>L,
                "B"=>(nothing,nothing,B3 ),
                "f0"=>f, "g0"=>g)

  return params
end

"""
Two dimensional periodic Kelvin Helmholtz instability

# Arguments
 k - k=1 is the stable mode in periodic domain
     chose k<1 for instability in corresponding dimension
     domain stability in 2-3
"""
function KelvinHelmholtz{T}(x1n::Array{T,1},x2n,x3n,v1n,v2n,v3n;
                   epsilon::T=0.015,
                   k::Array{T,1}=[0.4;1.;1.],
                   q=-1.,m=1., B0::Array{T,1}=[0.;0.;10.])

  L=ones(T,3)*2*pi./k;

  g=maxwellian_6d(x1n,x2n,x3n,v1n,v2n,v3n,L)

f(x1,x2,x3,v1,v2,v3)=(1+ sin.(k[2].*x2)+epsilon.*cos.(k[1].*x1) ).*
                        exp.(-0.5.*(v1.^2.+v2.^2.+v3.^2))./sqrt(2*pi).^3;

# Default parameters
params=Dict("dt"=>0.1/norm(B0),"tmax"=>20*norm(B0), "q"=>q, "m"=>m, "c"=>1.,
              "k"=>k, "epsilon"=>epsilon,"L"=>L,
              "B"=>((x1,x2,x3)->B0[1],(x1,x2,x3)->B0[2],(x1,x2,x3)->B0[3]),
              "f0"=>f, "g0"=>g)

      return params

end

end

max_stars_repo_name: ameresj/VlasovPIF

max_issues_repo_name: ameresj/VlasovPIF

max_forks_repo_name: ameresj/VlasovPIF


text:
@testset "995.minimum-number-of-k-consecutive-bit-flips.jl" begin
    @test min_k_bit_flips([0, 1, 0], 1) == 2
    @test min_k_bit_flips([1, 1, 0], 2) == -1
    @test min_k_bit_flips([0, 0, 0, 1, 0, 1, 1, 0], 3) == 3
    @test min_k_bit_flips([1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
                           0, 1, 0, 0, 0, 0, 1, 0], 2) == -1
end