text:
# # Chapter 3 - 数学のおさらい

## #src
# ## 3.1 線形代数
# ### 3.1.1 スカラーとベクトル
## 列ベクトル: 2行1列のArrayを定義
## Juliaはcolumn-major
w = [5.0, 3.0]

## #src
## 行ベクトル
#-
## 行ベクトル: 1行2列
x = [5.0 3.0]

## #src
#-
## すべての要素が0の1行5列のArrayを生成
x_zeros = zeros(1, 5)

## #src
#-
## すべての要素が1の1行5列のArrayを生成
x_ones = ones(1, 5)

## #src
#-
## 一様分布または正規分布にしたがってランダムに1行5列のArrayを生成
using Random
Random.seed!(1234)

## 一様分布
uniform = rand(1, 5)

## #src
#-
## 正規分布
normal = randn(1, 5)

## #src
#-
## 標準出力
for s in (:w, :x, :x_zeros, :x_ones, :uniform, :normal)
    y = eval(s)
    println("ベクトル $(s)) 形: $(size(y)), 要素の型:$(eltype(y))\n$(y)\n")
end

## #src
### 3.1.2 ベクトルの内積
## 列ベクトル: 2行1列のArrayを定義
w = [5.0, 3.0]

## 行ベクトル: 1行2列
x = [1.0 5.0]

## 内積の計算
## \cdot
using LinearAlgebra
xw = x ⋅ w

## #src
#-
## wのノルムの計算: wの転置(行ベクトル)とw(列ベクトル)の掛け算
ww = transpose(w) ⋅ w

## #src
#-
## ノルムを計算する関数が用意されている
norm(w)

## #src
#-
println("xとwの内積) 形: $(size(xw)), 型:$(typeof(xw))\n$(xw)\n")
println("wのノルム) 形: $(size(ww)), 型:$(typeof(ww))\n$(ww)\n")

## #src
# ### 3.1.5 行列とベクトルの関係
## 行列: 3行2列のArrayを定義
X = [1.0 2.0; 2.0 4.0; 3.0 6.0]

## #src
#-
## 1行目の行ベクトル(1行2列)の取り出し
Xrow1 = X[[1], :]

## #src
#-
## 2列目の列ベクトル(3行1列)の取り出し
Xcol2 = X[:, [2]]

## #src
#-
## 標準出力
println("行列X) 形:$(size(X)), 要素の型:$(eltype(X))\n$(X)\n")
println("1行目) 形:$(size(Xrow1)), 要素の型:$(eltype(Xrow1))\n$(Xrow1)\n")
println("2列目) 形:$(size(Xcol2)), 要素の型:$(eltype(Xcol2))\n$(Xcol2)\n")

## #src
#-
## リストなしの場合
X[1, :]

## #src
#-
## リストありの場合
X[[1], :]

## #src
# ### 3.1.6 行列の積と和
## 行列 X: 3行2列のArrayを定義
X = [1.0 2.0; 2.0 4.0; 3.0 6.0]

## 列ベクトル b: 2行1列のArrayを定義
w = [5.0, 3.0]

## 列ベクトル b: 3行1列のArrayを定義
b = [1.0, 1.0, 1.0]

## 行列とベクトルの積と和
res = X * w .+ b
println("積和の結果 \n$(res)")

## #src
# ### 3.1.8 行列の階数
## 行列: 2行2列のArrayを定義
A = [6.0 2.0; 2.0 5.0]
B = [6.0 3.0; 2.0 1.0]

## 行列のランクの計算
println("Rank of A: $(rank(A))")
println("Rank of B: $(rank(B))")

## #src
#-
function find_inv(mat)
    if rank(mat) == size(mat)[1]
        println("行列:\n$(mat)\nランク$(rank(mat))\n逆行列:\n$(inv(mat))\n")
    else
        println("行列:\n$(mat)\nランク$(rank(mat))\n特異行列")
    end
end

find_inv(A)
find_inv(B)

## #src
# ### 3.1.10 行列と行列式の関係
## 行列: 2行2列のArrayを定義
A = [6.0 2.0; 2.0 5.0]
B = [6.0 3.0; 2.0 1.0]

## 行列式の計算
println("行列Aの行列式: $(det(A))")
println("行列Bの行列式: $(det(B))")

## #src
# ### 3.1.12 固有値問題の解法
## 行列Aの定義
A = [3 2; 4 1]

## 固有値問題の解
eig_A = eigen(A)

## #src
# ### 3.1.13 固有値と固有ベクトルの性質
## 行列Aの定義
A = [3 1; 1 3]

## 固有値・固有ベクトル
eig_A = eigen(A)

println("行列Aの固有値:\n$(eig_A.values)")
println("行列Aの固有ベクトル:\n$(eig_A.vectors)")
println("固有ベクトルの内積:$(eig_A.vectors[:, 1] ⋅ eig_A.vectors[:, 2])")
println("固有値の和:$(sum(eig_A.values))")
println("行列Aのトレース(対角成分の和):$(tr(A))")
println("固有値の積:$(prod(eig_A.values))")
println("行列Aの行列式:$(det(A))")
println("固有ベクトルがなす行列の逆行列:\n$(eig_A.vectors)")
println("固有ベクトルがなす行列の転置行列:\n$(eig_A.vectors')")

## #src
# ## 3.2 最適化
## 行列Aの定義
A = [2 -3; 4 1]

## 列ベクトルbの定義
b = [5, -2]

## #src
#-
## 行列が非ゼロか否かを確認
if det(A) != 0
    ## Aの逆行列とベクトルbの積から解を求める
    w = inv(A) * b
    println("wの解\n$(w)")
else
    ## 解が存在しない
    println("解が存在しません.")
end

## #src
#-
# ### 3.2.2 微分を用いた解放
## 最急降下法による最適化
## 学習率の設定
α = 0.2

## パラメーターの初期化
w = 1

for ite in 1:50
    println("反復$(ite), w=$(round(w; digits = 2))")
    ## 最急降下法によるパラメーターの更新
    global w-= α * 3 * w^2
end

## #src
#-
### 3.3.2 ベルヌーイ分布
## p=6/13(青色のボールの確率)のベルヌーイ分布に従って10回試行を行う
using Distributions

b = Bernoulli(6/13)

X1 = rand(b, 10)
X2 = rand(b, 10)
X3 = rand(b, 10)

## 標準出力
println("データ X1:\n$(X1)")
println("データ X2:\n$(X2)")
println("データ X3:\n$(X3)")

## #src
### 3.3.9 正規分布
## 平均0, 分散1の正規分布に従って10回試行を行う
X1 = rand(Normal(0, 1), 10)
## 平均3, 分散1の正規分布に従って10回試行を行う
X2 = rand(Normal(3, 1), 10)
## 平均-3, 分散1の正規分布に従って10回試行を行う
X3 = rand(Normal(-3, 1), 10)

## 標準出力
println("データ X1:\n$(X1)")
println("データ X2:\n$(X2)")
println("データ X3:\n$(X3)")

## #src
# ## 3.4 統計
# ### 3.4.1 中心の統計量
## 3種類(身長、体重、胸囲)のデータを格納する8行3列の行列
X = [
    170 60 80;
    167 52 93;
    174 57 85;
    181 70 80;
    171 62 70;
    171 66 95;
    171 66 95;
    168 54 85;
]

## 行方向(dims=1)に対して、平均値を計算
means = mean(X; dims=1)

## 行方向(dims=1)に対して、中央値を計算
medians = median(X; dims=1)

## 標準出力
println("データ X:\n$X")
println("身長の平均値: $(means[1]), 体重の平均値:$(means[2]), 胸囲の平均値$(means[3])")
println("身長の中央値: $(medians[1]), 体重の中央値:$(medians[2]), 胸囲の中央値$(medians[3])")

## src
#-
## 分散共分散行列の計算
## 3種類(身長、体重、胸囲)のデータを格納する8行3列の行列
X = [
    170 60 80;
    167 52 93;
    174 57 85;
    181 70 80;
    171 62 70;
    171 66 95;
    171 66 95;
    168 54 85;
]
vars = var(X; corrected=false, dims=1)
stds = std(X; corrected=false, dims=1)
cov_bias = cov(X)
cov_nobias = cov(X; corrected=false)
println("データ X:\n$X")
println("分散) 身長:$(vars[1]), 体重:$(vars[2]), 胸囲:$(vars[3])")
println("標準偏差) 身長:$(stds[1]), 体重:$(stds[2]), 胸囲:$(stds[3])")
println("分散共分散行列 バイアスあり:\n$(cov_bias)")
println("分散共分散行列 バイアスなし:\n$(cov_nobias)")

## #src
# ### 3.4.7 相関係数と相関行列
## 3種類(身長、体重、胸囲)のデータを格納する8行3列の行列
X = [
    170 60 80;
    167 52 93;
    174 57 85;
    181 70 80;
    171 62 70;
    171 66 95;
    171 66 95;
    168 54 85;
]
println("データ X:\n$X")
println("相関行列:\n$(cor(X))")


text:
using Test
using NativeSVG

dr =
    Drawing(width = "300", height = "200") do
        rect(width = "100%", height = "100%", fill = "red")
        circle(cx = "150", cy = "100", r = "80", fill = "green")
        text(
            x = "150",
            y = "125",
            font_size = "60",
            text_anchor = "middle",
            fill = "white"
        ) do
            str("Drawing")
        end
    end
display(dr)

dr =
    Drawing(width = "200", height = "250") do
        rect(
            x = "10",
            y = "10",
            width = "30",
            height = "30",
            stroke = "black",
            fill = "transparent",
            stroke_width = "5"
        )
        rect(
            x = "60",
            y = "10",
            rx = "10",
            ry = "10",
            width = "30",
            height = "30",
            stroke = "black",
            fill = "transparent",
            stroke_width = "5"
        )
        circle(
            cx = "25",
            cy = "75",
            r = "20",
            stroke = "red",
            fill = "transparent",
            stroke_width = "5"
        )
        ellipse(
            cx = "75",
            cy = "75",
            rx = "20",
            ry = "5",
            stroke = "red",
            fill = "transparent",
            stroke_width = "5"
        )
        line(
            x1 = "10",
            x2 = "50",
            y1 = "110",
            y2 = "150",
            stroke = "orange",
            stroke_width = "5"
        )
        polyline(
            points = "60 110 65 120 70 115 75 130 80 125 85 140 90 135 95 150 100 145",
            stroke = "orange",
            fill = "transparent",
            stroke_width = "5"
        )
        polygon(
            points = "50 160 55 180 70 180 60 190 65 205 50 195 35 205 40 190 30 180 45 180",
            stroke = "green",
            fill = "transparent",
            stroke_width = "5"
        )
        path(
            d = "M20,230 Q40,205 50,230 T90,230",
            fill = "none",
            stroke = "blue",
            stroke_width = "5"
        )
    end
display(dr)

dr = Drawing(width = "100", height = "100") do
    path(d = "M 10 10 H 90 V 90 H 10 L 10 10")
    circle(cx = "10", cy = "10", r = "2", fill = "red")
    circle(cx = "90", cy = "90", r = "2", fill = "red")
    circle(cx = "90", cy = "10", r = "2", fill = "red")
    circle(cx = "10", cy = "90", r = "2", fill = "red")
end
display(dr)

dr =
    Drawing(width = "190", height = "160") do
        path(
            d = "M 10 10 C 20 20, 40 20, 50 10",
            stroke = "gray",
            fill = "transparent"
        )
        path(
            d = "M 70 10 C 70 20, 120 20, 120 10",
            stroke = "gray",
            fill = "transparent"
        )
        path(
            d = "M 130 10 C 120 20, 180 20, 170 10",
            stroke = "gray",
            fill = "transparent"
        )
        path(
            d = "M 10 60 C 20 80, 40 80, 50 60",
            stroke = "gray",
            fill = "transparent"
        )
        path(
            d = "M 70 60 C 70 80, 110 80, 110 60",
            stroke = "gray",
            fill = "transparent"
        )
        path(
            d = "M 130 60 C 120 80, 180 80, 170 60",
            stroke = "gray",
            fill = "transparent"
        )
        path(
            d = "M 10 110 C 20 140, 40 140, 50 110",
            stroke = "gray",
            fill = "transparent"
        )
        path(
            d = "M 70 110 C 70 140, 110 140, 110 110",
            stroke = "gray",
            fill = "transparent"
        )
        path(
            d = "M 130 110 C 120 140, 180 140, 170 110",
            stroke = "gray",
            fill = "transparent"
        )
    end
display(dr)

dr = Drawing(width = "200", height = "200") do
    defs() do
        style(type = "text/css") do
            cdata("""#MyRect {
                        stroke: black;
                        fill: red;
                     }""")
        end
    end
    rect(x = "10", height = "180", y = "10", width = "180", id = "MyRect")
end
display(dr)

dr =
    Drawing(width = "120", height = "120") do
        defs() do
            radialGradient(
                id = "Gradient",
                cx = "0.5",
                cy = "0.5",
                r = "0.5",
                fx = "0.25",
                fy = "0.25"
            ) do
                stop(offset = "0%", stop_color = "red")
                stop(offset = "100%", stop_color = "blue")
            end
        end
        rect(
            x = "10",
            y = "10",
            rx = "15",
            ry = "15",
            width = "100",
            height = "100",
            fill = "url(#Gradient)",
            stroke = "black",
            stroke_width = "2"
        )
        circle(
            cx = "60",
            cy = "60",
            r = "50",
            fill = "transparent",
            stroke = "white",
            stroke_width = "2"
        )
        circle(cx = "35", cy = "35", r = "2", fill = "white", stroke = "white")
        circle(cx = "60", cy = "60", r = "2", fill = "white", stroke = "white")
        text(
            x = "38",
            y = "40",
            fill = "white",
            font_family = "sans-serif",
            font_size = "10pt"
        ) do
            str("(fx,fy)")
        end
        text(
            x = "63",
            y = "63",
            fill = "white",
            font_family = "sans-serif",
            font_size = "10pt"
        ) do
            str("(cx,cy)")
        end
    end
display(dr)

dr =
    Drawing(width = "200", height = "200") do
        defs() do
            linearGradient(id = "Gradient1") do
                stop(offset = "5%", stop_color = "white")
                stop(offset = "95%", stop_color = "blue")
            end
            linearGradient(
                id = "Gradient2",
                x1 = "0",
                x2 = "0",
                y1 = "0",
                y2 = "1"
            ) do
                stop(offset = "5%", stop_color = "red")
                stop(offset = "95%", stop_color = "orange")
            end
            pattern(
                id = "Pattern",
                x = "0",
                y = "0",
                width = ".25",
                height = ".25"
            ) do
                rect(
                    x = "0",
                    y = "0",
                    width = "50",
                    height = "50",
                    fill = "skyblue"
                )
                rect(
                    x = "0",
                    y = "0",
                    width = "25",
                    height = "25",
                    fill = "url(#Gradient2)"
                )
                circle(
                    cx = "25",
                    cy = "25",
                    r = "20",
                    fill = "url(#Gradient1)",
                    fill_opacity = "0.5"
                )
            end
        end
        rect(
            fill = "url(#Pattern)",
            stroke = "black",
            width = "200",
            height = "200"
        )
    end
