text:
# imports
using Random
using Statistics
using PyPlot

mutable struct CircularBitArray
    array::BitArray
    function CircularBitArray(b::BitArray, rng=Random.MersenneTwister(0))
        new(b)
    end
end

CircularBitArray(n::Int64) = CircularBitArray(Random.bitrand(n))

Base.:length(c::CircularBitArray) = Base.length(c.array)

function get_k_neighborhood(circ_bit_arr::CircularBitArray, index, k)

    # catch more than entire array case
    if k > (length(circ_bit_arr) / 2) - 1
        error("Subsetting with the chosen k exceeds the length of the CircularBitArray.")
    end

    if index - k < 1  # underflow
        lower_bound_low = 1
        upper_bound_low = index + k
        lower_bound_high = length(circ_bit_arr) - abs(index - k)
        upper_bound_high = length(circ_bit_arr)
        return vcat(
            deepcopy(circ_bit_arr.array[lower_bound_high:upper_bound_high]),
            deepcopy(circ_bit_arr.array[lower_bound_low:upper_bound_low])
        )
    elseif index + k > length(circ_bit_arr)  # overflow
        lower_bound_low = 1
        upper_bound_low = abs(index + k) - length(circ_bit_arr)
        lower_bound_high = index - k
        upper_bound_high = length(circ_bit_arr)
        return vcat(
            deepcopy(circ_bit_arr.array[lower_bound_high:upper_bound_high]),
            deepcopy(circ_bit_arr.array[lower_bound_low:upper_bound_low])
        )
    else  # regular case
        return circ_bit_arr.array[index - k:index + k]
    end

end

# this is a sample change

mutable struct Config

    agent_list::CircularBitArray
    radius_list::Array{Int64, 1}
    tolerance::Float64
    sim_iterations::Int64
    noise::Float64

    function Config(
        circ_bit_arr::CircularBitArray,
        max_radius,
        tolerance,
        sim_iterations,
        noise=0.0,
        rng=Random.MersenneTwister(0)
    )
        new(
            circ_bit_arr,
            Random.rand!(rng, zeros(length(circ_bit_arr)), 1:max_radius),
            tolerance,
            sim_iterations,
            noise
        )
    end

end

function compute_norm(agent_list::CircularBitArray, agent::Int64, radius::Int64)
    return Statistics.mean(get_k_neighborhood(agent_list, agent, radius))
end

function update_radius!(radius_list, agent_list, current_agent, tolerance)

    # current properties
    current_radius = radius_list[current_agent]
    current_norm = agent_list.array[current_agent]

    # update radius
    if (
        (abs(compute_norm(agent_list, current_agent, current_radius)
            - compute_norm(agent_list, current_agent, current_radius + 1))
        > tolerance)
        & (current_radius < ((length(agent_list) / 2) - 1))
    )
        radius_list[current_agent] += 1
        print("INCREASED")
    elseif (
        (abs(compute_norm(agent_list, current_agent, current_radius)
            - compute_norm(agent_list, current_agent, current_radius - 1))
        < tolerance)
        & (current_radius > 1)
    )
        radius_list[current_agent] -= 1
        print("DECREASED")
    end

    return radius_list

end

function update_norm!(agent_list, radius_list, current_agent, noise=0.0, rng=Random.MersenneTwister(0))

    current_radius = radius_list[current_agent]
    current_norm = agent_list.array[current_agent]
    computed_norm = compute_norm(agent_list, current_agent, current_radius)

    # update norm regularly
    if computed_norm > 0.5
        agent_list.array[current_agent] = true
    elseif computed_norm < 0.5
        agent_list.array[current_agent] = false
    end

    # introduce some noise
    if rand(rng, Float64) < noise
        agent_list.array[current_agent] = Random.bitrand(rng, 1)[1]
    end

    return agent_list

end

function tick!(state, config, rng=Random.MersenneTwister(0))

    for i in 1:length(state[1])
        adapting_agent = rand(rng, 1:length(state[1]))
        update_radius!(state[2], state[1], adapting_agent, config.tolerance)
        update_norm!(state[1], state[2], adapting_agent, config.noise, rng)
    end

    return state

end

function simulate(config; display=true)

    agent_list = deepcopy(config.agent_list)
    radius_list = deepcopy(config.radius_list)
    state = (agent_list, radius_list)

    norm_matrix = zeros(Int64, config.sim_iterations + 1, length(state[1]))
    radius_matrix = zeros(Int64, config.sim_iterations + 1, length(state[1]))

    # add initial state to matrices
    norm_matrix[1, :] = state[1].array
    radius_matrix[1, :] = state[2]

    # simulation
    for i in 1:config.sim_iterations
        new_state = tick!(state, config)
        norm_matrix[i + 1, :] = deepcopy(new_state[1].array)
        radius_matrix[i + 1, :] = deepcopy(new_state[2])
    end
    results = (norm_matrix, radius_matrix)

    # visualize results
    if display
        display_results(results)
    end

    return results

end

function display_results(results)

    PyPlot.clf()
    PyPlot.subplot(1, 2, 1)
    PyPlot.tick_params(
        axis="both",          # changes apply to the x-axis
        which="both",      # both major and minor ticks are affected
        bottom=false,      # ticks along the bottom edge are off
        top=false,         # ticks along the top edge are off
        labelbottom=false
    )
    PyPlot.imshow(results[1])
    PyPlot.subplot(1, 2, 2)
    PyPlot.tick_params(
        axis="both",          # changes apply to the x-axis
        which="both",      # both major and minor ticks are affected
        bottom=false,      # ticks along the bottom edge are off
        top=false,         # ticks along the top edge are off
        labelbottom=false
    )
    PyPlot.imshow(results[2])
    display(gcf())

end

# simulation runs
Random.seed!(7)
cfg1 = Config(
    CircularBitArray(191),
    20,
    0.05,
    400,
    0.0
)
simulate(cfg1)

Random.seed!(2)
cfg2 = Config(
    CircularBitArray(BitArray(zeros(191))),
    60,
    0.05,
    400,
    0.0
)
res2 = simulate(cfg2)

max_stars_repo_name: JohannesNakayama/SocialNorms

max_issues_repo_name: JohannesNakayama/SocialNorms

max_forks_repo_name: JohannesNakayama/SocialNorms


text:
"""
    genlasso(G, y, α, β, iters, tol, reg::Regularizer)

    Minimize |Gu - y|² + α|Ψu|₁ + β|u|²

    # Arguments
    - `G`: measurement matrix.
    - `y`: measured vector.
    - `α`: scaling of ℓ₁ term |Ψu|₁
    - `β`: scaling of ℓ₂ term |u|²
    - `reg::Regularizer`: regularizer interface, which defines Ψ and
        other necessary operators for the forward + backward solve.

    # Output
    - 'u': recovered vector.
    - 'info': solver info.
"""
genlasso(G, y, α, β, iters, tol, reg::Regularizer) = fista(G, y, α, β, iters, tol, reg)

function fake_genlasso(u, G, y, α, β, iters, tol, reg::Regularizer)

    supp = support(u, reg)
    P = projection_op(supp, reg)
    Ψ = transform_op(reg)

    # set up and solve linear system
    A = P * G' * G * P' + β * Identity(size(P)[1])
    b = P * G' * y - 1 / 2 * α * (P * Ψ' * sign.(Ψ * u))

    x, ch = cg(A, b; maxiter=iters ÷ 10, log=true)

    P' * x
end

function rrule(config::RuleConfig{>:HasReverseMode}, ::typeof(genlasso), G, y, α, β, iters, tol, reg::Regularizer)

    u, info = genlasso(G, y, α, β, iters, tol, reg)

    # ensure gradient accuracy
    #ufake = fake_reconstruct(u, G, y, α, β, iters, tol, reg)
    #@assert sum((u - ufake).^2) / sum(u.^2) < 1e-3

    # Takes in dL/du and returns dL/d(args).
    function pullback(∂out)

        supp = support(u, reg)
        P = projection_op(supp, reg)
        Ψ = transform_op(reg)

        # We define ϵ = b - APu.
        # λ ⋅ dϵ/d(args) gives the backpropagated adjoint variable.
        function ϵ(G, y, α, β)
            # CompositeMaps may / may not be differentiable, so use right associativity to be safe
            APu = P * (G' * (G * u)) + β * (P * u)
            b = P * (G' * y) - 1 / 2 * α * (P * (Ψ' * sign.(Ψ * u)))
            b - APu
        end

        A = P * G' * G * P' + β * Identity(size(P)[1])

        args_pullback = rrule_via_ad(config, (G, y, α, β) -> ϵ(G, y, α, β), G, y, α, β)[2]

        ∂u = ∂out[1]
        ∂u_supp = P * ∂u
        λ = cg(A, ∂u_supp; maxiter=iters)
        ∂args = args_pullback(λ)
        x = ∂args..., NoTangent(), NoTangent(), NoTangent()
        x
    end

    (u, info), pullback
end

ext: jl


text:
module VectorPartitions
using StaticArrays

export all_vector_partitions, increment_vector_partition_state!

struct VectorPartition
  n_elements::Int
  n_partitions::Int
end

# A partition of {1,...,n} into k subsets is equivalent to a function
# f: {1,...,n} -> {1,...,k} such that
# g(i) = max_{j <= i} f(j) is surjective.
# So we can generate partitions by generating all such functions f.
# here partition is f, upper_bound is g, and first_index keeps track of the points at which g changes value (which helps enforce surjectivity)
mutable struct VectorPartitionState{n,k}
  upper_bound::MVector{n,Int}
  partition::MVector{n,Int}
  first_index::MVector{k,Int}
  done::Bool
end

"""
    all_vector_partitions(n,k)

Create an iterator that produces all partitions of the set {1,...,`n`} into `k` nonempty subsets.

Partitions are represented as vectors of length `n` with values between 1 and `k`.
"""
function all_vector_partitions(n,k)
  if n <= 0
    throw(DomainError(n, "Number of elements in the set must be positive."))
  end
  if k <= 0
    throw(DomainError(k, "Number of sets in partition must be positive."))
  end
  if n < k
    throw(DomainError((n,k),"Cannot produce partitions with more elements than the underlying set."))
  end
  return VectorPartition(n,k)
end

"""
    all_vector_partitions(n)

Create an iterator that produces all partitions of the set {1,...,'n'} into any number of nonempty subsets.

Partitions into k subsets are represented as vectors of length `n` with values between 1 and k.
"""
all_vector_partitions(n) = Iterators.flatten((all_vector_partitions(n,k) for k in 1:n))

function Base.iterate(I::VectorPartition)
  state = initial_vector_partition_state(I)
  return state.partition, state
end

function Base.iterate(I::VectorPartition,state)
  next_state = next_vector_partition_state(I,state)
  if next_state.done
    return nothing
  end
  return next_state.partition, next_state
end

function initial_vector_partition_state(I::VectorPartition)
  upper_bound = cat(ones(Int, I.n_elements-I.n_partitions),collect(1:I.n_partitions),dims=1)
  first_index = cat(1, (I.n_elements-Int64(I.n_partitions)) .+ collect(2:I.n_partitions),dims=1)
  state = VectorPartitionState{I.n_elements,I.n_partitions}(MVector(upper_bound...),MVector(copy(upper_bound)...),MVector(first_index...),false)
  return state
end

# because it is not recommended to have iterators mutate their state directly,
# this function copies before incrementing.
function next_vector_partition_state(I::VectorPartition,state)
  if state.done
    return state
  end
  state_c = VectorPartitionState{I.n_elements,I.n_partitions}(state.upper_bound,state.partition,state.first_index,false)
  increment_vector_partition_state!(I,state_c)
  return state_c
end

"""
    increment_vector_partition_state!(I,state)

Update the state of a VectorPartition iterator.
Useful to avoid copying the state unnecessarily at the cost of destructive mutations.
This can result in significant speedups when you only need to look at each partition once.

# Examples
```julia
iter = all_vector_partitions(5,3)
_, state = iterate(iter)
while !state.done
  do_stuff(state.partition)
  increment_vector_partition_state!(iter,state)
end
```
"""
function increment_vector_partition_state!(I::VectorPartition,state)
  # increment the sequence subject to upper bound and carry
  if state.done
    return
  end
  @inbounds begin
  state.partition[2] += 1
  for i in 2:I.n_elements-1
    if state.partition[i] > state.upper_bound[i]
      if state.upper_bound[i] > state.upper_bound[i-1]
        state.partition[i] = state.upper_bound[i]
      else
        state.partition[i] = 1
      end
      state.partition[i+1] += 1
    end
  end
  end

  # overflow condition: need to change the upper bound
  @inbounds if state.partition[I.n_elements] > state.upper_bound[I.n_elements]
    stop = increment_surjective_monotone_sequence!(state.upper_bound,I.n_partitions,state.first_index)
    if stop
      state.done = true
    else
      # first partition for the new upper bound set
      state.partition[:] .= 1
      state.partition[state.first_index] = 1:I.n_partitions
    end
  end
end

function increment_surjective_monotone_sequence!(seq,maxval,step_locations)
  stop = true
  #update location of the increments
  @inbounds begin
  for i in 2:length(step_locations)
    if step_locations[i] > step_locations[i-1] + 1
      step_locations[i] -= 1
      k = 1
      for j in i-1:-1:2
        step_locations[j] = step_locations[i] - k
        k += 1
      end
      stop = false
      break
    end
  end

  for i in 1:length(step_locations)-1
    seq[step_locations[i]:step_locations[i+1]-1] .= i
  end
  seq[step_locations[end]:end] .= maxval
  end
  return stop
end

end


text:
module _Series

using Brainstorm
using Base.Test

include("reciprocal.jl")
include("sqrt.jl")
include("arctan.jl")
include("pi.jl")
include("euler.jl")
include("ln2.jl")

function test_all()
    test_reciprocal_all()
    test_sqrt_all()
    test_arctan_all()
    test_pi_all()
    test_euler_all()
    test_ln2_all()
end

end


text:
using CompScienceMeshes, BEAST

o, x, y, z = euclidianbasis(3)

Γ = meshsphere(1.0, 0.11)
X = lagrangec0d1(Γ)
@show numfunctions(X)

κ = 1.0; γ = im*κ
a = -1Helmholtz3D.hypersingular(gamma=γ)
b = Helmholtz3D.doublelayer(gamma=γ) - 0.5Identity()

uⁱ = Helmholtz3D.planewave(wavenumber=κ, direction=z)
f = strace(uⁱ,Γ)
g = ∂n(uⁱ)

@hilbertspace u
@hilbertspace v
eq1 = @discretise a[v,u] == g[v] u∈X v∈X
eq2 = @discretise b[v,u] == f[v] u∈X v∈X

x1 = solve(eq1)
x2 = solve(eq2)

fcr1, geo1 = facecurrents(x1, X)
fcr2, geo2 = facecurrents(x2, X)

include(Pkg.dir("CompScienceMeshes","examples","plotlyjs_patches.jl"))
p1 = patch(geo1, real.(norm.(fcr1)))
p2 = patch(geo2, real.(norm.(fcr2)))


