text:
#=
if:
- Julia version: 1.5.0
- Author: shisa
- Date: 2020-08-08
=#

module If
    # methods
    function get_greater_value(val1, val2)
        if val1 > val2
            return val1
        elseif val1 < val2
            return val2
        else
            return nothing
        end
    end

    function check_greater_0(val)
        return val > 0 ? true : false
    end

    function check_negative_value(val)
        return val >= 0 && error("val must be negative")
    end

    function check_non_negative_value(val)
        return val >= 0 || error("val must be non-negative")
    end

    function main()
        println("Get greater value")
        println("val1:5, val2:1 = ", get_greater_value(5, 1))
        println("val1:4, val2:5 = ", get_greater_value(4, 5))
        println("val1:1, val2:1 = ", get_greater_value(1, 1))
        println("")
        println("100 is greater than 0? ", check_greater_0(100))
        println("-1 is greater than 0? ", check_greater_0(-1))
    end
end

if abspath(PROGRAM_FILE) == @__FILE__
    using .If
    If.main()
end

max_stars_repo_name: ShisatoYano/JuliaPractice

max_issues_repo_name: ShisatoYano/JuliaPractice

max_forks_repo_name: ShisatoYano/JuliaPractice


text:
abstract type Filter <: InverterComponent end

@def filter_ports begin
    #TODO: If converter has dynamics, need to connect state_input
    state_input = [:δθ_vsm] #[:Vd_c, :Vq_c] #, :Id_c, :Iq_c]
    inner_input = [VR_inv_var,VI_inv_var,Vdcnv_var,Vqcnv_var,δdqRI_var,Vdo_var,Vqo_var]
end

"""
*  `lf`::Float64 : filter inductance
*  `rf`::Float64 : filter resistance
*  `cf`::Float64 : filter capacitance
"""
struct LCFilter <: Filter
    lf::Float64
    rf::Float64
    cf::Float64
    n_states::Int64
    states::Vector{Symbol}
    ports::Ports

        function LCFilter(lf::Float64,
                          rf::Float64,
                          cf::Float64)

            @filter_ports

            new(lf,
                rf,
                cf,
                4,
                [:id_o, :iq_o],
                Ports(state_input, inner_input))

        end

    end

"""
Parameters of a LCL filter outside the converter
# Conmutable structor
```julia
LCLFilter(lf, rf, cf, lg, rg)
```

# Arguments
* `lf`::Float64 : Series inductance in p.u. of converter filter
* `rf`::Float64 : Series resistance in p.u. of converter filter
* `cf`::Float64 : Shunt capacitance in p.u. of converter filter
* `lg`::Float64 : Series inductance in p.u. of converter filter to the grid
* `rg`::Float64 : Series resistance in p.u. of converter filter to the grid

"""
struct LCLFilter <: Filter
        lf::Float64
        rf::Float64
        cf::Float64
        lg::Float64
        rg::Float64
        n_states::Int64
        states::Vector{Symbol}
        ports::Ports

            function LCLFilter(lf::Float64,
                               rf::Float64,
                               cf::Float64,
                               lg::Float64,
                               rg::Float64)

                n_states = 6
                states = [:id_c, :iq_c, :vd_cap, :vq_cap, :id_o, :iq_o]
                @filter_ports

                new(lf,
                    rf,
                    cf,
                    lg,
                    rg,
                    n_states,
                    states,
                    Ports(state_input, inner_input))
            end
end

ext: jl


text:
module API

using AWS.EC2

import Base: start, next, done, getindex, isempty

for f in (:start, :next, :done, :getindex, :isempty)
    @eval $(f)(a::DescribeInstancesResponseType, args...) = $(f)(a.reservationSet,args...)
end

end


text:
"""
	Contains all function for sampling expressions and from expressions
"""

"""
    rand(::Type{RuleNode}, grammar::Grammar, typ::Symbol, max_depth::Int=10)

Generates a random RuleNode of return type typ and maximum depth max_depth.
"""
function Base.rand(::Type{RuleNode}, grammar::Grammar, typ::Symbol, max_depth::Int=10,
    bin::Union{NodeRecycler,Nothing}=nothing)
    rules = grammar[typ]

    if max_depth <= 1
        terminals = filter(r->isterminal(grammar,r), rules)
        rule_index = !isempty(terminals) ? StatsBase.sample(terminals) : StatsBase.sample(rules)
    else
        rule_index = StatsBase.sample(rules)
    end

    rulenode = iseval(grammar, rule_index) ?
        RuleNode(bin, rule_index, Core.eval(grammar, rule_index)) :
        RuleNode(bin, rule_index)

    if !grammar.isterminal[rule_index]
        for ch in child_types(grammar, rule_index)
            push!(rulenode.children, rand(RuleNode, grammar, ch, max_depth-1, bin))
        end
    end
    return rulenode
end
"""
    rand(::Type{RuleNode}, grammar::Grammar, typ::Symbol, dmap::AbstractVector{Int}, max_depth::Int=10)

Generates a random RuleNode of return type typ and maximum depth max_depth guided by a minimum depth map dmap.
"""
function Base.rand(::Type{RuleNode}, grammar::Grammar, typ::Symbol, dmap::AbstractVector{Int},
    max_depth::Int=10, bin::Union{NodeRecycler,Nothing}=nothing)
    rules = grammar[typ]
    rule_index = StatsBase.sample(filter(r->dmap[r] ≤ max_depth, rules))

    rulenode = iseval(grammar, rule_index) ?
        RuleNode(bin, rule_index, Core.eval(grammar, rule_index)) :
        RuleNode(bin, rule_index)

    if !grammar.isterminal[rule_index]
        for ch in child_types(grammar, rule_index)
            push!(rulenode.children, rand(RuleNode, grammar, ch, dmap, max_depth-1, bin))
        end
    end
    return rulenode
end

mutable struct RuleNodeAndCount
    node::RuleNode
    cnt::Int
end
"""
    sample(root::RuleNode, typ::Symbol, grammar::Grammar, maxdepth::Int=typemax(Int))

Selects a uniformly random node from the tree, limited to maxdepth.
"""
function StatsBase.sample(root::RuleNode, maxdepth::Int=typemax(Int))
    x = RuleNodeAndCount(root, 1)
    for child in root.children
        _sample(child, x, maxdepth-1)
    end
    x.node
end
function _sample(node::RuleNode, x::RuleNodeAndCount, maxdepth::Int)
    maxdepth < 1 && return
    x.cnt += 1
    if rand() <= 1/x.cnt
        x.node = node
    end
    for child in node.children
        _sample(child, x, maxdepth-1)
    end
end

"""
    sample(root::RuleNode, typ::Symbol, grammar::Grammar,
                          maxdepth::Int=typemax(Int))

Selects a uniformly random node of the given return type, typ, limited to maxdepth.
"""
function StatsBase.sample(root::RuleNode, typ::Symbol, grammar::Grammar,
                          maxdepth::Int=typemax(Int))
    x = RuleNodeAndCount(root, 0)
    if grammar.types[root.ind] == typ
        x.cnt += 1
    end
    for child in root.children
        _sample(child, typ, grammar, x, maxdepth-1)
    end
    grammar.types[x.node.ind] == typ || error("type $typ not found in RuleNode")
    x.node
end
function _sample(node::RuleNode, typ::Symbol, grammar::Grammar, x::RuleNodeAndCount,
                 maxdepth::Int)
    maxdepth < 1 && return
    if grammar.types[node.ind] == typ
        x.cnt += 1
        if rand() <= 1/x.cnt
            x.node = node
        end
    end
    for child in node.children
        _sample(child, typ, grammar, x, maxdepth-1)
    end
end

mutable struct NodeLocAndCount
	loc::NodeLoc
	cnt::Int
end

"""
	sample(::Type{NodeLoc}, root::RuleNode, maxdepth::Int=typemax(Int))

Selects a uniformly random node in the tree no deeper than maxdepth using reservoir sampling.
Returns a NodeLoc that specifies the location using its parent so that the subtree can be replaced.
"""

function StatsBase.sample(::Type{NodeLoc}, root::RuleNode, maxdepth::Int=typemax(Int))
	x = NodeLocAndCount(root_node_loc(root), 1)
	_sample(NodeLoc, root, x, maxdepth-1)
	x.loc
end

function _sample(::Type{NodeLoc}, node::RuleNode, x::NodeLocAndCount, maxdepth::Int)
	maxdepth < 1 && return
	for (j,child) in enumerate(node.children)
	    x.cnt += 1
	    if rand() <= 1/x.cnt
		x.loc = NodeLoc(node, j)
	    end
	    _sample(NodeLoc, child, x, maxdepth-1)
	end
end

"""
	sample(::Type{NodeLoc}, root::RuleNode, typ::Symbol, grammar::Grammar)

Selects a uniformly random node in the tree of a given type, specified using its parent such that the subtree can be replaced.
Returns a NodeLoc.
"""
function StatsBase.sample(::Type{NodeLoc}, root::RuleNode, typ::Symbol, grammar::Grammar,
			      maxdepth::Int=typemax(Int))
	x = NodeLocAndCount(root_node_loc(root), 0)
	if grammar.types[root.ind] == typ
	    x.cnt += 1
	end
	_sample(NodeLoc, root, typ, grammar, x, maxdepth-1)
	grammar.types[get(root,x.loc).ind] == typ || error("type $typ not found in RuleNode")
	x.loc
end

function _sample(::Type{NodeLoc}, node::RuleNode, typ::Symbol, grammar::Grammar,
		     x::NodeLocAndCount, maxdepth::Int)
	maxdepth < 1 && return
	for (j,child) in enumerate(node.children)
	    if grammar.types[child.ind] == typ
		x.cnt += 1
		if rand() <= 1/x.cnt
		    x.loc = NodeLoc(node, j)
		end
	    end
	    _sample(NodeLoc, child, typ, grammar, x, maxdepth-1)
	end
end


text:
using MPI

mutable struct WandbLoggerMPI{L<:Union{Nothing,WandbLogger},C}
    logger::L
    config::C
end

function Base.getproperty(wl::WandbLoggerMPI, id::Symbol)
    return hasfield(typeof(wl), id) ? getfield(wl, id) : getproperty(wl.logger, id)
end

function WandbLoggerMPI(args...; name::Union{Nothing,String}=nothing, group::Union{Nothing,String}=nothing, kwargs...)
    comm = MPI.COMM_WORLD
    rank = MPI.Comm_rank(comm)
    size = MPI.Comm_size(comm)

    if isnothing(group)
        if rank == 0
            if size == 1
                return WandbLogger(args...; name=name, kwargs...)
            else
                return WandbLoggerMPI(WandbLogger(args...; name=name, kwargs...), get(kwargs, :config, Dict()))
            end
        else
            return WandbLoggerMPI(nothing, get(kwargs, :config, Dict()))
        end
    else
        if !isnothing(name)
            name = name * "_rank_$rank"
        end
        return WandbLogger(args...; name=name, group=group, kwargs...)
    end
end

function Base.show(io::IO, ::WandbLoggerMPI{Nothing})
    return Base.print(io, "WandbLogger(Non Logging Process)")
end

function Base.show(io::IO, wl::WandbLoggerMPI)
    return Base.show(io, wl.logger)
end

function update_config!(lg::WandbLoggerMPI, dict::Dict; kwargs...)
    # I forgot why I was throwing this error :'(
    return error("Updating Config when using MPI is not yet supported")
end

get_config(lg::WandbLoggerMPI, key::String) = get(lg.config, key, nothing)
get_config(lg::WandbLoggerMPI) = lg.config

for func in (:log, :close)
    @eval begin
        Base.$(func)(wa::WandbLoggerMPI, args...; kwargs...) = $(func)(wa.logger, args...; kwargs...)

        Base.$(func)(wa::WandbLoggerMPI{Nothing}, args...; kwargs...) = nothing
    end
end

for func in (:increment_step!, :finish, :save)
    @eval begin
        $(func)(wa::WandbLoggerMPI, args...; kwargs...) = $(func)(wa.logger, args...; kwargs...)

        $(func)(wa::WandbLoggerMPI{Nothing}, args...; kwargs...) = nothing
    end
end

export WandbLoggerMPI


text:
using BaseOnnx
using Documenter

makedocs(;
    modules=[BaseOnnx],
    authors="Peter Wolf, Julia Community",
    repo="https://github.com/opus111/BaseOnnx.jl/blob/{commit}{path}#L{line}",
    sitename="BaseOnnx.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://opus111.github.io/BaseOnnx.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
    ],
)

deploydocs(;
    repo="github.com/opus111/BaseOnnx.jl",
)


text:
# We want to extract the trees in a BART tree created by the bartMachine R package.
# The java object is avaialble in bart_machine$java_bart_machine and we can serialize
# that with .jserialize in the rJava package. Example code:
#
# library(bartMachine)
# n = 10
# p = 1
# X = data.frame(matrix(runif(n * p), ncol = p))
# y = 10 * X[ ,1]
# bart_machine = bartMachine(X,y, num_trees = 2, serialize = TRUE)
# str = .jserialize(bart_machine$java_bart_machine)
# length(str)
# fh <- file("bart_machine_java_serialized.bin", "wb")
# writeBin(str, fh)
# close(fh)

# Now we want to parse out the tree from this serialized java object.
# We create a small java serialized object parser in Julia. It will not be
# complete but will be focused for this particular use case.
#
function parse_java_serialized_object(o::Vector{UInt8})
    p = 1
    ensure_value(o, UInt8[0xAC, 0xED], p, "STREAM_MAGIC not matched")
end

o = open(fh -> read(fh), "bart_machine_java_serialized.bin")

function ensure_value(o::Vector{UInt8}, bytes::Vector{UInt8}, pos::Int = 1, message = "")
    allmatched = all(i -> o[pos + i - 1] == bytes[i], 1:length(bytes))
    if !allmatched
        error(message * " (at position $pos)")
    else
        return allmatched
    end
end