display(dr)

dr = Drawing() do
    text(x = "10", y = "10", fill = "gray") do
        str("This is ")
        tspan(font_weight = "bold", fill = "red") do
            str("bold and red")
        end
    end
end
display(dr)

dr =
    Drawing() do
        path(
            id = "my_path",
            d = "M 20,20 C 80,60 100,40 120,20",
            fill = "transparent"
        )
        text(fill = "red") do
            textPath(
                xmlns!xlink = "http://www.w3.org/1999/xlink",
                xlink!href = "#my_path"
            ) do
                str("A curve.")
            end
        end
    end
display(dr)

t = Turtle()
penup(t)
forward(t, -100)
turn(t, -90)
forward(t, 180)
turn(t, 90)
pendown(t)
for c in (:black, :red, :orange, :yellow, :green, :blue, :indigo, :violet)
    pencolor(t, c)
    forward(t, 100)
    turn(t, 45)
end
dr = Drawing(t, 400, 400)
display(dr)

dr =
    Drawing(width = "300", height = "200") do
        rect(width = "100%", height = "100%", fill = :white)
        latex("E=mc^2", x=20, y=20, width=50, height=20)
    end
display(dr)

ext: jl

max_stars_repo_name: BenLauwens/NativeSVG

max_issues_repo_name: BenLauwens/NativeSVG

max_forks_repo_name: BenLauwens/NativeSVG


text:
using PyCall

rclpy = pyimport("rclpy")
rosNode = pyimport("rclpy.node")
rosString = pyimport("std_msgs.msg")

@pydef mutable struct MinimialPublisher <: rosNode.Node
    function __init__(self)
        rosNode.Node.__init__(self, "minimal_publisher")
        self.publisher_ = self.create_publisher(rosString.String, "topic", 10)
        timer_period = 0.5
        self.i = 0
        function timer_callback(self)
            msg = rosString.String()
            msg.data = "Hello world: $(self.i)"
            self.publisher_.publish(msg)
            self.get_logger().info("Publishing: $(msg.data)")
            self.i = self.i + 1
        end
        self.timer = self.create_timer(timer_period, () -> timer_callback(self))
    end
end

function main(args=nothing)
    rclpy.init(args=args)
    minimal_publisher = MinimialPublisher()
    rclpy.spin(minimal_publisher)
    minimal_publisher.destroy_node()
    rclpy.shutdown()
end


text:
isdefined(@__MODULE__, :DUMMY_MOD) || (const DUMMY_MOD = true)

# taken from StatsModels
# https://github.com/JuliaStats/StatsModels.jl/blob/dee41c287033c0e9c18714a8d63bae61302027a6/test/statsmodel.jl

using StatsBase

# A dummy RegressionModel type
struct DummyMod <: RegressionModel
    beta::Vector{Float64}
    x::Matrix
    y::Vector
end

## dumb fit method: just copy the x and y input over
StatsBase.fit(::Type{DummyMod}, x::Matrix, y::Vector) =
    DummyMod(collect(1:size(x, 2)), x, y)
StatsBase.response(mod::DummyMod) = mod.y
## dumb coeftable: just prints the "beta" values
StatsBase.coeftable(mod::DummyMod) =
    CoefTable(reshape(mod.beta, (size(mod.beta,1), 1)),
              ["'beta' value"],
              ["" for n in 1:size(mod.x,2)],
              0)
# dumb predict: return values predicted by "beta" and dummy confidence bounds
function StatsBase.predict(mod::DummyMod;
                           interval::Union{Nothing,Symbol}=nothing)
    pred = mod.x * mod.beta
    if interval === nothing
        return pred
    elseif interval === :prediction
        return (prediction=pred, lower=pred .- 1, upper=pred .+ 1)
    else
        throw(ArgumentError("value not allowed for interval"))
    end
end
function StatsBase.predict(mod::DummyMod, newX::Matrix;
                           interval::Union{Nothing,Symbol}=nothing)
    pred = newX * mod.beta
    if interval === nothing
        return pred
    elseif interval === :prediction
        return (prediction=pred, lower=pred .- 1, upper=pred .+ 1)
    else
        throw(ArgumentError("value not allowed for interval"))
    end
end
StatsBase.dof(mod::DummyMod) = length(mod.beta)
StatsBase.dof_residual(mod::DummyMod) = length(mod.y) - length(mod.beta)
StatsBase.nobs(mod::DummyMod) = length(mod.y)
StatsBase.deviance(mod::DummyMod) = sum((response(mod) .- predict(mod)).^2)
# Incorrect but simple definition
StatsModels.isnested(mod1::DummyMod, mod2::DummyMod; atol::Real=0.0) =
    dof(mod1) <= dof(mod2)
StatsBase.loglikelihood(mod::DummyMod) = -sum((response(mod) .- predict(mod)).^2)
StatsBase.loglikelihood(mod::DummyMod, ::Colon) = -(response(mod) .- predict(mod)).^2

# A dummy RegressionModel type that does not support intercept
struct DummyModNoIntercept <: RegressionModel
    beta::Vector{Float64}
    x::Matrix
    y::Vector
end

StatsModels.drop_intercept(::Type{DummyModNoIntercept}) = true

## dumb fit method: just copy the x and y input over
StatsBase.fit(::Type{DummyModNoIntercept}, x::Matrix, y::Vector) =
    DummyModNoIntercept(collect(1:size(x, 2)), x, y)
StatsBase.response(mod::DummyModNoIntercept) = mod.y
## dumb coeftable: just prints the "beta" values
StatsBase.coeftable(mod::DummyModNoIntercept) =
    CoefTable(reshape(mod.beta, (size(mod.beta,1), 1)),
              ["'beta' value"],
              ["" for n in 1:size(mod.x,2)],
              0)
# dumb predict: return values predicted by "beta" and dummy confidence bounds
function StatsBase.predict(mod::DummyModNoIntercept;
                           interval::Union{Nothing,Symbol}=nothing)
    pred = mod.x * mod.beta
    if interval === nothing
        return pred
    elseif interval === :prediction
        return (prediction=pred, lower=pred .- 1, upper=pred .+ 1)
    else
        throw(ArgumentError("value not allowed for interval"))
    end
end
function StatsBase.predict(mod::DummyModNoIntercept, newX::Matrix;
                           interval::Union{Nothing,Symbol}=nothing)
    pred = newX * mod.beta
    if interval === nothing
        return pred
    elseif interval === :prediction
        return (prediction=pred, lower=pred .- 1, upper=pred .+ 1)
    else
        throw(ArgumentError("value not allowed for interval"))
    end
end
StatsBase.dof(mod::DummyModNoIntercept) = length(mod.beta)
StatsBase.dof_residual(mod::DummyModNoIntercept) = length(mod.y) - length(mod.beta)
StatsBase.nobs(mod::DummyModNoIntercept) = length(mod.y)
StatsBase.deviance(mod::DummyModNoIntercept) = sum((response(mod) .- predict(mod)).^2)


text:
# default model
@model function gdemo_d()
    s ~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s))
    1.5 ~ Normal(m, sqrt(s))
    2.0 ~ Normal(m, sqrt(s))
    return s, m
end
const gdemo_default = gdemo_d()

function test_model_ad(model, logp_manual)
    vi = VarInfo(model)
    x = DynamicPPL.getall(vi)

    # Log probabilities using the model.
    function logp_model(x)
        new_vi = VarInfo(vi, SampleFromPrior(), x)
        model(new_vi)
        return getlogp(new_vi)
    end

    # Check that both functions return the same values.
    lp = logp_manual(x)
    @test logp_model(x) ≈ lp

    # Gradients based on the manual implementation.
    grad = ForwardDiff.gradient(logp_manual, x)

    y, back = Tracker.forward(logp_manual, x)
    @test Tracker.data(y) ≈ lp
    @test Tracker.data(back(1)[1]) ≈ grad

    y, back = Zygote.pullback(logp_manual, x)
    @test y ≈ lp
    @test back(1)[1] ≈ grad

    # Gradients based on the model.
    @test ForwardDiff.gradient(logp_model, x) ≈ grad

    y, back = Tracker.forward(logp_model, x)
    @test Tracker.data(y) ≈ lp
    @test Tracker.data(back(1)[1]) ≈ grad

    y, back = Zygote.pullback(logp_model, x)
    @test y ≈ lp
    @test back(1)[1] ≈ grad
end

"""
    test_setval!(model, chain; sample_idx = 1, chain_idx = 1)

Test `setval!` on `model` and `chain`.

Worth noting that this only supports models containing symbols of the forms
`m`, `m[1]`, `m[1, 2]`, not `m[1][1]`, etc.
"""
function test_setval!(model, chain; sample_idx = 1, chain_idx = 1)
    var_info = VarInfo(model)
    spl = SampleFromPrior()
    θ_old = var_info[spl]
    DynamicPPL.setval!(var_info, chain, sample_idx, chain_idx)
    θ_new = var_info[spl]
    @test θ_old != θ_new
    nt = DynamicPPL.tonamedtuple(var_info)
    for (k, (vals, names)) in pairs(nt)
        for (n, v) in zip(names, vals)
            chain_val = if Symbol(n) ∉ keys(chain)
                # Assume it's a group
                vec(MCMCChains.group(chain, Symbol(n)).value[sample_idx, :, chain_idx])
            else
                chain[sample_idx, n, chain_idx]
            end
            @test v == chain_val
        end
    end
end


text:
using SQLite_Octo
using Base.Test


text:
# evodistances.jl
# ===============
#
# Types and methods for computing evolutionary and genetic distances.
#
# This file is a part of BioJulia.
# License is MIT: https://github.com/BioJulia/GeneticVariation.jl/blob/master/LICENSE.md

# Types
# -----

abstract type EvolutionaryDistance end
abstract type TsTv <: EvolutionaryDistance end

include("proportion.jl")


text:
"""
$(SIGNATURES)
Create dictionary of mesh generation options with default values. These at once describe the
keyword arguments available to the methods of the package and are listed in the following table:

| keyword        | default | 2D  | 3D  | Explanation                                                |
|:---------------|:-------:|:---:|:---:|:-----------------------------------------------------------|
| PLC            | true    | -p  | -p  | Triangulate/tetraheralize PLSG/PLC                         |
| refine         | false   | -r  | -r  | Refines a previously generated mesh.                       |
| quality        | true    | -q  | -q  | Quality mesh generation                                    |
| minangle       | 20      |     |     | Minimum angle for quality                                  |
| volumecontrol  | true    | -a  | -a  | Maximum area constraint                                    |
| maxvolume      | Inf     |     |     | Value of area/volume constraint if less than Inf           |
| attributes     | true    | -A  | -A  | Regional attribute to each simplex.                        |
| confdelaunay   | true    | -D  |     | Ensure that all circumcenter lie within the domain.        |
| nosteiner      | false   | -Y  | -Y  | Prohibits insertion of Steiner points on the mesh boundary |
| quiet          | true    | -Q  | -Q  | Suppress all output unless an error occurs.                |
| verbose        | false   | -V  | -V  | Give detailed information.                                 |
| debugfacets    | true    |     | -d  | Detects self-intersections of facets of the PLC.           |
| check          | false   | -C  | -C  | Checks the consistency of the final mesh.                  |
| optlevel       | 1       |     | -O  | Specifies the level of mesh optimization.                  |
| unsuitable     | nothing |     |     | Unsuitable function                                        |
| addflags       | ""      |     |     | Additional flags                                           |
| flags          | nothing |     |     | Set flags, overwrite all other options                     |

For mesh generation, these are turned into mesh generator control flags. This process can be completely
ovewritten by specifying the flags parameter.

For the flags parameter in 2D see the
[short](https://juliageometry.github.io/Triangulate.jl/stable/#Triangulate.triangulate-Tuple{String,TriangulateIO})
resp. [long](https://juliageometry.github.io/Triangulate.jl/stable/triangle-h/)
documentation of the Triangle control flags.

For the 3D case, see the corresponding [TetGen flags](https://juliageometry.github.io/TetGen.jl/stable/#TetGen.tetrahedralize-Tuple{RawTetGenIO{Float64},String})

The `unsuitable` parameter should be a function, see
[`triunsuitable`](https://juliageometry.github.io/TetGen.jl/stable/#TetGen.triunsuitable-Tuple{Function}) .

"""
default_options()=Dict{Symbol,Any}(
    :PLC          => true,
    :refine       => false,
    :quality      => true,
    :minangle     => 20,
    :volumecontrol=> true,
    :maxvolume    => Inf,
    :attributes   => true,
    :confdelaunay => true,
    :optlevel     => 1,
    :nosteiner    => false,
    :quiet        => true,
    :verbose      => false,
    :debugfacets  => true,
    :check        => false,
    :unsuitable   => nothing,
    :flags        => nothing,
    :addflags     => "")

function blendoptions!(opt; kwargs...)
    for (k,v) in kwargs
        if haskey(opt,Symbol(k))
            opt[Symbol(k)]=v
        end
    end

    if opt[:verbose]
        for (k,v) in kwargs
            if !haskey(opt,Symbol(k))
                println("Warning: ignored kwarg $(k)=$(v) for simplexgrid")
            end
        end
    end
    opt
end

function makeflags(options,mesher)
    if isnothing(options[:flags])
        flags=""
        options[:PLC] ? flags*="p" : nothing
        options[:refine] ? flags*="r" : nothing
        if options[:quality]
            minangle=Float64(options[:minangle])
            flags*=@sprintf("q%.2f",minangle)
        end
        if options[:volumecontrol]
            flags*="a"
            maxvolume=options[:maxvolume]
            if !isinf(maxvolume)
                flags*=@sprintf("%.40f",maxvolume)
            end
        end
        options[:attributes] ? flags*="A" : nothing
        !isnothing(options[:unsuitable]) && mesher==:triangle ? flags*="u" : nothing
        options[:confdelaunay] ? flags*="D" : nothing
        if options[:optlevel]>0 && mesher==:tetgen
            optlevel=options[:optlevel]
            flags*=@sprintf("O%d",optlevel)
        end
        options[:nosteiner] ? flags*="Y" : nothing
        options[:quiet] ? flags*="Q" : nothing
        options[:verbose] ? flags*="V" : nothing
        options[:debugfacets] && mesher==:teten ? flags*="d" : nothing
        options[:check] ? flags*="C" : nothing
        flags*=options[:addflags]
    else
        options[:flags]
    end
end


text:
module CountTimeSeries

using Optim, Distributions, LinearAlgebra, Plots, Calculus, Roots, Random
using Test, StatsBase, Distributed

include("ModelTypes.jl")
include("parameter.jl")
include("MLEControl.jl")
include("results.jl")

include("AIC.jl")
include("BIC.jl")
include("convert.jl")
include("convolution.jl")
include("fit.jl")
include("GetProbFromP.jl")
include("HQIC.jl")
include("LinPred.jl")
include("ll.jl")
include("MLESettings.jl")
include("Model.jl")
include("par2theta.jl")
include("parametercheck.jl")
include("pit.jl")
include("predict.jl")
include("QPois.jl")
include("show.jl")
include("simulate.jl")
include("theta2par.jl")
include("thinning.jl")