text:
T=9
tsname="joRomberg"
@testset "$tsname" begin
for t=2:T # start test loop
    m=4*t
    n=m+rand(-2:2:2)
    A=joRomberg(m,n)

    verbose && println("$tsname ($m)")
    @testset "$m x $m" begin
        @test isadjoint(A)[1]
        @test islinear(A)[1]
    end

end # end test loop
end


text:
module BABEL

import ..LABELS
import ..LOCATIONS

using Glob

function parse_transcription(trans)
    uttidprefix = splitext(basename(trans))[1]
    segments = []
    state = :start_time
    start_t = 0
    end_t = 0
    label = ""
    open(trans, "r") do f
        for line in eachline(f)
            if state == :start_time
                start_t = parse(Float64, line[2:end-1])
                state = :label
            elseif state == :label
                label = replace(line, "(())" => LABELS[:unk])
                label = replace(label, "~" => "")
                label = replace(label, "<no-speech>" => LABELS[:sil])
                state = :end_time
            else
                end_t = parse(Float64, line[2:end-1])
                uttid = uttidprefix*"__$(start_t)_$(end_t)"
                push!(segments, (uttid, start_t, end_t, label))
                start_t = end_t
                state = :label
            end
        end
    end
    segments
end

function prepare(datadir, rootdir, subdirs = ["training", "dev"])

    nonspeechunits = Set()
    for dirname in subdirs
        dir = mkpath(joinpath(datadir, dirname == "training" ? "train" : dirname))
        @info "preparing $dir"

        segments = []
        for trans in glob("*txt", joinpath(rootdir, dirname, "transcription"))
            push!(segments, parse_transcription(trans)...)
        end

        # wav.scp
        uttids = Set()
        audiodir = joinpath(rootdir, dirname, "audio")
        scp = joinpath(dir, LOCATIONS[:wavs])
        open(scp, "w") do f
            for segment in segments
                uttid, start_t, end_t, _ = segment
                push!(uttids, uttid)
                trunc_uttid = split(uttid, "__")[1]
                println(f, "$uttid\tsph2pipe -t $(start_t):$(end_t) -f wav $(joinpath(audiodir, "$(trunc_uttid).sph")) |")
            end
        end

        # uttids
        open(joinpath(dir, LOCATIONS[:uttids]), "w") do f
            for uttid in sort(collect(uttids))
                println(f, uttid)
            end
        end

        # uttids_speakers
        uttids_spk = joinpath(dir, LOCATIONS[:utt2spk])
        spks = Set()
        open(uttids_spk, "w") do f
            for uttid in sort(collect(uttids))
                spk = split(uttid, "__")[1]
                push!(spks, spk)
                println(f, "$uttid\t$uttid $spk")
            end
        end

        # speakers
        spkfile = joinpath(dir, LOCATIONS[:speakers])
        open(spkfile, "w") do f
            for trans in glob("*txt", joinpath(rootdir, dirname, "transcription"))
                for spk in sort(collect(spks)) println(f, spk) end
            end
        end

        # trans.wrd
        open(joinpath(dir, LOCATIONS[:trans]*".wrd"), "w") do f
            for segment in segments
                uttid, _, _, text = segment
                ns_tokens = filter(t -> startswith(t, "<"), split(text))
                if ! isempty(ns_tokens) push!(nonspeechunits, ns_tokens...) end
                println(f, "$uttid\t$text")
            end
        end
    end

    langdir = mkpath(joinpath(datadir, "lang"))
    @info "preparing $langdir"

    phones = Set()
    open(joinpath(langdir, "lexicon"), "w") do fl
        open(joinpath(rootdir, "reference_materials", "lexicon.txt"), "r") do f
            for line in eachline(f)
                fields = split(line, "\t")
                word = fields[1]
                for field in fields[3:end]
                    print(fl, word, "\t")
                    for syllable in split(field, ".")
                        tokens = split(syllable)
                        suffix = startswith(tokens[end], "_") ? tokens[end] : ""
                        if suffix == ""
                            for token in tokens
                                push!(phones, token)
                                print(fl, token, " ")
                            end
                        else
                            for token in tokens[1:end-1]
                                newtoken = token*suffix
                                push!(phones, newtoken)
                                print(fl, newtoken, " ")
                            end
                        end
                    end
                    println(fl)
                end
            end
        end
    end

    open(joinpath(langdir, "units"), "w") do f
        for unit in nonspeechunits println(f, "$unit\tnon-speech-unit") end
        for phone in phones println(f, "$phone\tspeech-unit") end
    end

    return nothing
end

end

max_issues_repo_name: lucasondel/SpeechDatasets

max_forks_repo_name: lucasondel/SpeechDatasets


text:
using Documenter, KirchMig

makedocs(
    modules = [KirchMig],
    doctest = true,
    sitename = "KirchMig.jl",
)

deploydocs(
    deps   = Deps.pip("mkdocs", "mkdocs-material", "python-markdown-math"),
    repo = "github.com/cako/KirchMig.jl",
    julia  = "1.0",
    osname = "linux"
)


text:
using PathWeightSampling
using DiffEqJump
using StochasticDiffEq
using Catalyst
using Test

@variables t L(t)
@parameters κ λ

D = Differential(t)

eqs = [D(L) ~ λ * (κ / λ - L)]
noiseeqs = [sqrt(κ / λ)]

@named sn = SDESystem(eqs, noiseeqs, t, [L], [κ, λ])

rn = @reaction_network rn begin
    ρ, L + R --> L + LR
    μ, LR --> R
end ρ μ

xn = @reaction_network xn begin
    δ, LR + Y --> Yp + LR
    χ, Yp --> Y
end δ χ

# create a SDE driven jump problem:

tspan = (0.0, 5.0)
u0s = [50.0]
ps = [50.0, 1.0]
sde_problem = SDEProblem(sn, u0s, tspan, ps)

u0r = [50.0, 100.0, 0.0]
pr = [50.0 / 50, 50.0]
discrete_problem = DiscreteProblem(rn, u0r, tspan, pr)
jump_problem = JumpProblem(rn, discrete_problem, Direct())

driven_jump_problem = PathWeightSampling.DrivenJumpProblem(jump_problem, sde_problem, save_jumps=true)
sol = solve(driven_jump_problem)

sds = PathWeightSampling.SDEDrivenSystem(
    sn, rn, xn,
    [50, 100, 0, 100, 0], # u0
    ps,
    pr,  # pr
    [1.0, 10.0],  # px
    0.0:0.1:5.0  # dtimes
)

conf = PathWeightSampling.generate_configuration(sds)

me = PathWeightSampling.MarginalEnsemble(sds)
ce = PathWeightSampling.ConditionalEnsemble(sds)

@test ce.dist === me.dist === sds.dist
@test ce.indep_idxs == [2, 3]
@test ce.index_map == [1]
@test ce.dtimes == me.dtimes == sds.dtimes

new_conf = PathWeightSampling.sample(conf, me)

@test conf.s_traj != new_conf.s_traj
@test conf.x_traj == new_conf.x_traj

alg = SMCEstimate(128)
mi = PathWeightSampling.mutual_information(sds, alg)

# Simpler SDEDrivenSystem
xn = @reaction_network GeneExpression begin
    ρ, L --> L + X
    μ, X --> ∅
end ρ μ

sds = PathWeightSampling.SDEDrivenSystem(
    sn, xn,
    [50, 50], # u0
    ps,
    [10.0, 10.0],  # px
    0.0:0.1:2.0  # dtimes
)

mi = PathWeightSampling.mutual_information(sds, alg)

# using Plots
# conf = PathWeightSampling.generate_configuration(sds, seed=3)
# plot(conf)

# me = PathWeightSampling.MarginalEnsemble(sds)

# x = PathWeightSampling.trajectory_energy(
#     me.dist,
#     PathWeightSampling.merge_trajectories(conf.s_traj, conf.x_traj)
# )
# -PathWeightSampling.energy_difference(conf, me)[end]
# plot(-PathWeightSampling.energy_difference(conf, me))

# samples = [PathWeightSampling.sample(conf, me) for i = 1:1024]
# log_probs = hcat(map(c -> -PathWeightSampling.energy_difference(c, me), samples)...)

# log_prob = mean(log_probs, dims=2)

# plot(-PathWeightSampling.energy_difference(conf, me) - log_prob)

# conf.s_traj
# merged = PathWeightSampling.collect_trajectory(PathWeightSampling.merge_trajectories(conf.s_traj, conf.x_traj))
# plot(conf)
# plot(merged)

# traj = PathWeightSampling.propagate(conf, me, [50], (0.0, 0.1))
# plot(traj)

# alg = SMCEstimate(128)
# mi = PathWeightSampling.mutual_information(sds, alg, num_samples=100)

# using Statistics
# plot(sds.dtimes, mean(mi.MutualInformation))
# plot!(sds.dtimes, 1.0 .* sds.dtimes)


text:
const epsi = 0.00001

function SMD1_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = zeros(upperDimensions)
    lowerMember = zeros(lowerDimensions)

    upperMember, lowerMember
end

function SMD2_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = zeros(upperDimensions)
    lowerMember = [zeros(q); ones(r)]

    upperMember, lowerMember
end

function SMD3_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = zeros(upperDimensions)
    lowerMember = zeros(lowerDimensions)

    upperMember, lowerMember
end

function SMD4_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = zeros(upperDimensions)
    lowerMember = zeros(lowerDimensions)

    upperMember, lowerMember
end

function SMD5_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = zeros(upperDimensions)
    lowerMember = [ones(q); zeros(r)]

    upperMember, lowerMember
end

function SMD6_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = floor(Int,(lowerDimensions - r)/2 - epsi)
    s = ceil(Int, (lowerDimensions - r)/2 + epsi)

    upperMember = zeros(upperDimensions)
    lowerMember = zeros(lowerDimensions)

    upperMember, lowerMember
end

function SMD7_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = zeros(upperDimensions)
    lowerMember = [zeros(q); ones(r)]

    upperMember, lowerMember
end

function SMD8_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = zeros(upperDimensions)
    lowerMember = [ones(q); zeros(r)]

    upperMember, lowerMember
end

function SMD9_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = zeros(upperDimensions)
    lowerMember = zeros(lowerDimensions)

    upperMember, lowerMember
end

function SMD10_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = 1/sqrt(p+r-1)*ones(upperDimensions)
    lowerMember = [1/sqrt(q-1)*ones(q); atan.(1/sqrt(p+r-1)*ones(r))]

    upperMember, lowerMember
end

function SMD11_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = zeros(upperDimensions)
    lowerMember = [zeros(q); exp(-1/sqrt(r))*ones(r)]

    upperMember, lowerMember
end

function SMD12_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = 1/sqrt(p+r-1)*ones(upperDimensions)
    lowerMember = [1/sqrt(q-1)*ones(q); atan.(1/sqrt(p+r-1)-1/sqrt(r))*ones(r)]

    upperMember, lowerMember
end

function SMD13_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = lowerDimensions - r

    upperMember = [ones(p); zeros(r)]
    lowerMember = [zeros(p); ones(r)]

    upperMember, lowerMember
end

function SMD14_optimum(upperDimensions,lowerDimensions)

    r = floor(Int,upperDimensions/2)
    p = upperDimensions - r
    q = floor(Int,(lowerDimensions - r)/2 - epsi)
    s = ceil(Int, (lowerDimensions - r)/2 + epsi)

    upperMember = [ones(p); zeros(r)]
    lowerMember = zeros(lowerDimensions)

    upperMember, lowerMember
end

function SMD_ranges(fno, ulDim, llDim)
    if fno == 6
        r = floor(Int, ulDim/2)
        p = ulDim - r
        q = floor(Int, (llDim - r)/2 - epsi)
        s = ceil((llDim - r)/2 + epsi)
    elseif fno in [1,2,3,4,5,7,8,9,10,11,12]
        r = floor(Int, ulDim/2)
        p = ulDim - r
        q = llDim - r
    end

    if fno ==  1 #ok
        ulDimMin = -5*ones(ulDim)
        ulDimMax = 10*ones(ulDim)
        llDimMin = [-5*ones(q); -pi/2*ones(r).+epsi]
        llDimMax = [10*ones(q);  pi/2*ones(r).-epsi]
    elseif fno ==  2 #ok
        ulDimMin = -5*ones(ulDim)
        ulDimMax = [10*ones(p); 1*ones(r)]
        llDimMin = [-5*ones(q); epsi*ones(r)]
        llDimMax = [10*ones(q); exp(1)*ones(r)]
    elseif fno ==  3 #ok
        ulDimMin = -5*ones(ulDim)
        ulDimMax = 10*ones(ulDim)
        llDimMin = [-5*ones(q); -pi/2*ones(r).+epsi]
        llDimMax = [10*ones(q);  pi/2*ones(r).-epsi]
    elseif fno ==  4 #ok
        ulDimMin = [-5*ones(p); -1*ones(r)]
        ulDimMax = [10*ones(p); 1*ones(r)]
        llDimMin = [-5*ones(q); zeros(r)]
        llDimMax = [10*ones(q); exp(1)*ones(r)]
    elseif fno ==  5 #ok
        ulDimMin = -5*ones(ulDim)
        ulDimMax = 10*ones(ulDim)
        llDimMin = [-5*ones(q); -5*ones(r)]
        llDimMax = [10*ones(q); 10*ones(r)]
    elseif fno ==  6 #ok
        ulDimMin = -5*ones(ulDim)
        ulDimMax = 10*ones(ulDim)
        llDimMin = -5*ones(llDim)
        llDimMax = 10*ones(llDim)
    elseif fno ==  7 #ok
        ulDimMin = -5*ones(ulDim)
        ulDimMax = [10*ones(p); 1*ones(r)]
        llDimMin = [-5*ones(q); epsi*ones(r)]
        llDimMax = [10*ones(q); exp(1)*ones(r)]
    elseif fno ==  8 #ok
        ulDimMin = -5*ones(ulDim)
        ulDimMax = 10*ones(ulDim)
        llDimMin = [-5*ones(q); -5*ones(r)]
        llDimMax = [10*ones(q); 10*ones(r)]
    elseif fno ==  9 #ok
        ulDimMin = -5*ones(ulDim)
        ulDimMax = [10*ones(p); 1*ones(r)]
        llDimMin = [-5*ones(q); -1 .+ epsi*ones(r)]
        llDimMax = [10*ones(q); (-1 .+ exp(1)*ones(r))]
    elseif fno ==  10	#ok
        ulDimMin = -5*ones(ulDim)
        ulDimMax = 10*ones(ulDim)
        llDimMin = [-5*ones(q); -pi/2*ones(r).+epsi]
        llDimMax = [10*ones(q);  pi/2*ones(r).-epsi]
    elseif fno ==  11 #ok
        ulDimMin = [-5*ones(p); -1*ones(r)]
        ulDimMax = [10*ones(p); 1*ones(r)]
        llDimMin = [-5*ones(q); 1/exp(1)*ones(r)]
        llDimMax = [10*ones(q); exp(1)*ones(r)]
    elseif fno ==  12 #???? inconsistent with the paper
        ulDimMin = [-5*ones(p); -1*ones(r)]
        ulDimMax = [10*ones(p); 1*ones(r)]
        llDimMin = [-5*ones(q); -pi/4*ones(r).+epsi]
        llDimMax = [10*ones(q);  pi/4*ones(r).-epsi]
    end

    bounds_ul = [ulDimMin ulDimMax]
    bounds_ll = [llDimMin llDimMax]

    return bounds_ul, bounds_ll