# The basic format of the seralized object is as a series of objects that adds a few different
# but related methods/vars and then has an array of bartMachineTreeNode objects to represent the
# root of each BART tree. Each node has left, right, split dimension and split value, plus flags
# and intermediate values. So basically we just need to skip ahead to the first splitAttributeM
# int and then read its double splitValue and just recurse.
# Seems fairly simple in theory. :)

# Example of how to parse these objects: http://www.javaworld.com/article/2072752/the-java-serialization-algorithm-revealed.html
# Format spec: https://docs.oracle.com/javase/7/docs/platform/serialization/spec/protocol.html


text:
module MaxHelpingHandSidewaysMovingPlatform

using ..Ahorn, Maple

@pardef SidewaysMovingPlatform(x::Integer, y::Integer, height::Integer=Maple.defaultBlockHeight, left::Bool=true, mode::String="Loop", texture::String="default", moveTime::Number=2.0, pauseTime::Number=0.0, easing::Bool=true, amount::Int=1, offset::Number=0.0, flag::String="", emitSound::Bool=true) =
    Entity("MaxHelpingHand/SidewaysMovingPlatform", x=x, y=y, nodes=Tuple{Int, Int}[], height=height, left=left, mode=mode, texture=texture, moveTime=moveTime, pauseTime=pauseTime, easing=easing, amount=amount, offset=offset, flag=flag, emitSound=emitSound)

const placements = Ahorn.PlacementDict()

const modes = ["Loop", "LoopNoPause", "BackAndForth", "BackAndForthNoPause", "TeleportBack"]

for texture in Maple.wood_platform_textures
    placements["Sideways Moving Platform ($(uppercasefirst(texture))) (max480's Helping Hand)"] = Ahorn.EntityPlacement(
        SidewaysMovingPlatform,
        "rectangle",
        Dict{String, Any}(
            "texture" => texture
        ),
        function(entity)
            x, y = Int(entity.data["x"]), Int(entity.data["y"])
            entity.data["x"], entity.data["y"] = x + 16, y
            entity.data["nodes"] = [(x, y)]
        end
    )
end

Ahorn.editingOptions(entity::SidewaysMovingPlatform) = Dict{String, Any}(
    "texture" => Maple.wood_platform_textures,
    "mode" => modes
)

Ahorn.nodeLimits(entity::SidewaysMovingPlatform) = 1, -1

Ahorn.resizable(entity::SidewaysMovingPlatform) = false, true

Ahorn.minimumSize(entity::SidewaysMovingPlatform) = 0, 8

function Ahorn.selection(entity::SidewaysMovingPlatform)
    height = Int(get(entity.data, "height", 8))

    nodes = get(entity.data, "nodes", ())
    startX, startY = Int(entity.data["x"]), Int(entity.data["y"])
    rectangles = Ahorn.Rectangle[Ahorn.Rectangle(startX, startY, 8, height)]

    for node in nodes
        nodeX, nodeY = Int.(node)
        push!(rectangles, Ahorn.Rectangle(nodeX, nodeY, 8, height))
    end

    return rectangles
end

outerColor = (30, 14, 25) ./ 255
innerColor = (10, 0, 6) ./ 255

function renderConnection(ctx::Ahorn.Cairo.CairoContext, x::Number, y::Number, nx::Number, ny::Number, height::Number)
    cx, cy = x + 4, y + floor(Int, height / 2)
    cnx, cny = nx + 4, ny + floor(Int, height / 2)

    length = sqrt((x - nx)^2 + (y - ny)^2)
    theta = atan(cny - cy, cnx - cx)

    Ahorn.Cairo.save(ctx)

    Ahorn.translate(ctx, cx, cy)
    Ahorn.rotate(ctx, theta)

    Ahorn.setSourceColor(ctx, outerColor)
    Ahorn.set_antialias(ctx, 1)
    Ahorn.set_line_width(ctx, 3);

    Ahorn.move_to(ctx, 0, 0)
    Ahorn.line_to(ctx, length, 0)

    Ahorn.stroke(ctx)

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

    Ahorn.move_to(ctx, 0, 0)
    Ahorn.line_to(ctx, length, 0)

    Ahorn.stroke(ctx)

    Ahorn.Cairo.restore(ctx)
end

function renderPlatform(ctx::Ahorn.Cairo.CairoContext, texture::String, x::Number, y::Number, height::Number, left::Bool)
    tilesHeight = div(height, 8)

    Ahorn.Cairo.save(ctx)
    Ahorn.translate(ctx, x, y)
    Ahorn.rotate(ctx, left ? - pi / 2 : pi / 2)

    offsetX = left ? -height : 0
    offsetY = left ? 0 : -8
    for i in 2:tilesHeight - 1
        Ahorn.drawImage(ctx, "objects/woodPlatform/$texture", 8 * (i - 1) + offsetX, offsetY, 8, 0, 8, 8)
    end

    Ahorn.drawImage(ctx, "objects/woodPlatform/$texture", offsetX, offsetY, 0, 0, 8, 8)
    Ahorn.drawImage(ctx, "objects/woodPlatform/$texture", tilesHeight * 8 - 8 + offsetX, offsetY, 24, 0, 8, 8)
    Ahorn.drawImage(ctx, "objects/woodPlatform/$texture", floor(Int, height / 2) - 4 + offsetX, offsetY, 16, 0, 8, 8)

    Ahorn.Cairo.restore(ctx)
end

function Ahorn.renderAbs(ctx::Ahorn.Cairo.CairoContext, entity::SidewaysMovingPlatform, room::Maple.Room)
    height = Int(get(entity.data, "height", 8))
    mode = get(entity.data, "mode", "Loop")
    left = get(entity.data, "left", true)

    firstNodeX, firstNodeY = Int(entity.data["x"]), Int(entity.data["y"])
    previousNodeX, previousNodeY = firstNodeX, firstNodeY

    texture = get(entity.data, "texture", "default")

    nodes = get(entity.data, "nodes", ())
    for node in nodes
        nodeX, nodeY = Int.(node)
        renderConnection(ctx, previousNodeX, previousNodeY, nodeX, nodeY, height)
        previousNodeX, previousNodeY = nodeX, nodeY
    end

    if mode == "Loop" || mode == "LoopNoPause"
        renderConnection(ctx, previousNodeX, previousNodeY, firstNodeX, firstNodeY, height)
    end

    renderPlatform(ctx, texture, firstNodeX, firstNodeY, height, left)
end

function Ahorn.renderSelectedAbs(ctx::Ahorn.Cairo.CairoContext, entity::SidewaysMovingPlatform, room::Maple.Room)
    height = Int(get(entity.data, "height", 8))
    mode = get(entity.data, "mode", "Loop")
    left = get(entity.data, "left", true)

    firstNodeX, firstNodeY = Int(entity.data["x"]), Int(entity.data["y"])
    previousNodeX, previousNodeY = firstNodeX, firstNodeY

    texture = get(entity.data, "texture", "default")

    nodes = get(entity.data, "nodes", ())
    for node in nodes
        nodeX, nodeY = Int.(node)
        renderPlatform(ctx, texture, nodeX, nodeY, height, left)
        Ahorn.drawArrow(ctx, previousNodeX + 4, previousNodeY + height / 2, nodeX + 4, nodeY + height / 2, Ahorn.colors.selection_selected_fc, headLength=6)
        previousNodeX, previousNodeY = nodeX, nodeY
    end

    if mode == "Loop" || mode == "LoopNoPause"
        Ahorn.drawArrow(ctx, previousNodeX + 4, previousNodeY + height / 2, firstNodeX + 4, firstNodeY + height / 2, Ahorn.colors.selection_selected_fc, headLength=6)
    end
end

end

max_stars_repo_name: Kitty-Cats/MaxHelpingHand

max_issues_repo_name: Kitty-Cats/MaxHelpingHand

max_forks_repo_name: Kitty-Cats/MaxHelpingHand


text:
module bfgaReverseString

    import Base.isless

    include("Types.jl")
    using .Types

    using Distributed

    #using GeneticAlgorithms
    #include("GeneticAlgorithms.jl")
    #using .GeneticAlgorithms

    include("bfga.jl")
    using .bfga

    include("Bf.jl")
    using .BfInterpreter

    words = ["s", "me", "jay", "kory", "jamie"]

    function fitness(ent, instructionsSet)
        score = 0
        score = @distributed (+) for i = 1:5
            fitness_aux(ent, i, instructionsSet)
        end
        ent.fitness = score
        score
    end

    function fitness_aux(ent, instructionsSet)
        n = rand(1:5)
        fitness_aux(ent, n)
    end

    function fitness_aux(ent, num , instructionsSet)
        #goal = takeAString(num)
        input = words[num]
        goal = reverse(input)
        target_length = length(goal)
        #target_score = target_length*256 #+10
        try
            output, m_Ticks = execute(ent.program, input, instructionsSet)

            score = 0
            n= length(output)

            compteur =0
            for i in output
                #print(i)
                compteur += 1
                if compteur > target_length
                    break
                end
                score += 256 - abs(i - goal[compteur])
            end

            ent.bonus += (2000 - m_Ticks)
            #ent.bonus += bonus

            abs(score) + 6# - target_score)
        catch y
            0
        end
    end

    function simulate_entity(ent, instructionsSet)
        goal = "try to Reverse me"
        target_goal = length(goal)
        _res = "code : $(ent.program ) "
        try
            output, _ = execute(ent.program,goal, instructionsSet)
            if length(output) > target_goal
                return " $_res \n $goal --> "*join(output[1:target_goal], "")
            else
                return " $_res \n $goal --> "*join(output, "")
            end
        catch y
            return " $_res \n BEST raises Errors \n Error : $y "
        end
    end

    function getTargetFitness()
        256* length(join(words, "")) + 30
    end

    function getParams()
        #=
        populationSize ::  Int
        generations ::  Int
        genomeSize ::  Int
        maxGenomeSize :: Int
        crossoverRate :: Float64
        mutationRate :: Float64
        elitism  :: Bool # Keep previous generation's fittest individual in place of worst in current
        historyPath :: String  # Path to save log of fitness history at each generation. Can be used to plot on Excel chart etc.

        totalFitness :: Float64
        targetFitness :: Float64
        targetFitnessCount ::  Int
        currentGeneration ::  Int

        #thisGeneration :: Array
        #nextGeneration :: Array
        #fitnessTable :: Array{Float64,1}
        =#
        logfile = open("../Results/logReversingString.log", "w")

        tgFitness =  getTargetFitness()
        println("targetFitness = $tgFitness ")
        return Main.GeneticAlgorithms.Types.GAParams(136, 1000000 , 120, 150, 0.7, 0.015, true, logfile ,  0.0 , tgFitness, 0.0 , 0 )
    end

    function getBfCode(ent)
        join( ent.program , "")
    end

end

include("../src/GeneticAlgorithms.jl")
using .GeneticAlgorithms
include("bfga.jl")
using .bfga

using Distributed
using Pkg

function test_serial()
    GeneticAlgorithms.runga(bfga, bfgaReverseString) #, initial_pop_size = 135)
end


text:
using Documenter, CSV

makedocs(;
    modules=[CSV],
    format=Documenter.HTML(prettyurls=false),
    pages=[
        "Home" => "index.md",
        "Reading" => "reading.md",
        "Writing" => "writing.md",
        "Examples" => "examples.md",
    ],
    repo="https://github.com/JuliaData/CSV.jl/blob/{commit}{path}#{line}",
    sitename="CSV.jl",
    authors="Jacob Quinn",
)

deploydocs(;
    repo="github.com/JuliaData/CSV.jl",
    devbranch = "main"
)


text:
# module model_fit

using DifferentialEquations, Flux, Optim, DiffEqFlux, DiffEqSensitivity, Plots
using BlackBoxOptim
using BenchmarkTools
using RecursiveArrayTools
# -------------------------------------------------------------------------