# Functions, types and structs with documentation
export AIC, BIC, fit, HQIC, ll, MLEControl, MLESettings, Model, CountModel
export INGARCH, INARMA, IIDModel, INARCHModel, INGARCHModel, INARMAModel
export INARModel, INMAModel, par2θ, parameter, pit, predict, QPois
export INGARCHresults, INARMAresults, simulate, θ2par, ∘

end


text:
"""
# KM3NeT Data Definitions v1.3.1-8-gae7dfb2
https://git.km3net.de/common/km3net-dataformat
"""

module Trigger
  const JTRIGGER3DSHOWER = 1
  const JTRIGGERMXSHOWER = 2
  const JTRIGGER3DMUON = 4
  const JTRIGGERNB = 5
  const FACTORY_LIMIT = 31
end


text:
using LinearAlgebra

export continuum, line_flux, equivalent_width

function chebvander(x::AbstractVector{T}, deg::Int) where {T <: Number}
    v = Matrix{T}(undef, length(x), deg + 1)
    v[:, 1] .= one(T)
    x2 = 2 .* x
    v[:, 2] .= x
    @inbounds for i in 3:deg + 1
        v[:, i] .= v[:, i - 1] .* x2 .- v[:, i - 2]
    end
    return v
end

function chebfit(wave, flux::AbstractVector{T}, deg) where {T}
    # gotta be a simpler way to convert to -1 to 1 domain
    x = (wave .- minimum(wave)) .* 2 ./ (maximum(wave) - minimum(wave)) .- 1
    vand = chebvander(x, deg)
    if T <: Measurement
        W = diagm(0 => Measurements.uncertainty.(flux))
        coeffs = (vand' * W * vand) \ (vand' * W * flux)
    else
        coeffs = pinv(vand) * flux
    end
    fit = vand * coeffs
    return coeffs, fit
end

"""
    continuum!(::AbstractSpectrum, deg::Int=3)

In-place version of [`continuum`](@ref)
"""
function continuum!(spec::AbstractSpectrum, deg::Int = 3)
    coeffs, fit = chebfit(spec.wave, spec.flux, deg)
    spec.flux .= spec.flux ./ ustrip.(fit)
    merge!(spec.meta, Dict(:normalized => true, :coeffs => coeffs))
    return spec
end

"""
    continuum(::AbstractSpectrum, deg::Int=3)

Return a continuum-normalized spectrum by fitting the continuum with a Chebyshev polynomial of degree `deg`.
"""
continuum(spec::AbstractSpectrum, deg::Int = 3) = continuum!(deepcopy(spec), deg)

"""
    equivalent_width(::AbstractSpectrum)

Calculate the equivalent width of the given continuum-normalized spectrum. Return value has units equal to wavelengths.
"""
function equivalent_width(spec::AbstractSpectrum)
    dx = spec.wave[end] - spec.wave[1]
    flux = ustrip(line_flux(spec))
    return dx - flux * unit(dx)
end

"""
    line_flux(::AbstractSpectrum)

Calculate the line flux of the given continuum-normalized spectrum. Return value has units equal to flux.
"""
function line_flux(spec::AbstractSpectrum)
    avg_dx = diff(spec.wave)
    return sum(spec.flux[2:end] .* avg_dx)
end


text:
using MultipleViewGeometry, Test, LinearAlgebra
using MultipleViewGeometry.ModuleTypes
using StaticArrays, Calculus, GeometryTypes
using MultipleViewGeometry.ModuleMove

# Tests for fundamental matrix estimation

𝒳 = [Point3D(x,y,rand(50:100)) for x = -100:5:100 for y = -100:5:100]
𝒳 = 𝒳[1:50:end]

# Specify the coordinate systems of the world, the camera frame and the picture
# plane.
world_basis = (Vec(1.0, 0.0, 0.0), Vec(0.0, 1.0, 0.0), Vec(0.0, 0.0, 1.0))
camera_basis = (Point(0.0, 0.0, 0.0), Vec(-1.0, 0.0, 0.0), Vec(0.0, -1.0, 0.0), Vec(0.0, 0.0, 1.0))
picture_basis = (Point(0.0, 0.0), Vec(-1.0, 0.0), Vec(0.0, -1.0))

# The focal length for both cameras is one.
f = 1
image_width = 640 / 10
image_height = 480 / 10

camera₁ = Pinhole(image_width, image_height, f, camera_basis..., picture_basis...)
camera₂ = Pinhole(image_width, image_height, f, camera_basis..., picture_basis...)

# Rotate and translate camera one.
𝐑₁ = Matrix{Float64}(I,3,3)
𝐭₁ = [-50.0, -2.0, 0.0]
relocate!(camera₁, 𝐑₁, 𝐭₁)

# Rotate and translate camera two.
𝐑₂ = Matrix{Float64}(I,3,3)
𝐭₂ = [50.0, 2.0, 0.0]
relocate!(camera₂, 𝐑₂, 𝐭₂)

𝐑₁′, 𝐭₁′ = ascertain_pose(camera₁, world_basis... )
𝐊₁′ = obtain_intrinsics(camera₁, CartesianSystem())
𝐑₂′, 𝐭₂′ = ascertain_pose(camera₂, world_basis... )
𝐊₂′ = obtain_intrinsics(camera₂, CartesianSystem())

# Camera projection matrices.
𝐏₁ = construct(ProjectionMatrix(),𝐊₁′,𝐑₁′,𝐭₁′)
𝐏₂ = construct(ProjectionMatrix(),𝐊₂′,𝐑₂′,𝐭₂′)

# Set of corresponding points.
ℳ = project(camera₁,𝐏₁,𝒳)
ℳʹ = project(camera₂,𝐏₂,𝒳)

# Estimate of the fundamental matrix and the true fundamental matrix.
𝐅 = estimate(FundamentalMatrix(), DirectLinearTransform(), (ℳ, ℳʹ))

#𝐅ₜ = construct(FundamentalMatrix(), 𝐏₁, 𝐏₂)
𝐅ₜ = construct(FundamentalMatrix(), 𝐊₁′,𝐑₁′,-𝐭₁′,𝐊₂′,𝐑₂′,-𝐭₂′)

# Ensure the estimated and true matrix have the same scale and sign.
𝐅 = 𝐅 / norm(𝐅)
𝐅 = 𝐅 / sign(𝐅[3,1])
𝐅ₜ = 𝐅ₜ / norm(𝐅ₜ)
𝐅ₜ = 𝐅ₜ / sign(𝐅ₜ[3,1])

@test 𝐅 ≈ 𝐅ₜ