end

"""
    SMD_get_problem(fnum; uldim = 2, lldim = 3)

Return upper and lower level objective functions, and the problem configuration in
a dictionary.

### Example

```juliarepl
julia> using HardTestProblems

julia> F, f, conf = SMD_get_problem(12,uldim=2,lldim=3);

julia> conf
Dict{Symbol, Any} with 14 entries:
  :follower_optimum      => 4.0
  :n_inequality_follower => 3
  :xbest                 => [1.0, 1.0]
  :n_equality_follower   => 0
  :lldim                 => 3
  :uldim                 => 2
  :n_equality_leader     => 0
  :n_inequality_leader   => 3
  :xmin                  => [-5.0, -1.0]
  :leader_optimum        => 3.0
  :xmax                  => [10.0, 1.0]
  :ymax                  => [10.0, 10.0, 0.785388]
  :ymin                  => [-5.0, -5.0, -0.785388]
  :ybest                 => [1.0, 1.0, 0.0]

julia> F(conf[:xbest], conf[:ybest]) # upper level function
(3.0, [-0.0, -0.0, -1.0], [0.0])

julia> f(conf[:xbest], conf[:ybest]) # lower level function
(4.0, [-0.0, -0.0, -0.0], [0.0])

```
"""
function SMD_get_problem(fnum; uldim = 2, lldim = 3)

    F = eval(Symbol("SMD"*string(fnum) * "_leader"))
    f = eval(Symbol("SMD"*string(fnum) * "_follower"))

    optimum = eval(Symbol("SMD"*string(fnum) * "_optimum"))

    x, y = optimum(uldim, lldim)

    Fmin,G,H = F(x,y)
    fmin,g,h = f(x,y)

    bounds_ul, bounds_ll = SMD_ranges(fnum, uldim, lldim)

    # upperMember, lowerMember
    conf = Dict(:xmin => bounds_ul[:,1],
                :xmax => bounds_ul[:,2],
                :ymin => bounds_ll[:,1],
                :ymax => bounds_ll[:,2],
                :xbest => x,
                :ybest => y,
                :leader_optimum => Fmin,
                :follower_optimum => fmin,
                :lldim => lldim,
                :uldim => uldim,
                :problem => "SMD" * string(fnum),
                :n_inequality_leader => length(G),
                :n_equality_leader => 0,
                :n_inequality_follower => length(g),
                :n_equality_follower => 0 )

    return F, f, conf
end

export SMD_get_problem


text:
"""

## Code length codes, I1 ##

In the first section, we read a series of 3 bit codes.

The meaning of these codes is follows, as specified in 3.2.7:

The alphabet for code lengths is as follows. This will make
more sense once we go through the actual values.

From 3.2.7:
0 - 15: Represent code lengths of 0 - 15
16: Copy the previous code length 3 - 6 times.
   The next 2 bits indicate repeat length
         (0 = 3, ... , 3 = 6)
      Example:  Codes 8, 16 (+2 bits 11),
                16 (+2 bits 10) will expand to
                12 code lengths of 8 (1 + 6 + 5)
17: Repeat a code length of 0 for 3 - 10 times.
   (3 bits of length)
18: Repeat a code length of 0 for 11 - 138 times
   (7 bits of length)

Finally, the 3 bit values are not in order but rather
are in the following order, allowing you to potentially save a few extra
bytes if they are not used.

"(HCLEN + 4) x 3 bits: code lengths for the code length
alphabet given just above, in the order: 16, 17, 18,
0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15"

So in brief summary, the next 3 bits to process correspond to code 16, which
when seen later indicates to copy a previous code 3 - 6 times. This made
absolutely no sense to me until I worked through an example.

"""


text:
## 1. Julia-only serialization. Use it for technical data (e.g. functions, codes, etc.)

"Return serialized object as an array of bytes"
function serialized(x)
    buf = IOBuffer()
    serialize(buf, x)
    return buf.data
end

"Return object deserialized from array of bytes"
function deserialized(x::Vector{UInt8})
    return deserialize(IOBuffer(x))
end

## Java-compatible serialization. Use it for data

from_bytes(::Type{Vector{UInt8}}, arr::Vector{UInt8}) = arr
function from_bytes{T}(::Type{T}, arr::Vector{Any})
    map(T, arr)
end
from_bytes(::Type{UTF8String}, arr::Vector{UInt8}) = utf8(arr)
from_bytes(::Type{ASCIIString}, arr::Vector{UInt8}) = bytestring(arr)
from_bytes{I<:Integer}(::Type{I}, arr::Vector{UInt8}) = begin
    io = IOBuffer(arr)
    ntoh(read(io, I))
end

to_bytes(x::Vector{UInt8}) = x
to_bytes(x::UTF8String) = convert(Vector{UInt8}, x)
to_bytes(x::ASCIIString) = convert(Vector{UInt8}, x)
to_bytes{I<:Integer}(x::I) = begin
    io = IOBuffer()
    write(io, hton(x))
    io.data
end

to_bytes(x) = serialized(x)  # generic serialization for Julia objects


text:
using SamplingHS3

# inverted egg crate function
f_ec = (x::Vector{Float64}) -> ( sin(x[1])^2 + sin(x[2])^2 ) / ( 0.1 + x[1]*x[1] + x[2]*x[2] )^(1/2.5)

# polytope
xlim = [-20.,20.]; ylim = [-20.,20.]
bounding_box_G =[eye(2);-eye(2)]
bounding_box_h =[-xlim[1];xlim[2];-ylim[1];ylim[2]]

x0 = [5.0;5.0]

# pure mcmc sampling using hr and mh:
conf_only_hr = SamplingHS3.DecorrelationConfig( 10000 , 1.0*eye(2) , 0.5 , 0.5 )
f_density    = f_ec
# this is quite slow.. most time is spent for the generation of the multivar. normal random numbers..
tic()
mcmc_result_01 = SamplingHS3.run_mcmc( x0 , f_density(x0) , f_density , (x) -> 0 , 1.0 , bounding_box_G  , bounding_box_h , conf_only_hr )
toc()

# run with adaptive mcmc
tic()
config_mcmc = SamplingHS3.MCMCConfig()
mcmc_result_adaptive_01 = SamplingHS3.run_adaptive_mcmc( 10000 , x0 , f_density(x0) , f_density , (x) -> 0 , 1.0 , bounding_box_G  , bounding_box_h , config_mcmc )
toc()

# Plot results


text:
# Polynomial Normal Form

"""
    labels!(dict, t)

Find all terms that are not + and * and replace them
with a symbol, store the symbol => term mapping in `dict`.
"""
function labels! end

# Turn a Term into a multivariate polynomial
function labels!(dicts, t::Sym)
    sym2term, term2sym = dicts
    if !haskey(term2sym, t)
        sym2term[t] = t
        term2sym[t] = t
    end
    return t
end

function labels!(dicts, t)
    if t isa Integer
        return t
    elseif istree(t) && (operation(t) == (*) || operation(t) == (+) || operation(t) == (-))
        tt = arguments(t)
        return similarterm(t, operation(t), map(x->labels!(dicts, x), arguments(t)))
    elseif istree(t) && operation(t) == (^) && length(arguments(t)) > 1 && isnonnegint(arguments(t)[2])
        return similarterm(t, operation(t), map(x->labels!(dicts, x), arguments(t)))
    else
        sym2term, term2sym = dicts
        if haskey(term2sym, t)
            return term2sym[t]
        end
        if istree(t)
            tt = arguments(t)
            sym = Sym{symtype(t)}(gensym(nameof(operation(t))))
            dicts2 = _dicts(dicts[2])
            sym2term[sym] = similarterm(t, operation(t),
                                        map(x->to_mpoly(x, dicts)[1], arguments(t)))
        else
            sym = Sym{symtype(t)}(gensym("literal"))
            sym2term[sym] = t
        end

        term2sym[t] = sym

        return sym
    end
end

ismpoly(x) = x isa MPoly || x isa Integer
isnonnegint(x) = x isa Integer && x >= 0

_dicts(t2s=OrderedDict{Any, Sym}()) = (OrderedDict{Sym, Any}(), t2s)

let
    mpoly_preprocess = [@rule(identity(~x) => ~x)
                        @rule(zero(~x) => 0)
                        @rule(one(~x) => 1)]

    mpoly_rules = [@rule(~x::ismpoly - ~y::ismpoly => ~x + -1 * (~y))
                   @rule(-(~x) => -1 * ~x)
                   @acrule(~x::ismpoly + ~y::ismpoly => ~x + ~y)
                   @rule(+(~x) => ~x)
                   @acrule(~x::ismpoly * ~y::ismpoly => ~x * ~y)
                   @rule(*(~x) => ~x)
                   @rule((~x::ismpoly)^(~a::isnonnegint) => (~x)^(~a))]
    MPOLY_CLEANUP = Fixpoint(Postwalk(PassThrough(RestartedChain(mpoly_preprocess))))
    MPOLY_MAKER = Fixpoint(Postwalk(PassThrough(RestartedChain(mpoly_rules))))

    global MPOLY_CLEANUP

    global to_mpoly
    function to_mpoly(t, dicts=_dicts())
        # term2sym is only used to assign the same
        # symbol for the same term -- in other words,
        # it does common subexpression elimination
        t = MPOLY_CLEANUP(t)
        sym2term, term2sym = dicts
        labeled = labels!((sym2term, term2sym), t)

        if isempty(sym2term)
            return MPOLY_MAKER(labeled), Dict{Sym,Any}()
        end

        ks = sort(collect(keys(sym2term)), lt=<ₑ)
        R, vars = PolynomialRing(ZZ, String.(nameof.(ks)))

        replace_with_poly = Dict{Sym,MPoly}(zip(ks, vars))
        t_poly = substitute(labeled, replace_with_poly, fold=false)
        MPOLY_MAKER(t_poly), sym2term
    end
end

function to_term(reference, x, dict)
    syms = Dict(zip(nameof.(keys(dict)), keys(dict)))
    dict = copy(dict)
    for (k, v) in dict
        dict[k] = _to_term(reference, v, dict, syms)
    end
    _to_term(reference, x, dict, syms)
end

function _to_term(reference, x::MPoly, dict, syms)

    function mul_coeffs(exps, ring)
        l = length(syms)
        ss = symbols(ring)
        monics = [e == 1 ? syms[ss[i]] : syms[ss[i]]^e for (i, e) in enumerate(exps) if !iszero(e)]
        if length(monics) == 1
            return monics[1]
        elseif length(monics) == 0
            return 1
        else
            return similarterm(reference, *, monics)
        end
    end

    monoms = [mul_coeffs(exponent_vector(x, i), x.parent) for i in 1:x.length]
    if length(monoms) == 0
        return 0
    elseif length(monoms) == 1
        t = !isone(x.coeffs[1]) ?  monoms[1] * x.coeffs[1] : monoms[1]
    else
        t = similarterm(reference,
                        +,
                        map((x,y)->isone(y) ? x : y*x,
                            monoms, x.coeffs[1:length(monoms)]))
    end

    substitute(t, dict, fold=false)
end

function _to_term(reference, x, dict, vars)
    if istree(x)
        t=similarterm(x, operation(x), _to_term.((reference,), arguments(x), (dict,), (vars,)))
    else
        if haskey(dict, x)
            return dict[x]
        else
            return x
        end
    end
end

<ₑ(a::MPoly, b::MPoly) = false

function polynormalize(x)
    to_term(x, to_mpoly(x)...)
end


text:
module test_voxelplots_magicavoxel_chunktree

using Test
using VoxelPlots.MagicaVoxel
using .MagicaVoxel: VoxData, ChunkStream, ChunkTree, chunk_to_data
using AbstractTrees

vox_dir = normpath(@__DIR__, "resources")

function resource(block, filename)
    path = normpath(vox_dir, filename)
    f = open(path)
    tree = ChunkTree([], UInt8[])
    stream = ChunkStream(f, tree)
    block(stream)
    close(stream)
end

function Base.show(io::IO, tree::ChunkTree)
    print(io, "ChunkTree")
end

resource("placeholder.vox") do f
    vox = MagicaVoxel.parse_vox_file(f)
    buf = IOBuffer()
    AbstractTrees.print_tree(buf, f.tree)
    @test String(take!(buf)) == """
ChunkTree
├─ ChunkUnit(:MAIN, 1, 20 bytes)
├─ ChunkUnit(:SIZE, 1, 24 bytes)
├─ ChunkUnit(:XYZI, 1, 32 bytes)
├─ ChunkUnit(:nTRN, 1, 40 bytes)
├─ ChunkUnit(:nGRP, 1, 28 bytes)
├─ ChunkUnit(:nTRN, 1, 55 bytes)
├─ ChunkUnit(:nSHP, 1, 32 bytes)
├─ ChunkUnit(:LAYR, 8, 304 bytes)
├─ ChunkUnit(:RGBA, 1, 1036 bytes)
├─ ChunkUnit(:MATL, 256, 26880 bytes)
├─ ChunkUnit(:rLIT, 2, 176 bytes)
├─ ChunkUnit(:rAIR, 1, 93 bytes)
├─ ChunkUnit(:rLEN, 1, 99 bytes)
├─ ChunkUnit(:POST, 1, 83 bytes)
└─ ChunkUnit(:rDIS, 1, 87 bytes)
"""
    total_num_bytes = sum(length(unit.bytes) for unit in f.tree.units)

    seekstart(f)
    bytes = read(f)
    @test length(bytes) == total_num_bytes

    data = chunk_to_data(f.tree, vox)
    @test data == bytes
end

end # module test_voxelplots_magicavoxel_chunktree


text:
import .OpenSpiel:
    load_game,
    get_type,
    provides_information_state_tensor,
    provides_observation_tensor,
    provides_information_state_string,
    provides_observation_string,
    dynamics,
    new_initial_state,
    chance_mode,
    is_chance_node,
    information,
    information_state_tensor,
    information_state_tensor_size,
    information_state_tensor_shape,
    information_state_string,
    num_distinct_actions,
    num_players,
    apply_action,
    player_reward,
    legal_actions,
    legal_actions_mask,
    rewards,
    reward_model,
    observation_tensor_size,
    observation_tensor_shape,
    observation_tensor,
    observation_string,
    chance_mode,
    chance_outcomes,
    max_chance_outcomes,
    utility