function generate_data(sol)
    t = collect(range(0,stop=10,length=101))

    solution = sum(sol(t),dims=1)
    # randomized = VectorOfArray([(sol(t[i]) + .02randn(size(sol,1))) for i in 1:length(t)])
    # dataset = convert(Array,randomized)
    randomized = solution .+ .01randn(size(solution))
    dataset = randomized
    display(scatter!(t,dataset'))
    return dataset
end

function generate_data(sol,t)

    solution = sum(sol(t),dims=1)
    # randomized = VectorOfArray([(sol(t[i]) + .02randn(size(sol,1))) for i in 1:length(t)])
    # dataset = convert(Array,randomized)
    randomized = solution .+ .01randn(size(solution))
    dataset = randomized
    display(scatter!(t,dataset'))
    return dataset
end

# function run_model(model,p,data,densities,constants,t) # version of run function with multiple models
#
#     # Σ_sol_stack = Array{Any}(undef, 1, size(data,2))
#     Σ_sol_stack = zeros(1, size(data,2))
#     # display(1:size(data,1))
#     for i in 1:size(data,1)
#         # run model with given densities
#         densities_i = densities[i,:]
#         f = (du,u,p,t) -> model(du,u,10 .^ p,t,densities_i,constants)
#         tmp_prob = ODEProblem(f,u₀,tspan,p)
#         # tmp_sol = solve(tmp_prob,Rosenbrock23(),saveat=t)
#         tmp_sol = solve(tmp_prob,Rodas4(),saveat=t)
#         # stack temp solution
#         # stack Σ of solution across n species
#         Σ_sol = sum(Array(tmp_sol),dims=1)
#         Σ_sol_stack = vcat(Σ_sol_stack,Σ_sol)
#     end
#     return Σ_sol_stack[2:end,:]
# end

function run_model(model,p,data,densities,constants,t) # version of run function with multiple models

    # Σ_sol_stack = Array{Any}(undef, 1, size(data,2))
    # Σ_sol_stack = zeros(1, size(data,2))

    f = (du,u,p,t) -> model(du,u,10 .^ p,t,densities,constants)
    tmp_prob = ODEProblem(f,u₀,tspan,p)
    # tmp_sol = solve(tmp_prob,Rosenbrock23(),saveat=t)
    # tmp_sol = solve(tmp_prob,Rodas4(),saveat=t)
    tmp_sol = solve(tmp_prob,Tsit5(),saveat=t)
    # stack temp solution
    # stack Σ of solution across n species
    Σ_sol = sum(Array(tmp_sol),dims=1)

end

function loss(p,data,model,dens,cons,t)
    Σ_sol = run_model(model,p,data,dens,cons,t)
    # display(Σ_sol)
    # sum(abs2, (Σ_sol - data) .* t), Σ_sol
    sum(abs2, (Σ_sol - data))#, Σ_sol
end

function callback(p,l,tmp_sol,data,model,dens,cons,t)
    @show l

    Σ_sol = run_model(model,p,data,dens,cons,t)

    fig = plot(t,Σ_sol')
    scatter!(fig,t,data',legend=:bottomright)
    display(fig)

    false
end

function scan_param_space(p,data,model,dens,cons,t,lb,ub)
        #create rand mesh
        n = 10000
        ps = rand(n,size(p,1)) .* 9 .- 7
        errors = zeros(n)
        for i in 1:n
            # error, a = loss(ps[i,:],data,model,dens,cons,t)
            error = loss(ps[i,:],data,model,dens,cons,t)
            errors[i] = error
            # @show error
        end
        min_ind = argmin(errors)
        min_error = minimum(errors)
        @show findmin(errors)
        p_best = ps[min_ind,:]
        @show p_best
        if size(p,1) == 2
            fig = scatter(ps[:,1],ps[:,2],log10.(errors),
            zcolor = log10.(errors),camera=[0,90])
            scatter!([p_best[1]],[p_best[2]],[log10(min_error)],markercolor=:green,markersize=5)
            display(fig)
        end
        return p_best
end

function optimization(model,data,dens,cons,options,t)
# fit function - given model, data, densities, options get best parameters

    loss_in = (p) -> loss(p,data,model,dens,cons,t)
    callback_in = (p,l,tmp_sol) -> callback(p,l,tmp_sol,data,model,dens,cons,t)

    # @unpack lb,ub = options
    lb,ub = options
    # f = (du,u,p,t) -> model(du,u,p,t,dens,cons) # optimize in log space
    # prob = ODEProblem(f,u₀,tspan,p)

    # start = scan_param_space(pinit,data,model,dens,cons,t,lb,ub) # !! change behavior so that it doesnt need pinit
    # use ADAM first to find ballparck solution
    # res = DiffEqFlux.sciml_train(loss_in,pinit,ADAM(0.001),cb=callback_in,maxiters=300)
    # res = DiffEqFlux.sciml_train(loss_in,pinit,BFGS(initial_stepnorm = 0.0001),cb=callback_in)
    start = [-4.,-1.]
    res = DiffEqFlux.sciml_train(loss_in,start,BFGS(),cb=callback_in)
    # res = DiffEqFlux.sciml_train(loss_in,start,NelderMead(),cb=callback_in)
    @show res
    rates = res.minimizer
    # rates = start

    f = (du,u,p,t) -> model(du,u,p,t,dens,cons) # optimize in log space
    prob = ODEProblem(f,u₀,tspan,10 .^ rates)
    sol = solve(prob,Rodas4())
    h = plot!(sol)
    display(h)
    display([model,rates,start,dens,cons])
    return rates
end

# end


text:
using CompScienceMeshes, BEAST
o, x, y, z = euclidianbasis(3)

Γ = readmesh(joinpath(dirname(@__FILE__),"sphere2.in"))
X, Y = raviartthomas(Γ), buffachristiansen(Γ)

ω = κ = 1.0
μ = ϵ = 1.0

K, N = MWDoubleLayer3D(im*κ), NCross()

E = PlaneWaveMW(z, x, κ, complex(1.0))
H = -1/(im*μ*ω)*curl(E)
h = (n × H) × n

@hilbertspace j; @hilbertspace m;
mfie = @discretise (K+0.5N)[m,j] == h[m]  j∈X m∈Y
u = solve(mfie)

using PlotlyJS
include(Pkg.dir("CompScienceMeshes","examples","plotlyjs_patches.jl"))

fcr, geo = facecurrents(u, X)
p = patch(geo, real.(norm.(fcr)))


text:
#=
This file is auto-generated. Do not edit.
=#
"""
    mutable struct AndersonFouadMachine <: Machine
        R::Float64
        Xd::Float64
        Xq::Float64
        Xd_p::Float64
        Xq_p::Float64
        Xd_pp::Float64
        Xq_pp::Float64
        Td0_p::Float64
        Tq0_p::Float64
        Td0_pp::Float64
        Tq0_pp::Float64
        MVABase::Float64
        ext::Dict{String, Any}
        states::Vector{Symbol}
        n_states::Int64
        internal::InfrastructureSystemsInternal
    end

Parameters of 6-states synchronous machine: Anderson-Fouad model

# Arguments
- `R::Float64`: Resistance after EMF in machine per unit, validation range: (0, nothing)
- `Xd::Float64`: Reactance after EMF in d-axis per unit, validation range: (0, nothing)
- `Xq::Float64`: Reactance after EMF in q-axis per unit, validation range: (0, nothing)
- `Xd_p::Float64`: Transient reactance after EMF in d-axis per unit, validation range: (0, nothing)
- `Xq_p::Float64`: Transient reactance after EMF in q-axis per unit, validation range: (0, nothing)
- `Xd_pp::Float64`: Sub-Transient reactance after EMF in d-axis per unit, validation range: (0, nothing)
- `Xq_pp::Float64`: Sub-Transient reactance after EMF in q-axis per unit, validation range: (0, nothing)
- `Td0_p::Float64`: Time constant of transient d-axis voltage, validation range: (0, nothing)
- `Tq0_p::Float64`: Time constant of transient q-axis voltage, validation range: (0, nothing)
- `Td0_pp::Float64`: Time constant of sub-transient d-axis voltage, validation range: (0, nothing)
- `Tq0_pp::Float64`: Time constant of sub-transient q-axis voltage, validation range: (0, nothing)
- `MVABase::Float64`: Nominal Capacity in MVA, validation range: (0, nothing)
- `ext::Dict{String, Any}`
- `states::Vector{Symbol}`
- `n_states::Int64`
- `internal::InfrastructureSystemsInternal`: power system internal reference, do not modify
"""
mutable struct AndersonFouadMachine <: Machine
    "Resistance after EMF in machine per unit"
    R::Float64
    "Reactance after EMF in d-axis per unit"
    Xd::Float64
    "Reactance after EMF in q-axis per unit"
    Xq::Float64
    "Transient reactance after EMF in d-axis per unit"
    Xd_p::Float64
    "Transient reactance after EMF in q-axis per unit"
    Xq_p::Float64
    "Sub-Transient reactance after EMF in d-axis per unit"
    Xd_pp::Float64
    "Sub-Transient reactance after EMF in q-axis per unit"
    Xq_pp::Float64
    "Time constant of transient d-axis voltage"
    Td0_p::Float64
    "Time constant of transient q-axis voltage"
    Tq0_p::Float64
    "Time constant of sub-transient d-axis voltage"
    Td0_pp::Float64
    "Time constant of sub-transient q-axis voltage"
    Tq0_pp::Float64
    "Nominal Capacity in MVA"
    MVABase::Float64
    ext::Dict{String, Any}
    states::Vector{Symbol}
    n_states::Int64
    "power system internal reference, do not modify"
    internal::InfrastructureSystemsInternal
end

function AndersonFouadMachine(R, Xd, Xq, Xd_p, Xq_p, Xd_pp, Xq_pp, Td0_p, Tq0_p, Td0_pp, Tq0_pp, MVABase, ext=Dict{String, Any}(), )
    AndersonFouadMachine(R, Xd, Xq, Xd_p, Xq_p, Xd_pp, Xq_pp, Td0_p, Tq0_p, Td0_pp, Tq0_pp, MVABase, ext, [:ψq, :ψd, :eq_p, :ed_p, :eq_pp, :ed_pp], 6, InfrastructureSystemsInternal(), )
end

function AndersonFouadMachine(; R, Xd, Xq, Xd_p, Xq_p, Xd_pp, Xq_pp, Td0_p, Tq0_p, Td0_pp, Tq0_pp, MVABase, ext=Dict{String, Any}(), )
    AndersonFouadMachine(R, Xd, Xq, Xd_p, Xq_p, Xd_pp, Xq_pp, Td0_p, Tq0_p, Td0_pp, Tq0_pp, MVABase, ext, )
end

# Constructor for demo purposes; non-functional.
function AndersonFouadMachine(::Nothing)
    AndersonFouadMachine(;
        R=0,
        Xd=0,
        Xq=0,
        Xd_p=0,
        Xq_p=0,
        Xd_pp=0,
        Xq_pp=0,
        Td0_p=0,
        Tq0_p=0,
        Td0_pp=0,
        Tq0_pp=0,
        MVABase=0,
        ext=Dict{String, Any}(),
    )
end

"""Get AndersonFouadMachine R."""
get_R(value::AndersonFouadMachine) = value.R
"""Get AndersonFouadMachine Xd."""
get_Xd(value::AndersonFouadMachine) = value.Xd
"""Get AndersonFouadMachine Xq."""
get_Xq(value::AndersonFouadMachine) = value.Xq
"""Get AndersonFouadMachine Xd_p."""
get_Xd_p(value::AndersonFouadMachine) = value.Xd_p
"""Get AndersonFouadMachine Xq_p."""
get_Xq_p(value::AndersonFouadMachine) = value.Xq_p
"""Get AndersonFouadMachine Xd_pp."""
get_Xd_pp(value::AndersonFouadMachine) = value.Xd_pp
"""Get AndersonFouadMachine Xq_pp."""
get_Xq_pp(value::AndersonFouadMachine) = value.Xq_pp
"""Get AndersonFouadMachine Td0_p."""
get_Td0_p(value::AndersonFouadMachine) = value.Td0_p
"""Get AndersonFouadMachine Tq0_p."""
get_Tq0_p(value::AndersonFouadMachine) = value.Tq0_p
"""Get AndersonFouadMachine Td0_pp."""
get_Td0_pp(value::AndersonFouadMachine) = value.Td0_pp
"""Get AndersonFouadMachine Tq0_pp."""
get_Tq0_pp(value::AndersonFouadMachine) = value.Tq0_pp
"""Get AndersonFouadMachine MVABase."""
get_MVABase(value::AndersonFouadMachine) = value.MVABase
"""Get AndersonFouadMachine ext."""
get_ext(value::AndersonFouadMachine) = value.ext
"""Get AndersonFouadMachine states."""
get_states(value::AndersonFouadMachine) = value.states
"""Get AndersonFouadMachine n_states."""
get_n_states(value::AndersonFouadMachine) = value.n_states
"""Get AndersonFouadMachine internal."""
get_internal(value::AndersonFouadMachine) = value.internal


text:
"Abstract type for PDDL simulators."
abstract type Simulator end

"""
	(sim::Simulator)(domain::Domain, state::State, actions)

Simulates the evolution of a PDDL `domain` as a sequence of `actions` are
executed from an initial `state`.
"""
(sim::Simulator)(domain::Domain, state::State, actions) =
    simulate(sim, domain, state, actions)

"""
	simulate([sim=StateRecorder()], domain::Domain, state::State, actions)

Simulates the evolution of a PDDL `domain` as a sequence of `actions` are
executed from an initial `state`. The type of simulator, `sim`, specifies
what information is collected and returned.

By default, `sim` is a [`StateRecorder`](@ref), which records and returns the
state trajectory.
"""
simulate(sim::Simulator, domain::Domain, state::State, actions) =
	error("Not implemented.")

include("state_recorder.jl")
include("end_state.jl")

simulate(domain::Domain, state::State, actions) =
	simulate(StateRecorder(), domain, state, actions)


text:
@testset "eval scalar" begin
    mmesh = Mesh(
        [2.2 2
        3. 4.
        2.5 10.], [1 2 3]
    )
    edge = [1 2]
    out = eval_scalar_on_boundary_edge([5.0;6.0;10000.0], edge, mmesh)
    sess = Session(); init(sess)
    @test run(sess, out)≈[5.069431844202973
    5.330009478207572
    5.669990521792428
    5.930568155797027]
end


text:
module Gomalish

using Libdl
using Pkg.Artifacts

using CxxWrap

# types
export vector, COO, CRS, Dense, tridiagonal_toeplitz_matrix
export CG, Jacobi, BiCGSTAB
# functions
export print_all
export get_row, get_col, get_nnz
export matvec, add, sub, axpy, xpay, nrm2
export set_create_precond, set_apply_precond, set_tol, set_maxiter, solve, solver_check

const libgomalish = joinpath(@__DIR__, "..", "deps", "build", "lib", "libgomalish.$(dlext)")
# const libgomalish = joinpath(artifact"libgomalish","libgomalish.$(Libdl.dlext)")
isfile(libgomalish) && @wrapmodule(libgomalish, :define_julia_module)

function __init__()
    @initcxx
end

function Base.show(io::IO, x::vector)
    print_all(x)
end

end # module

max_stars_repo_name: AtelierArith/gomalish

max_issues_repo_name: AtelierArith/gomalish

max_forks_repo_name: AtelierArith/gomalish


text:
"""
requires git

returns location of all the models (every version), and the

for a particular version just do

    `filter(x->occursin("l1v2", x), fns)`
"""
function sbml_test_suite(repo_path="$(datadir)/sbml-test-suite/")
    isdir(repo_path) && return nothing
    run(`git clone "https://github.com/anandijain/sbml-test-suite" $(repo_path)`)
end

function get_sbml_suite_fns(repo_path="$(datadir)/sbml-test-suite/"; sfx="l3v2.xml")
    ds = filter(isdir, readdir(joinpath(repo_path, "semantic"); join=true))
    fns = reduce(vcat, glob.("*.xml", ds))
    # fs = map(x -> splitdir(x)[end], fns)
    sfx !==nothing && filter!(endswith(sfx), fns) # latest level and version
    fns
end


text:
###############################
### Result reduction functions
###############################

"""
Reduce buffers

Join buffers returned by multiple runs of simulation

**Arguments**
* `buffer` : list of `OpenStreetMapXSim.Road` objects containing informations about routes selected during the simulation run.

"""
function reduce_results(buffer::Array{OpenStreetMapXSim.Road,1}...)::Array{OpenStreetMapXSim.Road,1}
    reduced_buffer = OpenStreetMapXSim.Road[]
    buffer = vcat(buffer...)
    buffer  = [(Tuple(getfield(buffer[i],field) for field in fieldnames(typeof(buffer[i]))[1:end-1]), buffer[i].count) for i = 1:length(buffer)]
    unique_roads = Set(map(road -> road[1], buffer))
    for road in unique_roads
        count = sum(buffer[i][2] for i in findall(x->(x[1] == road), buffer))
        push!(reduced_buffer,OpenStreetMapXSim.Road(road...,count))
    end
    return reduced_buffer
end

"""
Reduce nodes statistics

Join nodes statistics returned by multiple runs of simulation

**Arguments**
* `nodes` : dictionary of `OpenStreetMapXSim.NodeStat` objects containing informations about each intersection in simulation.

"""
function reduce_results(nodes::Dict{Int64,OpenStreetMapXSim.NodeStat}...)::Dict{Int64,OpenStreetMapXSim.NodeStat}
    reduced_nodes = Dict{Int64,OpenStreetMapXSim.NodeStat}()
    ids = keys(merge(nodes...))
    for id in ids
        count = sum(node[id].count for node in nodes)
        lat = unique(node[id].latitude for node in nodes)[1]
        lon = unique(node[id].longitude for node in nodes)[1]
        agents_data = vcat([node[id].agents_data for node in nodes]...)
        reduced_nodes[id] = OpenStreetMapXSim.NodeStat(count,lat,lon,agents_data)
    end
    return reduced_nodes
end


text:
"""
    abstract type AbstractParticleCollection{AP} end

Abstract supertype for storing data of multiple particle types.

The particles are expected to be stored in a `Dict{Symbol,<:AbstractParticles}`.

The inbuilt functionality of `AbstractParticleCollection` includes accessing and setting properties
via the following syntax:
```julia
P<:AbstractParticles
pc::<:AbstractParticleCollection{P}
p::<:P
pc.dm = p
pc[:dm] === p
```

In addition, the following syntax is equivalent to creating an [`AllParticles`](@ref) object: `pc.all`.
The syntax `pc[:all]` is not valid, however.

If the struct has additional fields, these can also be accessed by `pc.field`, but not by
`pc[:field]`. The latter syntax can only be used to access the particles.

# Methods
The methods `Base.keys`, `Base.values`, `Base.haskey`, `Base.empty`, `Base.empty!`, `Base.isempty`, and
`Base.copy!` are forwarded to the particle `Dict`.

Concrete types of `AbstractParticleCollection` should have the following methods implemented
(also see the implementation of [`ParticleCollection`](@ref)):
- `Base.copy`: returns new object containing a copy of the `Dict`
- `Base.empty`: returns an identical object, but with an empty `Dict`
- `Base.:(==)`
- [`redshift`](@ref): implement this if the redshift of the particle collection is non-zero
- `Base.propertynames`: implement this if there are additional struct fields
- `Base.show(io, mime, pc)`
"""
abstract type AbstractParticleCollection{AP} end

"""
    get_particles(pc::AbstractParticleCollection)

Return the particles `Dict` belonging to the particle collection.

This returns `pc.particles` by default if not overridden.

This is not exported.
"""
get_particles(pc::AbstractParticleCollection) = pc.particles

function Base.getproperty(pc::APC, sym::Symbol) where {APC<:AbstractParticleCollection}
    if sym === :all
        return AllParticles(pc)
    elseif sym in fieldnames(APC)
        return getfield(pc, sym)
    else
        return getindex(pc, sym)
    end
end

function Base.setproperty!(pc::APC, sym::Symbol, val) where {APC<:AbstractParticleCollection}
    if sym === :all
        error("The property 'all' cannot be set, but only gotten.")
    elseif sym in fieldnames(APC)
        setfield!(pc, sym, val)
    else
        setindex!(pc, val, sym)
    end
end

Base.getindex(pc::AbstractParticleCollection, sym::Symbol) = getindex(get_particles(pc), sym)

function Base.setindex!(pc::AbstractParticleCollection, val, sym::Symbol)
    (setindex!(get_particles(pc), val, sym); pc)
end

Base.keys(pc::AbstractParticleCollection) = keys(get_particles(pc))
Base.haskey(pc::AbstractParticleCollection, key) = key in keys(pc)
Base.values(pc::AbstractParticleCollection) = values(get_particles(pc))
Base.propertynames(pc::AbstractParticleCollection) = [:all; keys(pc) |> collect]
Base.empty!(pc::AbstractParticleCollection) = (empty!(get_particles(pc)); pc)
Base.isempty(pc::AbstractParticleCollection) = isempty(get_particles(pc))
Base.copy!(dst::AbstractParticleCollection, src::AbstractParticleCollection) =
    (copy!(get_particles(dst), get_particles(src)); dst)

# to implement:
# Base.copy(pc::AbstractParticleCollection) = AbstractParticleCollection(copy(pc.particles))
# Base.empty(pc::AbstractParticleCollection) = AbstractParticleCollection(empty(pc.particles))
# Base.:(==)(pc1::AbstractParticleCollection, pc2::AbstractParticleCollection) = pc1.particles == pc2.particles

"""
    redshift(pc::AbstractParticleCollection) = 0

Returns the redshift at which the particles are located.

By default, 0 is returned. This method should be overridden for concrete types of `AbstractParticleCollection`
for which the redshift differs.
"""
redshift(pc::AbstractParticleCollection) = 0

"""
    CosmoParticles.show_properties(io::IO, mime, p::AbstractParticleCollection)

Prints the properties of the particles in the collection.

Should be used internally when overriding `Base.show` for concrete implementations of
`AbstractParticleCollection`.

This is not exported.
"""
show_properties(io::IO, mime::AbstractString, p::AbstractParticleCollection) =
    show_properties(io, MIME(mime), p)

function show_properties(io::IO, mime::MIME"text/plain", pc::AbstractParticleCollection)
    if !isempty(pc.particles)
        k = keys(pc) |> collect |> sort
        for key in k
            show(io, mime, pc[key])
            key != k[end] && println(io)
        end
    end
end


text:
function add_legend(legs_pos, spec; legend_attr...)
	leg, cb = draw_legend!(spec)

	has_legend   = !isnothing(leg)
	has_colorbar = !isnothing(cb)

	legend_attr = legend_attributes(legend_attr, has_colorbar)
	@unpack orientation = legend_attr

	positions = inner_legend_positions(has_legend, has_colorbar, orientation, legs_pos)
	add_legend_and_colorbar(leg, cb, legend_attr, positions)
end

function legend_attributes(legend_attr, has_colorbar)
    legend_attr = Dict(pairs(legend_attr))

    legend_position = pop!(legend_attr, :position, :top)
	orientation     = pop!(legend_attr, :orientation, default_orientation(legend_position))
	titleposition   = pop!(legend_attr, :titleposition, default_titleposition(orientation))
	nbanks          = pop!(legend_attr, :nbanks, default_nbanks(orientation, has_colorbar))
	framevisible    = pop!(legend_attr, :framevisible, false)
	titlevisible    = pop!(legend_attr, :titlevisible, true)

    attr = (; legend_position, orientation, titleposition, nbanks, framevisible, titlevisible)
end

function add_legend_and_colorbar(leg_contents, cb_contents, attr, positions)
    has_colorbar = !isnothing(cb_contents)
    has_legend   = !isnothing(leg_contents)

    @unpack leg_pos, cb_pos = positions
    @unpack legend_position, orientation, titleposition, nbanks, titlevisible = attr

    if has_legend
        leg_attributes = legend_attributes(orientation, has_colorbar, titleposition, nbanks)
        add_legend(leg_pos, leg_contents, leg_attributes)
    end

    if has_colorbar
        cb_attributes = colorbar_attributes(orientation)
        add_colorbar(cb_contents, cb_pos, titleposition, titlevisible, has_legend, cb_attributes)
    end
end

#leg_attr = (; orientation, titlevisible, framevisible, titleposition, nbanks, legend_attr...)

# -----------------------------
# -------- L E G E N D --------
# -----------------------------

function add_legend(figpos, legend, leg_attributes)
	leg = Legend(figpos, legend...)
	adjust_attributes!(leg; leg_attributes...)
end

function legend_attributes(orientation, has_colorbar, titleposition, nbanks)
	vertical = orientation == :vertical
	horizontal = !vertical

	stretch_height = has_colorbar && vertical
	stretch_width  = has_colorbar && horizontal

	(; nbanks, orientation, titleposition,
	   tellwidth = vertical    || stretch_width,
	   tellheight = horizontal || stretch_height,
	   framevisible = false)
end

function adjust_attributes!(legend; attr...)
	for (a,b) in pairs(attr)
		setproperty!(legend, a, b)
	end
end

# -----------------------------
# ------ C O L O R B A R ------
# -----------------------------

function add_colorbar(cb_contents, cbpos, titlepos, titlevisible, has_legend, cb_attributes)
	cb = Colorbar(cbpos[1,1]; cb_contents.limits, cb_attributes...)

	squeeze_label_height = titlepos == :top
	squeeze_label_width  = cb_attributes.vertical || titlepos == :left

	if !isnothing(cb_contents.title) && titlevisible
		cbtitlepos = colorbar_titleposition(cbpos, titlepos, has_legend)
		Label(cbtitlepos, cb_contents.title, tellheight = squeeze_label_height, tellwidth = squeeze_label_width)
	end
end

function colorbar_titleposition(cbpos, titlepos, has_legend)
	if titlepos == :top
		cbtitlepos = cbpos[0,1]
	elseif titlepos == :left
		cbtitlepos = cbpos[1,0]
	end
end

function colorbar_attributes(orientation)
	vertical = orientation == :vertical
	horizontal = !vertical

	if horizontal
		cb_attributes = (height = 18, width = Relative(1.0),
			tellwidth = true,
			vertical = vertical,
			valign = :center,
			ticksize = 5,
  			ticklabelpad = 1.5)
	else
		cb_attributes = (width = 18, height = Relative(1.0),
			vertical = vertical,
			halign = :center,
	)

	end
end

# -----------------------------
# ------- H E L P E R S -------
# -----------------------------

has_legend_or_colorbar(spec) = (length(spec.group_dict) > 0) || (length(spec.style_dict) > 0)

function outer_legend_position(fig, has_legend_or_colorbar, legend_position)
	if has_legend_or_colorbar
		if legend_position == :bottom
			ax_pos 	 = fig[1,1]
			legs_pos = fig[2,1]
		elseif legend_position == :top
			ax_pos 	 = fig[2,1]
			legs_pos = fig[1,1]
		elseif legend_position == :right
			ax_pos   = fig[1,1]
			legs_pos = fig[1,2]
		elseif legend_position == :left
			ax_pos   = fig[1,2]
			legs_pos = fig[1,1]
		end
	else
        ax_pos = fig[1,1]
        legs_pos = nothing
	end

	(; ax_pos,  legs_pos)
end

function inner_legend_positions(has_legend, has_colorbar, orientation, legs_pos)
    vertical = orientation == :vertical
    i = 1

    if has_legend
		leg_pos = vertical ? legs_pos[i,1] : legs_pos[1,i]
		i += 1
	else
		leg_pos = nothing
	end
	if has_colorbar
		cb_pos = vertical ? legs_pos[i,1] : legs_pos[1,i]
	else
		cb_pos = nothing
    end
    (; leg_pos, cb_pos)
end

default_orientation(legend_position) = legend_position in [:top, :bottom] ? :horizontal : :vertical

default_nbanks(orientation, has_colorbar) = has_colorbar && (orientation == :horizontal) ? 2 : 1

default_titleposition(orientation) = orientation == :horizontal ? :left : :top

max_stars_repo_name: greimel/TabularMakie

max_issues_repo_name: greimel/TabularMakie

max_forks_repo_name: greimel/TabularMakie


text:
# abstract type AbstractDensity end

# struct LineDensity{T} <: AbstractDensity
#     x::Vector{T}
#     N::Int
#     bins::Int
#     function LineDensity(x::Vector{<:Real}; bins::Int=100)
#         T = eltype(x)
#         N = length(x)
#         return new{T}(x, N, bins)
#     end
# end

"""
    polar1d(y::AbstractVector, theta::AbstractVector, grid::AbstractVector; normalize::Bool=True)
Compute polar order across channel. Normalized such that int n dy =1.
"""
function polar1d(y::AbstractVector, theta::AbstractVector, grid::AbstractVector; normalize::Bool=true)
    bins = length(grid) -1
    # initialize array to store number
    n = zeros(bins); np = zeros(bins);
    m = zeros(bins); mp = zeros(bins);
    # in a cell [a,b], particles that has a<=y<b is counted.
    # for the last cell, y==b is also counted.
    for i in 1:bins
        for (position, angle) in zip(y, theta)
            if grid[i] <=position <grid[i+1]
                n[i] += 1; m[i] += sin(angle);
                if angle<pi
                    np[i] += 1; mp[i] += sin(angle);
                end
            end
        end
    end
    # last cell: add particles on the right boundary
    ind=findall(y->y==grid[end], y)
    for angle in y[ind]
        m[end] += sin(angle);
        if angle<pi
            np[i] += 1; mp[i] += sin(angle);
        end
    end
    n[end] += length(ind)

    # use bin centers as representative locations.
    dy = diff(grid)
    bin_centers = grid[1:end-1] + dy/2
    ind = findall(n->n>0, n)
    m[ind] ./= n[ind]
    ind = findall(np->np>0, np)
    mp[ind] ./= np[ind]
    if normalize
        n ./= dy *length(y)
        np ./= dy*length(y)
    end
    return bin_centers, n, np, m, mp
end

"""
    polar1d(y::AbstractVector, theta::AbstractVector, ymin::Real, ymax::Real; bins::Int=100, normalize::Bool=true)
Compute polar order across channel. Normalized such that int n dy =1.
"""
function polar1d(y::AbstractVector, theta::AbstractVector, ymin::Real, ymax::Real; bins::Int=100, normalize::Bool=true)
    ymin < ymax ||throw(ArgumentError("ymin>=ymax"))
    grid = LinRange(ymin, ymax, bins+1)
    return polar1d(y, theta, grid, normalize=normalize)
end

"""
    polar1d(y::AbstractVector, theta::AbstractVector; bins::Int=100, normalize::Bool=true)
Compute polar order across channel.
"""
function polar1d(y::AbstractVector, theta::AbstractVector; bins::Int=100, normalize::Bool=true)
    ymin = minimum(y)
    ymax = maximum(y)
    return polar1d(y, theta, ymin, ymax, bins=bins, normalize=normalize)
end


text:
# This file was generated, do not modify it. # hide
fitted_params(mtm).best_model.tree


text:
# Unit tests for Run type.
# This file is supposed to be included from runtests.jl.

@testset "Run" begin
    @test Run(0, 0:0).row == 0
    @test Run(0, 0:0).columns.start == 0
    @test Run(0, 0:0).columns.stop == 0

    @test Run(0, 0:-1).columns == 0:-1
    @test Run(0, 0:-1).columns.start == 0
    @test Run(0, 0:-1).columns.stop == -1
    @test length(Run(0, 0:-1).columns) == 0
    @test isempty(Run(0, 0:-1).columns)

    @test Run(0, 0:0).columns == 0:0
    @test Run(0, 0:0).columns.start == 0
    @test Run(0, 0:0).columns.stop == 0
    @test length(Run(0, 0:0).columns) == 1
    @test !isempty(Run(0, 0:0).columns)

    @test Run(0, 0:1).columns == 0:1
    @test Run(0, 0:1).columns.start == 0
    @test Run(0, 0:1).columns.stop == 1
    @test length(Run(0, 0:1).columns) == 2
    @test !isempty(Run(0, 0:1).columns)

    @test Run(0, 0:1) == Run(0, 0:1)
    @test Run(0, 0:1) ≠ Run(1, 0:1)
    @test Run(0, 0:1) ≠ Run(0, 1:2)

    @test Run(0, 0:1) < Run(1, 0:1)
    @test Run(0, 0:1) ≤ Run(1, 0:1)
    @test Run(0, 0:1) ≤ Run(0, 0:1)

    @test Run(0, 0:1) < Run(0, 1:2)
    @test Run(0, 0:1) ≤ Run(0, 1:2)
    @test Run(0, 0:1) ≤ Run(0, 0:1)

    @test Run(1, 0:1) > Run(0, 0:1)
    @test Run(1, 0:1) ≥ Run(0, 0:1)
    @test Run(0, 0:1) ≥ Run(0, 0:1)

    @test Run(0, 1:2) > Run(0, 0:1)
    @test Run(0, 1:2) ≥ Run(0, 0:1)
    @test Run(0, 0:1) ≥ Run(0, 0:1)

    @test translate(Run(1, 1:2), [-5, -6]) == Run(-5, -4:-3)
    @test translate(Run(1, 1:2), [5, 6]) == Run(7, 6:7)
    @test Run(1, 1:2) - [5, 6] == Run(-5, -4:-3)
    @test Run(1, 1:2) + [5, 6] == Run(7, 6:7)

    @test -Run(1, 1:2) == Run(-1, -2:-1)
    @test -Run(-1, -1:0) == Run(1, 0:1)
    @test -(-(Run(1, 1:2))) == Run(1, 1:2)

    @test invert(Run(1, 1:2)) == Run(-1, -2:-1)
    @test invert(Run(-1, -1:0)) == Run(1, 0:1)
    @test invert(invert(Run(1, 1:2))) == Run(1, 1:2)

    @test !contains(Run(0, 0:-1), 0, -1)
    @test !contains(Run(0, 0:-1), 0, 0)
    @test !contains(Run(0, 0:-1), 0, 1)
    @test !contains(Run(0, 0:0), -1, -1)
    @test !contains(Run(0, 0:0), 0, -1)
    @test !contains(Run(0, 0:0), -1, 0)
    @test contains(Run(0, 0:0), 0, 0)
    @test !contains(Run(0, 0:0), 0, 1)
    @test !contains(Run(0, 0:0), 1, 0)
    @test !contains(Run(0, 0:1), -1, 0)
    @test !contains(Run(0, 0:1), 0, -1)
    @test contains(Run(0, 0:1), 0, 0)
    @test contains(Run(0, 0:1), 1, 0)
    @test !contains(Run(0, 0:1), 2, 0)
    @test !contains(Run(0, 0:1), 1, 1)

    @test [0, -1] ∉ Run(0, 0:-1)
    @test [0, 0] ∉ Run(0, 0:-1)
    @test [0, 1] ∉ Run(0, 0:-1)
    @test [-1, -1] ∉ Run(0, 0:0)
    @test [0, -1] ∉ Run(0, 0:0)
    @test [-1, 0] ∉ Run(0, 0:0)
    @test [0, 0] ∈ Run(0, 0:0)
    @test [0, 1] ∉ Run(0, 0:0)
    @test [1, 0] ∉ Run(0, 0:0)
    @test [-1, 0] ∉ Run(0, 0:1)
    @test [0, -1] ∉ Run(0, 0:1)
    @test [0, 0] ∈ Run(0, 0:1)
    @test [1, 0] ∈ Run(0, 0:1)
    @test [2, 0] ∉ Run(0, 0:1)
    @test [1, 1] ∉ Run(0, 0:1)

    @test !isoverlapping(Run(0, 0:1), Run(0, 6:7))
    @test !isoverlapping(Run(0, 1:2), Run(0, 5:6))
    @test !isoverlapping(Run(0, 2:3), Run(0, 4:5))
    @test !isoverlapping(Run(-1, 2:3), Run(0, 3:4))
    @test !isoverlapping(Run(0, 2:3), Run(-1, 3:4))
    @test isoverlapping(Run(0, 2:3), Run(0, 3:4))
    @test !isoverlapping(Run(1, 2:3), Run(0, 3:4))
    @test !isoverlapping(Run(0, 2:3), Run(1, 3:4))
    @test !isoverlapping(Run(-1, 3:4), Run(0, 3:4))
    @test !isoverlapping(Run(0, 3:4), Run(-1, 3:4))
    @test isoverlapping(Run(0, 3:4), Run(0, 3:4))
    @test !isoverlapping(Run(0, 3:4), Run(1, 3:4))
    @test !isoverlapping(Run(1, 3:4), Run(0, 3:4))
    @test !isoverlapping(Run(0, 4:5), Run(0, 2:3))
    @test !isoverlapping(Run(0, 5:6), Run(0, 1:2))
    @test !isoverlapping(Run(0, 6:7), Run(0, 0:1))

    @test !istouching(Run(0, 0:1), Run(0, 6:7))
    @test !istouching(Run(0, 1:2), Run(0, 5:6))
    @test !istouching(Run(0, 2:3), Run(2, 4:5))
    @test istouching(Run(0, 2:3), Run(-1, 4:5))
    @test istouching(Run(0, 2:3), Run(1, 4:5))
    @test istouching(Run(0, 2:3), Run(0, 4:5))
    @test istouching(Run(1, 2:3), Run(0, 4:5))
    @test istouching(Run(-1, 2:3), Run(0, 4:5))
    @test !istouching(Run(2, 2:3), Run(0, 4:5))
    @test !istouching(Run(-2, 2:3), Run(0, 3:4))
    @test !istouching(Run(0, 2:3), Run(-2, 3:4))
    @test istouching(Run(-1, 2:3), Run(0, 3:4))
    @test istouching(Run(0, 2:3), Run(-1, 3:4))
    @test istouching(Run(0, 2:3), Run(0, 3:4))
    @test istouching(Run(0, 2:3), Run(1, 3:4))
    @test istouching(Run(1, 2:3), Run(0, 3:4))
    @test !istouching(Run(0, 2:3), Run(2, 3:4))
    @test !istouching(Run(2, 2:3), Run(0, 3:4))
    @test !istouching(Run(0, 3:4), Run(-2, 3:4))
    @test !istouching(Run(-2, 3:4), Run(0, 3:4))
    @test istouching(Run(0, 3:4), Run(-1, 3:4))
    @test istouching(Run(-1, 3:4), Run(0, 3:4))
    @test istouching(Run(0, 3:4), Run(0, 3:4))
    @test istouching(Run(0, 3:4), Run(1, 3:4))
    @test istouching(Run(1, 3:4), Run(0, 3:4))
    @test !istouching(Run(0, 3:4), Run(2, 3:4))
    @test !istouching(Run(2, 3:4), Run(0, 3:4))
    @test !istouching(Run(0, 4:5), Run(-2, 2:3))
    @test !istouching(Run(-2, 4:5), Run(0, 2:3))
    @test istouching(Run(0, 4:5), Run(-1, 2:3))
    @test istouching(Run(-1, 4:5), Run(0, 2:3))
    @test istouching(Run(0, 4:5), Run(0, 2:3))
    @test istouching(Run(0, 4:5), Run(1, 2:3))
    @test istouching(Run(1, 4:5), Run(0, 2:3))
    @test !istouching(Run(0, 4:5), Run(2, 2:3))
    @test !istouching(Run(2, 4:5), Run(0, 2:3))
    @test !istouching(Run(0, 5:6), Run(0, 1:2))
    @test !istouching(Run(0, 6:7), Run(0, 0:1))

    @test !isclose(Run(0, 0:1), Run(0, 6:7), 0, 0)
    @test !isclose(Run(0, 1:2), Run(0, 5:6), 0, 0)
    @test !isclose(Run(0, 2:3), Run(0, 4:5), 0, 0)
    @test !isclose(Run(-1, 2:3), Run(0, 3:4), 0, 0)
    @test !isclose(Run(0, 2:3), Run(-1, 3:4), 0, 0)
    @test isclose(Run(0, 2:3), Run(0, 3:4), 0, 0)
    @test !isclose(Run(1, 2:3), Run(0, 3:4), 0, 0)
    @test !isclose(Run(0, 2:3), Run(1, 3:4), 0, 0)
    @test !isclose(Run(-1, 3:4), Run(0, 3:4), 0, 0)
    @test !isclose(Run(0, 3:4), Run(-1, 3:4), 0, 0)
    @test isclose(Run(0, 3:4), Run(0, 3:4), 0, 0)
    @test !isclose(Run(0, 3:4), Run(1, 3:4), 0, 0)
    @test !isclose(Run(1, 3:4), Run(0, 3:4), 0, 0)
    @test !isclose(Run(0, 4:5), Run(0, 2:3), 0, 0)
    @test !isclose(Run(0, 5:6), Run(0, 1:2), 0, 0)
    @test !isclose(Run(0, 6:7), Run(0, 0:1), 0, 0)

    @test !isclose(Run(0, 0:1), Run(0, 6:7), 1, 1)
    @test !isclose(Run(0, 1:2), Run(0, 5:6), 1, 1)
    @test !isclose(Run(0, 2:3), Run(2, 4:5), 1, 1)
    @test isclose(Run(0, 2:3), Run(-1, 4:5), 1, 1)
    @test isclose(Run(0, 2:3), Run(1, 4:5), 1, 1)
    @test isclose(Run(0, 2:3), Run(0, 4:5), 1, 1)
    @test isclose(Run(1, 2:3), Run(0, 4:5), 1, 1)
    @test isclose(Run(-1, 2:3), Run(0, 4:5), 1, 1)
    @test !isclose(Run(2, 2:3), Run(0, 4:5), 1, 1)
    @test !isclose(Run(-2, 2:3), Run(0, 3:4), 1, 1)
    @test !isclose(Run(0, 2:3), Run(-2, 3:4), 1, 1)
    @test isclose(Run(-1, 2:3), Run(0, 3:4), 1, 1)
    @test isclose(Run(0, 2:3), Run(-1, 3:4), 1, 1)
    @test isclose(Run(0, 2:3), Run(0, 3:4), 1, 1)
    @test isclose(Run(0, 2:3), Run(1, 3:4), 1, 1)
    @test isclose(Run(1, 2:3), Run(0, 3:4), 1, 1)
    @test !isclose(Run(0, 2:3), Run(2, 3:4), 1, 1)
    @test !isclose(Run(2, 2:3), Run(0, 3:4), 1, 1)
    @test !isclose(Run(0, 3:4), Run(-2, 3:4), 1, 1)
    @test !isclose(Run(-2, 3:4), Run(0, 3:4), 1, 1)
    @test isclose(Run(0, 3:4), Run(-1, 3:4), 1, 1)
    @test isclose(Run(-1, 3:4), Run(0, 3:4), 1, 1)
    @test isclose(Run(0, 3:4), Run(0, 3:4), 1, 1)
    @test isclose(Run(0, 3:4), Run(1, 3:4), 1, 1)
    @test isclose(Run(1, 3:4), Run(0, 3:4), 1, 1)
    @test !isclose(Run(0, 3:4), Run(2, 3:4), 1, 1)
    @test !isclose(Run(2, 3:4), Run(0, 3:4), 1, 1)
    @test !isclose(Run(0, 4:5), Run(-2, 2:3), 1, 1)
    @test !isclose(Run(-2, 4:5), Run(0, 2:3), 1, 1)
    @test isclose(Run(0, 4:5), Run(-1, 2:3), 1, 1)
    @test isclose(Run(-1, 4:5), Run(0, 2:3), 1, 1)
    @test isclose(Run(0, 4:5), Run(0, 2:3), 1, 1)
    @test isclose(Run(0, 4:5), Run(1, 2:3), 1, 1)
    @test isclose(Run(1, 4:5), Run(0, 2:3), 1, 1)
    @test !isclose(Run(0, 4:5), Run(2, 2:3), 1, 1)
    @test !isclose(Run(2, 4:5), Run(0, 2:3), 1, 1)
    @test !isclose(Run(0, 5:6), Run(0, 1:2), 1, 1)
    @test !isclose(Run(0, 6:7), Run(0, 0:1), 1, 1)

end # "Run"


text:
using Plots
plotlyjs()

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]

p = scatter(x, y)
savefig(p, "/tmp/testplot.png")

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
function _hist_add!{T}(counts::Dict{T,Int}, y::Vector{T}, region::UnitRange{Int})
    for i in region
        lbl = y[i]
        counts[lbl] = get(counts, lbl, 0) + 1
    end
    return counts
end

"""
Given a vector of labels, this returns a Dict where the keys are
the unique y[i] and the values are the number of times that y[i]
occurs in the vector y.
"""
_hist{T}(y::Vector{T}, region::UnitRange{Int} = 1:endof(y)) = _hist_add!(Dict{T,Int}(), y, region)

"""
Given the vector y, this simply returns the value that
appears most frequently in y.
"""
function majority_vote(y::Vector)
    if length(y) == 0
        return nothing
    end
    counts = _hist(y)
    top_vote = y[1]
    top_count = -1
    for (k,v) in counts
        if v > top_count
            top_vote = k
            top_count = v
        end
    end
    return top_vote
end

# n = 1000
# y = rand([true, false], n);
# @time majority_vote(y)

"""
This was formerly called neg_z1_loss() in Ben's original DecisionTree code,
and the variable `y` was formerlly called `labels`
"""
function _classifcation_error_loss(y::Vector, weights::Vector)
    missmatches = y .!= majority_vote(y)
    loss = sum(weights[missmatches])
    return -loss
end

# This method is dispatched when weights are omitted. This
# allows us to compute the loss function 5x faster
function _classifcation_error_loss(y::Vector)
    loss = sum(y)
    return -loss        # tons of mem-alloc here
end

#
# n = 1000
# y = rand([true, false], n);
# wgt = repeat([1], inner = n);
#
# @time _classifcation_error_loss(y)

function mean_squared_error(actual, predicted)
    return mean((actual - predicted).^2)
end

function rsq(actual, predicted)
    ss_residual = sum((actual - predicted).^2)
    ss_total = sum((actual .- mean(actual)).^2)
    return 1.0 - ss_residual/ss_total
end


text:
using StructJuMP, JuMP

firststage = StructuredModel()
@defVar(firststage, x[1:2])
@addConstraint(firststage, sum(x) == 100)
@setNLObjective(firststage, Min, x[1]^2 + x[2]^2)

for scen in 1:2
    bl = StructuredModel(parent=firststage)
    @defVar(bl, y[1:2])
    @addConstraint(bl, x[3-scen] + sum(y) ≥  0)
    @addConstraint(bl, x[3-scen] + sum(y) ≤ 50)
    @setNLObjective(bl, Min, y[1]^2 + y[2]^2)
end

solve(firststage)


text:
@testset "Single objective functions" begin

@testset "Sphere" begin
    p = BlackBoxOptim.example_problems["Sphere"]
    sphere = objfunc(p)

    @test sphere([0]) == 0
    @test sphere([1]) == 1
    @test sphere([1, 2]) == 5
    @test sphere([1, 2, 3]) == 14
    @test sphere([-1, 2, -3]) == 14
    @test_throws MethodError sphere([])

    p2 = instantiate(p, 3)
    @test numdims(p2) == 3
    @test dimrange(search_space(p2)) == [(-100.0, 100.0), (-100.0, 100.0), (-100.0, 100.0)]
end

@testset "Schwefel2.22" begin
    p = BlackBoxOptim.example_problems["Schwefel2.22"]
    schwefel2_22 = objfunc(p)

    @test schwefel2_22([0]) == 0
    @test schwefel2_22([1]) == 2
    @test schwefel2_22([1, 2]) == (1+2)+(1*2)
    @test schwefel2_22([1, 2, 3]) == (1+2+3)+(1*2*3)
    @test schwefel2_22([-1, 2, -3]) == (1+2+3)+(1*2*3)
    @test_throws MethodError schwefel2_22([])

    p2 = instantiate(p, 4)
    @test numdims(p2) == 4
    @test dimrange(search_space(p2)) == [(-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0)]
end

@testset "Schwefel1.2" begin
    p = BlackBoxOptim.example_problems["Schwefel1.2"]
    schwefel1_2 = objfunc(p)

    @test schwefel1_2([0]) == 0
    @test schwefel1_2([1]) == 1
    @test schwefel1_2([1, 2]) == 1+9
    @test schwefel1_2([1, 2, 3]) == 1+9+36
    @test schwefel1_2([-1, 2, -3]) == 1+1+4
    @test schwefel1_2([]) == 0
end

@testset "Schwefel2.21" begin
    p = BlackBoxOptim.example_problems["Schwefel2.21"]
    schwefel2_21 = objfunc(p)

    @test schwefel2_21([0]) == 0
    @test schwefel2_21([1]) == 1
    @test schwefel2_21([1, 2]) == 2
    @test schwefel2_21([1, 2, 3]) == 3
    @test schwefel2_21([-1, 2, -3]) == 3
    @test_throws MethodError schwefel2_21([])
end

@testset "Rosenbrock" begin
    p = BlackBoxOptim.example_problems["Rosenbrock"]
    rosenbrock = objfunc(p)

    @test rosenbrock([1, 2]) == 100
    @test rosenbrock([1, 2, 3]) == 201
    @test rosenbrock([-1, 2, -3]) == 5005
    @test_throws MethodError rosenbrock([])
end

end


text:
type WeinerProcess
    a :: Float64
    σ :: Float64
end

function MSE(p :: WeinerProcess, T)
    x = 2*p.a*T
    p.σ^2/(2*p.a) * ( ( exp(x) - 1 ) / x - 1)
end

function total_error(users::Vector{WeinerProcess}, rates)
    N = length(users)
    T = 1.0 ./rates
    sum([MSE(users[i], T[i]) for i in 1:N])
end

# We implement two functions to find the best response at the user. The first
# directly optimizes the user's objective, the sencond finds a root of the
# derivative being equal to zero.

using Optim

user_objective(p :: WeinerProcess, T, λ) = MSE(p, T) + λ/T

function user_optim_A(p :: WeinerProcess, λ :: Float64)
   # I did not find an implementation of gradient search in Julia
   # The code below uses Brent's method (whatever that is)
   result = Optim.optimize(r -> user_objective(p, 1/r, λ), 0, 1e6)
   return Optim.minimizer(result)
end

using Roots
function user_optim_B(p::WeinerProcess, λ)
    f(T) = exp(2*p.a*T) * (2*p.a*T - 1) + 1 - 4*p.a^2*λ/p.σ^2
    root = fzero(r -> f(1/r), 0, 1e6)
end

# There were some experiments where option `B` gave incorrect results. Option
# `A` is faster, which is an added benefit!
user_optim = user_optim_A

using DataFrames
include("ADAM.jl")

function syncTrace(users::Vector{WeinerProcess}, C::Float64;
    iterations :: Int     = 1_000,
       initial :: Float64 = 1e-3,
       lr      :: ADAM    = ADAM(alpha=1.0),
        )

    N = length(users)

    r = zeros(Float64, (iterations,N))
    Λ = zeros(Float64, iterations)
    err = zeros(Float64, iterations)

    Λ[1] = initial

    @inbounds for k in 1:iterations
        #r[k,:] = pmap(i -> user_optim(users[i], Λ[k]), 1:N)
        @inbounds for i in 1:N
            r[k,i] = user_optim(users[i], Λ[k])
        end
        err[k] = total_error(users, r[k,:])

        if k < iterations
            gradient = C - sum(r[k,:])

            Λ[k+1] = Λ[k] - gradient_step!(lr,gradient)
            Λ[k+1] = max(Λ[k+1], 1e-8)
        end
    end

    df = DataFrame()
    df[:iter] = 1:iterations
    df[:lambda] = Λ

    @inbounds for i in 1:N
        df[Symbol("r", i)] = r[:,i]
    end
    df[:C] = vec(sum(r,2))
    df[:MSE] = err
    return df
end

function asyncTrace(users::Vector{WeinerProcess}, C::Float64;
    iterations :: Int     = 1_000,
       initial :: Float64 = 1e-3,
       lr      :: ADAM    = ADAM(alpha=1.0),
        )

    N = length(users)

    current_time = zeros(Float64, iterations)

    r  = zeros(Float64, (iterations,N))
    Λ  = zeros(Float64, iterations)
    tx = zeros(Int32, iterations)
    err = zeros(Float64, iterations)

    next_sampling_times = zeros(Float64, N)

    Λ[1] = initial

    current_time[1] = 0.0
    @inbounds for i in 1:N
        r[1,i] = user_optim(users[i], Λ[1]) + 1e-2*rand()
    end

    @inbounds for i in 1:N
        next_sampling_times[i] += 1.0/r[1,i]
    end

    @inbounds for k in 1:iterations
        err[k]  = total_error(users, r[k,:])

        (current_time[k], tx[k]) = findmin(next_sampling_times)

        if k < iterations
            gradient = C - sum(r[k,:])

            Λ[k+1] = Λ[k] - gradient_step!(lr,gradient)
            Λ[k+1] = max(Λ[k+1], 1e-8)

            r[k+1,:]     = r[k,:]
            r[k+1,tx[k]] = user_optim(users[tx[k]], Λ[k+1])
            next_sampling_times[tx[k]] += 1.0/r[k+1, tx[k]]
        end
    end

    df = DataFrame()
    df[:iter] = 1:iterations
    df[:lambda] = Λ

    @inbounds for i in 1:N
        df[Symbol("r", i)] = r[:,i]
    end
    df[:tx] = tx
    df[:C] = vec(sum(r,2))
    df[:time] = current_time
    df[:MSE] = err
    return df
end

using NLopt

function optimal_rates(users :: Vector{WeinerProcess}, C :: Float64)
    N = length(users)

    objective(rates, gradient)  = total_error(users, rates)
    constraint(rates, gradient) = C - sum(rates)

    opt = Opt(:LN_COBYLA, N)

    lower_bounds!(opt, zeros(N))
    upper_bounds!(opt, C*ones(N))
    min_objective!(opt, objective)
    equality_constraint!(opt, constraint)

    guess = ones(N)./N

    (err, rates, ret) = NLopt.optimize(opt, guess)
end

users = [ WeinerProcess(1,1), WeinerProcess(1,1), WeinerProcess(1,1),
          WeinerProcess(1,1), WeinerProcess(1,2)]

change = [ WeinerProcess(1,1), WeinerProcess(1,1), WeinerProcess(1,1),
           WeinerProcess(1,2)]

max_stars_repo_name: adityam/periodic-sensor-scheduling

max_issues_repo_name: adityam/periodic-sensor-scheduling

max_forks_repo_name: adityam/periodic-sensor-scheduling


text:
# Example showing how dispatch ambiguities with traits compare to the normal ones.

println("""
## Normal dispatch
##################
""")

f(x,y::Int) = x-y
f(x::Int,y) = x+y # ->
# Warning: New definition
#     f(Int64,Any) at none:1
# is ambiguous with:
#     f(Any,Int64) at none:1.
# To fix, define
#     f(Int64,Int64)
# before the new definition.
# f (generic function with 2 methods)

@show f(5,6) # picks one method definition at random

# fix ambiguity:
f(x::Int, y::Int) = x*y
@show f(5,6)

println("""

## Trait dispatch ambiguities
#############################
""")
using Traits
println(stringmime("text/plain", Docs.doc(Traits.traitdispatch)))

println("""

## case 1: similar to normal dispatch

""")

@traitdef TrTr1{X} begin
    len1(X)
end

@traitfn tf{X<:Integer,Y; TrTr1{X}}(x::X,y::Y) = x-y
@traitfn tf{X<:Integer,Y; TrTr1{Y}}(x::X,y::Y) = x+y

@traitimpl TrTr1{Int} begin
    len1(x::Int) = 5
end

# now ambiguous:
try
    tf(5,6)  # actually errors, as opposed to randomly choosing one method
catch e
    println(e)
end

# resolve as above does not work:
@traitfn tf{X<:Integer,Y; TrTr1{X}, TrTr1{Y}}(x::X,y::Y) = x*y
tf(5,6)

# another way to resolve it would be:
@traitdef TrTr22{X,Y} <: TrTr1{X}, TrTr1{Y} begin
    # empty
end

@traitfn tf{X<:Integer,Y; TrTr22{X,Y}}(x::X,y::Y) = x*y*1000
try
    tf(5,6)  # but now errors again as it is ambiguous again
catch e
    println(e)
end

###########
println("""

## case 2: with just one argument

""")
# This case does not really exist for normal types, where there can
# never be ambiguities in methods with one argument.

@traitdef TrTr2{X} begin
    len2(X)
end

@traitfn tttf{X; TrTr1{X}}(x::X) = len1(x)
@traitfn tttf{X; TrTr2{X}}(x::X) = len2(x)

@show tttf(5)  # works as TrTr2{Int} is not a trait

@traitimpl TrTr1{Float64} begin
    len1(x::Float64) = 5
end
@traitimpl TrTr2{Float64} begin
    len2(x::Float64) = 55
end

try
    tttf(5.)  # errors
catch e
    println(e)
end

# this can be resolved by making a method which dispatches on both types:
@traitfn tttf{X; TrTr1{X}, TrTr2{X}}(x::X) = len2(x) # pick len2 over len1

@show tttf(5.) # now works

# this could also be resolved by adding a sub-trait:
@traitdef STrTr{X} <: TrTr1{X}, TrTr2{X} begin
    # empty
end

# no need to implement it for Float64: it's already a member:
@assert istrait(STrTr{Float64})

@traitfn tttf{X; STrTr{X}}(x::X) = len2(x) # pick len2 over len1
try
    tttf(5.)  # but now errors again as is ambiguous with above new definition
catch e
    println(e)
end


text:
using SQLite
using Tables

struct SourceInSQL <: Source
  db::SQLite.DB
  cache::SourceInMem

  function SourceInSQL(file::AbstractString)
    db = new(SQLite.DB(file))
    init(db)
    return db
  end
end
SourceInSQL() = SourceInSQL(":memory:")

function haspatch(source::SourceInSQL, patch::Int)
  stmt = DBInterface.prepare(source.db, """
    SELECT * FROM meta WHERE patch = ?;
  """)
  results = DBInterface.execute(stmt, [patch])
  return length(result) > 0
end

function addpatch(source::SourceInSQL, patch::Int,
    notes::AbstractString, sql::AbstractString)
  stmt = DBInterface.prepare(source.db, """
    INSERT INTO meta VALUES(?, ?, ?, ?)")
  """)
  res = DBInterface.execute(stmt, [patch, notes, false, nothing])

  if !res
    stmt = DBInterface.prepare(source.db, """
      INSERT INTO meta VALUES(?, ?, ?, ?)")
    """)
    DBInterface.execute(stmt, [patch, notes, true, error_msg])
  end
end

function init(source::SourceInSQL)
  DBInterface.execute(source.db, "PRAGMA foreign_keys = ON;")

  DBInterface.execute(source.db, """
    CREATE TABLE IF NOT EXISTS resources(
      id TEXT PRIMARY KEY,
      val INTEGER NOT NULL DEFAULT 0
    );
  """)

  DBInterface.execute(source.db, """
    CREATE TABLE IF NOT EXISTS operators(
      id TEXT PRIMARY KEY,
      level INTEGER NOT NULL DEFAULT 0,
      promotion INTEGER NOT NULL CHECK (promotion BETWEEN 0 and 2) DEFAULT 0,
      xp INTEGER NOT NULL DEFAULT 0,
      skill_rank INTEGER NOT NULL DEFAULT 0,
      skill_1_mastery INTEGER NOT NULL DEFAULT 0,
      skill_2_mastery INTEGER NOT NULL DEFAULT 0,
      skill_3_mastery INTEGER NOT NULL DEFAULT 0,
      trust INTEGER NOT NULL DEFAULT 0,
      potential INTEGER NOT NULL DEFAULT 0
    );
  """)
end

function operators(source::SourceInSQL, gamedata::GameData.Source)
  query = DBInterface.execute(source.db, "SELECT * FROM operators;")
  ops = map(Tables.rows(query)) do row
    bases = filter(b -> row.id == b.id, GameData.operator_bases(gamedata))
    if length(bases) == 0
      throw(DomainError(row.id, "Could not find a matching operator base"))
    end
    level = OperatorLevel(row.level, PromotionPhase(row.promotion))
    skills = OperatorSkills(row.skill_rank, row.skill_1_mastery, row.skill_2_mastery, row.skill_3_mastery)
    Operator(first(bases), level, row.trust, row.xp, skills, row.potential)
  end
  return ops
end

function Base.append!(source::SourceInSQL, ops::AbstractArray{Operator})
  stmt = DBInterface.prepare(source.db, """
    INSERT INTO operators (id) VALUES (?);")
  """)
  for op in ops
    DBInterface.execute(stmt, [op.base.id])
  end
end

function resources(source::SourceInSQL)
  stmt = DBInterface.execute(source.db, """
    SELECT * FROM resources;
  """)
  return stmt
end


text:
# ---
# title: Custom Title
# description: Custom Description
# ---

# This is the content


text:
using myJuliaUtils
using Test
using LinearAlgebra

randomdim = rand(1:10)
c = Int(randomdim * (randomdim + 1) / 2)
a = randn(c)
b = @inferred vec2sym(a)
@test a == vech(b)
b = vec2ltri(a)
@test a == vech(b)

reps = 1000
q = randn(c, reps)
w = vec2sym(q)
@test w == vec2sym(q', 2)

e = similar(q)
for i = 1:reps
    e[:,i] = vech(w[:,:,i])
end
@test e == q

# testing vec2ltriW1 and vech(,-1)
v = [0.3]
B = [1. 0. ; 0.3 1.]
@test vec2ltriW1(v) == B
@test vec2ltriW1(v, 2) == B
@test vech(B, -1) == v

v = [0.5, 0.3, 0.2]
B = [1. 0. 0.; 0.5 1. 0.; 0.3 0.2 1.]
@test vec2ltriW1(v) == B
@test vec2ltriW1(v, 2) == B
@test vech(B, -1) == v

v = [4., 3., 2., 1., 5., 7.]
B = [1.0  0.0  0.0  0.0;
4.0  1.0  0.0  0.0;
3.0  2.0  1.0  0.0;
1.0  5.0  7.0  1.0]

A = [1.0  0.0  0.0  0.0;
4.0  1.0  0.0  0.0;
3.0  1.0  1.0  0.0;
2.0  5.0  7.0  1.0]
@test vec2ltriW1(v, 2) == B
@test vec2ltriW1(v, 1) != B
@test vec2ltriW1(v, 1) == A
@test vech(A, -1) == v
@test vech(B, -1) != v

randomdim = Int(ceil.(rand() * 20)) + 1
c = Int(randomdim * (randomdim - 1) / 2)
a = randn(c)
b = @inferred vec2ltriW1(a)
@test a == vech(b, -1)

# testing the length of results to be all fine

randomdim = Int(ceil.(rand() * 20)) + 1
c = Int(randomdim * (randomdim - 1) / 2)
a = randn(c)
@test diag(vec2ltriW1(a)) == ones(randomdim)

randomdim = Int(ceil.(rand() * 20))
c = Int(randomdim * (randomdim + 1) / 2)
a = randn(randomdim, randomdim)
@test length(vech(a)) == c

randomdim = Int(ceil.(rand() * 20)) + 1
c = Int(randomdim * (randomdim - 1) / 2)
a = randn(randomdim, randomdim)
@test length(vech(a, -1)) == c

# testing vechRshp
N=rand(1:20)
b=randn(N,N,N);
for i=1:N
    b[:,:,i]=genPSDmat(N)
end

A=@inferred vechRshp(b)
@test A[:,end]==vech(b[:,:,end])
@test A[:,1]==vech(b[:,:,1])
c=rand(1:N)
@test A[:,c]==vech(b[:,:,c])

max_stars_repo_name: zymbuzz/myJuliaUtils

max_issues_repo_name: zymbuzz/myJuliaUtils

max_forks_repo_name: zymbuzz/myJuliaUtils


text:
"""
    read_packages(registry::AbstractString; kwargs...)
    read_packages(f, registry; recursive=true, kwargs...)

Read all packages stored in registry `registry`.

If predicate function `f` is given, package that satisfies `f(pkg)==true` is put
into the return list. If `recursive==true`, then all dependency packages are also
added to the return list.

Kerword arguments:

- `latest_versions_num::Integer`: only get the latest `latest_versions_num` versions for each package.
- `fetch_full_registry::Bool = false`: `true` to disable incremental parsing.

# Examples

List all packages:

```julia
pkgs = read_packages("General")
```

List only packages under JuliaArrays:

```julia
pkgs = read_packages("General") do pkg
    occursin("JuliaArrays", pkg.url)
end
```
"""
function read_packages(
    registry_root::AbstractString;
    latest_versions_num::Union{Nothing,Integer} = nothing,
    static_dir = nothing,
    fetch_full_registry = false
)
    reg_file = joinpath(registry_root, "Registry.toml")
    reg_info = TOML.parsefile(reg_file)

    pkgs = [
        Package(
            info["name"],
            uuid,
            joinpath(registry_root, info["path"]),
            latest_versions_num = latest_versions_num,
        ) for (uuid, info) in reg_info["packages"]
    ]

    if !fetch_full_registry && !isnothing(static_dir)
        # If a certain version is already built, then skip that version without downloading and extracting.
        # Even if not downloaded, artifacts of that version will be skipped, too.
        for pkg in pkgs
            uuid = pkg.uuid
            for (ver, hash_info) in pkg.versions
                hash = hash_info["git-tree-sha1"]

                tarball = joinpath(static_dir, "package", uuid, hash)
                isfile(tarball) && delete!(pkg.versions, ver)
            end
        end
        pkgs = [pkg for pkg in pkgs if !isempty(pkg.versions)]
    end

    sort!(pkgs, by = x -> x.name)

    return pkgs
end

function read_packages(f, registry_root::AbstractString; recursive = true, kwargs...)
    all_packages = read_packages(registry_root; kwargs...)
    init_pkgs = filter(f, all_packages)

    recursive || return init_pkgs

    pkgs = collect(init_pkgs)
    foreach(init_pkgs) do pkg
        append_deps!(pkgs, pkg, all_packages)
    end
    sort!(pkgs, by = x -> x.name)

    return pkgs
end

"""
    append_deps!(pkgs, pkg, full_pkglist)

Recursively find dependency packages of `pkg` and append them into `pkgs`.
"""
function append_deps!(
    pkgs::AbstractVector{Package},
    pkg::Package,
    full_pkglist::AbstractVector{Package},
)
    deps_file = joinpath(pkg.registry_dir, "Deps.toml")
    isfile(deps_file) || return pkgs

    dep_info = TOML.parsefile(deps_file)
    isempty(dep_info) && return pkgs

    # NOTE:
    # This doesn't check versions info, just returns all packages listed in Deps.toml
    dep_pkgs_names = mapreduce(Set, union, keys.(values(dep_info)))
    init_pkgs = filter(full_pkglist) do pkg
        pkg.name in dep_pkgs_names && !(pkg in pkgs)
    end
    append!(pkgs, init_pkgs)

    isempty(init_pkgs) && return pkgs

    foreach(init_pkgs) do pkg
        append_deps!(pkgs, pkg, full_pkglist)
    end
    return pkgs
end


text:
module visualization
using Plots, PyPlot

function scatter_plot(x, y, name, output=false, output_path=NaN)
    scatter(x, y, label=name)
    if output
        savefig(output_path)
    end
end

function scatter3d_plot(x, y, z, file_name, view_x=35, view_y=25)

    ax = gca(projection="3d")
    fig = scatter3D(x, y, z, alpha=0.01, color=:blue)
    ax[:view_init](view_x, view_y)
    PyPlot.savefig(file_name)
end

end  # module visualization


text:
function neumann_series(mat::SparseMatrixCSC)
    inverse = I + mat
    next_term = mat^2

    while nnz(next_term) != 0
        inverse += next_term
        next_term *= mat
    end

    return inverse
end

function make_onelement_array(A)
    isa(A, Array) ? nothing : (A = [A])
    return A
end

function semvec(observed, imply, loss, diff)

    observed = make_onelement_array(observed)
    imply = make_onelement_array(imply)
    loss = make_onelement_array(loss)
    diff = make_onelement_array(diff)

    #sem_vec = Array{AbstractSem}(undef, maximum(length.([observed, imply, loss, diff])))
    sem_vec = Sem.(observed, imply, loss, diff)

    return sem_vec
end

function get_observed(rowind, data, semobserved;
            args = (),
            kwargs = NamedTuple())
    observed_vec = Vector{semobserved}(undef, length(rowind))
    for i in 1:length(rowind)
        observed_vec[i] = semobserved(
                            args...;
                            data = Matrix(data[rowind[i], :]),
                            kwargs...)
    end
    return observed_vec
end

function skipmissing_mean(mat)
    means = Vector{Float64}(undef, size(mat, 2))
    for i = 1:size(mat, 2)
        @views means[i] = mean(skipmissing(mat[:,i]))
    end
    return means
end

function F_one_person(imp_mean, meandiff, inverse, data, logdet)
    F = logdet
    @. meandiff = data - imp_mean
    F += dot(meandiff, inverse, meandiff)
    return F
end

function remove_all_missing(data)
    keep = Vector{Int64}()
    for i = 1:size(data, 1)
        if any(.!ismissing.(data[i, :]))
            push!(keep, i)
        end
    end
    return data[keep, :], keep
end

function batch_inv!(fun::Union{LossFunction, DiffFunction}, model)
    for i = 1:size(fun.inverses, 1)
        fun.inverses[i] .= LinearAlgebra.inv!(fun.choleskys[i])
    end
end

function batch_sym_inv_update!(fun::Union{LossFunction, DiffFunction}, model)
    M_inv = inv(fun.choleskys[1])
    for i = 1:size(fun.inverses, 1)
        if size(model.observed.patterns_not[i]) == 0
            fun.inverses[i] .= M_inv
        else
            ind_not = model.observed.patterns_not[i]
            ind = model.observed.patterns[i]

            A = M_inv[ind_not, ind]
            H = cholesky(M_inv[ind_not, ind_not])
            D = H \ A
            out = M_inv[ind, ind] - LinearAlgebra.BLAS.gemm('T', 'N', 1.0, A, D)
            fun.inverses[i] .= out
        end
    end
end

function sparse_outer_mul!(C, A, B, ind) #computes A*S*B -> C, where ind gives the entries of S that are 1
    fill!(C, 0.0)
    for i in 1:length(ind)
        BLAS.ger!(1.0, A[:, ind[i][1]], B[ind[i][2], :], C)
    end
end

function sparse_outer_mul!(C, A, ind) #computes A*∇m, where ∇m ind gives the entries of ∇m that are 1
    fill!(C, 0.0)
    @views C .= sum(A[:, ind], dims = 2)
    return C
end

function sparse_outer_mul!(C, A, B::Vector, ind) #computes A*S*B -> C, where ind gives the entries of S that are 1
    fill!(C, 0.0)
    @views @inbounds for i in 1:length(ind)
        C .+= B[ind[i][2]].*A[:, ind[i][1]]
    end
end

function cov_and_mean(rows; corrected = false)
    data = permutedims(hcat(rows...))
    size(rows, 1) > 1 ?
        obs_cov = Statistics.cov(data; corrected = corrected) :
        obs_cov = reshape([0.0],1,1)
    obs_mean = vcat(Statistics.mean(data, dims = 1)...)
    return obs_cov, obs_mean
end

function duplication_matrix(nobs)
    nobs = Int(nobs)
    n1 = Int(nobs*(nobs+1)*0.5)
    n2 = Int(nobs^2)
    Dt = zeros(n1, n2)

    for j in 1:nobs
        for i in j:nobs
            u = zeros(n1)
            u[Int((j-1)*nobs + i-0.5*j*(j-1))] = 1
            T = zeros(nobs, nobs)
            T[j,i] = 1; T[i, j] = 1
            Dt += u*transpose(vec(T))
        end
    end
    D = transpose(Dt)
    return D
end

function elimination_matrix(nobs)
    nobs = Int(nobs)
    n1 = Int(nobs*(nobs+1)*0.5)
    n2 = Int(nobs^2)
    L = zeros(n1, n2)

    for j in 1:nobs
        for i in j:nobs
            u = zeros(n1)
            u[Int((j-1)*nobs + i-0.5*j*(j-1))] = 1
            T = zeros(nobs, nobs)
            T[i, j] = 1
            L += u*transpose(vec(T))
        end
    end
    return L
end


text:
using Printf

function anonymous_function_examples()
    println("--------------------------------------")
    println("Anonymous function examples")

    println("Anonymous functions can use map to apply a function to each element of an array")
    some_array = [1, 2, 3]
    squarer = map(x -> x * x, some_array)
    println(squarer)

    println("We can add arrays")
    another_array = [4, 5, 6]
    array_adder = map((x,y) -> x + y, some_array, another_array)
    println(array_adder)

    println("We can use reduce to apply something to every element to achieve a single result")
    println(reduce(+, some_array))

    println("We can use reduce to find the longest word in a sentence")
    some_sentence = "This is a string and some of the words are extremely long"
    println(some_sentence)
    # Convert string to array
    string_array = split(some_sentence)
    longest = reduce((x, y) -> length(x) > length(y) ? x : y, string_array )
    println(longest)
end

max_stars_repo_name: James-P-D/JuliaDump

max_issues_repo_name: James-P-D/JuliaDump

max_forks_repo_name: James-P-D/JuliaDump


text:
struct KBState{TG<:MultivariateGaussian} <: AbstractFilterState
    gauss::TG
end

struct KBF{T1, T2, T3, T4, TI<:KBState} <: AbstractFilteringAlgorithm{ContinuousTime, ContinuousTime}
    A::T1
    BB::T2
    C::T3
    CC::T4
    init::TI
    function KBF(A::AbstractMatrix{S}, BB::AbstractMatrix{S}, C::AbstractMatrix{S}, CC::AbstractMatrix{S}, init::KBState) where {S, TI}
        if size(A, 1) == size(A, 2) == size(BB, 1) == size(BB, 2) == size(CC, 1) == size(C, 2)
            return new{typeof(A), typeof(BB), typeof(C), typeof(CC), typeof(init)}(A, BB, C, CC, init)
        else
            throw(DimensionMismatch("Input matrices have inconsistent sizes."))
        end
    end
end

#####################
###### METHODS ######
#####################

initial_condition(kbf::KBF) = kbf.init

mean(st::KBState) = mean(st.gauss)
cov(st::KBState)  = cov(st.gauss)
var(st::KBState)  = var(st.gauss)

######################
### MAIN ALGORITHM ###
######################

function initialize(kbf::KBF)
    return KBState(kbf)
end

function update!(filter_state::KBState, filter_algo::KBF, dY, dt) where {TM, TP}
    mean1  = mean(filter_state.gauss)
    cov1   = cov(filter_state.gauss)

    A      = filter_algo.A
    BB     = filter_algo.BB
    C      = filter_algo.C
    CC     = filter_algo.CC

    mean2  = mean1 + dt * A * mean1 + cov1 * C' * (dY .- C * mean1 * dt)
    cov2   = cov1  + dt * (BB + A * cov1 + cov1 * A' - cov1 * CC * cov1) |> LinearAlgebra.Symmetric

    mean1 .= mean2
    cov1  .= cov2

    return filter_state
end

################################
### CONVENIENCE CONSTRUCTORS ###
################################

KBState(mean::AbstractVector{T}, cov::AbstractMatrix{T}) where T = KBState(MultivariateGaussian(mean, cov))
KBState(n::Int; T = Float64)                                     = KBState(zeros(T, n), zeros(T, n, n))
KBState(filt_prob::FilteringProblem)                             = KBState(initial_condition(state_model(filt_prob)))
KBState(kbf::KBF)                                                = initial_condition(kbf)

function KBState(init::AbstractVector)
    mean = init
    cov  = zeros(eltype(mean), length(mean), length(mean))
    return KBState(mean, cov)
end

function KBState(init::Distributions.Sampleable)
    if init isa Distributions.AbstractMvNormal
        mean = init.μ
        cov  = Matrix(init.Σ)
    else
        error("Error: invalid initial condition in state_model. Initial condition must be Gaussian.")
    end
    return KBState(mean, cov)
end

function KBF(A, B, C)
    BB = B*B'
    Sigma = find_stationary_variance(A, BB)
    init = KBState(MultivariateGaussian(zeros(eltype(Sigma), size(Sigma, 1)), Sigma))
    CC = C'*C
    return KBF(A, BB, C, CC, init)
end

function KBF(filt_prob::AbstractFilteringProblem)
    st_mod = state_model(filt_prob)
    ob_mod = obs_model(filt_prob)
    return KBF(st_mod, ob_mod)
end

function KBF(state_model::LinearDiffusionStateModel, obs_model::LinearDiffusionObservationModel)
    A  = drift(state_model)
    B  = diffusion(state_model)
    C  = drift(obs_model)
    init = KBState(initial_condition(state_model))
    return KBF(A, B, C, init)
end

function KBF(A, B, C, init)
    BB = B*B'
    CC = C'*C
    return KBF(A, BB, C, CC, init)
end

max_stars_repo_name: simsurace/FeedbackParticleFilters

max_issues_repo_name: simsurace/FeedbackParticleFilters

max_forks_repo_name: simsurace/FeedbackParticleFilters


text:
__precompile__()
module RemoteGtkIDE

    using Reexport
    @reexport using Gadfly

    import Base.remotecall_fetch #doesn't need to be exported, it gets propagated in parent module automatically

    export eval_command_remotely, isdone, interrupt_task, run_task, eval_symbol

    function __init__()
        global _run_task = @schedule begin end
    end

    include("eval.jl")
    include("server.jl")
    include("doc.jl")
    include("stdio.jl")

end # module


text:
module SmallExample

using FlatBuffers

@enum(Color, Red = 1, Green = 2, Blue = 8)
@DEFAULT Color Red

@STRUCT struct Test
	a::Int16
	b::UInt8
	# _1::UInt8 # padding
end

mutable struct TestSimpleTableWithEnum
	color::Color
end

@DEFAULT TestSimpleTableWithEnum color=Green

@STRUCT struct Vec3
	x::Float32
	y::Float32
	z::Float32
	# _::UInt32 # padding
	test1::Float64
	test2::Color
	# __::UInt8 # padding
	test3::Test
	# ___::UInt16 # padding
end

@ALIGN Vec3 16

mutable struct Stat
	id::Union{Nothing, String}
	val::Int64
	count::UInt16
end

# Julia doesn't support forward referencing of types
# @union Any_ Union{Monster, TestSimpleTableWithEnum}

mutable struct Monster
	pos::Vec3
	mana::Int16
	hp::Int16
	name::Union{Nothing, String}
	friendly::Bool # deprecated
	inventory::Union{Nothing, Vector{UInt8}}
	color::Color
	# test_type::Any_
	# test::Union{Nothing, Vector{UInt8}}
	test4::Union{Nothing, Vector{Test}}
	testarrayofstring::Union{Nothing, Vector{String}}
	testarrayoftables::Union{Nothing, Vector{Monster}}
	# don't support nested circulr reference objects yet
	# enemy::Monster
	testnestedflatbuffer::Union{Nothing, Vector{UInt8}}
	testempty::Union{Nothing, Stat}
	testbool::Bool
	testhashs32_fnv1::Int32
	testhashu32_fnv1::UInt32
	testhashs64_fnv1::Int64
	testhashu64_fnv1::UInt64
	testhashs32_fnv1a::Int32
	testhashu32_fnv1a::UInt32
	testhashs64_fnv1a::Int64
	testhashu64_fnv1a::UInt64
	testarrayofbools::Union{Nothing, Vector{Bool}}
	testf::Float32
	testf2::Float32
	testf3::Float32
end

@DEFAULT Monster hp=Int16(100) mana=Int16(150) color=convert(UInt8, Blue) friendly=false testf=Float32(3.14159) testf2=Float32(3)

end # module


text:
using FlightMechanics.Models

# Constant input
ci_one = ConstantInput(1.0)
ci_minus_one = ConstantInput(-1.0)

@test isapprox(get_value(ci_one, 10.), 1.0)
@test isapprox(get_value(ci_minus_one, 10.), -1.0)
@test isapprox(get_value(vcat(ci_one, ci_minus_one), 10.), 0.0, atol=1e-15)

# StepInput
si1 = StepInput(1.0, 5.0, 10.0)
si2 = StepInput(-1.0, 10.0, 15.0)

@test isapprox(get_value(si1, 0.0), 0.0)
@test isapprox(get_value(si2, 0.0), 0.0)
@test isapprox(get_value(si1, 5.0), 1.0)
@test isapprox(get_value(si1, 10.0), 0.0)
@test isapprox(get_value(si2, 10.0), -1.0)
@test isapprox(get_value(si2, 15.0), 0.0)

@test isapprox(get_value(vcat(si1, si2), 8), 1.0)
@test isapprox(get_value(vcat(si1, si2), 10), -1.0)
@test isapprox(get_value(vcat(si1, si2), 12), -1.0)

# Doublet input
d = DoubletInput(2, 0, 10)
id = InverseDoubletInput(2, 0, 10)

@test isapprox(get_value(d, 2.5), 1)
@test isapprox(get_value(d, 5), -1)
@test isapprox(get_value(d, 7.5), -1)
@test isapprox(get_value(d, 10.), 0)

@test isapprox(get_value(id, 2.5), -1)
@test isapprox(get_value(id, 5), 1)
@test isapprox(get_value(id, 7.5), 1)
@test isapprox(get_value(id, 10.), 0)

@test isapprox(get_value(vcat(d, id), 2.5), 0)
@test isapprox(get_value(vcat(d, id), 5), 0)
@test isapprox(get_value(vcat(d, id), 7.5), 0)
@test isapprox(get_value(vcat(d, id), 10.), 0)

# Ramp input
r1 = RampInput(10, 0, 10)
r2 = RampInput(-10, 10, 15)

@test isapprox(get_value(r1, 0.0), 0.0)
@test isapprox(get_value(r1, 10.0), 0.0)
@test isapprox(get_value(r1, 5.0), 5.0)
@test isapprox(get_value(r2, 10.0), 0.0)
@test isapprox(get_value(r2, 15.0), 0.0)
@test isapprox(get_value(r2, 12.5), -5.0)

@test isapprox(get_value(vcat(r1, r2, StepInput(10, 10, 15)), 10), 10.0)
@test isapprox(get_value(vcat(r1, r2, StepInput(10, 10, 15)), 5), 5.0)
@test isapprox(get_value(vcat(r1, r2, StepInput(10, 10, 15)), 12.5), 5.0)

# Sinusoidal input
s = SinusoidalInput(2, 1, 0, 0, Inf)

@test isapprox(get_value(s, 0), 0)
@test isapprox(get_value(s, 1), 0, atol=1e-15)
@test isapprox(get_value(s, 0.5), 0, atol=1e-15)
@test isapprox(get_value(s, 0.25), 1)
@test isapprox(get_value(s, 0.75), -1)

sA = SinusoidalInput(20, 1, 0, 0, Inf)

@test isapprox(get_value(sA, 0.25), 10)
@test isapprox(get_value(sA, 0.75), -10)

sf = SinusoidalInput(2, 2, 0, 0, Inf)

@test isapprox(get_value(sf, 0.5), 0, atol=1e-15)
@test isapprox(get_value(sf, 0.25), 0, atol=1e-15)

sϕ = SinusoidalInput(2, 1, π/2, 0, Inf)

@test isapprox(get_value(sϕ, 0), 1.0)
@test isapprox(get_value(sϕ, 1), 1.0, atol=1e-15)


text:
module NoncommutativeGraphsTesting

include("test_header.jl")

@testset "Classical graph" begin
    include("classical_graph.jl")
end

@testset "Simple duality" begin
    include("simple_duality.jl")
end

@testset "Block duality" begin
    include("block_duality.jl")
end

@testset "Block duality 2" begin
    include("block_duality2.jl")
end

# slow and doesn't meet accuracy tolerance
if false
@testset "Thin diag" begin
    include("thin_diag.jl")
end
end

@testset "Diag optimization" begin
    include("diag_optimization.jl")
end

@testset "Unitary transform" begin
    include("unitary_transform.jl")
end

@testset "Compatible matrices" begin
    include("compatible_matrices.jl")
end

@testset "Empty classical graph" begin
    include("empty_classical.jl")
end

@testset "Entropy splitting" begin
    include("entropy_splitting.jl")
end

end # NoncommutativeGraphsTesting

max_stars_repo_name: dstahlke/NoncommutativeGraphs

max_issues_repo_name: dstahlke/NoncommutativeGraphs

max_forks_repo_name: dstahlke/NoncommutativeGraphs