# Check that the fundamental matrix satisfies the corresponding point equation.
npts = length(ℳ)
residual = zeros(Float64,npts,1)
for correspondence in zip(1:length(ℳ),ℳ, ℳʹ)
    i, m , mʹ = correspondence
    𝐦  = hom(m)
    𝐦ʹ = hom(mʹ)
    residual[i] = (𝐦ʹ'*𝐅*𝐦)
end

@test isapprox(sum(residual), 0.0; atol = 1e-7)

# Test the Fundamental Numerical Scheme on the Fundamental matrix problem.
Λ₁ =  [SMatrix{3,3}(Matrix(Diagonal([1.0,1.0,0.0]))) for i = 1:length(ℳ)]
Λ₂ =  [SMatrix{3,3}(Matrix(Diagonal([1.0,1.0,0.0]))) for i = 1:length(ℳ)]
𝐅₀ = estimate(FundamentalMatrix(),DirectLinearTransform(),  (ℳ, ℳʹ))
𝐅 = estimate(FundamentalMatrix(),
              FundamentalNumericalScheme(vec(𝐅₀), 5, 1e-10),
               (Λ₁,Λ₂), (ℳ, ℳʹ))

# Ensure the estimated and true matrix have the same scale and sign.
𝐅 = 𝐅 / norm(𝐅)
𝐅 = 𝐅 / sign(𝐅[3,1])

@test 𝐅 ≈ 𝐅ₜ

# Test the Bundle Adjustment estimator on the Fundamental matrix problem.
𝐅, lsqFit = estimate(FundamentalMatrix(),
                      BundleAdjustment(vec(𝐅₀), 5, 1e-10),
                        (ℳ, ℳʹ))
𝐅 = 𝐅 / norm(𝐅)
𝐅 = 𝐅 / sign(𝐅[3,1])
@test 𝐅 ≈ 𝐅ₜ


text:
"""
    $(SIGNATURES)

Clear a directory and its sub-directories
"""
function clear_directory(tgDir :: AbstractString; askFirst :: Bool = true)
    if isdir(tgDir)
        if askFirst
            ans1 = ask_yes_no("Clear directory  $tgDir");
        else
            ans1 = true;
        end
        ans1  &&  rm(tgDir, recursive = true);
    end
    isdir(tgDir)  ||  mkpath(tgDir);
    return nothing
end

"""
	$(SIGNATURES)

Make a directory for a full path, if it does not already exist. Input `d` is a file path which may include name and extension. Also creates (using `mkpath`) intermediate directories.

# Example
```
make_dir("/abc/def/ghi.txt") # makes "/abc/def"
```
"""
function make_dir(d :: AbstractString)
    fDir, _ = splitdir(d);
    if !isempty(fDir)
        isdir(fDir)  ||  mkpath(fDir);
    end
end

"""
	$(SIGNATURES)

Is a directory empty?
"""
is_dir_empty(d :: AbstractString) = isempty(readdir(d));

"""
	$(SIGNATURES)

Return a string with the `nDirs` "rightmost" directories. Note that the right most "directly" is the file name if the input string contains one.

# Example
```
right_dirs("/abc/def/ghi/", 2) == "def/ghi"
right_dirs("abc/def/ghi.jl", 2) == "def/ghi.jl"
```
"""
function right_dirs(d :: AbstractString, nDirs :: Integer)
    # Locations of interior file separators
    # idxV = findall(j -> d[j] == filesep(), 2 : (length(d) - 1));
    # if length(idxV) < nDirs
    #     pd = d;
    # else
    #     idx1 = idxV[length(idxV) - nDirs] + 1;
    #     pd = d[idx1 : end];
    # end
    pV = splitpath(d);
    n = length(pV);
    if n > nDirs
        idxV = max(1, n - nDirs + 1) : n;
        pd = joinpath(pV[idxV]...);
    else
        pd = rstrip(d, filesep());
    end
    return pd
end

"""
	$(SIGNATURES)

Find common base directory for a set of absolute paths.
"""
function find_common_base_dir(pathV :: AbstractVector{T}) where T <: AbstractString
    cbd = pathV[1];
    for j = 2 : length(pathV)
        cbd = find_common_base_dir(cbd, pathV[j]);
    end
    return cbd
end

function find_common_base_dir(d1, d2)
    if isempty(d1) || isempty(d2)
        return nothing
    end

    p1V = splitpath(d1);
    p2V = splitpath(d2);
    n = min(length(p1V), length(p2V));
    jd = findfirst(j -> !isequal(p1V[j], p2V[j]), 1 : n);

    if isnothing(jd)
        jd = n+1;
    end
    return joinpath(p1V[1 : (jd-1)]...)
end

"""
	$(SIGNATURES)

Make a list of all files in a given directory. Recurses sub-directories. Each line is of the form "subdir/file.ext"
"""
function files_in_dir(d :: AbstractString)
    fList = Vector{String}();
    for (root, _, files) in walkdir(d)
        subDir = relpath(root, d);
        if subDir == "."
            subDir = "";
        end
        for file in files
            push!(fList, joinpath(subDir, file));
        end
    end
    return fList
end

"""
	$(SIGNATURES)

Make a list of files that occur in dir1, but not in dir2. Recurses sub-directories. Only compares file names.
"""
function files_not_in_dir2(dir1 :: AbstractString, dir2 :: AbstractString)
    fList1 = files_in_dir(dir1);
    fList2 = files_in_dir(dir2);
    missList = Vector{String}();
    for f in fList1
        if !(f ∈ fList2)
            push!(missList, f);
        end
    end
    return missList
end

"""
	$(SIGNATURES)

Report differences between two directories and their sub-directories. Based on file names only.

# Arguments
- `dir1`, `dir2`: Directories to be compared.
- `io`: where output is to be written
- `exclude`: case sensitive substrings to be excluded

# Example
```julia
dir_diff_report("my/dir1", "my/dir2"; io = stdout, exclude = ["_not", "Drop"])
```
"""
function dir_diff_report(dir1 :: AbstractString, dir2 :: AbstractString;
    io = stdout, exclude = :nothing)
    cbd = find_common_base_dir(dir1, dir2);
    @assert !isnothing(cbd)  "Must have common base dir"
    miss2V = files_not_in_dir2(dir1, dir2);
    filter_excludes!(miss2V, exclude);
    miss1V = files_not_in_dir2(dir2, dir1);
    filter_excludes!(miss1V, exclude);
    println(io, "\nComparing files by name in base directory\n  ",  cbd);

    relDir1 = relpath(dir1, cbd);
    println(io, "Files missing in $relDir1:");
    for f in miss1V
        println(io, "  $f");
    end
    relDir2 = relpath(dir2, cbd);
    println(io, "Files missing in $relDir2:");
    for f in miss2V
        println(io, "  $f");
    end
    println(io, "----------")
end

"""
	$(SIGNATURES)

Given a vector `v`, drop entries that contain any of the values in `exclude`.
"""
function filter_excludes!(v, exclude :: AbstractVector{T}) where T
    if !isnothing(exclude)
        keepV = trues(size(v));
        for excl in exclude
            filter_excludes!(v, excl);
        end
    end
    return nothing
end

filter_excludes!(v, exclude :: AbstractString) =
    filter!(x -> !contains(x, exclude), v);

# --------------


text:
### Log-likehood & log-prior

export negLogLikelihood_gauss, negLogPost, negLogPrior_gauss, negLogPrior_L1smooth

function negLogLikelihood_gauss(
	d::Data, m::Model, σ2_dat::Float32,
	F::FunctionMod2Dat;
	compute_grad::Bool = false)

	# Compute functional
	Fm = F.eval(m; store_extracomp = compute_grad)
	Δd = Fm-d
	f = 1f0/(2f0*σ2_dat)*norm(Δd).^2f0

	!compute_grad ? (return f) : (return f, F.jac_adj(m, Δd)/σ2_dat)

end

function negLogPrior_gauss(
	m::Model, σ2_mod::Float32;
	b::Union{Nothing, Model} = nothing, m0::Model = Model(ModelGeom(0, 0f0), zeros(Float32, 1)), D::LinFunctionMod2Mod = LinFunctionMod2Mod(m->m, m->m),
	compute_grad::Bool = false)

	# Compute functional
	(b == nothing) ? (r = D.eval(m-m0)) : (r = D.eval(m-m0)-b)
	f = 1f0/(2f0*σ2_mod)*norm(r).^2f0

	if !compute_grad
		return f

	# Compute gradient
	else
		return f, D.eval_adj(r)/σ2_mod
	end

end

function negLogPrior_L1smooth(
	m::Model, σ_mod::Float32, ϵ2::Float32;
	m0::Model = Model(ModelGeom(0, 0f0), zeros(Float32, 1)), D::LinFunctionMod2Mod = LinFunctionMod2Mod(m->m, m->m),
	compute_grad::Bool = false)

	# Compute functional
	Dm = D.eval(m-m0)
	w = sqrt.(abs.(Dm.m).^2f0.+ϵ2)
	f = 1f0/σ_mod*vec(sum(w; dims = 1))

	if !compute_grad
		return f

	# Compute gradient
	else
		return f, D.eval_adj(Dm/w)/σ_mod
	end

end

function negLogPost(
	m::Model,
	negLogLikelihood_fun::Function, negLogPrior_fun::Function;
	compute_grad::Bool = false)

	outlike = negLogLikelihood_fun(m; compute_grad = compute_grad)
	outpr   = negLogPrior_fun(m; compute_grad = compute_grad)
	if !compute_grad
		return outlike.+outpr
	else
		return outlike[1].+outpr[1], outlike[2]+outpr[2]
	end

end


text:
using JavaCall
DBtableTypeorString = Union{DBtableType, AbstractString}

function nmf(A::DBtableTypeorString, AT::DBtableTypeorString, k::Number, Wname::AbstractString, WTname ::AbstractString, Hname::AbstractString, HTname::AbstractString, maxiter::Number; forceDelete::Bool=true, cutoffThreshold::Number=0, maxColsPerTopic::Number=0)

# Original Java docstring:
# /**
# * Non-negative matrix factorization.
# * The main NMF loop stops when either (1) we reach the maximum number of iterations or
# *    (2) when the absolute difference in error between A and W*H is less than 0.01 from one iteration to the next.
# *
# *
# * @param Aorig Accumulo input table to factor
# * @param ATorig Transpose of Accumulo input table to factor
# * @param Wfinal Output table W. Must not exist before this method.
# * @param WTfinal Transpose of output table W. Must not exist before this method.
# * @param Hfinal Output table H. Must not exist before this method.
# * @param HTfinal Transpose of output table H. Must not exist before this method.
# * @param K Number of topics.
# * @param maxiter Maximum number of iterations
# * @param forceDelete Forcibly delete temporary tables used if they happen to exist. If false, throws an exception if they exist.
# * @param cutoffThreshold Set entries of W and H below this threshold to zero. Default 0.
# * @param maxColsPerTopic Only retain the top X columns for each topic in matrix H. If <= 0, this is disabled.
# * @return The absolute difference in error (between A and W*H) from the last iteration to the second-to-last.
# */
# public double NMF(String Aorig, String ATorig,
#                  String Wfinal, String WTfinal, String Hfinal, String HTfinal,
#                  final int K, final int maxiter,
#                  boolean forceDelete, double cutoffThreshold, int maxColsPerTopic)

    if isa(A, DBtablePair)
        Aname = A.name1
    elseif isa(A, DBtable)
        Aname = A.name
    else
        Aname = A
    end

    if isa(AT, DBtablePair)
        ATname = AT.name1
    elseif isa(AT, DBtable)
        ATname = AT.name
    else
        ATname = AT
    end

    DB = A.DB

    return jcall(DB.Graphulo,"NMF", jdouble,
        (JString,JString,JString,JString,JString,JString,jint,jint,jboolean,jdouble,jint,),
        Aname, ATname, Wname, WTname, Hname, HTname, k, maxiter, forceDelete, cutoffThreshold, maxColsPerTopic)

end


text:
using EntanglementDist
using Base.Test

@testset "Basic functions" begin
	rho = isotropicState(0.9)
	A = [1 im; im 1]
	@testset "Checks" begin
		@test true == isQuantumState(rho)
		@test false == isQuantumState(eye(2))
		@test true == isHermitian(rho)
		@test false == isHermitian(A)
		@test false == isUnitary(A)
		@test true == isPPT(eye(4)/4,2,2)
		@test false == isPPT(isotropicState(0.9),2,2)
	end

	@testset "Simple functions on states" begin
		@test copies(isotropicState(1),2) ≈ kron(maxEnt(2), maxEnt(2))
		@test entFidelity(sStateQutrit(1)) ≈ 1
		@test eprFidelity(bellDiagState(0,0,0.3)) ≈ 0.7
		@test eVec(2,1)*eVec(2,1)' + eVec(2,2)*eVec(2,2)' ≈ eye(2)
		@test kron(maxEnt(2),maxEnt(2)) ≈ permutesystems(maxEnt(4),[1,3,2,4], [2,2,2,2])
		# Test partial trace
		n = 4
		rho = maxEnt(n)
		@test eye(n)/n == partialtrace(rho, 1, [n;n])
		@test eye(n)/n == partialtrace(rho, 2, [n;n])
		n = 8
		rho_a = random_densitymatrix(n)
		rho_b = random_densitymatrix(n)
		rho = kron(rho_a, rho_b)
		@test rho_b ≈ partialtrace(rho, 1, [n; n])
		@test rho_a ≈ partialtrace(rho, 2, [n; n])
		#Test partial transpose
		@test partialtranspose(kron(maxEnt(2), maxEnt(2))) ≈ kron(maxEnt(2), maxEnt(2))
		@test partialtranspose(kron(maxEnt(3), maxEnt(2)), 2, [9,4]) ≈ kron(maxEnt(3), maxEnt(2))
		@test partialtrace(partialtranspose(maxEnt(2)),[2],[2,2]) ≈ eye(2)/2
	end
end

@testset "states" begin
	@test bellDiagState(0.25,0.25,0.25) ≈ eye(4)/4
	@test bellDiagState(1,0,0) ≈ maxEnt(2)
	@test sState(0.8) ≈ 0.8 * maxEnt(2) + 0.2 * kron(eVec(2,2),eVec(2,2))*kron(eVec(2,2),eVec(2,2))'
	@test rState(0.8) ≈ 0.8 * bell[3,1:4]* bell[3,1:4]' + 0.2 * kron(eVec(2,2),eVec(2,2))*kron(eVec(2,2),eVec(2,2))'
	@test sStateQutrit(0.8) ≈ 0.8 * maxEnt(3) + 0.2 * kron(eVec(3,1),eVec(3,1))*kron(eVec(3,1),eVec(3,1))'
	@test rStatePhase(0.8, pi) ≈ 0.8 * bell[4,1:4]*bell[4,1:4]' + 0.2 * kron(eVec(2,2),eVec(2,2))*kron(eVec(2,2),eVec(2,2))'
	@test rStateCorrPhase(0, 0.8) ≈ eVec(16,16) * eVec(16,16)'
	@test rStateCorrPhaseCopies(0, 3) ≈ eVec(64,64) * eVec(64,64)'
	@test isotropicState(1) ≈ maxEnt(2)
	@test isotropicState(0) ≈ eye(4)/4
	@test maxEnt(4)≈ maxEntVec(4)*maxEntVec(4)'
	@test trace(bellDiagState(0.25,0.25,0.25)) ≈ 1
	@test trace(maxEnt(4)) ≈ 1
	@test trace(sState(0.8)) ≈ 1
	@test trace(rState(0.8)) ≈ 1
	@test trace(sStateQutrit(0.8)) ≈ 1
	@test trace(rStatePhase(0.8, pi)) ≈ 1
	@test trace(rStateCorrPhase(0.6, 0.8)) ≈ 1
	@test trace(rStateCorrPhaseCopies(0.4, 3)) ≈ 1
	@test abs(det(random_unitary(3))) ≈ 1
	@test trace(random_densitymatrix(4)) ≈ 1
	@test true == isUnitary(random_unitary(4))
	@test true == isQuantumState(random_densitymatrix(4))
end

@testset "Protocols" begin
	#DEJMPS and BBPSSW cannot create entangled state if the initial fidelity is < 0.5.
	@test DEJMPSParam(bellDiagState(0.4,0.3,0.1))[1] <= 0.5
	@test BBPSSWParam(bellDiagState(0.4,0.3,0.1))[1] <= 0.5
	@test BBPSSWParam(0.6)[1] > 0.6
	#test EPL-D on rStateCorrPhase:
	@test EPLDParam(0.4,0.8)[1] ≈ EPLDParam(sortAB(rStateCorrPhase(0.4,0.8),2,2))[1]
	@test EPLDParam(0.4,0.8)[2] ≈ EPLDParam(sortAB(rStateCorrPhase(0.4,0.8),2,2))[2]
	#test the filtering protocol for a mixture of EPR pair and orthogonal product noise (rotated R-state). This protocol cannot deterministically increase fidelity:
	X = [0 1; 1 0];
	rho = kron(X, eye(2)) * rState(0.7) * kron(X, eye(2));
	@test filtering(rho, 1)[3] ≈ eprFidelity(rho)
end

@testset "Relaxations" begin
	# Test PPT Relax - no improvements are possible when demanding success probability 1 on single copy of the isotropic state
	rho = isotropicState(0.9);
	initF = entFidelity(rho);
	(problem,F,psucc) = pptRelax(rho,2,2,2,1, verbose = false);
	@test round(F,3) == round(initF,3)

	# Test PPT Relax - DEJMPS overlaps with the PPT bound for Bell diagonal states of rank 2
	rho = bellDiagState(0.7,0.3,0);
	initF = entFidelity(rho);
	(problem,F,psucc) = pptRelaxCopies(rho,2,2,2,2,DEJMPSParam(rho)[2], verbose = false);
	dejmpsF = DEJMPSParam(rho)[1];
	@test round(F,3) ≈ round(dejmpsF,3)

	# Same for 1 extension
	rho = bellDiagState(0.7,0.3,0);
	initF = entFidelity(rho);
	(problem,F,psucc) = pptRelax1ExtCopies(rho,2,2,2,2,DEJMPSParam(rho)[2], verbose = false);
	dejmpsF = DEJMPSParam(rho)[1];
	@test round(F,3) ≈ round(dejmpsF,3)

	# Test 2 extensions - no improvements are possible when demanding success probability 1 on single copy of the isotropic state
	rho = isotropicState(0.9);
	initF = entFidelity(rho);
	(problem,F,psucc) = pptRelax2Ext(rho,2,2,2,1, verbose = false);
	@test round(F,3) == round(initF,3)
end

@testset "Seesaw" begin

	#Seesaw finds the optimal filtering protocol for S-states which overlaps with the PPT bound
	rho = sState(0.7);
	eps = 0.5;
	(CA,CB) = filteringMakeChoi(eps);
    (rhoQC, P, F0, p0) = filtering(rho, eps);
    (newCA, newCB, Fnew, pnew) = seesaw(rho,2,2,2,CA, CB, P);
	(problem,F,psucc) = pptRelax(rho,2,2,2,pnew, verbose = false);
	@test round(F,3) ≈ round(Fnew,3)
end


text:
#
# COM API wrappers
#

function CoInitializeEx(concurrency_model)
    res = ccall( (:CoInitializeEx, l_ole32), Uint32, (Csize_t, DWORD,), C_NULL, concurrency_model)
    if (res == HRESULT.S_FALSE)
        warn("COM interface already initialized")
    elseif (res != HRESULT.S_OK)
        error("Unable to initialize COM interface")
    end
end
CoInitializeEx() = CoInitializeEx(COINIT.APARTMENTTHREADED)
CoInitialize() = CoInitializeEx()

function CLSIDFromProgID(id::String)
    clsid = [GUID()]
    res = ccall( (:CLSIDFromProgID, l_ole32), stdcall, Uint32, (LPCOLESTR, LPCLSID), utf16(id), pointer(clsid))
    res == HRESULT.S_OK || error("Unable to locate program $id")
    return CLSID(clsid[1])
end

# TODO
#function StringFromCLSID(clsid::CLSID)
#    s = Ptr{Uint16}[C_NULL]
#    res = ccall( (:StringFromCLSID, l_ole32), stdcall, Uint32,
#                (REFCLSID, Ptr{Uint16}), clsid, s)
#    return (res, s)
#end

function CoCreateInstance(clsid::CLSID; iid=None, clsctx=None)
    if (clsctx == None)
        clsctx = CLSCTX.SERVER
    end
    if (iid == None)
        iid = IID[IUnknown]
    end

    ppv = [C_NULL]
    res = ccall( (:CoCreateInstance, l_ole32), Uint32,
                (LPCLSID, LPUNKNOWN, DWORD, REFIID, Ptr{Ptr{Void}}),
                &clsid, C_NULL, clsctx, &iid, ppv)
    if (res == REGDB.E_CLASSNOTREG)
        error("Class not registered ($clsid)")
    end
    iid[ppv[1]]
end

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

#
# IUnknown interface
#
#   QueryInterface
#   AddRef
#   Release

function QueryInterface{T <: IUnknown}(this::Ptr{T}, clsid::CLSID; err=false)
    obj = [C_NULL]
    println("calling")
    res = @vcall(this, 1, HResult, &clsid::REFIID, pointer(obj)::Ptr{Ptr{Void}})
    if (res != HRESULT.S_OK)
        err && error("QueryInterface: $clsid not supported")
        return C_NULL
    end
    println("res: ", res)
    println("obj: ", obj)
    return reinterpret(Ptr{typeof(clsid)},obj[1])
end

function AddRef{T<:IUnknown}(this::Ptr{T})
    refcount = ccall( getvtptr(this,2), thiscall, Culong,
                      (Ptr{Void},), this)
end

function Release{T<:IUnknown}(this::Ptr{T})
    refcount = ccall( getvtptr(this,3), thiscall, Culong,
                      (Ptr{Void},), this)
end

#
# IDispatch methods
#
#   <: IUnknown
#       GetTypeInfoCount
#       GetTypeInfo
#       GetIDsOfNames
#       Invoke

function GetTypeInfoCount{T <: IDispatch}(this::Ptr{T})
    pctinfo = [zero(Cuint)]
    res = @vcall(this, 4, HResult, pctinfo::Ptr{Cuint})
    show(res)
    res != HRESULT.S_OK && error("failed GetTypeInfoCount")
    return pctinfo[1]
end

# TODO
type ITypeInfo
end

function GetTypeInfo{T <: IDispatch}(this::Ptr{T}, tinfokind::Cuint)
    lcid = C_NULL
    itypeinfo = Ptr{Ptr{ITypeInfo}}[C_NULL]

    res = ccall( getvtptr(this, 5), thiscall, Uint32,
                (THISPTR,
                Cuint, LCID, Ptr{Ptr{ITypeInfo}}),
                o.ptr, tinfokind, lcid, itypeinfo)
    res != HRESULT.S_OK && error("failed GetTypeInfo")
    return itypeinfo[1]
end

function GetIDsOfNames{T <: IDispatch}(this::Ptr{T}, numNames)
    lcid = DefaultLCID::LCID
    rgszNames = Ptr{LPOLESTR}[C_NULL]
    numNames = convert(Cuint, numNames)
    refiid::REFIID

    namesptr = Ptr{LPOLESTR}[C_NULL]
    res = ccall(getvtptr(this, 6), thiscall, Uint32,
                (THISPTR,
                REFIID, Ptr{LPOLESTR}, Cuint, LCID, Ptr{DISPID}),
                this,
                BaseIID.IID_NULL, rgszNames, cNames, lcid, rgDispId)
    res != HRESULT.S_OK && error("GetIDsOfNames error")
    return rgszNames[1]
end

################################################################################
#
# High-level API
#

function getindex(c::COMGlobal, name::String)
    # TODO: error message based on the HRESULT or REGDB value
    clsid = CLSIDFromProgID(name)
    CoCreateInstance(clsid)
end

# Intended interface:
#   ie = COM["InternetExplorer.Application"]
#   ie[:Navigate2]("www.julialang.org")

function getindex(c::COMGlobal, clsid::CLSID)
    CoCreateInstance(clsid)
end

function getindex(c::IDispatch, x::Symbol)

end


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

precompile(Tuple{Type{Base.Dict{K, V} where V where K}, Array{Base.Pair{A, B} where B where A, 1}})
precompile(Tuple{Type{Base.Dict{Pkg.Types.VersionRange, Base.Dict{String, Base.UUID}}}})
precompile(Tuple{Type{Base.Dict{Pkg.Types.VersionRange, Base.Dict{String, Pkg.Types.VersionSpec}}}})
precompile(Tuple{Type{Base.Dict{String, Any}}, Base.Pair{String, String}})
precompile(Tuple{Type{Base.Dict{String, Base.UUID}}})
precompile(Tuple{Type{Base.Dict{String, Pkg.Types.VersionSpec}}})
precompile(Tuple{Type{Base.Generator{I, F} where F where I}, Type{Base.UUID}, Base.ValueIterator{Base.Dict{String, Any}}})
precompile(Tuple{Type{Base.Generator{I, F} where F where I}, Type{Base.UUID}, Base.ValueIterator{Base.Dict{String, String}}})
precompile(Tuple{Type{Base.Generator{I, F} where F where I}, typeof(Base.close), Array{LibGit2.GitAnnotated, 1}})
precompile(Tuple{Type{Base.Generator{I, F} where F where I}, typeof(Pkg.TOML.is_tabular), Base.ValueIterator{Base.Dict{String, Any}}})
precompile(Tuple{Type{Base.Generator{I, F} where F where I}, typeof(Pkg.TOML.table2dict), Array{Any, 1}})
precompile(Tuple{Type{Base.IOContext{IO_t} where IO_t<:IO}, Base.GenericIOBuffer{Array{UInt8, 1}}, Base.TTY})
precompile(Tuple{Type{Base.Pair{A, B} where B where A}, Base.UUID, Int64})
precompile(Tuple{Type{Base.Pair{A, B} where B where A}, Base.UUID, Pkg.Types.VersionSpec})
precompile(Tuple{Type{Base.Pair{A, B} where B where A}, Base.VersionNumber, Base.SHA1})
precompile(Tuple{Type{Base.Pair{A, B} where B where A}, String, Base.UUID})
precompile(Tuple{Type{Base.SHA1}, Base.SubString{String}})
precompile(Tuple{Type{Base.SHA1}, String})
precompile(Tuple{Type{Char}, Int32})
precompile(Tuple{Type{NamedTuple{(:by,), T} where T<:Tuple}, Tuple{typeof(Base.identity)}})
precompile(Tuple{Type{NamedTuple{(:header, :color), T} where T<:Tuple}, Tuple{String, Symbol}})
precompile(Tuple{Type{NamedTuple{(:indent, :region_active), T} where T<:Tuple}, Tuple{Int64, Bool}})
precompile(Tuple{Type{NamedTuple{(:indent, :sorted, :by), T} where T<:Tuple}, Tuple{Int64, Bool, typeof(Base.identity)}})
precompile(Tuple{Type{NamedTuple{(:init,), T} where T<:Tuple}, Tuple{Int64}})
precompile(Tuple{Type{NamedTuple{(:mode,), T} where T<:Tuple}, Tuple{Symbol}})
precompile(Tuple{Type{NamedTuple{(:transfer_progress, :credentials), T} where T<:Tuple}, Tuple{Ptr{Nothing}, Ptr{Nothing}}})
precompile(Tuple{Type{Pkg.Display.DiffEntry}, Base.UUID, String, Pkg.Display.VerInfo, Pkg.Display.VerInfo})
precompile(Tuple{Type{Pkg.Display.VerInfo}, Base.SHA1, Nothing, Base.VersionNumber, Bool, Nothing})
precompile(Tuple{Type{Pkg.Display.VerInfo}, Base.SHA1, Nothing, Base.VersionNumber, Bool, Pkg.Types.GitRepo})
precompile(Tuple{Type{Pkg.Display.VerInfo}, Nothing, Nothing, Nothing, Bool, Nothing})
precompile(Tuple{Type{Pkg.Display.VerInfo}, Nothing, String, Base.VersionNumber, Bool, Nothing})
precompile(Tuple{Type{Pkg.Types.EnvCache}, Nothing, Nothing, String, String, Nothing, Base.Dict{String, Any}, Base.Dict{String, Any}, Base.Dict{String, Array{Base.UUID, 1}}, Base.Dict{Base.UUID, Array{String, 1}}, Base.Dict{Base.UUID, Array{String, 1}}})
precompile(Tuple{Type{Pkg.Types.GitRepo}, String, String, Base.SHA1})
precompile(Tuple{Type{Pkg.Types.GitRepo}, String, String})
precompile(Tuple{Type{Pkg.Types.PackageSpec}, Base.SubString{String}, Pkg.Types.VersionSpec})
precompile(Tuple{Type{Pkg.Types.PackageSpec}, Base.SubString{String}})
precompile(Tuple{Type{Pkg.Types.PackageSpec}, String, Base.UUID, Pkg.Types.VersionSpec})
precompile(Tuple{Type{Pkg.Types.PackageSpec}, String})
precompile(Tuple{Type{Pkg.Types.VersionBound}, Base.SubString{String}})
precompile(Tuple{Type{Pkg.Types.VersionBound}, Int64, Int64})
precompile(Tuple{Type{Pkg.Types.VersionBound}, Tuple{Int64, Int64, Int64}})
precompile(Tuple{Type{Pkg.Types.VersionBound}, Tuple{Int64, Int64}})
precompile(Tuple{Type{Pkg.Types.VersionBound}, Tuple{UInt32, UInt32}})
precompile(Tuple{Type{Pkg.Types.VersionBound}, UInt32, UInt32})
precompile(Tuple{Type{Pkg.Types.VersionRange}, Base.VersionNumber})
precompile(Tuple{Type{Pkg.Types.VersionSpec}, String})
precompile(Tuple{Type{REPL.LineEdit.PrefixSearchState}, REPL.Terminals.TTYTerminal, REPL.LineEdit.PrefixHistoryPrompt, String, Base.GenericIOBuffer{Array{UInt8, 1}}})
precompile(Tuple{Type{REPL.LineEdit.PromptState}, REPL.Terminals.TTYTerminal, REPL.LineEdit.Prompt, Base.GenericIOBuffer{Array{UInt8, 1}}, Symbol, Array{Base.GenericIOBuffer{Array{UInt8, 1}}, 1}, Int64, REPL.LineEdit.InputAreaState, Int64, Base.Threads.TatasLock, Float64})
precompile(Tuple{Type{REPL.LineEdit.SearchState}, REPL.Terminals.TTYTerminal, REPL.LineEdit.HistoryPrompt, Bool, Base.GenericIOBuffer{Array{UInt8, 1}}, Base.GenericIOBuffer{Array{UInt8, 1}}})
precompile(Tuple{Type{REPL.REPLHistoryProvider}, Array{String, 1}, Nothing, Int64, Int64, Int64, Base.GenericIOBuffer{Array{UInt8, 1}}, Nothing, Base.Dict{Symbol, Any}, Array{UInt8, 1}})
precompile(Tuple{Type{REPL.REPLHistoryProvider}, Base.Dict{Symbol, Any}})
precompile(Tuple{getfield(Base, Symbol("#kw##printstyled")), NamedTuple{(:bold, :color), Tuple{Bool, Symbol}}, typeof(Base.printstyled), Base.TTY, String})
precompile(Tuple{getfield(Base, Symbol("#kw##sort!")), NamedTuple{(:by,), Tuple{typeof(Base.Unicode.lowercase)}}, typeof(Base.sort!), Array{String, 1}})
precompile(Tuple{getfield(Base, Symbol("#kw##sort!")), NamedTuple{(:by,), Tuple{typeof(Base.identity)}}, typeof(Base.sort!), Array{String, 1}})
precompile(Tuple{getfield(Base.Cartesian, Symbol("#@nloops")), LineNumberNode, Module, Int64, Symbol, Expr, Expr, Expr})
precompile(Tuple{getfield(Core, Symbol("#kw#Type")), NamedTuple{(:header, :color), Tuple{String, Symbol}}, Type{Pkg.GitTools.MiniProgressBar}})
precompile(Tuple{getfield(Core, Symbol("#kw#Type")), NamedTuple{(:payload, :transfer_progress, :credentials), Tuple{Base.Dict{Symbol, Any}, Ptr{Nothing}, Ptr{Nothing}}}, Type{LibGit2.RemoteCallbacks}})
precompile(Tuple{getfield(Pkg.API, Symbol("#kw##add_or_develop")), NamedTuple{(:mode,), Tuple{Symbol}}, typeof(Pkg.API.add_or_develop), Pkg.Types.Context, Array{Pkg.Types.PackageSpec, 1}})
precompile(Tuple{getfield(Pkg.TOML, Symbol("#kw##_print")), NamedTuple{(:indent, :sorted, :by), Tuple{Int64, Bool, typeof(Base.identity)}}, typeof(Pkg.TOML._print), Base.IOStream, Base.Dict{String, Any}, Array{String, 1}})
precompile(Tuple{getfield(Pkg.TOML, Symbol("#kw##print")), NamedTuple{(:sorted,), Tuple{Bool}}, typeof(Pkg.TOML.print), Base.IOStream, Base.Dict{String, Any}})
precompile(Tuple{getfield(Pkg.TOML, Symbol("#kw##printvalue")), NamedTuple{(:sorted,), Tuple{Bool}}, typeof(Pkg.TOML.printvalue), Base.IOStream, Array{String, 1}})
precompile(Tuple{getfield(Pkg.TOML, Symbol("#kw##printvalue")), NamedTuple{(:sorted,), Tuple{Bool}}, typeof(Pkg.TOML.printvalue), Base.IOStream, String})
precompile(Tuple{getfield(REPL.LineEdit, Symbol("#kw##add_nested_key!")), NamedTuple{(:override,), Tuple{Bool}}, typeof(REPL.LineEdit.add_nested_key!), Base.Dict{Char, Any}, String, Nothing})
precompile(Tuple{getfield(REPL.LineEdit, Symbol("#kw##refresh_multi_line")), NamedTuple{(:indent, :region_active), Tuple{Int64, Bool}}, typeof(REPL.LineEdit.refresh_multi_line), REPL.Terminals.TerminalBuffer, REPL.Terminals.TTYTerminal, Base.GenericIOBuffer{Array{UInt8, 1}}, REPL.LineEdit.InputAreaState, REPL.LineEdit.PromptState})
precompile(Tuple{typeof(Base.:(!=)), Base.SubString{String}, Nothing})
precompile(Tuple{typeof(Base.:(!=)), Base.UUID, Base.UUID})
precompile(Tuple{typeof(Base.:(==)), Base.Dict{String, Any}, Nothing})
precompile(Tuple{typeof(Base.:(==)), Base.SHA1, Nothing})
precompile(Tuple{typeof(Base.:(==)), Base.UUID, Base.UUID})
precompile(Tuple{typeof(Base.:(==)), Expr, Int64})
precompile(Tuple{typeof(Base.:(==)), Nothing, Base.UUID})
precompile(Tuple{typeof(Base.:(==)), Nothing, Nothing})
precompile(Tuple{typeof(Base.:(==)), String, Nothing})
precompile(Tuple{typeof(Base.:(==)), Symbol, Int64})
precompile(Tuple{typeof(Base.Cartesian._nloops), Int64, Symbol, Expr, Expr, Expr})
precompile(Tuple{typeof(Base.Cartesian.exprresolve), LineNumberNode})
precompile(Tuple{typeof(Base.Cartesian.lreplace!), Int64, Base.Cartesian.LReplace{String}})
precompile(Tuple{typeof(Base.Filesystem.ispath), String})
precompile(Tuple{typeof(Base.Filesystem.mtime), String})
precompile(Tuple{typeof(Base.Iterators.enumerate), Array{Base.VersionNumber, 1}})
precompile(Tuple{typeof(Base._array_for), Type{Array{Base.BitArray{2}, 1}}, Base.UnitRange{Int64}, Base.HasShape{1}})
precompile(Tuple{typeof(Base._array_for), Type{Array{Base.VersionNumber, 1}}, Base.UnitRange{Int64}, Base.HasShape{1}})
precompile(Tuple{typeof(Base._array_for), Type{Base.BitArray{1}}, Base.UnitRange{Int64}, Base.HasShape{1}})
precompile(Tuple{typeof(Base._array_for), Type{Base.BitArray{2}}, Base.UnitRange{Int64}, Base.HasShape{1}})
precompile(Tuple{typeof(Base._array_for), Type{Base.Dict{Base.VersionNumber, Int64}}, Base.UnitRange{Int64}, Base.HasShape{1}})
precompile(Tuple{typeof(Base._array_for), Type{Base.UUID}, Base.ValueIterator{Base.Dict{String, Any}}, Base.HasLength})
precompile(Tuple{typeof(Base._collect), Array{Pkg.REPLMode.Statement, 1}, Base.Generator{Array{Pkg.REPLMode.Statement, 1}, Type{Pkg.REPLMode.PkgCommand}}, Base.EltypeUnknown, Base.HasShape{1}})
precompile(Tuple{typeof(Base._compute_eltype), Type{Tuple{Array{String, 1}, LibGit2.CachedCredentials}}})
precompile(Tuple{typeof(Base._compute_eltype), Type{Tuple{Bool, LibGit2.CachedCredentials}}})
precompile(Tuple{typeof(Base._compute_eltype), Type{Tuple{Int32, Base.Cstring, Ptr{Nothing}}}})
precompile(Tuple{typeof(Base._deepcopy_array_t), Array{Base.Dict{String, Any}, 1}, Type{Base.Dict{String, Any}}, Base.IdDict{Any, Any}})
precompile(Tuple{typeof(Base._getindex), Base.IndexLinear, Base.BitArray{2}, Base.LogicalIndex{Int64, Base.BitArray{1}}, Int64})
precompile(Tuple{typeof(Base._iterate), Base.Dict{String, Any}, Int64})
precompile(Tuple{typeof(Base._promote_typejoin), Type{Any}, Type{Ptr{Nothing}}})
precompile(Tuple{typeof(Base._promote_typejoin), Type{Array{String, 1}}, Type{LibGit2.CachedCredentials}})
precompile(Tuple{typeof(Base._promote_typejoin), Type{Bool}, Type{LibGit2.CachedCredentials}})
precompile(Tuple{typeof(Base._promote_typejoin), Type{Int32}, Type{Base.Cstring}})
precompile(Tuple{typeof(Base._promote_typejoin), Type{Union{}}, Type{Array{String, 1}}})
precompile(Tuple{typeof(Base._promote_typejoin), Type{Union{}}, Type{Bool}})
precompile(Tuple{typeof(Base._promote_typejoin), Type{Union{}}, Type{Int32}})
precompile(Tuple{typeof(Base._shrink), typeof(Base.setdiff!), Array{Base.UUID, 1}, Tuple{Array{Base.UUID, 1}}})
precompile(Tuple{typeof(Base.add_sum), Int64, Int64})
precompile(Tuple{typeof(Base.afoldl), typeof(Base.:(+)), Int64, Int64, Int64})
precompile(Tuple{typeof(Base.all), Base.Generator{Base.ValueIterator{Base.Dict{String, Any}}, typeof(Pkg.TOML.is_tabular)}})
precompile(Tuple{typeof(Base.close), Base.Channel{Any}})
precompile(Tuple{typeof(Base.close), LibGit2.GitAnnotated})
precompile(Tuple{typeof(Base.close), LibGit2.GitConfig})
precompile(Tuple{typeof(Base.close), LibGit2.GitDiff})
precompile(Tuple{typeof(Base.close), LibGit2.GitReference})
precompile(Tuple{typeof(Base.close), LibGit2.GitRemote})
precompile(Tuple{typeof(Base.close), LibGit2.GitRepo})
precompile(Tuple{typeof(Base.close), LibGit2.GitTree})
precompile(Tuple{typeof(Base.cmd_gen), Tuple{Tuple{Base.Cmd}}})
precompile(Tuple{typeof(Base.collect), Base.Generator{Array{Any, 1}, typeof(Pkg.TOML.table2dict)}})
precompile(Tuple{typeof(Base.collect), Base.Generator{Base.ValueIterator{Base.Dict{String, Any}}, Type{Base.UUID}}})
precompile(Tuple{typeof(Base.collect), Base.Generator{Base.ValueIterator{Base.Dict{String, String}}, Type{Base.UUID}}})
precompile(Tuple{typeof(Base.collect), Base.KeySet{String, Base.Dict{String, Any}}})
precompile(Tuple{typeof(Base.collect_similar), Array{LibGit2.GitAnnotated, 1}, Base.Generator{Array{LibGit2.GitAnnotated, 1}, typeof(Base.close)}})
precompile(Tuple{typeof(Base.collect_to_with_first!), Array{Base.UUID, 1}, Base.UUID, Base.Generator{Base.ValueIterator{Base.Dict{String, Any}}, Type{Base.UUID}}, Int64})
precompile(Tuple{typeof(Base.collect_to_with_first!), Array{String, 1}, String, Base.Generator{Array{String, 1}, typeof(Pkg.REPLMode.word2token)}, Int64})
precompile(Tuple{typeof(Base.convert), Type{Array{Array{Base.BitArray{2}, 1}, 1}}, Array{Array{Base.BitArray{2}, 1}, 1}})
precompile(Tuple{typeof(Base.convert), Type{Array{Array{Base.VersionNumber, 1}, 1}}, Array{Array{Base.VersionNumber, 1}, 1}})
precompile(Tuple{typeof(Base.convert), Type{Array{Array{Int64, 1}, 1}}, Array{Array{Int64, 1}, 1}})
precompile(Tuple{typeof(Base.convert), Type{Array{Base.BitArray{1}, 1}}, Array{Base.BitArray{1}, 1}})
precompile(Tuple{typeof(Base.convert), Type{Array{Base.Dict{Base.VersionNumber, Int64}, 1}}, Array{Base.Dict{Base.VersionNumber, Int64}, 1}})
precompile(Tuple{typeof(Base.convert), Type{Array{Base.UUID, 1}}, Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.convert), Type{Array{Char, 1}}, Array{Char, 1}})
precompile(Tuple{typeof(Base.convert), Type{Array{Int64, 1}}, Array{Int64, 1}})
precompile(Tuple{typeof(Base.convert), Type{Array{Symbol, 1}}, Array{UInt8, 1}})
precompile(Tuple{typeof(Base.convert), Type{Array{Union{Pkg.Types.VersionRange, String, Pkg.REPLMode.Rev}, 1}}, Array{String, 1}})
precompile(Tuple{typeof(Base.convert), Type{Base.Dict{Base.UUID, Int64}}, Base.Dict{Base.UUID, Int64}})
precompile(Tuple{typeof(Base.convert), Type{Base.Dict{Base.UUID, Pkg.GraphType.ResolveLogEntry}}, Base.Dict{Base.UUID, Pkg.GraphType.ResolveLogEntry}})
precompile(Tuple{typeof(Base.convert), Type{Base.Dict{K, V} where V where K}, Base.Dict{Symbol, Any}})
precompile(Tuple{typeof(Base.convert), Type{Base.Dict{Symbol, Any}}, Base.Dict{Any, Any}})
precompile(Tuple{typeof(Base.convert), Type{Base.UUID}, Base.UUID})
precompile(Tuple{typeof(Base.convert), Type{REPL.LineEdit.TextInterface}, REPL.LineEdit.Prompt})
precompile(Tuple{typeof(Base.convert), Type{REPL.Terminals.AbstractTerminal}, REPL.Terminals.TTYTerminal})
precompile(Tuple{typeof(Base.convert), Type{REPL.Terminals.TextTerminal}, REPL.Terminals.TTYTerminal})
precompile(Tuple{typeof(Base.convert), Type{Union{Nothing, IO}}, Base.IOStream})
precompile(Tuple{typeof(Base.convert), Type{Union{Nothing, IO}}, Nothing})
precompile(Tuple{typeof(Base.convert), Type{Union{Nothing, REPL.LineEdit.Prompt}}, Nothing})
precompile(Tuple{typeof(Base.convert), Type{Union{Pkg.Types.UpgradeLevel, Base.VersionNumber, Pkg.Types.VersionSpec}}, Base.VersionNumber})
precompile(Tuple{typeof(Base.copy_chunks!), Array{UInt64, 1}, Int64, Array{UInt64, 1}, Int64, Int64})
precompile(Tuple{typeof(Base.count), Base.BitArray{1}})
precompile(Tuple{typeof(Base.deepcopy), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.deepcopy_internal), Array{Base.Dict{String, Any}, 1}, Base.IdDict{Any, Any}})
precompile(Tuple{typeof(Base.deepcopy_internal), Base.Dict{Any, Any}, Base.IdDict{Any, Any}})
precompile(Tuple{typeof(Base.deepcopy_internal), Base.Dict{String, Any}, Base.IdDict{Any, Any}})
precompile(Tuple{typeof(Base.deepcopy_internal), Base.Dict{String, String}, Base.IdDict{Any, Any}})
precompile(Tuple{typeof(Base.deepcopy_internal), String, Base.IdDict{Any, Any}})
precompile(Tuple{typeof(Base.delete!), Base.Dict{String, Any}, String})
precompile(Tuple{typeof(Base.delete!), Base.IdDict{Any, Any}, Symbol})
precompile(Tuple{typeof(Base.empty), Base.Dict{Any, Any}, Type{Base.UUID}, Type{Int64}})
precompile(Tuple{typeof(Base.empty), Base.Dict{Any, Any}, Type{String}, Type{Base.UUID}})
precompile(Tuple{typeof(Base.empty), Base.Dict{Any, Any}, Type{String}, Type{String}})
precompile(Tuple{typeof(Base.eof), Base.IOStream})
precompile(Tuple{typeof(Base.get!), Base.Dict{Base.UUID, Array{String, 1}}, Base.UUID, Array{String, 1}})
precompile(Tuple{typeof(Base.get!), Base.Dict{Pkg.Types.VersionRange, Base.Dict{String, Base.UUID}}, Pkg.Types.VersionRange, Base.Dict{String, Base.UUID}})
precompile(Tuple{typeof(Base.get!), Base.Dict{Pkg.Types.VersionRange, Base.Dict{String, Pkg.Types.VersionSpec}}, Pkg.Types.VersionRange, Base.Dict{String, Pkg.Types.VersionSpec}})
precompile(Tuple{typeof(Base.get!), Base.Dict{String, Any}, String, Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Base.get!), Base.Dict{String, Array{Base.UUID, 1}}, String, Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.get), Base.Dict{String, Any}, String, Base.Dict{Any, Any}})
precompile(Tuple{typeof(Base.get), Base.Dict{String, Pkg.REPLMode.CommandSpec}, String, Nothing})
precompile(Tuple{typeof(Base.getindex), Array{Array{Base.VersionNumber, 1}, 1}, Int64})
precompile(Tuple{typeof(Base.getindex), Array{Array{Int64, 1}, 1}, Int64})
precompile(Tuple{typeof(Base.getindex), Array{Array{UInt64, 1}, 1}, Int64})
precompile(Tuple{typeof(Base.getindex), Array{Base.BitArray{1}, 1}, Int64})
precompile(Tuple{typeof(Base.getindex), Array{Base.BitArray{2}, 1}, Int64})
precompile(Tuple{typeof(Base.getindex), Array{Base.Dict{Int64, Int64}, 1}, Int64})
precompile(Tuple{typeof(Base.getindex), Array{Base.Dict{String, Any}, 1}, Int64})
precompile(Tuple{typeof(Base.getindex), Array{Base.UUID, 1}, Int64})
precompile(Tuple{typeof(Base.getindex), Array{Base.VersionNumber, 1}, Base.BitArray{1}})
precompile(Tuple{typeof(Base.getindex), Array{Int64, 1}, Int64})
precompile(Tuple{typeof(Base.getindex), Base.BitArray{1}, Base.UnitRange{Int64}})
precompile(Tuple{typeof(Base.getindex), Base.BitArray{2}, Base.BitArray{1}, Base.BitArray{1}})
precompile(Tuple{typeof(Base.getindex), Base.Dict{Int64, Int64}, Int64})
precompile(Tuple{typeof(Base.getindex), Base.Dict{String, Base.UUID}, String})
precompile(Tuple{typeof(Base.getindex), Base.Dict{Symbol, Function}, Symbol})
precompile(Tuple{typeof(Base.getindex), NamedTuple{(:indent, :region_active), Tuple{Int64, Bool}}, Symbol})
precompile(Tuple{typeof(Base.getindex), NamedTuple{(:prompt_prefix, :prompt_suffix, :complete, :sticky), Tuple{String, String, Pkg.REPLMode.PkgCompletionProvider, Bool}}, Symbol})
precompile(Tuple{typeof(Base.getindex), NamedTuple{(:prompt_prefix, :prompt_suffix, :repl, :complete, :on_enter), Tuple{String, typeof(Base.input_color), REPL.LineEditREPL, REPL.REPLCompletionProvider, typeof(REPL.return_callback)}}, Symbol})
precompile(Tuple{typeof(Base.getindex), Pkg.TOML.Table, String})
precompile(Tuple{typeof(Base.getindex), Type{Pkg.Types.VersionRange}, Pkg.Pkg2.Pkg2Types.VersionInterval})
precompile(Tuple{typeof(Base.getproperty), Pkg.TOML.Table, Symbol})
precompile(Tuple{typeof(Base.getproperty), Pkg.Types.PackageSpec, Symbol})
precompile(Tuple{typeof(Base.getproperty), REPL.Terminals.TerminalBuffer, Symbol})
precompile(Tuple{typeof(Base.hash), Tuple{String, UInt64}, UInt64})
precompile(Tuple{typeof(Base.hash), Tuple{String}, UInt64})
precompile(Tuple{typeof(Base.haskey), Base.Dict{Base.UUID, Base.Dict{K, V} where V where K}, Base.UUID})
precompile(Tuple{typeof(Base.haskey), Base.Dict{String, Base.UUID}, String})
precompile(Tuple{typeof(Base.haskey), Base.Dict{String, Pkg.Types.VersionSpec}, String})
precompile(Tuple{typeof(Base.haskey), NamedTuple{(:indent, :region_active), Tuple{Int64, Bool}}, Symbol})
precompile(Tuple{typeof(Base.haskey), NamedTuple{(:prompt_prefix, :prompt_suffix, :complete, :sticky), Tuple{String, String, Pkg.REPLMode.PkgCompletionProvider, Bool}}, Symbol})
precompile(Tuple{typeof(Base.haskey), NamedTuple{(:prompt_prefix, :prompt_suffix, :repl, :complete, :on_enter), Tuple{String, typeof(Base.input_color), REPL.LineEditREPL, REPL.REPLCompletionProvider, typeof(REPL.return_callback)}}, Symbol})
precompile(Tuple{typeof(Base.haskey), Pkg.TOML.Table, String})
precompile(Tuple{typeof(Base.ident_cmp), Tuple{String, UInt64}, Tuple{String, UInt64}})
precompile(Tuple{typeof(Base.ident_cmp), Tuple{String}, Tuple{String}})
precompile(Tuple{typeof(Base.ident_cmp), Tuple{}, Tuple{}})
precompile(Tuple{typeof(Base.identity), Int64})
precompile(Tuple{typeof(Base.in), Base.UUID, Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.in), Base.VersionNumber, Pkg.Types.VersionSpec})
precompile(Tuple{typeof(Base.in), String, Array{String, 1}})
precompile(Tuple{typeof(Base.in), String, Base.KeySet{String, Base.Dict{String, Any}}})
precompile(Tuple{typeof(Base.in), String, Base.KeySet{String, Base.Dict{String, Base.Dict{String, Pkg.REPLMode.CommandSpec}}}})
precompile(Tuple{typeof(Base.indexed_iterate), Base.Pair{Any, Any}, Int64, Int64})
precompile(Tuple{typeof(Base.indexed_iterate), Base.Pair{Any, Any}, Int64})
precompile(Tuple{typeof(Base.indexed_iterate), Base.Pair{String, Any}, Int64, Int64})
precompile(Tuple{typeof(Base.indexed_iterate), Base.Pair{String, Any}, Int64})
precompile(Tuple{typeof(Base.indexed_iterate), Tuple{Char, Bool}, Int64, Int64})
precompile(Tuple{typeof(Base.indexed_iterate), Tuple{Char, Bool}, Int64})
precompile(Tuple{typeof(Base.indexed_iterate), Tuple{String, Array{String, 1}, Array{String, 1}}, Int64, Int64})
precompile(Tuple{typeof(Base.indexed_iterate), Tuple{String, Array{String, 1}, Array{String, 1}}, Int64})
precompile(Tuple{typeof(Base.input_color)})
precompile(Tuple{typeof(Base.invokelatest), typeof(Pkg.REPLMode.do_status!), Base.Dict{Symbol, Any}, Array{String, 1}, Base.Dict{Symbol, Any}})
precompile(Tuple{typeof(Base.isempty), Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Base.isempty), Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.isempty), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.isempty), Base.Dict{String, String}})
precompile(Tuple{typeof(Base.isempty), NamedTuple{(:mode,), Tuple{Symbol}}})
precompile(Tuple{typeof(Base.isopen), Base.Channel{Any}})
precompile(Tuple{typeof(Base.iterate), Array{Base.Dict{String, Any}, 1}, Int64})
precompile(Tuple{typeof(Base.iterate), Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Base.iterate), Array{Base.UUID, 1}, Int64})
precompile(Tuple{typeof(Base.iterate), Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.iterate), Base.Channel{Any}})
precompile(Tuple{typeof(Base.iterate), Base.Dict{Any, Any}, Int64})
precompile(Tuple{typeof(Base.iterate), Base.Dict{Any, Any}})
precompile(Tuple{typeof(Base.iterate), Base.Dict{String, Any}, Int64})
precompile(Tuple{typeof(Base.iterate), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.iterate), Tuple{Base.BitArray{1}}, Int64})
precompile(Tuple{typeof(Base.iterate), Tuple{Base.BitArray{1}}})
precompile(Tuple{typeof(Base.join), Base.GenericIOBuffer{Array{UInt8, 1}}, Tuple{String}, Char})
precompile(Tuple{typeof(Base.join), Base.GenericIOBuffer{Array{UInt8, 1}}, Tuple{Symbol, Symbol}, String})
precompile(Tuple{typeof(Base.join), Base.GenericIOBuffer{Array{UInt8, 1}}, Tuple{UInt32, UInt32, UInt32}, Char})
precompile(Tuple{typeof(Base.join), Base.GenericIOBuffer{Array{UInt8, 1}}, Tuple{UInt32, UInt32}, Char})
precompile(Tuple{typeof(Base.join), Tuple{Symbol, Symbol}, String})
precompile(Tuple{typeof(Base.keys), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.keys), Base.Dict{String, Base.Dict{String, Pkg.REPLMode.CommandSpec}}})
precompile(Tuple{typeof(Base.lastindex), Base.BitArray{1}})
precompile(Tuple{typeof(Base.length), Array{Array{Base.BitArray{2}, 1}, 1}})
precompile(Tuple{typeof(Base.length), Array{Array{Base.VersionNumber, 1}, 1}})
precompile(Tuple{typeof(Base.length), Array{Array{Int64, 1}, 1}})
precompile(Tuple{typeof(Base.length), Array{Base.BitArray{1}, 1}})
precompile(Tuple{typeof(Base.length), Array{Base.Dict{Base.VersionNumber, Int64}, 1}})
precompile(Tuple{typeof(Base.length), Array{Base.Dict{Int64, Int64}, 1}})
precompile(Tuple{typeof(Base.length), Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Base.length), Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.length), Array{Int64, 1}})
precompile(Tuple{typeof(Base.length), Base.BitArray{1}})
precompile(Tuple{typeof(Base.length), Base.Dict{Base.UUID, Int64}})
precompile(Tuple{typeof(Base.length), Base.Dict{Base.UUID, Pkg.GraphType.ResolveLogEntry}})
precompile(Tuple{typeof(Base.length), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.map), Type{Base.UUID}, Base.ValueIterator{Base.Dict{String, Any}}})
precompile(Tuple{typeof(Base.map), Type{Base.UUID}, Base.ValueIterator{Base.Dict{String, String}}})
precompile(Tuple{typeof(Base.map), typeof(Base.close), Array{LibGit2.GitAnnotated, 1}})
precompile(Tuple{typeof(Base.mapreduce_first), typeof(Base.identity), typeof(Base.add_sum), Int64})
precompile(Tuple{typeof(Base.match), Base.Regex, String})
precompile(Tuple{typeof(Base.merge!), Base.Dict{String, Any}, Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.merge), Base.Dict{String, Any}, Base.Dict{String, String}})
precompile(Tuple{typeof(Base.merge), NamedTuple{(), Tuple{}}, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}})
precompile(Tuple{typeof(Base.merge), NamedTuple{(), Tuple{}}, NamedTuple{(:mode,), Tuple{Symbol}}})
precompile(Tuple{typeof(Base.merge), NamedTuple{(:payload,), Tuple{Base.Dict{Symbol, Any}}}, NamedTuple{(:transfer_progress, :credentials), Tuple{Ptr{Nothing}, Ptr{Nothing}}}})
precompile(Tuple{typeof(Base.merge_names), Tuple{Symbol, Symbol, Symbol}, Tuple{Symbol}})
precompile(Tuple{typeof(Base.merge_names), Tuple{Symbol, Symbol}, Tuple{Symbol, Symbol}})
precompile(Tuple{typeof(Base.merge_names), Tuple{Symbol, Symbol}, Tuple{Symbol}})
precompile(Tuple{typeof(Base.merge_names), Tuple{Symbol}, Tuple{Symbol, Symbol}})
precompile(Tuple{typeof(Base.merge_names), Tuple{Symbol}, Tuple{Symbol}})
precompile(Tuple{typeof(Base.merge_names), Tuple{Symbol}, Tuple{}})
precompile(Tuple{typeof(Base.notify_error), Base.Channel{Any}, Base.InvalidStateException})
precompile(Tuple{typeof(Base.peek), Base.IOStream})
precompile(Tuple{typeof(Base.prepend!), Array{Base.Dict{Any, Any}, 1}, Array{Base.Dict{Any, Any}, 1}})
precompile(Tuple{typeof(Base.print), Base.GenericIOBuffer{Array{UInt8, 1}}, Base.SubString{String}})
precompile(Tuple{typeof(Base.print), Base.GenericIOBuffer{Array{UInt8, 1}}, Pkg.Types.VersionSpec})
precompile(Tuple{typeof(Base.print), Base.IOStream, String, String, String, Char})
precompile(Tuple{typeof(Base.print), Base.TTY, String, String, Char})
precompile(Tuple{typeof(Base.promote_eltype), Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg.Types.VersionSpec}}})
precompile(Tuple{typeof(Base.push!), Array{Base.UUID, 1}, Base.UUID})
precompile(Tuple{typeof(Base.push!), Array{Int64, 1}, Int64})
precompile(Tuple{typeof(Base.push!), Array{Pkg.Types.VersionRange, 1}, Pkg.Types.VersionRange})
precompile(Tuple{typeof(Base.push!), Array{Tuple{Base.UUID, String}, 1}, Tuple{Base.UUID, String}})
precompile(Tuple{typeof(Base.push!), Base.Set{Base.VersionNumber}, Base.VersionNumber})
precompile(Tuple{typeof(Base.push!), Base.Set{Symbol}, Symbol})
precompile(Tuple{typeof(Base.push!), Pkg.GraphType.ResolveLogEntry, Tuple{Nothing, String}})
precompile(Tuple{typeof(Base.push!), Pkg.GraphType.ResolveLogEntry, Tuple{Pkg.GraphType.ResolveLogEntry, String}})
precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Tuple{String, Array{String, 1}, Array{String, 1}}})
precompile(Tuple{typeof(Base.rethrow), Base.InvalidStateException})
precompile(Tuple{typeof(Base.rstrip), String})
precompile(Tuple{typeof(Base.seek), Base.IOStream, Int64})
precompile(Tuple{typeof(Base.setdiff!), Base.Set{Base.UUID}, Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.setindex!), Array{Base.BitArray{1}, 1}, Base.BitArray{1}, Int64})
precompile(Tuple{typeof(Base.setindex!), Base.BitArray{1}, Bool, Int64})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{Base.UUID, Base.Dict{K, V} where V where K}, Base.Dict{String, Any}, Base.UUID})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{Base.UUID, Int64}, Int64, Base.UUID})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{Base.UUID, Pkg.Types.VersionSpec}, Pkg.Types.VersionSpec, Base.UUID})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{Base.UUID, String}, String, Base.UUID})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{Base.VersionNumber, Base.SHA1}, Base.SHA1, Base.VersionNumber})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{Int64, Int64}, Int64, Int64})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Array{Any, 1}, String})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Array{Base.Dict{String, Any}, 1}, String})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Array{String, 1}, String})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Base.Dict{Any, Any}, String})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Base.Dict{String, String}, String})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Base.UUID, String})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Base.UUID}, Base.UUID, String})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Pkg.Types.VersionSpec}, Pkg.Types.VersionSpec, String})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{Symbol, Any}, LibGit2.CredentialPayload, Symbol})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{Symbol, Any}, Pkg.GitTools.MiniProgressBar, Symbol})
precompile(Tuple{typeof(Base.setindex!), Base.EnvDict, String, String})
precompile(Tuple{typeof(Base.setproperty!), Pkg.GraphType.Graph, Symbol, Array{Array{Base.BitArray{2}, 1}, 1}})
precompile(Tuple{typeof(Base.setproperty!), Pkg.GraphType.Graph, Symbol, Array{Array{Int64, 1}, 1}})
precompile(Tuple{typeof(Base.setproperty!), Pkg.GraphType.Graph, Symbol, Array{Base.BitArray{1}, 1}})
precompile(Tuple{typeof(Base.setproperty!), Pkg.GraphType.Graph, Symbol, Array{Int64, 1}})
precompile(Tuple{typeof(Base.setproperty!), Pkg.GraphType.GraphData, Symbol, Array{Array{Base.VersionNumber, 1}, 1}})
precompile(Tuple{typeof(Base.setproperty!), Pkg.GraphType.GraphData, Symbol, Array{Base.Dict{Base.VersionNumber, Int64}, 1}})
precompile(Tuple{typeof(Base.setproperty!), Pkg.GraphType.GraphData, Symbol, Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.setproperty!), Pkg.GraphType.GraphData, Symbol, Array{Int64, 1}})
precompile(Tuple{typeof(Base.setproperty!), Pkg.GraphType.GraphData, Symbol, Base.Dict{Base.UUID, Int64}})
precompile(Tuple{typeof(Base.setproperty!), Pkg.GraphType.ResolveLog, Symbol, Base.Dict{Base.UUID, Pkg.GraphType.ResolveLogEntry}})
precompile(Tuple{typeof(Base.setproperty!), Pkg.REPLMode.Statement, Symbol, Pkg.REPLMode.CommandSpec})
precompile(Tuple{typeof(Base.setproperty!), Pkg.Types.PackageSpec, Symbol, Base.UUID})
precompile(Tuple{typeof(Base.setproperty!), Pkg.Types.PackageSpec, Symbol, Base.VersionNumber})
precompile(Tuple{typeof(Base.setproperty!), Pkg.Types.PackageSpec, Symbol, String})
precompile(Tuple{typeof(Base.similar), Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Base.skip_deleted_floor!), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.string), String, Base.SubString{String}, String, String})
precompile(Tuple{typeof(Base.string), Symbol, Int64})
precompile(Tuple{typeof(Base.strip), Base.SubString{String}})
precompile(Tuple{typeof(Base.structdiff), NamedTuple{(:indent, :region_active), Tuple{Int64, Bool}}, Type{NamedTuple{(:indent, :region_active), T} where T<:Tuple}})
precompile(Tuple{typeof(Base.structdiff), NamedTuple{(:prompt_prefix, :prompt_suffix, :complete, :sticky), Tuple{String, String, Pkg.REPLMode.PkgCompletionProvider, Bool}}, Type{NamedTuple{(:prompt_prefix, :prompt_suffix, :keymap_dict, :repl, :complete, :on_enter, :on_done, :hist, :sticky), T} where T<:Tuple}})
precompile(Tuple{typeof(Base.structdiff), NamedTuple{(:prompt_prefix, :prompt_suffix, :repl, :complete, :on_enter), Tuple{String, typeof(Base.input_color), REPL.LineEditREPL, REPL.REPLCompletionProvider, typeof(REPL.return_callback)}}, Type{NamedTuple{(:prompt_prefix, :prompt_suffix, :keymap_dict, :repl, :complete, :on_enter, :on_done, :hist, :sticky), T} where T<:Tuple}})
precompile(Tuple{typeof(Base.sum), Array{Int64, 1}})
precompile(Tuple{typeof(Base.sym_in), Symbol, Tuple{Symbol, Symbol}})
precompile(Tuple{typeof(Base.sym_in), Symbol, Tuple{Symbol}})
precompile(Tuple{typeof(Base.sym_in), Symbol, Tuple{}})
precompile(Tuple{typeof(Base.to_indices), Base.BitArray{2}, Tuple{Base.OneTo{Int64}}, Tuple{Int64}})
precompile(Tuple{typeof(Base.trues), Int64})
precompile(Tuple{typeof(Base.union!), Base.Set{Base.UUID}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg.Types.Fixed}}})
precompile(Tuple{typeof(Base.union!), Base.Set{Base.UUID}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg.Types.VersionSpec}}})
precompile(Tuple{typeof(Base.unique!), Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.unique!), Array{String, 1}})
precompile(Tuple{typeof(Base.values), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.values), Base.Dict{String, String}})
precompile(Tuple{typeof(Base.vcat), Base.BitArray{1}, Base.BitArray{1}})
precompile(Tuple{typeof(Base.vcat), Base.BitArray{1}})
precompile(Tuple{typeof(Base.vcat), Base.BitArray{2}, Base.BitArray{2}, Base.BitArray{2}, Base.BitArray{2}})
precompile(Tuple{typeof(Base.vcat), Base.BitArray{2}, Base.BitArray{2}})
precompile(Tuple{typeof(Base.vect), Base.Cmd, Base.Cmd})
precompile(Tuple{typeof(Base.vect), Base.VersionNumber})
precompile(Tuple{typeof(Base.vect), Nothing})
precompile(Tuple{typeof(Base.write), Base.TTY, Array{UInt8, 1}})
precompile(Tuple{typeof(Base.write), REPL.Terminals.TTYTerminal, Array{UInt8, 1}})
precompile(Tuple{typeof(Core.Compiler.eltype), Type{Array{Base.BitArray{2}, 1}}})
precompile(Tuple{typeof(Core.Compiler.eltype), Type{Array{Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg.Types.VersionSpec}}, 1}}})
precompile(Tuple{typeof(Core.Compiler.eltype), Type{Array{Pkg.Pkg2.Pkg2Types.VersionInterval, 1}}})
precompile(Tuple{typeof(Core.Compiler.eltype), Type{Array{UInt32, 1}}})
precompile(Tuple{typeof(Core.Compiler.eltype), Type{Array{UInt8, 1}}})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}, typeof(Base.invokelatest), Nothing}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}, typeof(Base.invokelatest), typeof(Pkg.REPLMode.do_help!)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}, typeof(Base.open), typeof(Pkg.Pkg2.Reqs.read)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}, typeof(Base.open), typeof(Pkg.TOML.parse)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Base.IteratorsMD.CartesianIndex{0}}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Base.Missing, Int64}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Base.Missing}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Base.Val{1}, typeof(Base.cat_t), Union}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Bool, typeof(Pkg.Types.parse_toml)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Int64, Tuple{Int64, Tuple{Int64, Tuple{Int64, Tuple{}}}}}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{NamedTuple{(:dims,), Tuple{Base.Val{1}}}, typeof(Base.cat_t), Union}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Nothing, Int64, typeof(Base.sprint), typeof(Base.showerror)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Nothing, Int64, typeof(Base.sprint), typeof(Pkg.GraphType.showlog)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{Pkg.REPLMode.CommandKind, Int64}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.:(!))}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.:(&))}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.:(+))}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.:(-))}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.:(==))}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.:(>))}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.:(~))}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.Unicode.lowercase)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.abs)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.first)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.identity)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Base.maximum)}, Int64})
precompile(Tuple{typeof(Core.Compiler.getindex), Tuple{typeof(Pkg.BinaryProvider.parse_tar_list)}, Int64})
precompile(Tuple{typeof(Pkg.Display.filter_manifest), Pkg.Display.InProject{Base.Dict{String, Any}}, Base.Dict{String, Any}})
precompile(Tuple{typeof(Pkg.Display.in_project), Base.Dict{String, Any}})
precompile(Tuple{typeof(Pkg.Display.manifest_diff), Pkg.Types.Context, Base.Dict{String, Any}, Base.Dict{String, Any}})
precompile(Tuple{typeof(Pkg.Display.name_ver_info), Base.Dict{String, Any}})
precompile(Tuple{typeof(Pkg.Display.not_in_project), Base.Dict{String, Any}})
precompile(Tuple{typeof(Pkg.Display.print_diff), Base.TTY, Pkg.Types.Context, Array{Pkg.Display.DiffEntry, 1}, Bool})
precompile(Tuple{typeof(Pkg.Operations.load_package_data_raw), Type{Base.UUID}, String})
precompile(Tuple{typeof(Pkg.REPLMode.do_add!), Base.Dict{Symbol, Any}, Array{Pkg.Types.PackageSpec, 1}, Base.Dict{Symbol, Any}})
precompile(Tuple{typeof(Pkg.REPLMode.do_status!), Base.Dict{Symbol, Any}, Array{String, 1}, Base.Dict{Symbol, Any}})
precompile(Tuple{typeof(Pkg.REPLMode.promptf)})
precompile(Tuple{typeof(Pkg.TOML.SOME), Array{String, 1}})
precompile(Tuple{typeof(Pkg.TOML.SOME), Pkg.TOML.Table})
precompile(Tuple{typeof(Pkg.TOML.insertpair), Pkg.TOML.Parser{Base.IOStream}, Pkg.TOML.Table, String, Array{String, 1}, Int64})
precompile(Tuple{typeof(Pkg.TOML.insertpair), Pkg.TOML.Parser{Base.IOStream}, Pkg.TOML.Table, String, Pkg.TOML.Table, Int64})
precompile(Tuple{typeof(Pkg.TOML.is_array_of_tables), Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Pkg.TOML.is_array_of_tables), Array{String, 1}})
precompile(Tuple{typeof(Pkg.TOML.is_array_of_tables), String})
precompile(Tuple{typeof(Pkg.TOML.is_tabular), Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Pkg.TOML.is_tabular), Array{String, 1}})
precompile(Tuple{typeof(Pkg.TOML.is_tabular), Base.Dict{String, Any}})
precompile(Tuple{typeof(Pkg.TOML.is_tabular), String})
precompile(Tuple{typeof(Pkg.TOML.parsefile), String})
precompile(Tuple{typeof(Pkg.Types.printpkgstyle), Base.TTY, Symbol, String})
precompile(Tuple{typeof(Pkg.Types.semver_interval), Base.RegexMatch})
precompile(Tuple{typeof(Pkg.Types.write_env_usage), String})
precompile(Tuple{typeof(REPL.LineEdit._clear_input_area), REPL.Terminals.TerminalBuffer, REPL.LineEdit.InputAreaState})
precompile(Tuple{typeof(REPL.LineEdit.add_history), REPL.REPLHistoryProvider, REPL.LineEdit.PromptState})
precompile(Tuple{typeof(REPL.LineEdit.clear_input_area), REPL.Terminals.TerminalBuffer, REPL.LineEdit.PromptState})
precompile(Tuple{typeof(REPL.LineEdit.edit_abort), REPL.LineEdit.MIState, Bool})
precompile(Tuple{typeof(REPL.LineEdit.edit_insert), REPL.LineEdit.MIState, String})
precompile(Tuple{typeof(REPL.LineEdit.edit_insert), REPL.LineEdit.PromptState, String})
precompile(Tuple{typeof(REPL.LineEdit.fixup_keymaps!), Base.Dict{Char, Any}, Int64, Char, Nothing})
precompile(Tuple{typeof(REPL.LineEdit.init_state), REPL.Terminals.TTYTerminal, REPL.LineEdit.Prompt})
precompile(Tuple{typeof(REPL.LineEdit.move_input_end), REPL.LineEdit.MIState})
precompile(Tuple{typeof(REPL.LineEdit.normalize_key), Int64})
precompile(Tuple{typeof(REPL.LineEdit.normalize_key), String})
precompile(Tuple{typeof(REPL.LineEdit.on_enter), REPL.LineEdit.MIState})
precompile(Tuple{typeof(REPL.LineEdit.postprocess!), Base.Dict{Char, Any}})
precompile(Tuple{typeof(REPL.LineEdit.prompt_string), String})
precompile(Tuple{typeof(REPL.LineEdit.push_undo), REPL.LineEdit.PromptState, Bool})
precompile(Tuple{typeof(REPL.LineEdit.refresh_line), REPL.LineEdit.PromptState, REPL.Terminals.TTYTerminal})
precompile(Tuple{typeof(REPL.LineEdit.refresh_multi_line), REPL.Terminals.TerminalBuffer, REPL.LineEdit.PromptState})
precompile(Tuple{typeof(REPL.LineEdit.state), REPL.LineEdit.MIState, REPL.LineEdit.Prompt})
precompile(Tuple{typeof(REPL.LineEdit.update_key_repeats), REPL.LineEdit.MIState, Array{Char, 1}})
precompile(Tuple{typeof(REPL.LineEdit.write_prompt), REPL.Terminals.TerminalBuffer, REPL.LineEdit.Prompt})
precompile(Tuple{typeof(REPL.LineEdit.write_prompt), REPL.Terminals.TerminalBuffer, String})