"""
    OpenSpielEnv(name; state_type=nothing, kwargs...)

# Arguments

- `name`::`String`, you can call `OpenSpiel.registered_names()` to see all
  the supported names. Note that the name can contains parameters, like
  `"goofspiel(imp_info=True,num_cards=4,points_order=descending)"`. Because the
  parameters part is parsed by the backend C++ code, the bool variable must be
  `True` or `False` (instead of `true` or `false`). Another approach is to just
  specify parameters in `kwargs` in the Julia style.
"""
function OpenSpielEnv(name="kuhn_poker"; kwargs...)
    game = load_game(String(name); kwargs...)
    state = new_initial_state(game)
    OpenSpielEnv(state, game)
end

Base.copy(env::OpenSpielEnv) = OpenSpielEnv(copy(env.state), env.game)

RLBase.reset!(env::OpenSpielEnv) = env.state = new_initial_state(env.game)

(env::OpenSpielEnv)(action::Integer) = apply_action(env.state, action)

RLBase.current_player(env::OpenSpielEnv) = OpenSpiel.current_player(env.state)
RLBase.chance_player(env::OpenSpielEnv) = convert(Int, OpenSpiel.CHANCE_PLAYER)

function RLBase.players(env::OpenSpielEnv)
    p = 0:(num_players(env.game) - 1)
    if ChanceStyle(env) === EXPLICIT_STOCHASTIC
        (p..., RLBase.chance_player(env))
    else
        p
    end
end

function RLBase.action_space(env::OpenSpielEnv, player)
    if player == chance_player(env)
        # !!! this bug is already fixed in OpenSpiel
        # replace it with the following one later
        # ZeroTo(max_chance_outcomes(env.game)-1)
        ZeroTo(max_chance_outcomes(env.game))
    else
        ZeroTo(num_distinct_actions(env.game) - 1)
    end
end

function RLBase.legal_action_space(env::OpenSpielEnv, player)
    if player == chance_player(env)
        [k for (k, v) in chance_outcomes(env.state)]
    else
        legal_actions(env.state, player)
    end
end

function RLBase.prob(env::OpenSpielEnv, player)
    # @assert player == chance_player(env)
    p = zeros(length(action_space(env)))
    for (k, v) in chance_outcomes(env.state)
        p[k + 1] = v
    end
    p
end

function RLBase.legal_action_space_mask(env::OpenSpielEnv, player)
    n =
        player == chance_player(env) ? max_chance_outcomes(env.game) :
        num_distinct_actions(env.game)
    mask = BitArray(undef, n)
    for a in legal_actions(env.state, player)
        mask[a + 1] = true
    end
    mask
end

RLBase.is_terminated(env::OpenSpielEnv) = OpenSpiel.is_terminal(env.state)

function RLBase.reward(env::OpenSpielEnv, player)
    if DynamicStyle(env) === SIMULTANEOUS &&
       player == convert(Int, OpenSpiel.SIMULTANEOUS_PLAYER)
        rewards(env.state)
    elseif player < 0
        0
    elseif RewardStyle(env) == RLBase.TERMINAL_REWARD && !RLBase.is_terminated(env)
        0
    else
        player_reward(env.state, player)
    end
end

function RLBase.state(env::OpenSpielEnv, ss::RLBase.AbstractStateStyle, player)
    if player < 0  # TODO: revisit this in OpenSpiel@v0.2
        @warn "unexpected player $player, falling back to default state value." maxlog = 1
        s = state_space(env)
        if s isa WorldSpace
            ""
        elseif s isa Array{<:Interval}
            rand(s)
        end
    else
        _state(env, ss, player)
    end
end

_state(env::OpenSpielEnv, ::RLBase.InformationSet{String}, player) =
    information_state_string(env.state, player)
_state(env::OpenSpielEnv, ::RLBase.InformationSet{Array}, player) =
    reshape(information_state_tensor(env.state, player), reverse(information_state_tensor_shape(env.game))...)
_state(env::OpenSpielEnv, ::Observation{String}, player) =
    observation_string(env.state, player)
_state(env::OpenSpielEnv, ::Observation{Array}, player) =
    reshape(observation_tensor(env.state, player), reverse(observation_tensor_shape(env.game))...)

RLBase.state_space(
    env::OpenSpielEnv,
    ::Union{InformationSet{String},Observation{String}},
    p,
) = WorldSpace{AbstractString}()

RLBase.state_space(env::OpenSpielEnv, ::InformationSet{Array},
    p,
) = Space(
    fill(typemin(Float64)..typemax(Float64), reverse(information_state_tensor_shape(env.game))...),
)

RLBase.state_space(env::OpenSpielEnv, ::Observation{Array},
    p,
) = Space(
    fill(typemin(Float64)..typemax(Float64), reverse(observation_tensor_shape(env.game))...),
)

Random.seed!(env::OpenSpielEnv, s) = @warn "seed!(OpenSpielEnv) is not supported currently."

function RLBase.ChanceStyle(env::OpenSpielEnv)
    game_type = get_type(env.game)
    if chance_mode(game_type) == OpenSpiel.DETERMINISTIC
        RLBase.DETERMINISTIC
    elseif chance_mode(game_type) == OpenSpiel.EXPLICIT_STOCHASTIC
        RLBase.EXPLICIT_STOCHASTIC
    else
        RLBase.STOCHASTIC
    end
end

function RLBase.UtilityStyle(env::OpenSpielEnv)
    game_type = get_type(env.game)
    if utility(game_type) == OpenSpiel.ZERO_SUM
        RLBase.ZERO_SUM
    elseif utility(game_type) == OpenSpiel.CONSTANT_SUM
        RLBase.CONSTANT_SUM
    elseif utility(game_type) == OpenSpiel.GENERAL_SUM
        RLBase.GENERAL_SUM
    elseif utility(game_type) == OpenSpiel.IDENTICAL_SUM
        RLBase.IDENTICAL_SUM
    end
end

RLBase.ActionStyle(env::OpenSpielEnv) = FULL_ACTION_SET
RLBase.DynamicStyle(env::OpenSpielEnv) =
    dynamics(get_type(env.game)) == OpenSpiel.SEQUENTIAL ? RLBase.SEQUENTIAL :
    RLBase.SIMULTANEOUS
RLBase.InformationStyle(env::OpenSpielEnv) =
    information(get_type(env.game)) == OpenSpiel.PERFECT_INFORMATION ?
    RLBase.PERFECT_INFORMATION : RLBase.IMPERFECT_INFORMATION
RLBase.NumAgentStyle(env::OpenSpielEnv) = MultiAgent(num_players(env.game))
RLBase.RewardStyle(env::OpenSpielEnv) =
    reward_model(get_type(env.game)) == OpenSpiel.REWARDS ? RLBase.STEP_REWARD :
    RLBase.TERMINAL_REWARD

RLBase.StateStyle(env::OpenSpielEnv) = (RLBase.InformationSet{String}(),
    RLBase.InformationSet{Array}(),
    RLBase.Observation{String}(),
    RLBase.Observation{Array}(),)


text:
using Distributions, Statistics, LinearAlgebra

import Base: size, length, show

import Statistics: mean, var, std

export ENKF

""""
Define system ENKF which performs the data assimilation
using the stochastic ensemble Kalman filter

Fields:
 - 'f' : propagation function

 - 'A' : inflation

 - 'G' : filtering function acting on the state

 - 'm' : measurement function based on state

 - 'z' : real measurement function

 - 'ϵ' : measurement noise distribution

 - 'bounds' : bounds on certain states

 - 'isinflated' : Bool = true if state is inflated,
     = false otherwise

 - 'isfiltered' : Bool = true if state has to be filtered,
     = false otherwise

 - 'isaugmented' : Bool = true if measurement function is nonlinear,
     = false otherwise
"""
mutable struct ENKF{N, NZ}

    # "Ensemble of states"
    # ENS::EnsembleState{N, NS, TS}

    "Propagation function"
    f::PropagationFunction

    "Covariance Inflation"
    A::Union{InflationType, RecipeInflation}

    "Filter function"
    G::FilteringFunction

    "Measurement function based on state"
    m::MeasurementFunction

    "Real measurement function"
    z::RealMeasurementFunction

    "Measurement noise distribution"
    ϵ::AdditiveInflation{NZ}

    "Boolean: is data assimilation used"
    isenkf::Bool

    "Boolean: is state vector inflated"
    isinflated::Bool

    "Boolean: is state vector filtered"
    isfiltered::Bool

    "Boolean: is state vector augmented"
    isaugmented::Bool

    # "Bounds on certain state"
    # bounds

end