max_stars_repo_name: pochoi/julia

max_issues_repo_name: pochoi/julia

max_forks_repo_name: pochoi/julia


text:
import Pkg
Pkg.add("JuMP")
Pkg.add("SCS")
Pkg.add("LinearAlgebra")
Pkg.add("Test")
using JuMP
import SCS
import LinearAlgebra
import Test

function example_robust_uncertainty()
    R = 1
    d = 3
    𝛿 = 0.05
    ɛ = 0.05
    N = ceil((2 + 2 * log(2 / 𝛿))^2) + 1
    c = randn(d)
    μhat = rand(d)
    M = rand(d, d)
    Σhat = 1 / (d - 1) * (M - ones(d) * μhat')' * (M - ones(d) * μhat')
    Γ1(𝛿, N) = R / sqrt(N) * (2 + sqrt(2 * log(1 / 𝛿)))
    Γ2(𝛿, N) = 2 * R^2 / sqrt(N) * (2 + sqrt(2 * log(2 / 𝛿)))
    model = Model(SCS.Optimizer)

    @variable(model, Σ[1:d, 1:d], PSD)
    @variable(model, u[1:d])
    @variable(model, μ[1:d])
    @constraint(model, [Γ1(𝛿 / 2, N); μ - μhat] in SecondOrderCone())
    @constraint(model, [Γ2(𝛿 / 2, N); vec(Σ - Σhat)] in SecondOrderCone())
    @constraint(model, [((1-ɛ)/ɛ) (u - μ)'; (u-μ) Σ] in PSDCone())
    @objective(model, Max, LinearAlgebra.dot(c, u))
    optimize!(model)
    I = Matrix(1.0 * LinearAlgebra.I, d, d)
    exact =
        LinearAlgebra.dot(μhat, c) +
        Γ1(𝛿 / 2, N) * LinearAlgebra.norm(c) +
        sqrt((1 - ɛ) / ɛ) *
        sqrt(LinearAlgebra.dot(c, (Σhat + Γ2(𝛿 / 2, N) * I) * c))
    Test.@test objective_value(model) ≈ exact atol = 1e-2

    return
end

example_robust_uncertainty()


text:
import ..UncertainValues.AbstractUncertainValue
import ..UncertainValues.TheoreticalFittedUncertainScalar
import ..UncertainValues.UncertainScalarTheoreticalFit

import ..UncertainValues.FittedDistribution

########################################################################
# Resampling without constraints
########################################################################

resample(ue::UncertainScalarTheoreticalFit) =
    rand(ue.distribution.distribution)
resample(ue::UncertainScalarTheoreticalFit, n::Int) =
    rand(ue.distribution.distribution, n)

resample(fd::FittedDistribution) = rand(fd.distribution)
resample(fd::FittedDistribution, n::Int) = rand(fd.distribution, n)


text:
#=

  Jobs puzzle in ConstraintSolver.jl

  This is a standard problem in Automatic Reasoning.

  From http://www-unix.mcs.anl.gov/~wos/mathproblems/jobs.html
  """
  Jobs Puzzle

  There are four people:  Roberta, Thelma, Steve, and Pete.
  Among them, they hold eight different jobs.
  Each holds exactly two jobs.
  The jobs are chef, guard, nurse, clerk, police officer (gender
  not implied), teacher, actor, and boxer.
  The job of nurse is held by a male.
  The husband of the chef is the clerk.
  Roberta is not a boxer.
  Pete has no education past the ninth grade.
  Roberta, the chef, and the police officer went golfing together.

  Question:  Who holds which jobs?
  """

  The answer:
  Chef       Thelma
  Guard      Roberta
  Nurse      Steve
  Clerk      Pete
  Police     Steve
  Teacher    Roberta
  Actor      Pete
  Boxer      Thelma

  Model created by Hakan Kjellerstrand, hakank@gmail.com
  See also my Julia page: http://www.hakank.org/julia/

=#
using ConstraintSolver, JuMP
using Cbc, GLPK, Ipopt
const CS = ConstraintSolver
include("constraints_utils.jl")

function jobs_puzzle(print_solutions=true,all_solutions=true,timeout=6)

    cbc_optimizer = optimizer_with_attributes(Cbc.Optimizer, "logLevel" => 0)
    glpk_optimizer = optimizer_with_attributes(GLPK.Optimizer)
    ipopt_optimizer = optimizer_with_attributes(Ipopt.Optimizer)

    model = Model(optimizer_with_attributes(CS.Optimizer,   "all_solutions"=> all_solutions,
                                                            # "all_optimal_solutions"=>all_solutions,
                                                            "logging"=>[],

                                                            "traverse_strategy"=>:BFS,
                                                            # "traverse_strategy"=>:DFS,
                                                            # "traverse_strategy"=>:DBFS,

                                                            # "branch_split"=>:Smallest,
                                                            # "branch_split"=>:Biggest,
                                                            "branch_split"=>:InHalf,

                                                            # https://wikunia.github.io/ConstraintSolver.jl/stable/options/#branch_strategy-(:Auto)
                                                            "branch_strategy" => :IMPS, # default
                                                            # "branch_strategy" => :ABS, # Activity Based Search
                                                            # "activity.decay" => 0.999, # default 0.999
                                                            # "activity.max_probes" => 10, # default, 10
                                                            # "activity.max_confidence_deviation" => 20, # default 20

                                                            # "simplify"=>false,
                                                            # "simplify"=>true, # default

                                                            "time_limit"=>timeout,

                                                            # "backtrack" => false, # default true
                                                            # "backtrack_sorting" => false, # default true

                                                            # "lp_optimizer" => cbc_optimizer,
                                                            # "lp_optimizer" => glpk_optimizer,
                                                            # "lp_optimizer" => ipopt_optimizer,
                                        ))
   num_people = 4
   num_jobs = 8
   people = 1:num_people
   Roberta, Thelma, Steve, Pete = people

   @variable(model, 1 <= Jobs[1:num_jobs] <= num_people, Int)
   Chef, Guard, Nurse, Clerk, PoliceOfficer, Teacher, Actor, Boxer = Jobs

   # Each holds exactly two jobs.
   for i in 1:4
        count_ctr(model, Jobs, :(==), i, 2)
   end

   # The job of nurse is held by a male.
   # (Nurse == Steve \/ Nurse == Pete),
   # either_eq(model, Nurse,Steve, Nurse,Pete)
   # is_member_of(model,Nurse, [Steve,Pete])
   b1 = @variable(model, binary=true)
   @constraint(model, b1 := {Nurse == Steve || Nurse == Pete})
   @constraint(model, b1 == 1)

   # @either_eq(model, :(Nurse==Steve), :(Nurse==Pete))

   # The husband of the chef is the clerk.
   # (Clerk == Steve   \/ Clerk == Pete),
   # either_eq(model, Clerk,Steve, Clerk,Pete)
   # is_member_of(model,Clerk, [Steve,Pete])
   b2 = @variable(model, binary=true)
   @constraint(model, b2 := {Clerk == Steve || Clerk == Pete})
   @constraint(model, b2 == 1)

   # (Chef  #= Roberta #\/ Chef #= Thelma),
   # either_eq(model, Chef,Roberta, Chef,Thelma)
   # is_member_of(model,Chef, [Roberta,Thelma])
   b3 = @variable(model, binary=true)
   @constraint(model, b3 := {Chef  == Roberta || Chef == Thelma})
   @constraint(model, b3 == 1)

   @constraint(model, Chef != Clerk)

   # Roberta is not a boxer.
   @constraint(model, Roberta != Boxer)

   # Pete has no education past the ninth grade.
   @constraint(model, Pete != Teacher)
   @constraint(model, Pete != PoliceOfficer)
   @constraint(model, Pete != Nurse)

   # Roberta, [and] the chef, and the police officer
   # went golfing together.
   @variable(model,Roberta <= RobertaVar <= Roberta, Int)
   @constraint(model, [RobertaVar,Chef,PoliceOfficer] in CS.AllDifferent())

   # From the name of the job
   # (Actor == Steve \/ Actor == Pete)
   # either_eq(model, Actor,Steve, Actor,Pete)
   # is_member_of(model,Actor, [Steve,Pete])
   b4 = @variable(model, binary=true)
   @constraint(model, b4 := {(Actor == Steve || Actor == Pete)})
   @constraint(model, b4 == 1)

    # Solve the problem
    optimize!(model)

    status = JuMP.termination_status(model)
    # println("status:$status")
    num_sols = 0
    if status == MOI.OPTIMAL
        num_sols = MOI.get(model, MOI.ResultCount())
        println("num_sols:$num_sols\n")
        if print_solutions
            for sol in 1:num_sols
                println("solution #$sol")
                jobs_val = convert.(Integer,JuMP.value.(Jobs; result=sol))
                println("jobs:$jobs_val")

            end
        end
    else
        println("status:$status")
    end

    return status, num_sols
end

@time jobs_puzzle(true,true)

max_stars_repo_name: tias/hakank

max_issues_repo_name: tias/hakank

max_forks_repo_name: tias/hakank