"""
    Define action of ENKF on EnsembleState
"""
function (enkf::ENKF{N, NZ})(t::Float64,
         Δt::Float64,
         ens::EnsembleState{N, TS}) where {N, NZ, TS}

    "Propagate each ensemble member"
    enkf.f(t, ens)

    "Is data assimilation used"
    if enkf.isenkf ==true

    # println("good prop")
    "Covariance inflation if 'isinflated==true' "
    if enkf.isinflated ==true
        enkf.A(ens)
    end
    # prin
    "State filtering if 'isfiltered==true' "
    if enkf.isfiltered ==true
        enkf.G(ens)
    end
    # println("good filtering")

    "Compute mean and deviation"

    ensfluc = EnsembleState(N, ens.S[1])

    deviation(ensfluc, ens)

    A′ = hcat(ensfluc)

    " Additional computing for RTPS inflation"
    if typeof(enkf.A)<:Union{RTPSInflation, RTPSAdditiveInflation, RTPSRecipeInflation}
        # correct scaling by 1/N-1 instead of 1/N for small ensembles
        σᵇ = std(ensfluc.S, corrected=false)
    end

    # println("good deviation")

    "Compute measurement"
    mens = EnsembleState(N, zeros(NZ))

        for (i, s) in enumerate(ens.S)
            mens.S[i] = enkf.m(t, deepcopy(s))
        end
    Â = hcat(deepcopy(mens))

    "Define measurement matrix H for linear observations, can be time-varying"
    if enkf.isaugmented == false
        H = deepcopy(enkf.m(t))
    end

    "Compute deviation from measurement of the mean"
    Ŝ = mean(deepcopy(ens))

    Â′  = Â .- enkf.m(t, Ŝ)

    # println("good deviation mean")

    "Get actual measurement"
    zens = EnsembleState(N, zeros(NZ))
    enkf.z(t+Δt, zens)
    # @show zens
    # println("good actual measurement")

    "Perturb actual measurement"
    enkf.ϵ(zens)

    D = hcat(zens)

    "Analysis step with representers, Evensen, Leeuwen et al. 1998"

    "Construct representers"
    if enkf.isaugmented ==true

        b = ((Â′*Â′') + (N-1)*cov(enkf.ϵ)*I) \ (D - Â)

        Bᵀb = (A′*Â′')*b

    else

        b = ( H * (A′*A′') * H' + (N-1)*cov(enkf.ϵ)*I) \ (D - Â)

        Bᵀb = (A′*A′')* H' * b
    end

    "Analysis step"
    ens += cut(Bᵀb)

    " Additional computing for RTPS inflation"
    if typeof(enkf.A)<:Union{RTPSInflation, RTPSAdditiveInflation, RTPSRecipeInflation}
        ensfluc = EnsembleState(N, ens.S[1])
        deviation(ensfluc, ens)
        σᵃ = std(ensfluc.S, corrected=false)
        enkf.A(ens, σᵇ, σᵃ)
    end

    "State filtering if 'isfiltered==true' "
    if enkf.isfiltered ==true
        enkf.G(ens)
    end

    " Compute a posteriori covariance"
    deviation(ensfluc, ens)

    A′ = hcat(ensfluc)

    return t+Δt, ens, A′*A′'

    else
        return t+Δt, ens
    end

end

# Create constructor for ENKF

function ENKF(N, NZ, f, A, G, m, z, ϵ; isenkf::Bool= true, isinflated::Bool = false, isfiltered::Bool = false, isaugmented::Bool = false)
    return ENKF{N, NZ}(f, A, G, m, z, ϵ, isenkf, isinflated, isfiltered, isaugmented)
end

# size(enkf::ENKF{N, TS, NZ, TZ}) where {N, TS, NZ, TZ} = (N, size, NZ)

# function Base.show(io::IO, sys::ENKF{N, TS, NZ, TZ}) where {N, TS, NZ, TZ}
#     NS = size()
#     print(io, "Ensemble Kalman filter with $N members of state of size $ and measurement vector of length $NZ")
# end

max_stars_repo_name: mleprovost/EnKF

max_issues_repo_name: mleprovost/EnKF

max_forks_repo_name: mleprovost/EnKF


text:
include("p_h.jl")
include("p_f.jl")
include("p_alpha.jl")

include("p_t.jl")
include("p_e.jl")

include("p_w.jl")

include("p_kappa.jl")
include("p_br.jl")

include("p_ohmic.jl")
include("p_n.jl")

include("p_lh.jl")

include("p_l.jl")


text:
"""
`devices() -> Vector{String}`

get a list of available NIDAQ devices
"""
function devices()
    sz = GetSysDevNames(convert(Ptr{UInt8},C_NULL), UInt32(0))
    data=zeros(UInt8,sz)
    catch_error(GetSysDevNames(pointer(data), UInt32(sz)))
    devs = map((x)->convert(String,x), split(chop(ascii(String(data))),", "))
    devs[devs .!= ""]

end

for (jfunction, cfunction) in (
        (:analog_input_channels, GetDevAIPhysicalChans),
        (:analog_output_channels, GetDevAOPhysicalChans),
        (:digital_input_channels, GetDevDILines),
        (:digital_output_channels, GetDevDOLines),
        (:counter_input_channels, GetDevCIPhysicalChans),
        (:counter_output_channels, GetDevCOPhysicalChans))
    @eval function $jfunction(device::String)
        sz = $cfunction(pointer(device), convert(Ptr{UInt8},C_NULL), UInt32(0))
        data=zeros(UInt8,sz)
        catch_error( $cfunction(pointer(device), pointer(data),
                UInt32(sz)) )
        map((x)->convert(String,x), split(chop(ascii(String(data))),", "))
    end

    @eval function $jfunction()
        d = devices()
        length(d)!=1 && error("NIDAQmx: more than one device")
        $(Symbol(jfunction))(d[1])
    end

    @eval @doc $(string("`", jfunction, """() -> Vector{String}`

    `""", jfunction, """(device) -> Vector{String}`

    get a list of available channels for either the only available NIDAQ device or for the specified NIDAQ device
    """)) $jfunction
end

for (jfunction, cfunction) in (
        (:analog_input_ranges, GetDevAIVoltageRngs),
        (:analog_output_ranges, GetDevAOVoltageRngs))
    @eval function $jfunction(device::String)
        sz = $cfunction(pointer(device), convert(Ptr{Float64},C_NULL), UInt32(0))
        data=zeros(sz)
        catch_error( $cfunction(pointer(device), pointer(data),
                UInt32(sz)) )
        reshape(data,(2,length(data)>>1))'
    end

    @eval function $jfunction()
        d = devices()
        length(d)!=1 && error("NIDAQmx: more than one device")
        $jfunction(d[1])
    end

    @eval @doc $(string("`", jfunction, """() -> Matrix`

    `""", jfunction, """(device) -> Matrix`

    get a list of available ranges for either the only available NIDAQ device or for the specified NIDAQ device
    """)) $jfunction
end

"""
`channel_type(task,channel) -> channel_type, measurement/output_type`

get the type of the specified NIDAQ channel
"""
function channel_type(t::Task, channel::String)
    val1 = Cint[0]
    catch_error(
        GetChanType(t.th, pointer(channel), pointer(val1)) )

    val2 = Cint[0]
    if val1[1] == Val_AI
        ret = GetAIMeasType(t.th, pointer(channel), pointer(val2))
    elseif val1[1] == Val_AO
        ret = GetAOOutputType(t.th, pointer(channel), pointer(val2))
    elseif val1[1] == Val_DI || val1[1] == Val_DO
        return val1[1], nothing
    elseif val1[1] == Val_CI
        ret = GetCIMeasType(t.th, pointer(channel), pointer(val2))
    elseif val1[1] == Val_CO
        ret = GetCOOutputType(t.th, pointer(channel), pointer(val2))
    end
    catch_error(ret)

    val1[1], val2[1]
end

function _getproperties(args, suffix::String, warning::Bool)
    ret_val = Dict{String,Tuple{Any,Bool}}()
    local settable
    local data
    local ret
    for sym in names(NIDAQ,true)
        eval(:(!issubtype(typeof(NIDAQ.$sym),Function))) && continue
        if string(sym)[1:min(end,8+length(suffix))]=="DAQmxGet"*suffix
            cfunction = getfield(NIDAQ, sym)
	    ccall_args = code_lowered(cfunction)[1].code[end].args[1].args[3]
            try
                basetype = eltype(ccall_args[1+length(args)])
                if length(ccall_args)==1+length(args)
                    data = Ref{basetype}(0)
                    ret = cfunction(args..., data)
                    data = data[]
                else
                    sz = cfunction(args..., convert(Ptr{basetype},C_NULL), convert(UInt32,0))
                    if sz<0
                      ret=sz
                      throw()
                    end
                    data = zeros(basetype,sz)
                    ret = cfunction(args..., pointer(data), convert(UInt32,sz))
                end
                if ret!=0
                    throw()
                elseif basetype == Bool32
                    data = reinterpret(UInt32, data) != 0
                elseif basetype == Int32
                    try
                        data = map((x)->signed_constants[x], data)
                    end
                elseif basetype == UInt32
                    try
                        data = map((x)->unsigned_constants[x], data)
                    end
                elseif basetype == UInt8
                    data = split(chop(ascii(String(data))),", ")

                end
            catch
                if warning
                    if ret!=0
                        catch_error(ret, string(cfunction)*": ", err_fcn=warn)
                    else
                        warn("can't handle function signature for $cfunction: $ccall_args")
                    end
                end
                continue
            end
            try
                getfield(NIDAQ, Symbol(replace(string(cfunction),"Get"*suffix,"Set"*suffix)))
                settable=true
            catch
                settable=false
            end
            ret_val[string(cfunction)[15+length(suffix):end]] = (data, settable)
        end
    end
    ret_val
end

"""
`getproperties(warning=false) -> Dict`

get the NIDAQ system properties
"""
function getproperties(; warning=false)
    _getproperties((), "Sys", warning)
end

"""
`getproperties(device; warning=false) -> Dict`

get the properties of the specified NIDAQ device
"""
function getproperties(device::String; warning=false)
    _getproperties((pointer(device),), "Dev", warning)
end

"""
`getproperties(task; warning=false) -> Dict`

get the properties of the specified NIDAQ task
"""
function getproperties(t::Task; warning=false)
    _getproperties((t.th,), "Task", warning)
end

channel_types = ["Val_AI", "Val_AO",
                 "Val_DI", "Val_DO",
                 "Val_CI", "Val_CO"]

"""
`getproperties(task,channel; warning=false) -> Dict`

get the properties of the specified NIDAQ channel
"""
function getproperties(t::Task, channel::String; warning=false)
    kind = channel_types[ find(channel_type(t, channel)[1] .==
            map((x)->getfield(NIDAQ,Symbol(x)), channel_types))[1]][end-1:end]

    _getproperties((t.th, pointer(channel)), kind, warning)
end

"""
`setproperty!(task,channel,property,value)`

set the specified NIDAQ property to value
"""
function setproperty!(t::Task, channel::String, property::String, value)
    kind = channel_types[ find(channel_type(t, channel)[1] .==
            map((x)->getfield(NIDAQ,Symbol(x)), channel_types))[1]][end-1:end]

    @eval ret = $(Symbol("DAQmxSet"*kind*property))($t.th, pointer($channel), $value)
    catch_error(ret, "DAQmxSet$kind$property: ")
    nothing
end


text:
using MinAtar
using Test

@testset "MinAtar.jl" begin
    # Write your own tests here.
    env = MinAtarEnv("space_invaders")
end


text:
__precompile__(true)
module SearchBall

    using Reactive
    include("reactive_extension.jl")
    include("geometry_utils.jl")
    include("orders.jl")
    include("graphics_2d.jl")
    include("world_state.jl")
    include("handle_orders.jl")
    include("configuration.jl")
    include("strategy_utils.jl")
    include("strategies/compare_shadow.jl")
    include("strategies/show_shadow.jl")
    include("strategies/test_strategy.jl")
    include("strategies/global_com_shadow.jl")
    # include("strategies/ba_jakob.jl")
    include("strategies/startpositions01.jl")
    include("strategies/pushball_NN.jl")
    include("strategies/growing_regions.jl")

    include("game_state.jl")
    include("game_view_gtk.jl")

    export main

    function main(arguments::AbstractVector{<:AbstractString},
        ignore_commandline::Bool=false)

        if ignore_commandline || isinteractive()
            config = get_config(arguments)
        else
            # Parse the command line arguments as initialization
            config = get_config(ARGS)
        end

        start_view(config)
    end

    main(config_file_path::AbstractString) =
        main(String["--file", config_file_path], true)
    main(ignore_commandline::Bool=false) = main(String[], ignore_commandline)
end


text:
inpt = """Sue 1: goldfish: 6, trees: 9, akitas: 0
Sue 2: goldfish: 7, trees: 1, akitas: 0
Sue 3: cars: 10, akitas: 6, perfumes: 7
Sue 4: perfumes: 2, vizslas: 0, cars: 6
Sue 5: goldfish: 1, trees: 3, perfumes: 10
Sue 6: children: 9, vizslas: 7, cars: 9
Sue 7: cars: 6, vizslas: 5, cats: 3
Sue 8: akitas: 10, vizslas: 9, children: 3
Sue 9: vizslas: 8, cats: 2, trees: 1
Sue 10: perfumes: 10, trees: 6, cars: 4
Sue 11: cars: 9, children: 1, cats: 1
Sue 12: pomeranians: 4, akitas: 6, goldfish: 8
Sue 13: cats: 10, children: 5, trees: 9
Sue 14: perfumes: 8, vizslas: 3, samoyeds: 1
Sue 15: vizslas: 2, perfumes: 8, trees: 3
Sue 16: pomeranians: 10, trees: 9, samoyeds: 4
Sue 17: akitas: 7, vizslas: 0, goldfish: 6
Sue 18: trees: 5, vizslas: 9, cars: 0
Sue 19: akitas: 3, goldfish: 9, trees: 10
Sue 20: perfumes: 7, samoyeds: 3, vizslas: 10
Sue 21: perfumes: 7, pomeranians: 10, akitas: 8
Sue 22: vizslas: 6, trees: 8, akitas: 10
Sue 23: goldfish: 0, trees: 4, children: 9
Sue 24: goldfish: 7, pomeranians: 9, akitas: 4
Sue 25: cars: 7, trees: 4, pomeranians: 4
Sue 26: trees: 9, akitas: 9, pomeranians: 7
Sue 27: samoyeds: 0, perfumes: 9, goldfish: 10
Sue 28: cars: 5, trees: 7, vizslas: 1
Sue 29: perfumes: 9, trees: 1, children: 6
Sue 30: goldfish: 10, trees: 0, cars: 4
Sue 31: akitas: 2, perfumes: 5, goldfish: 5
Sue 32: goldfish: 0, akitas: 5, trees: 0
Sue 33: vizslas: 2, akitas: 2, samoyeds: 3
Sue 34: goldfish: 8, perfumes: 5, cars: 3
Sue 35: akitas: 1, cats: 4, trees: 9
Sue 36: cars: 4, vizslas: 4, goldfish: 7
Sue 37: akitas: 5, perfumes: 7, trees: 3
Sue 38: goldfish: 10, trees: 2, vizslas: 9
Sue 39: goldfish: 4, pomeranians: 5, vizslas: 5
Sue 40: perfumes: 5, samoyeds: 4, akitas: 6
Sue 41: goldfish: 9, cars: 4, perfumes: 5
Sue 42: trees: 6, pomeranians: 9, goldfish: 8
Sue 43: perfumes: 7, pomeranians: 1, akitas: 2
Sue 44: vizslas: 9, cars: 5, cats: 0
Sue 45: akitas: 1, goldfish: 6, trees: 0
Sue 46: akitas: 5, vizslas: 8, trees: 2
Sue 47: trees: 9, akitas: 2, vizslas: 9
Sue 48: goldfish: 10, trees: 5, akitas: 2
Sue 49: cars: 7, vizslas: 2, perfumes: 6
Sue 50: akitas: 5, goldfish: 6, perfumes: 0
Sue 51: cars: 9, cats: 7, trees: 5
Sue 52: akitas: 7, goldfish: 10, cars: 0
Sue 53: cars: 10, cats: 4, perfumes: 2
Sue 54: goldfish: 2, pomeranians: 5, perfumes: 10
Sue 55: vizslas: 5, akitas: 4, cars: 8
Sue 56: goldfish: 9, vizslas: 4, akitas: 5
Sue 57: perfumes: 8, samoyeds: 7, cars: 9
Sue 58: cars: 5, akitas: 7, perfumes: 8
Sue 59: samoyeds: 8, cars: 10, vizslas: 10
Sue 60: akitas: 6, samoyeds: 0, goldfish: 3
Sue 61: trees: 8, pomeranians: 0, akitas: 2
Sue 62: trees: 1, perfumes: 3, vizslas: 4
Sue 63: vizslas: 6, samoyeds: 9, goldfish: 8
Sue 64: goldfish: 7, trees: 6, vizslas: 3
Sue 65: cars: 1, vizslas: 0, akitas: 6
Sue 66: cats: 6, pomeranians: 4, cars: 9
Sue 67: trees: 10, pomeranians: 7, samoyeds: 3
Sue 68: pomeranians: 5, goldfish: 9, akitas: 1
Sue 69: akitas: 1, vizslas: 0, trees: 9
Sue 70: cats: 4, goldfish: 4, vizslas: 10
Sue 71: vizslas: 7, perfumes: 7, trees: 8
Sue 72: children: 2, vizslas: 9, cats: 3
Sue 73: cars: 8, pomeranians: 0, perfumes: 6
Sue 74: akitas: 1, pomeranians: 8, vizslas: 10
Sue 75: vizslas: 5, perfumes: 5, cars: 7
Sue 76: cars: 3, vizslas: 3, goldfish: 0
Sue 77: akitas: 9, samoyeds: 1, pomeranians: 3
Sue 78: trees: 0, vizslas: 0, akitas: 6
Sue 79: pomeranians: 9, cars: 1, perfumes: 0
Sue 80: perfumes: 10, trees: 1, cats: 0
Sue 81: goldfish: 5, akitas: 9, trees: 0
Sue 82: vizslas: 1, akitas: 6, children: 4
Sue 83: samoyeds: 7, perfumes: 8, pomeranians: 4
Sue 84: perfumes: 3, children: 3, cats: 7
Sue 85: goldfish: 9, trees: 3, cars: 9
Sue 86: cars: 0, perfumes: 9, vizslas: 0
Sue 87: children: 3, trees: 4, akitas: 3
Sue 88: trees: 1, samoyeds: 1, goldfish: 0
Sue 89: akitas: 8, cars: 3, vizslas: 9
Sue 90: pomeranians: 9, trees: 9, goldfish: 8
Sue 91: goldfish: 7, trees: 10, children: 0
Sue 92: cats: 9, cars: 7, perfumes: 7
Sue 93: vizslas: 2, goldfish: 7, cats: 9
Sue 94: akitas: 5, cars: 8, vizslas: 4
Sue 95: goldfish: 7, vizslas: 1, perfumes: 2
Sue 96: goldfish: 5, trees: 6, perfumes: 10
Sue 97: trees: 0, perfumes: 7, cars: 0
Sue 98: cars: 2, perfumes: 6, trees: 8
Sue 99: trees: 10, children: 7, cats: 9
Sue 100: samoyeds: 5, goldfish: 6, vizslas: 6
Sue 101: cars: 10, perfumes: 9, vizslas: 3
Sue 102: pomeranians: 6, trees: 1, samoyeds: 4
Sue 103: cars: 2, perfumes: 1, goldfish: 5
Sue 104: goldfish: 2, cars: 8, pomeranians: 2
Sue 105: goldfish: 6, vizslas: 0, trees: 10
Sue 106: trees: 10, akitas: 10, pomeranians: 0
Sue 107: vizslas: 2, pomeranians: 10, trees: 3
Sue 108: children: 3, vizslas: 8, akitas: 7
Sue 109: perfumes: 2, akitas: 2, samoyeds: 3
Sue 110: goldfish: 7, trees: 1, perfumes: 1
Sue 111: akitas: 2, cars: 9, perfumes: 2
Sue 112: children: 10, cars: 0, akitas: 3
Sue 113: akitas: 9, vizslas: 4, children: 3
Sue 114: pomeranians: 3, trees: 2, goldfish: 5
Sue 115: perfumes: 8, cars: 6, trees: 0
Sue 116: samoyeds: 6, children: 3, pomeranians: 1
Sue 117: goldfish: 1, trees: 2, akitas: 1
Sue 118: goldfish: 10, akitas: 10, samoyeds: 0
Sue 119: vizslas: 10, perfumes: 6, cars: 0
Sue 120: cars: 2, perfumes: 9, goldfish: 5
Sue 121: vizslas: 2, trees: 2, cars: 6
Sue 122: vizslas: 3, trees: 0, akitas: 2
Sue 123: akitas: 5, samoyeds: 7, goldfish: 1
Sue 124: goldfish: 8, samoyeds: 7, trees: 8
Sue 125: trees: 3, goldfish: 8, perfumes: 5
Sue 126: cats: 3, vizslas: 9, goldfish: 0
Sue 127: pomeranians: 9, goldfish: 3, perfumes: 6
Sue 128: vizslas: 4, cars: 8, goldfish: 5
Sue 129: vizslas: 8, children: 5, perfumes: 8
Sue 130: cars: 7, children: 7, cats: 3
Sue 131: perfumes: 1, akitas: 8, vizslas: 9
Sue 132: perfumes: 7, samoyeds: 10, pomeranians: 6
Sue 133: cars: 5, perfumes: 3, goldfish: 7
Sue 134: perfumes: 9, akitas: 2, cats: 3
Sue 135: perfumes: 1, trees: 9, vizslas: 9
Sue 136: akitas: 7, cars: 3, perfumes: 7
Sue 137: vizslas: 9, goldfish: 8, cars: 5
Sue 138: trees: 0, samoyeds: 1, cars: 3
Sue 139: cars: 0, perfumes: 6, trees: 0
Sue 140: pomeranians: 4, cars: 1, perfumes: 7
Sue 141: vizslas: 10, akitas: 8, cats: 3
Sue 142: trees: 1, cats: 6, vizslas: 5
Sue 143: pomeranians: 9, cars: 7, perfumes: 9
Sue 144: cars: 0, perfumes: 2, pomeranians: 1
Sue 145: trees: 1, goldfish: 9, perfumes: 8
Sue 146: cars: 8, children: 5, vizslas: 2
Sue 147: perfumes: 2, goldfish: 5, cars: 0
Sue 148: akitas: 2, perfumes: 7, pomeranians: 6
Sue 149: goldfish: 8, cars: 0, trees: 1
Sue 150: akitas: 6, perfumes: 5, trees: 0
Sue 151: vizslas: 6, samoyeds: 8, akitas: 10
Sue 152: trees: 7, akitas: 7, perfumes: 6
Sue 153: goldfish: 9, cats: 9, cars: 3
Sue 154: vizslas: 10, trees: 0, cars: 9
Sue 155: perfumes: 3, children: 2, goldfish: 1
Sue 156: goldfish: 7, perfumes: 5, akitas: 6
Sue 157: cats: 10, trees: 1, goldfish: 0
Sue 158: cats: 7, children: 7, vizslas: 6
Sue 159: perfumes: 9, akitas: 0, cars: 0
Sue 160: akitas: 3, goldfish: 10, pomeranians: 2
Sue 161: goldfish: 10, cars: 6, perfumes: 3
Sue 162: trees: 0, cars: 9, goldfish: 1
Sue 163: cars: 8, perfumes: 9, vizslas: 5
Sue 164: goldfish: 1, trees: 10, children: 6
Sue 165: goldfish: 0, vizslas: 6, cars: 0
Sue 166: akitas: 5, vizslas: 1, cars: 5
Sue 167: vizslas: 1, samoyeds: 1, children: 4
Sue 168: samoyeds: 7, vizslas: 7, akitas: 3
Sue 169: goldfish: 3, cats: 9, trees: 2
Sue 170: cars: 5, perfumes: 9, vizslas: 5
Sue 171: goldfish: 7, cars: 6, perfumes: 10
Sue 172: cats: 6, akitas: 1, children: 6
Sue 173: cats: 4, goldfish: 1, children: 3
Sue 174: cars: 2, pomeranians: 2, vizslas: 7
Sue 175: trees: 0, children: 4, goldfish: 7
Sue 176: children: 8, cars: 5, cats: 9
Sue 177: pomeranians: 4, vizslas: 7, trees: 3
Sue 178: vizslas: 6, perfumes: 10, akitas: 6
Sue 179: cars: 4, akitas: 4, trees: 4
Sue 180: akitas: 8, goldfish: 6, trees: 9
Sue 181: perfumes: 3, vizslas: 10, cars: 3
Sue 182: vizslas: 3, samoyeds: 3, goldfish: 7
Sue 183: goldfish: 10, perfumes: 2, cats: 1
Sue 184: goldfish: 5, trees: 1, perfumes: 1
Sue 185: vizslas: 10, trees: 9, perfumes: 2
Sue 186: goldfish: 6, perfumes: 9, trees: 1
Sue 187: cars: 0, trees: 9, goldfish: 6
Sue 188: cars: 0, trees: 1, vizslas: 9
Sue 189: akitas: 7, vizslas: 2, trees: 0
Sue 190: pomeranians: 5, perfumes: 8, akitas: 10
Sue 191: vizslas: 5, akitas: 3, cats: 0
Sue 192: children: 1, trees: 1, cars: 2
Sue 193: cars: 3, goldfish: 9, trees: 2
Sue 194: samoyeds: 3, akitas: 4, perfumes: 8
Sue 195: trees: 1, vizslas: 8, akitas: 10
Sue 196: akitas: 6, cars: 5, pomeranians: 0
Sue 197: akitas: 5, vizslas: 5, cats: 1
Sue 198: trees: 4, cars: 6, goldfish: 6
Sue 199: cats: 7, cars: 5, goldfish: 6
Sue 200: vizslas: 4, cats: 0, akitas: 9
Sue 201: pomeranians: 1, perfumes: 4, children: 2
Sue 202: cats: 1, perfumes: 4, vizslas: 3
Sue 203: vizslas: 1, akitas: 9, children: 5
Sue 204: perfumes: 8, cars: 7, trees: 4
Sue 205: perfumes: 7, pomeranians: 5, cats: 9
Sue 206: vizslas: 8, trees: 2, akitas: 2
Sue 207: akitas: 6, vizslas: 2, perfumes: 10
Sue 208: vizslas: 1, children: 7, akitas: 4
Sue 209: perfumes: 4, trees: 2, children: 1
Sue 210: goldfish: 0, vizslas: 2, samoyeds: 10
Sue 211: cars: 8, perfumes: 3, trees: 1
Sue 212: cars: 8, samoyeds: 5, pomeranians: 8
Sue 213: akitas: 2, goldfish: 8, pomeranians: 2
Sue 214: akitas: 6, pomeranians: 2, cars: 0
Sue 215: trees: 10, pomeranians: 4, vizslas: 0
Sue 216: perfumes: 0, cars: 8, trees: 0
Sue 217: samoyeds: 8, akitas: 7, children: 10
Sue 218: perfumes: 1, vizslas: 6, children: 0
Sue 219: children: 1, goldfish: 4, trees: 1
Sue 220: akitas: 10, goldfish: 10, trees: 5
Sue 221: cars: 7, pomeranians: 6, perfumes: 3
Sue 222: vizslas: 6, children: 0, akitas: 5
Sue 223: perfumes: 9, cars: 1, trees: 6
Sue 224: pomeranians: 1, trees: 0, vizslas: 0
Sue 225: goldfish: 8, akitas: 4, perfumes: 10
Sue 226: pomeranians: 7, cats: 7, children: 4
Sue 227: trees: 0, akitas: 2, perfumes: 1
Sue 228: vizslas: 6, cars: 10, perfumes: 9
Sue 229: cars: 0, perfumes: 6, trees: 4
Sue 230: pomeranians: 7, perfumes: 5, trees: 2
Sue 231: goldfish: 9, cars: 6, trees: 7
Sue 232: akitas: 1, vizslas: 5, cars: 3
Sue 233: akitas: 7, samoyeds: 2, vizslas: 5
Sue 234: akitas: 6, cats: 8, pomeranians: 0
Sue 235: pomeranians: 5, akitas: 5, vizslas: 3
Sue 236: goldfish: 5, trees: 6, akitas: 5
Sue 237: goldfish: 9, perfumes: 5, cats: 5
Sue 238: cats: 8, goldfish: 4, perfumes: 0
Sue 239: samoyeds: 8, children: 6, pomeranians: 6
Sue 240: akitas: 4, samoyeds: 10, trees: 8
Sue 241: trees: 2, goldfish: 8, cars: 1
Sue 242: perfumes: 2, cars: 0, akitas: 10
Sue 243: pomeranians: 1, cars: 7, trees: 2
Sue 244: trees: 9, vizslas: 2, akitas: 10
Sue 245: cars: 9, pomeranians: 4, trees: 0
Sue 246: cars: 9, pomeranians: 7, perfumes: 1
Sue 247: trees: 0, goldfish: 1, akitas: 8
Sue 248: vizslas: 1, cats: 4, akitas: 4
Sue 249: cats: 6, children: 4, goldfish: 9
Sue 250: vizslas: 1, cars: 10, samoyeds: 5
Sue 251: cars: 0, goldfish: 1, vizslas: 7
Sue 252: cars: 7, akitas: 9, vizslas: 10
Sue 253: akitas: 7, vizslas: 2, perfumes: 5
Sue 254: vizslas: 10, akitas: 5, samoyeds: 0
Sue 255: pomeranians: 8, goldfish: 0, cats: 6
Sue 256: cars: 10, goldfish: 8, vizslas: 9
Sue 257: goldfish: 3, perfumes: 9, cats: 3
Sue 258: trees: 6, goldfish: 6, cars: 6
Sue 259: trees: 0, goldfish: 2, perfumes: 8
Sue 260: trees: 5, akitas: 0, cars: 0
Sue 261: pomeranians: 9, goldfish: 7, perfumes: 8
Sue 262: perfumes: 8, vizslas: 6, goldfish: 2
Sue 263: vizslas: 6, trees: 5, goldfish: 9
Sue 264: vizslas: 4, perfumes: 7, cars: 9
Sue 265: goldfish: 10, trees: 3, perfumes: 1
Sue 266: trees: 10, akitas: 8, goldfish: 8
Sue 267: goldfish: 4, trees: 0, samoyeds: 9
Sue 268: vizslas: 1, trees: 0, goldfish: 8
Sue 269: cars: 2, perfumes: 10, goldfish: 5
Sue 270: perfumes: 7, cars: 2, vizslas: 1
Sue 271: cars: 6, perfumes: 10, goldfish: 6
Sue 272: samoyeds: 4, goldfish: 2, vizslas: 9
Sue 273: perfumes: 4, goldfish: 4, vizslas: 1
Sue 274: children: 4, cars: 4, perfumes: 3
Sue 275: children: 8, vizslas: 3, trees: 2
Sue 276: vizslas: 5, children: 7, perfumes: 3
Sue 277: perfumes: 3, cats: 4, vizslas: 5
Sue 278: cars: 1, samoyeds: 10, akitas: 2
Sue 279: trees: 9, perfumes: 9, cars: 10
Sue 280: vizslas: 5, trees: 0, perfumes: 6
Sue 281: vizslas: 3, akitas: 10, pomeranians: 7
Sue 282: trees: 1, children: 2, akitas: 8
Sue 283: akitas: 9, goldfish: 6, cats: 5
Sue 284: cars: 9, children: 10, pomeranians: 2
Sue 285: pomeranians: 0, perfumes: 4, cars: 7
Sue 286: perfumes: 0, vizslas: 10, akitas: 10
Sue 287: cats: 2, perfumes: 3, trees: 5
Sue 288: akitas: 9, vizslas: 8, samoyeds: 9
Sue 289: perfumes: 6, children: 2, cars: 7
Sue 290: akitas: 0, children: 5, cars: 5
Sue 291: cars: 4, perfumes: 0, trees: 1
Sue 292: cats: 0, cars: 8, perfumes: 6
Sue 293: akitas: 9, cats: 5, children: 5
Sue 294: akitas: 4, cars: 9, goldfish: 3
Sue 295: cars: 2, akitas: 3, perfumes: 7
Sue 296: perfumes: 4, cars: 7, goldfish: 10
Sue 297: trees: 5, akitas: 8, vizslas: 1
Sue 298: perfumes: 0, goldfish: 6, trees: 9
Sue 299: perfumes: 6, samoyeds: 8, cars: 1
Sue 300: goldfish: 10, perfumes: 4, akitas: 2
Sue 301: cars: 3, trees: 0, goldfish: 8
Sue 302: perfumes: 7, samoyeds: 2, vizslas: 7
Sue 303: children: 10, goldfish: 7, perfumes: 2
Sue 304: samoyeds: 8, vizslas: 2, cars: 1
Sue 305: trees: 1, cats: 0, goldfish: 10
Sue 306: trees: 4, perfumes: 2, cars: 7
Sue 307: cars: 6, vizslas: 2, children: 6
Sue 308: vizslas: 2, cars: 0, akitas: 7
Sue 309: cars: 3, vizslas: 8, perfumes: 6
Sue 310: goldfish: 7, perfumes: 7, vizslas: 3
Sue 311: pomeranians: 10, trees: 2, cars: 0
Sue 312: samoyeds: 2, vizslas: 9, akitas: 1
Sue 313: cars: 4, pomeranians: 7, goldfish: 7
Sue 314: akitas: 2, pomeranians: 9, samoyeds: 10
Sue 315: akitas: 3, vizslas: 2, trees: 0
Sue 316: cars: 0, perfumes: 4, pomeranians: 6
Sue 317: akitas: 10, goldfish: 3, pomeranians: 7
Sue 318: cars: 9, trees: 0, pomeranians: 9
Sue 319: akitas: 3, vizslas: 7, children: 10
Sue 320: vizslas: 0, akitas: 8, pomeranians: 4
Sue 321: cars: 10, akitas: 9, vizslas: 3
Sue 322: perfumes: 0, akitas: 8, vizslas: 6
Sue 323: vizslas: 10, perfumes: 5, cars: 3
Sue 324: akitas: 0, goldfish: 6, vizslas: 7
Sue 325: perfumes: 9, vizslas: 5, pomeranians: 2
Sue 326: vizslas: 6, goldfish: 10, pomeranians: 8
Sue 327: vizslas: 10, cars: 1, akitas: 7
Sue 328: trees: 1, perfumes: 10, cars: 10
Sue 329: pomeranians: 5, samoyeds: 3, cars: 10
Sue 330: akitas: 6, cars: 1, pomeranians: 4
Sue 331: cars: 5, children: 2, trees: 0
Sue 332: vizslas: 6, pomeranians: 1, perfumes: 0
Sue 333: akitas: 7, trees: 1, cats: 9
Sue 334: vizslas: 6, goldfish: 9, akitas: 7
Sue 335: akitas: 3, samoyeds: 3, cars: 3
Sue 336: samoyeds: 10, perfumes: 9, trees: 6
Sue 337: vizslas: 2, cars: 9, akitas: 0
Sue 338: akitas: 6, perfumes: 9, vizslas: 3
Sue 339: cars: 3, samoyeds: 8, trees: 2
Sue 340: cats: 7, perfumes: 8, cars: 9
Sue 341: goldfish: 9, perfumes: 5, cars: 10
Sue 342: trees: 0, akitas: 3, perfumes: 5
Sue 343: perfumes: 2, children: 0, cars: 6
Sue 344: goldfish: 8, trees: 8, perfumes: 0
Sue 345: perfumes: 6, cars: 6, goldfish: 5
Sue 346: vizslas: 8, trees: 1, cars: 6
Sue 347: cars: 0, cats: 3, perfumes: 7
Sue 348: children: 7, perfumes: 10, cars: 7
Sue 349: pomeranians: 8, akitas: 5, children: 2
Sue 350: perfumes: 9, pomeranians: 4, goldfish: 3
Sue 351: perfumes: 8, pomeranians: 7, trees: 4
Sue 352: samoyeds: 1, goldfish: 9, akitas: 8
Sue 353: akitas: 6, goldfish: 10, vizslas: 8
Sue 354: akitas: 7, cars: 2, goldfish: 6
Sue 355: cars: 3, goldfish: 6, akitas: 5
Sue 356: akitas: 2, goldfish: 9, pomeranians: 1
Sue 357: goldfish: 10, cars: 6, pomeranians: 9
Sue 358: trees: 0, children: 2, goldfish: 6
Sue 359: samoyeds: 3, cars: 2, akitas: 4
Sue 360: trees: 1, goldfish: 8, cars: 5
Sue 361: akitas: 5, vizslas: 7, perfumes: 1
Sue 362: cats: 5, vizslas: 9, children: 4
Sue 363: goldfish: 9, perfumes: 3, vizslas: 9
Sue 364: children: 7, samoyeds: 2, pomeranians: 10
Sue 365: perfumes: 9, akitas: 10, pomeranians: 4
Sue 366: cars: 10, trees: 3, cats: 4
Sue 367: vizslas: 6, akitas: 10, perfumes: 5
Sue 368: akitas: 9, vizslas: 9, children: 4
Sue 369: goldfish: 8, trees: 2, perfumes: 5
Sue 370: trees: 0, children: 4, cars: 8
Sue 371: cats: 6, perfumes: 0, vizslas: 2
Sue 372: akitas: 7, cars: 5, perfumes: 3
Sue 373: cars: 0, perfumes: 4, pomeranians: 10
Sue 374: akitas: 5, perfumes: 5, vizslas: 2
Sue 375: goldfish: 7, trees: 10, pomeranians: 7
Sue 376: cars: 8, trees: 1, pomeranians: 8
Sue 377: cars: 0, akitas: 9, vizslas: 1
Sue 378: akitas: 5, perfumes: 3, vizslas: 7
Sue 379: trees: 2, goldfish: 8, pomeranians: 8
Sue 380: akitas: 5, cars: 9, perfumes: 9
Sue 381: cars: 2, perfumes: 6, trees: 3
Sue 382: perfumes: 6, vizslas: 2, goldfish: 9
Sue 383: akitas: 8, vizslas: 7, cats: 1
Sue 384: akitas: 9, trees: 10, vizslas: 7
Sue 385: cars: 0, perfumes: 7, vizslas: 2
Sue 386: vizslas: 10, akitas: 4, perfumes: 9
Sue 387: perfumes: 6, pomeranians: 5, samoyeds: 8
Sue 388: vizslas: 10, trees: 9, goldfish: 9
Sue 389: goldfish: 8, akitas: 4, perfumes: 10
Sue 390: goldfish: 6, trees: 8, akitas: 1
Sue 391: vizslas: 4, akitas: 10, goldfish: 7
Sue 392: akitas: 1, vizslas: 6, samoyeds: 5
Sue 393: trees: 6, cars: 3, akitas: 5
Sue 394: goldfish: 9, trees: 3, cars: 5
Sue 395: akitas: 6, samoyeds: 4, goldfish: 4
Sue 396: akitas: 2, trees: 1, cats: 5
Sue 397: cars: 0, children: 9, trees: 10
Sue 398: pomeranians: 3, samoyeds: 9, goldfish: 10
Sue 399: cars: 7, akitas: 4, goldfish: 8
Sue 400: cars: 4, akitas: 5, vizslas: 4
Sue 401: pomeranians: 5, akitas: 8, vizslas: 5
Sue 402: cats: 7, cars: 6, goldfish: 6
Sue 403: samoyeds: 8, perfumes: 4, cars: 5
Sue 404: akitas: 10, goldfish: 4, trees: 2
Sue 405: trees: 8, perfumes: 1, cars: 2
Sue 406: trees: 0, perfumes: 9, pomeranians: 10
Sue 407: perfumes: 4, trees: 7, goldfish: 3
Sue 408: akitas: 1, perfumes: 3, cars: 5
Sue 409: trees: 6, samoyeds: 3, cars: 9
Sue 410: vizslas: 3, goldfish: 5, akitas: 7
Sue 411: goldfish: 10, trees: 1, vizslas: 9
Sue 412: cars: 0, akitas: 6, trees: 6
Sue 413: goldfish: 7, trees: 0, cars: 3
Sue 414: pomeranians: 10, samoyeds: 3, cars: 10
Sue 415: perfumes: 6, trees: 9, cars: 4
Sue 416: trees: 2, cars: 4, goldfish: 8
Sue 417: goldfish: 2, cars: 9, cats: 5
Sue 418: vizslas: 1, cars: 9, akitas: 0
Sue 419: perfumes: 6, cats: 3, children: 9
Sue 420: cats: 5, goldfish: 7, akitas: 9
Sue 421: trees: 1, samoyeds: 6, pomeranians: 1
Sue 422: trees: 10, goldfish: 6, children: 7
Sue 423: cars: 8, goldfish: 7, vizslas: 3
Sue 424: samoyeds: 9, akitas: 7, trees: 5
Sue 425: akitas: 5, children: 4, perfumes: 9
Sue 426: goldfish: 1, children: 9, cats: 2
Sue 427: vizslas: 9, akitas: 7, goldfish: 9
Sue 428: pomeranians: 7, akitas: 5, vizslas: 1
Sue 429: vizslas: 7, goldfish: 7, cars: 9
Sue 430: trees: 7, perfumes: 0, pomeranians: 5
Sue 431: children: 9, perfumes: 5, vizslas: 7
Sue 432: trees: 6, samoyeds: 7, cats: 1
Sue 433: goldfish: 5, trees: 5, children: 6
Sue 434: goldfish: 9, akitas: 7, cars: 3
Sue 435: samoyeds: 10, perfumes: 2, cars: 0
Sue 436: akitas: 5, pomeranians: 4, perfumes: 7
Sue 437: vizslas: 5, cats: 6, perfumes: 5
Sue 438: trees: 2, goldfish: 6, vizslas: 7
Sue 439: samoyeds: 8, pomeranians: 10, goldfish: 1
Sue 440: akitas: 6, children: 9, perfumes: 4
Sue 441: cars: 2, goldfish: 9, children: 0
Sue 442: goldfish: 7, cars: 2, vizslas: 8
Sue 443: goldfish: 6, samoyeds: 3, perfumes: 2
Sue 444: trees: 2, goldfish: 7, cars: 8
Sue 445: trees: 2, pomeranians: 0, children: 0
Sue 446: perfumes: 4, akitas: 4, goldfish: 6
Sue 447: vizslas: 7, akitas: 9, cars: 3
Sue 448: goldfish: 6, trees: 9, cars: 0
Sue 449: samoyeds: 7, perfumes: 4, vizslas: 10
Sue 450: akitas: 7, cars: 10, goldfish: 7
Sue 451: goldfish: 4, children: 7, pomeranians: 4
Sue 452: cats: 4, vizslas: 6, trees: 7
Sue 453: cars: 1, trees: 10, goldfish: 9
Sue 454: trees: 2, goldfish: 3, vizslas: 10
Sue 455: pomeranians: 9, vizslas: 3, akitas: 2
Sue 456: vizslas: 10, akitas: 2, goldfish: 1
Sue 457: trees: 5, cats: 5, children: 8
Sue 458: cars: 6, goldfish: 3, akitas: 9
Sue 459: goldfish: 7, akitas: 2, cats: 7
Sue 460: akitas: 1, cars: 5, children: 8
Sue 461: cars: 8, perfumes: 0, goldfish: 6
Sue 462: pomeranians: 6, cats: 2, perfumes: 6
Sue 463: vizslas: 7, perfumes: 3, goldfish: 3
Sue 464: akitas: 10, goldfish: 10, trees: 1
Sue 465: vizslas: 0, akitas: 2, trees: 2
Sue 466: perfumes: 6, akitas: 8, cars: 2
Sue 467: goldfish: 1, cars: 10, perfumes: 3
Sue 468: goldfish: 4, trees: 2, cars: 9
Sue 469: perfumes: 6, pomeranians: 0, vizslas: 10
Sue 470: samoyeds: 8, children: 0, akitas: 7
Sue 471: children: 3, goldfish: 9, cats: 9
Sue 472: samoyeds: 0, goldfish: 0, trees: 0
Sue 473: trees: 3, goldfish: 4, vizslas: 1
Sue 474: perfumes: 10, cars: 3, trees: 7
Sue 475: akitas: 5, vizslas: 4, goldfish: 5
Sue 476: children: 2, akitas: 7, vizslas: 3
Sue 477: vizslas: 6, pomeranians: 9, trees: 6
Sue 478: vizslas: 7, pomeranians: 6, akitas: 7
Sue 479: trees: 2, perfumes: 2, children: 2
Sue 480: cars: 8, cats: 5, vizslas: 0
Sue 481: trees: 5, goldfish: 0, akitas: 3
Sue 482: cars: 8, perfumes: 6, goldfish: 10
Sue 483: goldfish: 0, cars: 3, perfumes: 10
Sue 484: pomeranians: 1, samoyeds: 1, perfumes: 3
Sue 485: trees: 0, akitas: 2, vizslas: 4
Sue 486: cars: 3, vizslas: 8, goldfish: 1
Sue 487: pomeranians: 9, vizslas: 2, children: 10
Sue 488: akitas: 6, vizslas: 10, perfumes: 9
Sue 489: goldfish: 6, vizslas: 4, cars: 2
Sue 490: vizslas: 10, cats: 8, samoyeds: 1
Sue 491: cats: 9, cars: 1, perfumes: 10
Sue 492: goldfish: 6, cars: 9, pomeranians: 9
Sue 493: children: 10, goldfish: 10, vizslas: 0
Sue 494: pomeranians: 5, cars: 0, vizslas: 0
Sue 495: vizslas: 7, perfumes: 6, samoyeds: 3
Sue 496: trees: 1, cats: 4, cars: 10
Sue 497: cats: 1, perfumes: 0, cars: 7
Sue 498: perfumes: 7, vizslas: 6, cats: 9
Sue 499: vizslas: 8, perfumes: 1, akitas: 3
Sue 500: perfumes: 4, cars: 9, trees: 4"""

good = Dict{ASCIIString, Int64}()
for l in split("""
children: 3
cats: 7
samoyeds: 2
pomeranians: 3
akitas: 0
vizslas: 0
goldfish: 5
trees: 3
cars: 2
perfumes: 1""", "\n")
	items = split(l)
	good[items[1][1:end-1]] = parse(Int, items[2])
end

sueList = Dict{ASCIIString, Dict{ASCIIString, Int64}}()
for line in split(inpt, "\n")
	items = split(line*",")
	sueProps = Dict{ASCIIString, Int64}()
	for i in 3:2:length(items)
		sueProps[items[i][1:end-1]] = parse(Int, items[i+1][1:end-1])
	end
	sueList[items[2][1:end-1]] = sueProps
end

function pred(k, v)
	for (gk, gv) in good
		value = get(v, gk, "forgot")
		if value == "forgot"
			continue
		end
		# part 1
		# if value != gv
		# 	return false
		# end

		# part 2
		if gk in ["cats", "trees"]
			if value <= gv
				return false
			end
		elseif gk in ["pomeranians", "goldfish"]
			if value >= gv
				return false
			end
		else
			if value != gv
				return false
			end
		end
	end
	return true
end

println(filter(pred, sueList))

max_stars_repo_name: jstrube/adventofcode

max_issues_repo_name: jstrube/adventofcode

max_forks_repo_name: jstrube/adventofcode


text:
extractargs!(arguments::Vector{Symbol}, defined::Set, sym, mod) = nothing
function extractargs!(arguments::Vector{Symbol}, defined::Set, sym::Symbol, mod)
  if ((sym ∉ defined) && sym ∉ (:nothing, :(+), :(*), :(-), :(/), :(÷), :(<<), :(>>), :(>>>), :zero, :one)) && !Base.isdefined(mod, sym)
    push!(defined, sym)
    push!(arguments, sym)
  end
  nothing
end
function define_tup!(defined::Set, ex::Expr)
  for a ∈ ex.args
    if a isa Symbol
      push!(defined, a)
    else
      define_tup!(defined, a)
    end
  end
end
function define!(defined::Set, s)
  if s isa Symbol
    push!(defined, s)
  else
    define_tup!(defined, s::Expr)
  end
end
function define_induction_variables!(defined::Set, ex::Expr) # add `i` in `for i ∈ looprange` to `defined`
  ex.head === :for || return
  loops = ex.args[1]
  if loops.head === :block
    for loop ∈ loops.args
      define!(defined, loop.args[1])
    end
  else
    define!(defined, loops.args[1])
  end
end

depends_on_defined(defined::Set, f)::Bool = false
depends_on_defined(defined::Set, f::Function)::Bool = f === Threads.threadid
depends_on_defined(defined::Set, f::QuoteNode) = f.value === :threadid
depends_on_defined(defined::Set, f::Symbol)::Bool = (f ∈ defined) || (f === :threadid)
function depends_on_defined(defined::Set, f::Expr)::Bool
  for a ∈ f.args
    depends_on_defined(defined, a) && return true
  end
  false
end
function extractargs!(arguments::Vector{Symbol}, defined::Set, expr::Expr, mod)
  define_induction_variables!(defined, expr)
  head = expr.head
  args = expr.args
  startind = 1
  if head === :call
    # (length(args) === 3) && args[1] ===
    startind = 2
  elseif head === :(=)
    arg1 = first(args)
    if arg1 isa Symbol
      push!(defined, arg1)
    elseif Meta.isexpr(arg1, :tuple)
      define_tup!(defined, arg1)
    end
  elseif head ∈ (:inbounds, :loopinfo)#, :(->))
    return
  elseif head === :(.)
    extractargs!(arguments, defined, args[1], mod)
    return
  elseif head === :(->)
    td = copy(defined)
    define!(td, args[1])
    extractargs!(arguments, td, args[1], mod)
    extractargs!(arguments, td, args[2], mod)
    return
  end
  for i ∈ startind:length(args)
    extractargs!(arguments, defined, args[i], mod)
  end
end

static_literals!(s::Symbol) = s
function static_literals!(q::Expr)
  for (i,ex) ∈ enumerate(q.args)
    if ex isa Integer
      q.args[i] = StaticInt(ex)
    elseif ex isa Expr
      static_literals!(ex)
    end
  end
  q
end
function maybestatic!(expr::Expr)::Expr
  if expr.head === :call
    f = first(expr.args)
    if f === :length
      expr.args[1] = static_length
    elseif f === :size && length(expr.args) == 3
      i = expr.args[3]
      if i isa Integer
        expr.args[1] = size
        expr.args[3] = StaticInt(i)
      end
    else
      static_literals!(expr)
    end
  end
  esc(expr)
end
function enclose(exorig::Expr, reserve_per, minbatchsize, per::Symbol, mod)
  Meta.isexpr(exorig, :for, 2) || throw(ArgumentError("Expression invalid; should be a for loop."))
  ex = copy(exorig)
  loop_sym = Symbol("##LOOP##")
  loopstart = Symbol("##LOOPSTART##")
  loop_step = Symbol("##LOOP_STEP##")
  loop_stop = Symbol("##LOOP_STOP##")
  iter_leng = Symbol("##ITER_LENG##")
  loop_offs = Symbol("##LOOPOFFSET##")

  arguments = Symbol[]#loop_offs, loop_step]
  defined = Set((loop_offs, loop_step));
  define_induction_variables!(defined, ex)
  if ex.args[1].head === :block
    for i ∈ 2:length(ex.args[1].args)
      extractargs!(arguments, defined, ex.args[1].args[i], mod)
    end
  end
  for i ∈ 2:length(ex.args)
    extractargs!(arguments, defined, ex.args[i], mod)
  end
  firstloop = ex.args[1]
  if firstloop.head === :block
    firstloop = firstloop.args[1]
  end
  loop = firstloop.args[2]
  firstloop.args[2] = Expr(:call, GlobalRef(Base, :(:)), loopstart, loop_step, loop_stop)
  # typexpr_incomplete is missing `funcs`
  q = quote
    $loop_sym = $(maybestatic!(loop))
    $iter_leng = static_length($loop_sym)
    $loop_step = $static_step($loop_sym)
    $loop_offs = $static_first($loop_sym)
  end
  threadtup = Expr(:tuple, iter_leng)
  num_thread_expr = Expr(:call, num_threads)
  if per === :core
    num_thread_expr = Expr(:call, min, num_thread_expr, Expr(:call, num_cores))
  end
  if minbatchsize isa Integer && minbatchsize ≤ 1
    if reserve_per ≤ 0
      push!(threadtup.args, :(min($iter_leng, $num_thread_expr)))
    else
      push!(threadtup.args, :(min($iter_leng, cld($num_thread_expr, $reserve_per))), reserve_per)
    end
  else
    il = :(div($iter_leng, $(minbatchsize isa Int ? StaticInt(minbatchsize) : esc(minbatchsize))))
    if reserve_per ≤ 0
      push!(threadtup.args, :(min($il, $num_thread_expr)))
    else
      push!(threadtup.args, :(min($il, cld($num_thread_expr, $reserve_per))), reserve_per)
    end
  end
  closure = Symbol("##closure##")
  args = Expr(:tuple, Symbol("##LOOPOFFSET##"), Symbol("##LOOP_STEP##"))
  closureq = quote
    $closure = let
      @inline ($args, var"##SUBSTART##"::Int, var"##SUBSTOP##"::Int) -> begin
        var"##LOOPSTART##" = var"##SUBSTART##" * var"##LOOP_STEP##" + var"##LOOPOFFSET##" - var"##LOOP_STEP##"
        var"##LOOP_STOP##" = var"##SUBSTOP##" * var"##LOOP_STEP##" + var"##LOOPOFFSET##" - var"##LOOP_STEP##"
        @inbounds begin
          $ex
        end
        nothing
      end
    end
  end
  push!(q.args, esc(closureq))
  batchcall = Expr(:call, batch, esc(closure), threadtup, Symbol("##LOOPOFFSET##"), Symbol("##LOOP_STEP##"))
  for a ∈ arguments
    push!(args.args, a)
    push!(batchcall.args, esc(a))
  end
  push!(q.args, batchcall)
  quote
    if $num_threads() == 1
      let
        $(esc(exorig))
      end
    else
      let
        $q
      end
    end
  end
end

"""
    @batch for i in Iter; ...; end

Evaluate the loop on multiple threads.

    @batch minbatch=N for i in Iter; ...; end

Evaluate at least N iterations per thread. Will use at most `length(Iter) ÷ N` threads.

    @batch per=core for i in Iter; ...; end
    @batch per=thread for i in Iter; ...; end

Use at most 1 thread per physical core, or 1 thread per CPU thread, respectively.
One thread per core will mean less threads competing for the cache, while (for example) if
there are two hardware threads per physical core, then using each thread means that there
are two independent instruction streams feeding the CPU's execution units. When one of
these streams isn't enough to make the most of out of order execution, this could increase
total throughput.

Which performs better will depend on the workload, so if you're not sure it may be worth
benchmarking both.

LoopVectorization.jl currently only uses up to 1 thread per physical core. Because there
is some overhead to switching the number of threads used, `per=core` is `@batch`'s default,
so that `Polyester.@batch` and `LoopVectorization.@tturbo` work well together by default.

You can pass both `per=(core/thread)` and `minbatch=N` options at the same time, e.g.

    @batch per=thread minbatch=2000 for i in Iter; ...; end
    @batch minbatch=5000 per=core   for i in Iter; ...; end
"""
macro batch(ex)
  enclose(macroexpand(__module__, ex), 0, 1, :core, __module__)
end
function interpret_kwarg(arg, reserve_per = 0, minbatch = 1, per = :core)
  a = arg.args[1]
  v = arg.args[2]
  if a === :reserve
    @assert v ≥ 0
    reserve_per = v
  elseif a === :minbatch
    minbatch = v
  elseif a === :per
    per = v::Symbol
    @assert (per === :core) | (per === :thread)
  else
    throw(ArgumentError("kwarg $(a) not recognized."))
  end
  reserve_per, minbatch, per
end
macro batch(arg1, ex)
  reserve, minbatch, per = interpret_kwarg(arg1)
  enclose(macroexpand(__module__, ex), reserve, minbatch, per, __module__)
end
macro batch(arg1, arg2, ex)
  reserve, minbatch, per = interpret_kwarg(arg1)
  reserve, minbatch, per = interpret_kwarg(arg2, reserve, minbatch, per)
  enclose(macroexpand(__module__, ex), reserve, minbatch, per, __module__)
end
macro batch(arg1, arg2, arg3, ex)
  reserve, minbatch, per = interpret_kwarg(arg1)
  reserve, minbatch, per = interpret_kwarg(arg2, reserve, minbatch, per)
  reserve, minbatch, per = interpret_kwarg(arg2, reserve, minbatch, per)
  enclose(macroexpand(__module__, ex), reserve, minbatch, per, __module__)
end


text:
module TracyWidom

using SpecialFunctions, FastGaussQuadrature

export TWcdf

function TWcdf(s::Real; beta::Integer=2, num_points::Integer=25)
    beta ∈ (1,2,4) || throw(ArgumentError("Beta must be 1, 2, or 4"))
    quad = gausslegendre(num_points)
    _TWcdf(s, beta, quad)
end

function TWcdf(s_vals::AbstractArray{T}; beta::Integer=2, num_points::Integer=25) where {T<:Real}
    beta ∈ (1,2,4) || throw(ArgumentError("Beta must be 1, 2, or 4"))
    quad = gausslegendre(num_points)
    [_TWcdf(s, beta, quad) for s in s_vals]
end

function _TWcdf(s::Real, beta::Integer, quad::Tuple{Array{T,1},Array{T,1}}) where {T<:Real}
    if beta == 2
        kernel = ((ξ,η) -> _K2tilde(ξ,η,s))
        return _fredholm_det(kernel, quad)
    elseif beta == 1
        kernel = ((ξ,η) -> _K1tilde(ξ,η,s))
        return _fredholm_det(kernel, quad)
    elseif beta ==4
        # This is from http://iopscience.iop.org/article/10.1088/0305-4470/38/33/L02/meta
        kernel2 = ((ξ,η) -> _K2tilde(ξ,η,s*sqrt(2)))
        kernel1 = ((ξ,η) -> _K1tilde(ξ,η,s*sqrt(2)))
        F2 = _fredholm_det(kernel2, quad)
        F1 = _fredholm_det(kernel1, quad)
        return (F1 + F2/F1) / 2
    end
end

function _fredholm_det(kernel::Function, quad::Tuple{Array{T,1},Array{T,1}}) where {T<:Real}
    nodes, weights = quad
    N = length(nodes)
    sqrt_weights = sqrt.(weights)
    weights_matrix = kron(transpose(sqrt_weights),sqrt_weights)
    K_matrix = [kernel(ξ,η) for ξ in nodes, η in nodes]
    det(eye(N) - weights_matrix .* K_matrix)
end

function _airy_kernel(x, y)
    if x==y
        return (airyaiprime(x))^2 - x * (airyai(x))^2
    else
        return (airyai(x) * airyaiprime(y) - airyai(y) * airyaiprime(x)) / (x - y)
    end
end

_ϕ(ξ, s) =  s + 10*tan(π*(ξ+1)/4)
_ϕprime(ξ) = (5π/2)*(sec(π*(ξ+1)/4))^2
_K2tilde(ξ,η,s) = sqrt(_ϕprime(ξ) * _ϕprime(η)) * _airy_kernel(_ϕ(ξ,s), _ϕ(η,s))

# For the GOE Tracy-Widom
_A_kernel(x,y) = airyai((x+y)/2) / 2
_K1tilde(ξ,η,s) = sqrt(_ϕprime(ξ) * _ϕprime(η)) * _A_kernel(_ϕ(ξ,s), _ϕ(η,s))

end # module

max_stars_repo_name: AustenLamacraft/TracyWidom

max_issues_repo_name: AustenLamacraft/TracyWidom

max_forks_repo_name: AustenLamacraft/TracyWidom


text:
function serialize_websocket(io::IO, message)
    serialize_binary(io, message)
end

function serialize_binary(io, @nospecialize(obj))
    data = serialize_js(obj) # apply custom, overloadable transformation
    write(io, MsgPack.pack(data))
end

function js_type(type::Symbol, @nospecialize(x))
    return Dict(
        :__javascript_type__ => type,
        :payload => x
    )
end

serialize_js(@nospecialize(x)) = x

function serialize_js(x::Vector{T}) where {T<:Number}
    return js_type(:typed_vector, x)
end

function serialize_js(jso::JSObject)
    return js_type(:JSObject, uuidstr(jso))
end

function serialize_js(x::Union{AbstractArray, Tuple})
    return map(serialize_js, x)
end

function serialize_js(dict::AbstractDict)
    result = Dict()
    for (k, v) in dict
        result[k] = serialize_js(v)
    end
    return result
end

serialize_js(jss::JSString) = jss.source

function serialize_js(jsc::Union{JSCode, JSString})
    return js_type(:js_code, serialize_readable(jsc))
end

serialize_readable(@nospecialize(x)) = sprint(io-> serialize_readable(io, x))
serialize_readable(io::IO, @nospecialize(object)) = JSON3.write(io, object)
serialize_readable(io::IO, x::JSString) = print(io, x.source)

function serialize_readable(io::IO, jsc::JSCode)
    for elem in jsc.source
        serialize_readable(io, elem)
    end
end

function serialize_readable(io::IO, jsss::AbstractVector{JSCode})
    for jss in jsss
        serialize_readable(io, jss)
        println(io)
    end
end

# Since there is no easy way to mess with JSON3 printer, we print
# Vectors & Dictionaries ourselves, so that we cann apply serialize_readable recursively
function serialize_readable(io::IO, vector::AbstractArray{T}) where {T<:Number}
    JSON3.write(io, vector)
end

function serialize_readable(io::IO, vector::AbstractVector{T}) where {T<:Number}
    JSON3.write(io, vector)
end

function serialize_readable(io::IO, vector::Union{AbstractVector, Tuple})
    print(io, '[')
    for (i, element) in enumerate(vector)
        serialize_readable(io, element)
        (i == length(vector)) || print(io, ',') # dont print for last item
    end
    print(io, ']')
end

function serialize_readable(io::IO, dict::Union{NamedTuple, AbstractDict})
    print(io, '{')
    for (i, (key, value)) in enumerate(pairs(dict))
        serialize_readable(io, key); print(io, ':')
        serialize_readable(io, value)
        (i == length(dict)) || print(io, ',') # dont print for last item
    end
    print(io, '}')
end

function serialize_readable(io::IO, jso::JSObject)
    serialize_readable(io, js"get_heap_object($(uuidstr(jso)))")
end

function serialize_readable(io::IO, assets::Set{Asset})
    for asset in assets
        serialize_readable(io, asset)
        println(io)
    end
end

function serialize_readable(io::IO, asset::Asset)
    if mediatype(asset) == :js
        println(
            io,
            "<script src='$(url(asset))'></script>"
        )
    elseif mediatype(asset) == :css
        println(
            io,
            "<link href = $(repr(url(asset))) rel = \"stylesheet\",  type=\"text/css\">"
        )
    else
        error("Unrecognized asset media type: $(mediatype(asset))")
    end
end

function serialize_readable(io::IO, dependency::Dependency)
    print(io, dependency.name)
end

serialize_readable(io::IO, x::Observable) = print(io, "'", x.id, "'")

# Handle interpolating into Javascript
function serialize_readable(io::IO, node::Node)
    # This relies on jsrender to give each node a unique id under the
    # attribute data-jscall-id. This is a bit brittle
    # improving this would be nice
    print(io, "(document.querySelector('[data-jscall-id=$(repr(uuid(node)))]'))")
end

# TODO move to msgpack
MsgPack.msgpack_type(::Type{Float16}) = MsgPack.FloatType()
MsgPack.to_msgpack(::MsgPack.FloatType, x::Float16) = Float32(x)
JSON3.StructType(::Type{Hyperscript.Node{Hyperscript.HTMLSVG}}) = JSON3.ObjectType()
MsgPack.msgpack_type(::Type{Hyperscript.Node{Hyperscript.HTMLSVG}}) = MsgPack.MapType()

function MsgPack.to_msgpack(::MsgPack.MapType, node::Hyperscript.Node{Hyperscript.HTMLSVG})
    return JSON3.keyvaluepairs(node)
end

function JSON3.keyvaluepairs(node::Hyperscript.Node{Hyperscript.HTMLSVG})
    return [
        :tag => getfield(node, :tag),
        :children => getfield(node, :children),
        getfield(node, :attrs)...
    ]
end

function Base.show(io::IO, jsc::JSCode)
    serialize_readable(io, jsc)
end


text:
using MakieGallery, AbstractPlotting, GLMakie, Test

tested_diff_path = joinpath(@__DIR__, "tested_different")
test_record_path = joinpath(@__DIR__, "test_recordings")
isdir(tested_diff_path) && rm(tested_diff_path, force = true, recursive = true)
mkpath(tested_diff_path)
isdir(test_record_path) && rm(test_record_path, force = true, recursive = true)
mkpath(test_record_path)

abstractplotting_test_dir = joinpath(dirname(pathof(AbstractPlotting)), "..", "test", "reference_image_tests")
abstractplotting_tests = joinpath.(abstractplotting_test_dir, readdir(abstractplotting_test_dir))
# Add GLMakie specific tests
push!(abstractplotting_tests, joinpath(@__DIR__, "glmakie_tests.jl"))
database = MakieGallery.load_database(abstractplotting_tests)

examples = MakieGallery.record_examples(test_record_path)
@test length(examples) == length(database)
MakieGallery.run_comparison(test_record_path, tested_diff_path)


text:
module Shorthands

# Write your package code here.
include("show_all.jl")
export show_all
end