text:
"""
    Nystroem(x_samples, num_fun, cov_kernel)

Stores the `num_func` eigenvectors and eigenvalues, with which via the
Nyström method the solution of Fredholm integral equations of the
second kind can be approximated regarding the
the covariance kernel `cov_kernel`. These are constructed from the points
sampled `x_samples`.
The procedure is described in

Shi, Jiaxin and Sun, Shengyang and Zhu, Jun,
*A Spectral Approach to Gradient Estimation for Implicit Distributions*,
Proceedings of the 35th International Conference on Machine Learning,
4651--4660,
2018

See also: [`(nyst::Nystroem)(x)`](@ref)
"""
struct Nystroem{F <: Real, V <: AbstractVector{F}, M <: AbstractMatrix{F}, C <: CovKer}
    num_samples::Integer
    num_func::Integer
    x_samples::M
    eig_vec::M
    eig_val_inv::V
    cov_kernel::C
end

function compute_eig_K(x_samples::M, cov_kernel::C) where {
    F <: Real, M <: AbstractMatrix{F}, C <: CovKer}

    K = cov_kernel(x_samples)
    eigen(Symmetric(K))
end

function Nystroem(x_samples::M, num_func::Integer, cov_kernel::C) where {
        F <: Real, M <: AbstractMatrix{F}, C <: CovKer}
    eig_val, eig_vec = compute_eig_K(x_samples, cov_kernel)

    Nystroem{F, typeof(eig_val), M, C}(size(x_samples, 2), num_func,
        x_samples, eig_vec[:,(end-(num_func-1)):end], eig_val[(end-(num_func-1)):end].^-1, cov_kernel)
end

function Nystroem(x_samples::M, r_bar::F) where {
    F <: Real, M <: AbstractMatrix{F}}

    cov_kernel = SqExp(median(pairwise(Euclidean(), x_samples, dims=2)))
    eig_val, eig_vec = compute_eig_K(x_samples, cov_kernel)

    num_func = findfirst(cumsum(reverse(eig_val)/sum(eig_val)) .> r_bar)

    Nystroem{F, typeof(eig_val), M, typeof(cov_kernel)}(size(x_samples, 2), num_func,
        x_samples, eig_vec[:,(end-(num_func-1)):end], eig_val[(end-(num_func-1)):end].^-1, cov_kernel)
end

"""
    (nyst::Nystroem)(x)

Estimates the corresponding the solution of Fredholm integral equations of the
second kind of `n` at point `x`.
"""
(nyst::Nystroem)(x::W) where {W <: AbstractVector}  =
    sqrt(nyst.num_samples) .* nyst.eig_val_inv .*
        ([nyst.cov_kernel(x, nyst.x_samples[:, m]) for m in 1:nyst.num_samples]' * nyst.eig_vec)'


text:
# ====================
# Test Clause creation
# ====================
lc = LinearConstraint([1.; zeros(7)], 0.35)
# vector of atoms
c1 = Clause([lc, LinearConstraint([zeros(4); 1.; zeros(3)], 0.45)])
# single atom
c2 = Clause(lc)

# ======================
# Test LinearConstraintProperty creation
# ======================
# vector of clauses
p1 = LinearConstraintProperty([c1, c2])
# single clause
p2 = LinearConstraintProperty(c1)
# single constraint
p3 = LinearConstraintProperty(lc)
# single raw constraint
p4 = LinearConstraintProperty([1.; zeros(7)], 0.35)

# just have one actual test case...
@test true

ext: jl


text:
using Documenter, SensorFeatureTracking

makedocs(
    modules = [SensorFeatureTracking],
    format = :html,
    sitename = "SensorFeatureTracking.jl",
    pages = Any[
        "Home" => "index.md",
        "Functions" => "func_ref.md"
    ]
    # html_prettyurls = !("local" in ARGS),
    )

deploydocs(
    repo   = "github.com/JuliaRobotics/SensorFeatureTracking.jl.git",
    target = "build",
    deps   = nothing,
    make   = nothing,
    julia  = "0.6",
    osname = "linux"
)

# deploydocs(
#     deps   = Deps.pip("mkdocs", "python-markdown-math", "mkdocs-material"),
#     repo   = "github.com/JuliaRobotics/SensorFeatureTracking.jl.git",
#     julia  = "release",
# )

max_stars_repo_name: dehann/SensorFeatureTracking

max_issues_repo_name: dehann/SensorFeatureTracking

max_forks_repo_name: dehann/SensorFeatureTracking


text:
module EarlyStopping

using Dates
using Statistics
import Base.+

export StoppingCriterion,
    Never, NotANumber, TimeLimit, GL, Patience, UP, PQ,
    Disjunction, criteria, stopping_time, EarlyStopper,
    done!, message, needs_in_and_out_of_sample

include("api.jl")
include("criteria.jl")
include("disjunction.jl")
include("stopping_time.jl")
include("object_oriented_api.jl")

end # module


text:
using AbstractTrees

"""
    OneTree

A tree in which each node has 0 or 1 children.
"""
struct OneTree
    nodes::Vector{Int}
end

AbstractTrees.ParentLinks(::Type{OneTree}) = StoredParents()
AbstractTrees.SiblingLinks(::Type{OneTree}) = StoredSiblings()

AbstractTrees.rootindex(::OneTree) = 1

function AbstractTrees.childindices(ot::OneTree, idx::Integer)
    idx == length(ot.nodes) ? () : (idx+1,)
end

AbstractTrees.nodevalue(ot::OneTree, idx::Integer) = ot.nodes[idx]

AbstractTrees.parentindex(ot::OneTree, idx::Integer) = (idx == 1) ? nothing : idx-1

AbstractTrees.nextsiblingindex(::OneTree, ::Integer) = nothing

AbstractTrees.prevsiblingindex(::OneTree, ::Integer) = nothing

Base.IteratorEltype(::Type{<:TreeIterator{<:IndexNode{OneTree}}}) = Base.HasEltype()
Base.eltype(::Type{<:TreeIterator{<:IndexNode{OneTree}}}) = IndexNode{OneTree,Int}


text:
ENV["GKSwstype"] = "100"

using Pkg; Pkg.instantiate()

using JLD2
using FourierFlows
using Plots
using Printf
using FFTW: irfft

filename = "./data/kolmogorovflow.jld2"

withoutgif(path) = (length(path)>3 && path[end-3:end] == ".gif") ? path[1:end-4] : path

"""
    uniquepath(path)

Returns `path` with a number appended if `isfile(path)`, incremented until `path` does not exist.
"""
function uniquegifpath(path)
  n = 1
  if isfile(path)
    path = withoutgif(path) * "_$n.gif"
  end
  while isfile(path)
    n += 1
    path = withoutgif(path)[1:end-length("_$(n-1)")] * "_$n.gif"
  end

  return path
end

moviegif_filename = "./movies/kolmogorov_onlyflow.gif"
moviegif_filename = uniquegifpath(moviegif_filename)
moviemp4_filename = moviegif_filename[1:end-4]*".mp4"

# ## Visualizing the simulation

function plot_output(x, y, ζ, ψ, t, k₀, ν, t_final)
    tν = ν * k₀^2 * t

    p_ζ = heatmap(x, y, ζ',
             aspectratio = 1,
                       c = :balance,
                    #clim = (-2, 2),
                   xlims = (x[1], x[end]),
                   ylims = (y[1], y[end]),
                  xlabel = "x",
                  ylabel = "y",
                   title = "vorticity, tν = "*@sprintf("%.2f", tν),
              framestyle = :box)

    p_ψ = contourf(x, y, ψ',
               aspectratio = 1,
                    levels = 11,
                     xlims = (x[1], x[end]),
                     ylims = (y[1], y[end]),
                    xlabel = "x",
                    ylabel = "y",
                     title = "streamfunction",
                framestyle = :box)

    l = @layout Plots.grid(1, 2)

    p = plot(p_ζ, p_ψ, layout = l, size = (900, 500))

    return p
end

# now let's make a movie of the flow fields

file = jldopen(filename)

nx, ny = file["grid/nx"], file["grid/ny"]
Lx, Ly = file["grid/Lx"], file["grid/Ly"]

global ν = file["params/ν"]
global k₀ = file["params/k₀"]
global nsubs = file["params/nsubs"]

grid = TwoDGrid(nx, Lx, ny, Ly)

x, y = grid.x, grid.y

iterations = parse.(Int, keys(file["snapshots/t"]))
final_iteration = iterations[end]

ζh_initial = file["snapshots/zetah/0"]
t_final = file["snapshots/t/$final_iteration"]

ζh = zeros(Complex{Float64}, (grid.nkr, grid.nl))
ψh = zeros(Complex{Float64}, (grid.nkr, grid.nl))

@. ζh = ζh_initial
ζ = irfft(deepcopy(ζh), grid.nx)
@. ψh = @. -grid.invKrsq * ζh
ψ = irfft(deepcopy(ψh), grid.nx)

global p = plot_output(x, y, ζ, ψ, 0.0, k₀, ν, t_final)

global total_iterations = length(iterations)

startwalltime = time()

anim = @animate for (i, iteration) in enumerate(iterations[1:end-1])

  if i%25== 0
    estimated_remaining_walltime = (time()-startwalltime)/60 / i * (total_iterations - i)
    log = @sprintf("estimated remaining walltime: %.2f min", estimated_remaining_walltime)
    println(log)
  end

  local t = file["snapshots/t/$iteration"]
  local tν = ν * k₀^2 * t

  local ζh = file["snapshots/zetah/$iteration"]

  @. ψh = -grid.invKrsq * ζh

  local ζ = irfft(ζh, grid.nx)
  local ψ = irfft(ψh, grid.nx)

  p[1][1][:z] = ζ
  p[1][:title] = "vorticity, tν = " * @sprintf("%.4f", tν)
  p[2][1][:z] = ψ
  p[2][:title] = "streamfunction"
end

gif(anim, moviegif_filename, fps=14)
mp4(anim, moviemp4_filename, fps=14)

max_stars_repo_name: navidcy/KolmogorovFlow

max_issues_repo_name: navidcy/KolmogorovFlow

max_forks_repo_name: navidcy/KolmogorovFlow


text:
## Reactive signal update performance: o, h, l, c vectors from TimeArray values-component
using TimeSeries
using Reactive

nma = 50
ohlc_BA = TimeSeries.readtimearray("../../data/OHLC_BA.csv")

s_ohlc = Reactive.Input(ohlc_BA.values[1,:])
#s_close = lift(s -> s[4], s_ohlc, typ=Float64)
#s_open = lift(s -> s[1], s_ohlc, typ=Float64)

vsig = [s_ohlc.value[4] - s_ohlc.value[1]]
function vsigupd!(vsig::Vector{Float64}, nma::Int64, nmax::Int64)
    for i in 2:nmax
        push!(s_ohlc, ohlc_BA.values[i,:])
        #ohlc_now = s_ohlc.value
        #push!(vsig, ohlc_now[4] - ohlc_now[1])
        push!(vsig, s_ohlc.value[4] - s_ohlc.value[1]) ## this is fine, calling s.value is efficient
    end
end

println("OHLC updates with signal value components instead of 2 lift-signals:")
println("reactive signal updates timing")
expr_run = parse("@time vsigupd!(vsig, nma, length(ohlc_BA))")
for i = 1:5
    eval(expr_run)
end

### results
# elapsed time: 0.062989983 seconds (13133720 bytes allocated, 62.13% gc time)
### use as few lift-signals as possible!

Profile.clear()  # in case we have any previous profiling data
@profile vsigupd!(vsig, nma, length(ohlc_BA))
Profile.print()


text:
# "A", "B", ..., "E", "A,B", ..., "A,B,C,D,E"

using DataFrames
using Distributions

USER = 1000
SKILL = 5
ITEM = 2^SKILL - 1
RECORD = 20000
INCREASE = 100 / (RECORD / USER)
# DECREASE = 200 / (RECORD / USER)
DECREASE = 0

srand(0)

# 項目の作成
function make_items()
  item = DataFrame(item_id = Int[], skill = Char[], a = Float64[], β = Float64[], c = Float64[])

  for i in 1:ITEM
    for j in SKILL:-1:1
      if bin(i, SKILL)[j] == '1'
        p = 0.1
        a = rand(LogNormal(0, 0.5))
        β = rand(Normal(0,2))
        c = rand(Beta(20*p+1, 20*(1-p)+1))
        push!(item, [i, Char(Int('A') + (SKILL-j)), a, β, c])
      end
    end
  end

  return item
end

# 能力値の初期値
function init_trait()
  mat = rand(Normal(-10,2), USER, SKILL)
  return mat
end

# Raschモデル
function rasch(Θ, β, a, c)
  numer = 1 - c
  denom = 1 + exp(-1.7 * a * (Θ - β))
  return c + numer / denom
end

# 忘却型Raschモデル
function decay_rasch(Θ, β, Θ̃, β̃, t, h, c)
  numer = (1 + h * t)^(-exp(Θ̃ - β̃)) - c
  denom = 1 + exp(-1.7(Θ - β))
  return c + numer / denom
end

# 回答結果
function calc_result(skills,traits, items)
  prob = 1
  for skill in skills
    Θ = traits[skill]
    β = items[items[:skill] .== Char(skill + 'A' - 1), :β][1]
    a = items[items[:skill] .== Char(skill + 'A' - 1), :a][1]
    c = items[items[:skill] .== Char(skill + 'A' - 1), :c][1]
    prob *= rasch(Θ, β, a, c)
  end

  if prob[1] > rand()
    return 1
  else
    return 0
  end
end

# 経過時間(hour)
function passed_hour(second1, second2)
  diff = second1 - second2
  return round(Int(Dates.Second(diff)) / (60*60))
end

# 能力値を成長させる
function grow_trait(trait)
  trait += rand(Beta(10,10)) * INCREASE
  return trait
end

# 能力値を衰退させる
function decline_trait(trait, time)
  trait -= rand(Beta(10,10)) * (DECREASE * time)
  return trait
end

# 初期化
items = make_items()
trait = init_trait()

# レコードを生成
data = DataFrame(result = Int[], user_id = Int[], item_id = Int[], skill = String[], date = DateTime[])
u_num = zeros(USER)
i_num = zeros(ITEM)

# スタート時刻
date = DateTime(2016, 4, 1, 12, 0, 0)

# 最後に回答した日時を記録
user_last_update = fill(date, USER, ITEM)

for record in 1:RECORD
  user_id = rand(1:USER)
  u_num[user_id] += 1
  item_id = rand(1:ITEM)
  i_num[item_id] += 1
  skills = [skill - 'A' + 1 for skill in items[items[:item_id] .== item_id, :skill]]

  passed_time = passed_hour(date, user_last_update[user_id, item_id])
  for skill_id in skills
    trait[user_id, skill_id] = decline_trait(trait[user_id, skill_id], passed_time)
  end

  result = calc_result(skills, trait[user_id, :], items[items[:item_id] .== item_id, :])
  print(result)

  # ランダムな秒数だけ経過させる
  date += Dates.Second(round(rand(Uniform(1,60))))
  user_last_update[user_id, item_id] = date

  push!(data, [result, user_id, item_id,  join([Char(i) for i in (skills + Int('A') - 1)], ","), date])

  for skill_id in skills
    trait[user_id, skill_id] = grow_trait(trait[user_id, skill_id])
  end
end

writetable("synthetic_multiskill_data.csv", data)


text:
"""
    x = harmonic_interp(adj_mat, S, vals; tol=1e-6)

Interpolates a function on a graph, given by its adjacency matrix,
by minizing the Laplacian quadratic form subject to the boundary
conditions that `x[S[i]] = vals[i]` for `i` in `S`.

This is the algorithm sometimes known as Label Propagation,
or Semi-Supervised Learning on Graphs.  The idea comes from the paper
"Semi-Supervised Learning Using Gaussian Fields and Harmonic Functions"
by Zhu, Gharamani, and Lafferty from ICML 2003.

This version might fail for disconnected graphs.
You can check if a graph is connected with `isConnected(adj_mat)`.
"""
function harmonic_interp(adj_mat, S::Vector, vals::Vector; tol=1e-6)
    n = size(adj_mat,1)
    b = zeros(n)
    b[S] = vals

    inds = ones(Bool,n)
    inds[S] .= false
    la = lap(adj_mat)
    la_sub = la[inds,inds]
    b_sub = (-la*b)[inds]

    f = approxchol_sddm(la_sub; tol=tol)
    x_sub = f(b_sub)

    x = copy(b)
    x[inds] = x_sub
    return x
end


text:
macro evalwithx(expr, a, b)
    return quote
        x = $a
        tmp = $expr
        x = $b
        return $expr - tmp
    end
end

@evalwithx(2 ^ x, 3, 5)     # raw expression (AST)

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
# extensions from other sources

##########################################################################
#
#   @devec_transform - a code-generating macro for associative types
#
#   Note: this extension was contributed by Tom Short
#
##########################################################################
#
#   Starting with an associative type `d`, the following assigns or
#   replaces key `a` with the result of `x + y` where `x` or `y` could
#   be keys in `d`.
#
#       @devec_transform d  a = x + y
#
#   This basically converts to the following:
#
#       var1 = has(d, :x) ? d[:x] : x
#       var2 = has(d, :y) ? d[:y] : y
#       @devec res = var1 + var2
#       d[:a] = res
#
#   It contains machinery to convert the symbol to a key type
#   appropriate for the associative type. For example, DataFrames have
#   string keys, so the symbol from the expression needs to be
#   converted to a string. Also of issue is
#
#   The following forms are supported:
#
#       @devec_transform d  a = x + y  b = x + sum(y)
#
#       @devec_transform(d, a => x + y, b => x + sum(y))
#
#
##########################################################################

# The following is like Base.haskey, but converts symbols to appropriate
# key types.
xhas(d, key) = haskey(d, key)
xhas{K<:AbstractString,V}(d::Associative{K,V}, key) = haskey(d, string(key))

# The appropriate key for the type
bestkey(d, key) = key
bestkey{K<:AbstractString,V}(d::Associative{K,V}, key) = string(key)

#### The following will be needed in package DataFrames for support
#
#   xhas(d::AbstractDataFrame, key::Symbol) = haskey(d, string(key))
#   bestkey(d::AbstractDataFrame, key) = string(key)
#   bestkey(d::NamedArray, key) = string(key)
#

# This replaces symbols with gensym'd versions and updates
# a lookup dictionary.
replace_syms(x, lookup::Associative) = x

function replace_syms(s::Symbol, lookup::Associative)
    if haskey(lookup, s)
        lookup[s]
    else
        res = gensym("var")
        lookup[s] = res
        res
    end
end

function replace_syms(e::Expr, lookup::Associative)
    if e.head == :(=>)
        e.head = :(=)
    end
    if e.head == :call
        length(e.args) <= 1 ? Expr(e.head, e.args) : Expr(e.head, e.args[1], map(x -> replace_syms(x, lookup), e.args[2:end])...)
    elseif e.head == :comparison
        Expr(e.head, replace_syms(e.args[1], lookup), e.args[2], replace_syms(e.args[3], lookup))
    else
        isempty(e.args) ? Expr(e.head, e.args) : Expr(e.head, map(x -> replace_syms(x, lookup), e.args)...)
    end
end

function devec_transform_helper(d, args...)
    var_lookup = Dict()
    lhs_lookup = Dict()
    body = Any[]
    for ex in args
        push!(body, compile(ScalarContext(), replace_syms(ex, var_lookup)))
        lhs_lookup[ex.args[1]] = true
    end
    # header
    header = Any[]
    for (s,v) in var_lookup
        push!(header, :($v = Devectorize.xhas(d, Devectorize.bestkey(d, $(Meta.quot(s)))) ?
            d[Devectorize.bestkey(d, $(Meta.quot(s)))] : isdefined($(Meta.quot(s))) ? $s : nothing))
    end
    # trailer
    trailer = Any[]
    for (s,v) in lhs_lookup
        push!(trailer, :(d[Devectorize.bestkey(d, $(Meta.quot(s)))] = $(var_lookup[s])))
    end
    push!(trailer, :(d))
    esc(:(let d = $d; $(Expr(:block, header..., body..., trailer...)); end))
end

macro devec_transform(df, args...)
    devec_transform_helper(df, args...)
end


text:
export orlm

response_vec(y::CategoricalArray) = y.refs
response_vec(y::Vector{Union{Missing,T}}) where {T<:Integer}= Vector{T}(y)
response_vec(y::Vector{T}) where {T<:Integer} = Vector{Int}(y)
response_vec(mf::ModelFrame) = response_vec(mf.df[!,mf.terms.eterms[1]])

function γinit(y::Vector, model::Symbol)
    cpy = cumsum(proportions(y))
    return invcdf.(cpy[1:end-1], Val{model})
end

"""
    orlm(fm::Formula, data::DataFrame, model::Symbol; method=Optim.Newton(), kwargs...)

Estimate ordered response model of variety `model ∈ (:logit, :probit)` with specification
`fm` and `data`. Optim options passed with `kwargs`. Set the optimizer with `method`.
Returns a tuple with negative log likelihood, gradient, hessian, and optimization results
`(LL::Real, grad::Vector, hess::Matrix, opt::Optim.MultivariateOptimizationResults)`
"""
function orlm(fm::Formula, data::DataFrame, model::Symbol; kwargs...)

    model ∈ (:probit, :logit) || throw(error("Can only do :probit or :logit model"))

    mf = ModelFrame(fm, data)
    mf.terms.intercept  && throw(error("Cannot have intercept. Try `y ~ 0 + x1 + x2 ...`"))

    X = ModelMatrix(mf).m'
    y = response_vec(mf)

    return orlm(y, X, model; kwargs...)

end

orlm(y::Vector{<:Integer}, X::AbstractMatrix{T}, model::Symbol; kwargs...) where {T} = orlm(y, Matrix(X), model; kwargs...)

function orlm(y::Vector{<:Integer}, X::Matrix{T}, model::Symbol; method=Optim.Newton(), kwargs...) where {T}
    model ∈ (:probit, :logit) || throw(error("Can only do :probit or :logit model"))

    # check dims
    k, n = size(X)
    length(y) == n || throw(DimensionMismatch("length(y) != size(X,2)"))

    L = num_categories(y)  # also checks that categories are 1:L
    KLm1 = k+L-1
    θ0 = zeros(T, KLm1)
    θ0[k+1:end] = γinit(y, model) # starting values
    tmpgrad = similar(θ0)
    η = Vector{T}(undef,n)

    # closures for optim
    td = NLSolversBase.TwiceDifferentiable(
        (θ::Vector)               -> orLL!(zeros(T,0)   , zeros(T,0,0), zeros(0), η, y, X, θ[1:k], θ[k+1:end], Val{model}, -1.0),
        (grad::Vector, θ::Vector) -> orLL!(grad         , zeros(T,0,0), tmpgrad , η, y, X, θ[1:k], θ[k+1:end], Val{model}, -1.0),
        (grad::Vector, θ::Vector) -> orLL!(grad         , zeros(T,0,0), tmpgrad , η, y, X, θ[1:k], θ[k+1:end], Val{model}, -1.0),
        (hess::Matrix, θ::Vector) -> orLL!(zeros(T,KLm1),         hess, tmpgrad , η, y, X, θ[1:k], θ[k+1:end], Val{model}, -1.0),
        θ0
    )

    opt =  Optim.optimize(td, θ0, method, Optim.Options(;kwargs...))

    # final eval
    hess = zeros(T, KLm1, KLm1)
    grad = similar(tmpgrad)
    θfinal = opt.minimizer
    LL = orLL!(grad, hess, tmpgrad, η, y, X, θfinal[1:k], θfinal[k+1:end], Val{model}, -1.0)

    return (opt.minimizer, LL, grad, hess, opt)

end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

struct VirtualNetworkGatewayConnectionsApi <: SwaggerApi
    client::Swagger.Client
end

"""

Creates or updates a virtual network gateway connection in the specified resource group.
Param: resourceGroupName::String (required)
Param: virtualNetworkGatewayConnectionName::String (required)
Param: parameters::VirtualNetworkGatewayConnection (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualNetworkGatewayConnection
"""
function _swaggerinternal_virtualNetworkGatewayConnectionsCreateOrUpdate(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PUT", VirtualNetworkGatewayConnection, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualNetworkGatewayConnectionsCreateOrUpdate(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsCreateOrUpdate(_api, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualNetworkGatewayConnectionsCreateOrUpdate(_api::VirtualNetworkGatewayConnectionsApi, response_stream::Channel, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsCreateOrUpdate(_api, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Deletes the specified virtual network Gateway connection.
Param: resourceGroupName::String (required)
Param: virtualNetworkGatewayConnectionName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualNetworkGatewayConnectionsDelete(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualNetworkGatewayConnectionsDelete(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsDelete(_api, resourceGroupName, virtualNetworkGatewayConnectionName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualNetworkGatewayConnectionsDelete(_api::VirtualNetworkGatewayConnectionsApi, response_stream::Channel, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsDelete(_api, resourceGroupName, virtualNetworkGatewayConnectionName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Gets the specified virtual network gateway connection by resource group.
Param: resourceGroupName::String (required)
Param: virtualNetworkGatewayConnectionName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualNetworkGatewayConnection
"""
function _swaggerinternal_virtualNetworkGatewayConnectionsGet(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualNetworkGatewayConnection, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualNetworkGatewayConnectionsGet(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsGet(_api, resourceGroupName, virtualNetworkGatewayConnectionName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualNetworkGatewayConnectionsGet(_api::VirtualNetworkGatewayConnectionsApi, response_stream::Channel, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsGet(_api, resourceGroupName, virtualNetworkGatewayConnectionName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified virtual network gateway connection shared key through Network resource provider.
Param: resourceGroupName::String (required)
Param: virtualNetworkGatewayConnectionName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: ConnectionSharedKey
"""
function _swaggerinternal_virtualNetworkGatewayConnectionsGetSharedKey(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", ConnectionSharedKey, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualNetworkGatewayConnectionsGetSharedKey(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsGetSharedKey(_api, resourceGroupName, virtualNetworkGatewayConnectionName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualNetworkGatewayConnectionsGetSharedKey(_api::VirtualNetworkGatewayConnectionsApi, response_stream::Channel, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsGetSharedKey(_api, resourceGroupName, virtualNetworkGatewayConnectionName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
Param: resourceGroupName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualNetworkGatewayConnectionListResult
"""
function _swaggerinternal_virtualNetworkGatewayConnectionsList(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualNetworkGatewayConnectionListResult, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualNetworkGatewayConnectionsList(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsList(_api, resourceGroupName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualNetworkGatewayConnectionsList(_api::VirtualNetworkGatewayConnectionsApi, response_stream::Channel, resourceGroupName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsList(_api, resourceGroupName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
Param: resourceGroupName::String (required)
Param: virtualNetworkGatewayConnectionName::String (required)
Param: parameters::ConnectionResetSharedKey (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: ConnectionResetSharedKey
"""
function _swaggerinternal_virtualNetworkGatewayConnectionsResetSharedKey(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", ConnectionResetSharedKey, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualNetworkGatewayConnectionsResetSharedKey(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsResetSharedKey(_api, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualNetworkGatewayConnectionsResetSharedKey(_api::VirtualNetworkGatewayConnectionsApi, response_stream::Channel, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsResetSharedKey(_api, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
Param: resourceGroupName::String (required)
Param: virtualNetworkGatewayConnectionName::String (required)
Param: parameters::ConnectionSharedKey (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: ConnectionSharedKey
"""
function _swaggerinternal_virtualNetworkGatewayConnectionsSetSharedKey(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PUT", ConnectionSharedKey, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualNetworkGatewayConnectionsSetSharedKey(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsSetSharedKey(_api, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualNetworkGatewayConnectionsSetSharedKey(_api::VirtualNetworkGatewayConnectionsApi, response_stream::Channel, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsSetSharedKey(_api, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Starts packet capture on virtual network gateway connection in the specified resource group.
Param: resourceGroupName::String (required)
Param: virtualNetworkGatewayConnectionName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Param: parameters::VpnPacketCaptureStartParameters
Return: String
"""
function _swaggerinternal_virtualNetworkGatewayConnectionsStartPacketCapture(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; parameters=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", String, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/startPacketCapture", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualNetworkGatewayConnectionsStartPacketCapture(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; parameters=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsStartPacketCapture(_api, resourceGroupName, virtualNetworkGatewayConnectionName, api_version, subscriptionId; parameters=parameters, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualNetworkGatewayConnectionsStartPacketCapture(_api::VirtualNetworkGatewayConnectionsApi, response_stream::Channel, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, api_version::String, subscriptionId::String; parameters=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsStartPacketCapture(_api, resourceGroupName, virtualNetworkGatewayConnectionName, api_version, subscriptionId; parameters=parameters, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Stops packet capture on virtual network gateway connection in the specified resource group.
Param: resourceGroupName::String (required)
Param: virtualNetworkGatewayConnectionName::String (required)
Param: parameters::VpnPacketCaptureStopParameters (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: String
"""
function _swaggerinternal_virtualNetworkGatewayConnectionsStopPacketCapture(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", String, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/stopPacketCapture", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualNetworkGatewayConnectionsStopPacketCapture(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsStopPacketCapture(_api, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualNetworkGatewayConnectionsStopPacketCapture(_api::VirtualNetworkGatewayConnectionsApi, response_stream::Channel, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsStopPacketCapture(_api, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Updates a virtual network gateway connection tags.
Param: resourceGroupName::String (required)
Param: virtualNetworkGatewayConnectionName::String (required)
Param: parameters::TagsObject (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualNetworkGatewayConnection
"""
function _swaggerinternal_virtualNetworkGatewayConnectionsUpdateTags(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PATCH", VirtualNetworkGatewayConnection, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualNetworkGatewayConnectionsUpdateTags(_api::VirtualNetworkGatewayConnectionsApi, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsUpdateTags(_api, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualNetworkGatewayConnectionsUpdateTags(_api::VirtualNetworkGatewayConnectionsApi, response_stream::Channel, resourceGroupName::String, virtualNetworkGatewayConnectionName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualNetworkGatewayConnectionsUpdateTags(_api, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

export virtualNetworkGatewayConnectionsCreateOrUpdate, virtualNetworkGatewayConnectionsDelete, virtualNetworkGatewayConnectionsGet, virtualNetworkGatewayConnectionsGetSharedKey, virtualNetworkGatewayConnectionsList, virtualNetworkGatewayConnectionsResetSharedKey, virtualNetworkGatewayConnectionsSetSharedKey, virtualNetworkGatewayConnectionsStartPacketCapture, virtualNetworkGatewayConnectionsStopPacketCapture, virtualNetworkGatewayConnectionsUpdateTags


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct AccessUri <: SwaggerModel
    properties::Any # spec type: Union{ Nothing, AccessUriOutput } # spec name: properties

    function AccessUri(;properties=nothing)
        o = new()
        validate_property(AccessUri, Symbol("properties"), properties)
        setfield!(o, Symbol("properties"), properties)
        o
    end
end # type AccessUri

const _property_map_AccessUri = Dict{Symbol,Symbol}(Symbol("properties")=>Symbol("properties"))
const _property_types_AccessUri = Dict{Symbol,String}(Symbol("properties")=>"AccessUriOutput")
Base.propertynames(::Type{ AccessUri }) = collect(keys(_property_map_AccessUri))
Swagger.property_type(::Type{ AccessUri }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_AccessUri[name]))}
Swagger.field_name(::Type{ AccessUri }, property_name::Symbol) =  _property_map_AccessUri[property_name]

function check_required(o::AccessUri)
    true
end

function validate_property(::Type{ AccessUri }, name::Symbol, val)
end


text:
########################################################################
#                       SETTING THE SCENE                              #
########################################################################

Cassette.@context TraceCtx

# allow assiciation of Int values with TraceCtx
Cassette.metadatatype(::Type{<:TraceCtx}, ::DataType) = Int
Cassette.hastagging(::Type{<:TraceCtx}) = true

########################################################################
#                            CUSTOM PASS                               #
########################################################################

is_gref_call(a, fn_name) = a isa GlobalRef && a.name == fn_name

function prepare_ir(::Type{<:TraceCtx}, reflection::Cassette.Reflection)
    ir = reflection.code_info
    Cassette.replace_match!(x -> Base.Meta.isexpr(x, :new), ir.code) do x
        return Expr(:call, __new__, x.args...)
    end
    Cassette.replace_match!(x -> Base.Meta.isexpr(x, :call) && is_gref_call(x.args[1], :tuple), ir.code) do x
        return Expr(:call, __tuple__, x.args[2:end]...)
    end
    Cassette.replace_match!(x -> Base.Meta.isexpr(x, :call) && is_gref_call(x.args[1], :getfield), ir.code) do x
        return Expr(:call, __getfield__, x.args[2:end]...)
    end
    return ir
end

@runonce const prepare_pass = Cassette.@pass prepare_ir

########################################################################
#                               TRACE                                  #
########################################################################

struct TapeBox
    tape::Tape
    primitives::Set{Any}
end

"""
Trace function execution using provided arguments.
Returns calculated value and a tape.

```
foo(x) = 2.0x + 1.0
val, tape = trace(foo, 4.0)
```
"""
function ctrace(f, args...; primitives=PRIMITIVES, optimize=true)
    # create tape
    tape = Tape(guess_device(args))
    box = TapeBox(tape, primitives)
    ctx = enabletagging(TraceCtx(metadata=box, pass=prepare_pass), f)
    tagged_args = Vector(undef, length(args))
    for (i, x) in enumerate(args)
        id = record!(tape, Input, x)
        tagged_args[i] = tag(x, ctx, i)
    end
    # trace f with tagged arguments
    tagged_val = overdub(ctx, f, tagged_args...)
    val = untag(tagged_val, ctx)
    tape.resultid = metadata(tagged_val, ctx)
    if optimize
        tape = simplify(tape)
    end
    return val, tape
end

function with_free_args_as_constants(ctx::TraceCtx, tape::Tape, args)
    new_args = []
    for x in args
        if istagged(x, ctx)
            push!(new_args, x)
        else
            # x = x isa Function ? device_function(ctx.metadata.tape.device, x) : x
            id = record!(tape, Constant, x)
            x = tag(x, ctx, id)
            push!(new_args, x)
        end
    end
    return new_args
end

function Cassette.overdub(ctx::TraceCtx, fargs...)
    f, args = fargs[1], fargs[2:end]
    fv = istagged(f, ctx) ? untag(f, ctx) : f
    tape = ctx.metadata.tape
    primitives = ctx.metadata.primitives
    if fv in primitives
        fargs = with_free_args_as_constants(ctx, tape, fargs)
        farg_ids = [metadata(x, ctx) for x in fargs]
        farg_ids = Int[id isa Cassette.NoMetaData ? -1 : id for id in farg_ids]
        # execute call
        retval = fallback(ctx, [untag(x, ctx) for x in fargs]...)
        # record to the tape and tag with a newly created ID
        ret_id = record!(tape, Call, retval, fv, farg_ids[2:end])
        retval = tag(retval, ctx, ret_id)
    elseif canrecurse(ctx, fv, args...)
        retval = Cassette.recurse(ctx, fargs...)
    else
        retval = fallback(ctx, fargs...)
    end
    return retval
end


text:
function handle_get_dimensions(handle::RsvgHandle, dimension_data::RsvgDimensionData)
    ccall((:rsvg_handle_get_dimensions,librsvg), Void,
                (RsvgHandle,Ptr{RsvgDimensionData}), handle, &dimension_data)
end

function handle_get_dimensions(handle::RsvgHandle)
    d = Rsvg.RsvgDimensionData(1,1,1,1);
    handle_get_dimensions(handle, d);
    d
end

function set_default_dpi(dpi::Float64)
    ccall((:rsvg_set_default_dpi, librsvg), Void,
                (Float64,), dpi)
end

function handle_set_dpi(handle::RsvgHandle, dpi::Float64)
    ccall((:rsvg_handle_set_dpi, librsvg), Void,
                (RsvgHandle,Float64), handle, dpi)
end

function handle_render_cairo(cr::CairoContext, handle::RsvgHandle)
	ccall((:rsvg_handle_render_cairo, librsvg), Bool,
                (RsvgHandle,Ptr{Void}), handle, cr.ptr)
end

function handle_new_from_file(filename::AbstractString,error::GError)
    ptr = ccall((:rsvg_handle_new_from_file, librsvg), Ptr{Void},
                (Ptr{UInt8},GError), bytestring(filename), error)
    RsvgHandle(ptr)
end

handle_new_from_file(filename::AbstractString) = handle_new_from_file(filename::AbstractString,GError(0,0,0))

function handle_new_from_data(data::AbstractString,error::GError)
    ptr = ccall((:rsvg_handle_new_from_data, librsvg), Ptr{Void},
                (Ptr{UInt8},UInt32,GError), bytestring(data), length(data),error)
    RsvgHandle(ptr)
end

handle_new_from_data(data::AbstractString) = handle_new_from_data(data::AbstractString,GError(0,0,0))


text:
function contin_data(N_line,N_time,N_scen_normal,N_scen_contin,N_event)
    # contin: Line Capacity Limiting Coefficient 0~1| normal=0, full trip=1
    contin_normal = Array{Float64}(N_line,N_time,N_scen_normal)
    contin_normal[:] = 0
    if N_event == 1
        contin_7scen = Array{Float64}(N_line,N_time,7)
        contin_7scen[1:end] = 0
        contin_7scen[1,6:end,1] = 0.9
        contin_7scen[12,6:end,2] = 0.9
        contin_7scen[4,6:end,3] = 0.9
        contin_7scen[8,6:end,4] = 0.9
        contin_7scen[9,6:end,5] = 0.9
        contin_7scen[5,6:end,6] = 0.9
        contin_7scen[13,6:end,7] = 0.9

        contin_5scen = Array{Float64}(N_line,N_time,5)
        contin_5scen[1:end] = 0
        contin_5scen[1,6:end,1] = 0.9
        contin_5scen[4,6:end,2] = 0.9
        contin_5scen[5,6:end,3] = 0.9
        contin_5scen[12,6:end,4] = 0.9
        contin_5scen[13,6:end,5] = 0.9

        contin_1scen = Array{Float64}(N_line,N_time,1)
        contin_1scen[1:end] = 0
        contin_1scen[13,6:end,1] = 0.9
    elseif N_event == 2
        contin_7scen = Array{Float64}(N_line,N_time,7)
        contin_7scen[1:end] = 0
        contin_7scen[1,6:end,1] = 0.9
        contin_7scen[12,18:end,1] = 0.9
        contin_7scen[12,6:end,2] = 0.9
        contin_7scen[4,18:end,2] = 0.9
        contin_7scen[4,6:end,3] = 0.9
        contin_7scen[12,18:end,3] = 0.9
        contin_7scen[8,6:end,4] = 0.9
        contin_7scen[12,18:end,4] = 0.9
        contin_7scen[9,6:end,5] = 0.9
        contin_7scen[12,18:end,5] = 0.9
        contin_7scen[5,6:end,6] = 0.9
        contin_7scen[12,18:end,6] = 0.9
        contin_7scen[13,6:end,7] = 0.9
        contin_7scen[4,18:end,7] = 0.9

        contin_5scen = Array{Float64}(N_line,N_time,5)
        contin_5scen[1:end] = 0
        contin_5scen[1,6:end,1] = 0.9
        contin_5scen[8,6:end,1] = 0.9
        contin_5scen[1,6:end,2] = 0.9
        contin_5scen[9,6:end,2] = 0.9
        contin_5scen[4,6:end,3] = 0.9
        contin_5scen[12,6:end,3] = 0.9
        contin_5scen[4,6:end,4] = 0.9
        contin_5scen[13,6:end,4] = 0.9
        contin_5scen[3,6:end,5] = 0.9
        contin_5scen[10,6:end,5] = 0.9

        contin_1scen = Array{Float64}(N_line,N_time,1)
        contin_1scen[1:end] = 0
        contin_1scen[4,6:end,1] = 0.9
        contin_1scen[12,18:end,1] = 0.9

    elseif N_event == 3
        contin_5scen = Array{Float64}(N_line,N_time,5)
        contin_5scen[1:end] = 0

        contin_5scen[1,6:end,1] = 0.9
        contin_5scen[8,6:end,1] = 0.9
        contin_5scen[13,6:end,1] = 0.9

        contin_5scen[1,6:end,2] = 0.9
        contin_5scen[9,6:end,2] = 0.9
        contin_5scen[12,6:end,2] = 0.9

        contin_5scen[1,6:end,3] = 0.9
        contin_5scen[4,6:end,3] = 0.9
        contin_5scen[11,6:end,3] = 0.9

        contin_5scen[4,6:end,4] = 0.9
        contin_5scen[8,6:end,4] = 0.9
        contin_5scen[12,6:end,4] = 0.9

        contin_5scen[1,6:end,5] = 0.9
        contin_5scen[4,6:end,5] = 0.9
        contin_5scen[12,6:end,5] = 0.9
    end

    contin = Array{Float64}(N_line,N_time,N_scen_normal+N_scen_contin)
    contin[:] = 0
    if N_scen_contin == 7
        contin[:,:,N_scen_normal+1:end] = contin_7scen
    elseif N_scen_contin == 5
        contin[:,:,N_scen_normal+1:end] = contin_5scen
    elseif N_scen_contin == 1
        contin[:,:,N_scen_normal+1:end] = contin_1scen
    elseif N_scen_contin == 0
        contin = contin_normal
    else
        error("Thre is no preset contingency scenario data: go edit <contin_data.jl>")
    end

    return contin
end


text:
using Test

push!(LOAD_PATH, expanduser(".")) # Assumed to be ran from the repl folder.

#include("RadioPropagation.jl")
using RadioPropagation

# Unit test methods.
@testset "RadioPropagation.jl" begin
    @test RadioPropagation.two_ray_propagation( 2e3, 10, 12, 20e9, -1 ) == 1.9993946082759417 + 0.03479104696580754im;
    @test RadioPropagation.rain_attenuation_db_per_km( 'v', 30, 20 ) == 3.3400000000000003;
    @test RadioPropagation.rain_attenuation_db_per_km_circular_pol( 30, 20 ) == 3.6755027981960815; # dB/km
    @test RadioPropagation.fog_attenuation_db_per_km( 10, 0.8, 23 ) == 4.68976; # dB/km
end

max_stars_repo_name: ErikBuer/RadioPropagation

max_issues_repo_name: ErikBuer/RadioPropagation

max_forks_repo_name: ErikBuer/RadioPropagation


text:
function plot_replica_benchmark(raw_data_df)

    sort!(raw_data_df, :num_samples)
    samples = unique(Vector{Int64}(raw_data_df[!, :num_samples]))
    algorithm_names = unique(Vector{String}(raw_data_df[!, :algorithm]))
    samples = unique(Vector{Int64}(raw_data_df[!, :num_samples]))
    x = samples ./ 0.001 # convert to Hz
    algorithm_names = unique(Vector{String}(raw_data_df[!, :algorithm]))

    fig = Figure(
        # resolution = (1000, 700),
        font = "Times New Roman"
    )
    ax = Axis(
        fig,
        xlabel = "Sampling Frequency [Hz]",
        ylabel = "Generation Time [s]",
        xscale = log10,
        yscale = log10,
        title = "Comparison between global memory and texture memory code replica generation for 1 ms signal",
        xminorgridvisible = true,
        xminorticksvisible = true,
        xminorticks = IntervalsBetween(9),
        # yticks = (10.0 .^(-5:1:-3)),
        xticklabelsize = 18,
        yticklabelsize = 18

    )
    xlims!(ax, 10^6, 5*10^8)
    ylims!(ax, 1.0e-5, 3.0e-3)

    lin = Array{Lines}(undef, length(algorithm_names));
    sca = Array{Scatter}(undef, length(algorithm_names));
    markers = [:circle, :rect]
    for (idx, name) = enumerate(algorithm_names)
        time = 10 ^ (-9) * vec((
            raw_data_df |>
            @filter(
                _.algorithm == name
            ) |> DataFrame
        ).Minimum)

        lin[idx] = lines!(
            ax,
            x,
            time
        )
        sca[idx] = scatter!(
            ax,
            x,
            time,
            marker = markers[idx],
            markersize = 15
        )
    end
    realtime = lines!(ax, [10^6, 5 * 10^8], [10 ^ (-3), 10 ^ (-3)], color=:grey, linestyle=:dashdot)

    fig[1,1] = ax
    elements = [[lin[1] sca[1]], [lin[2] sca[2]]]
    labels = ["Global Memory", "Texture Memory"]
    axislegend(ax, elements, labels, "Code Replication Algorithms",  position = :rb)
    return fig
end

function plot_reduction_benchmark(raw_data_df, num_ants, num_correlators)
# using GPUAcceleratedTracking, DrWatson, DataFrames
# @quickactivate "GPUAcceleratedTracking"
# raw_data_df = collect_results(datadir("benchmarks/reduction"))
# num_ants = 4; num_correlators = 3;
    elapsed_times = raw_data_df |>
    @filter(
        _.num_ants          == num_ants         &&
        _.num_correlators   == num_correlators
        ) |>
    @map(
        {
            _.num_samples,
            _.algorithm,
            _.Minimum,
            _.Median,
            _.Mean,
            _.Std
        }
    ) |> DataFrame

    sort!(elapsed_times, :num_samples)
    samples = unique(Vector{Int64}(elapsed_times[!, :num_samples]))
    algorithm_names = unique(Vector{String}(elapsed_times[!, :algorithm]))

    ## BAR PLOT
    # get the data to plot
    samples = unique(Vector{Int64}(elapsed_times[!, :num_samples]))
    mindata = reshape(elapsed_times.Minimum, (length(algorithm_names), length(samples)))
    mediandata = reshape(elapsed_times.Median, (length(algorithm_names), length(samples)))
    meandata = reshape(elapsed_times.Mean, (length(algorithm_names), length(samples)))
    stddata = reshape(elapsed_times.Std, (length(algorithm_names), length(samples)))
    algorithm_names = unique(Vector{String}(elapsed_times[!, :algorithm]))

    # defines figure and axes
    fig_bar = Figure(font = "Times New Roman")
    ax_bar = Axis(
        fig_bar,
        xlabel = "Number of elements",
        ylabel = "Processing Time [μs]",
        xscale = log10,
        # yscale = log10,
        title = "Reduction Algorithm Comparison for 4 antennas and 3 correlators",
        xticks = (samples, ["2048", "4096", "8192", "16384", "32768"]),
        xticklabelrotation = pi/8,
        xminorticksvisible = false
    )

    colors = Makie.wong_colors()[1:3]

    # plot the data to the axes
    barplot!(
        ax_bar,
        vec(repeat(samples, inner=3)),
        vec(reshape( 1e-6*mindata, (15, 1))),
        dodge = vec(repeat([1,2,3], 5)),
        color = vec(repeat(colors, 5)),
        # strokewidth = 0.1,
        width = 300 .* (2 .^ ((repeat(1:length(samples), inner=3))))
        )
    labels = ["cplx_multi", "cplx", "pure"]
    title = "Algorithms"
    elements = [PolyElement(polycolor = colors[i]) for i in 1:length(labels)]

    Legend(fig_bar[1,2], elements, labels, "Reduction Algorithms", position = :tr)
    fig_bar[1,1] = ax_bar
    fig_bar
end

max_stars_repo_name: mfkiwl/GPUAcceleratedTracking

max_issues_repo_name: mfkiwl/GPUAcceleratedTracking

max_forks_repo_name: mfkiwl/GPUAcceleratedTracking


text:
import Base.convert
import Base.==

abstract Pairwise
abstract Singleton

typealias FGG Graphs.GenericIncidenceList{Graphs.ExVertex,Graphs.Edge{Graphs.ExVertex},Array{Graphs.ExVertex,1},Array{Array{Graphs.Edge{Graphs.ExVertex},1},1}}

type FactorGraph
  g::FGG
  bn
  v::Dict{Int,Graphs.ExVertex} # TODO -- remove
  f::Dict{Int,Graphs.ExVertex} # TODO -- remove
  IDs::Dict{AbstractString,Int}
  fIDs::Dict{AbstractString,Int}
  id::Int64
  nodeIDs::Array{Int,1} # TODO -- ordering seems brittle
  factorIDs::Array{Int,1}
  bnverts::Dict{Int,Graphs.ExVertex} # TODO -- not sure if this is still used, remove
  bnid::Int # TODO -- not sure if this is still used
  dimID::Int64
  cg
  cgIDs::Dict{Int64,Int64}
  FactorGraph() = new()
  FactorGraph(x...) = new(
    x[1],
    x[2],
    x[3],
    x[4],
    x[5],
    x[6],
    x[7],
    x[8],
    x[9],
    x[10],
    x[11],
    x[12],
    x[13],
    x[14] )
end

type VariableNodeData
  initval::Array{Float64,2}
  initstdev::Array{Float64,2}
  val::Array{Float64,2}
  bw::Array{Float64,2}
  BayesNetOutVertIDs::Array{Int64,1}
  dimIDs::Array{Int64,1}
  dims::Int64
  eliminated::Bool
  BayesNetVertID::Int64
  separator::Array{Int64,1}
  VariableNodeData() = new()
  VariableNodeData(x...) = new(x[1],x[2],x[3],x[4],x[5],x[6],x[7],x[8],x[9],x[10])
end

type PackedVariableNodeData
  vecinitval::Array{Float64,1}
  diminitval::Int64
  vecinitstdev::Array{Float64,1}
  diminitdev::Int64
  vecval::Array{Float64,1}
  dimval::Int64
  vecbw::Array{Float64,1}
  dimbw::Int64
  BayesNetOutVertIDs::Array{Int64,1}
  dimIDs::Array{Int64,1}
  dims::Int64
  eliminated::Bool
  BayesNetVertID::Int64
  separator::Array{Int64,1}
  PackedVariableNodeData() = new()
  PackedVariableNodeData(x...) = new(x[1],x[2],x[3],x[4],x[5],x[6],x[7],x[8],x[9],x[10],x[11],x[12],x[13],x[14])
end

type FunctionNodeData{T}
  fncargvID::Array{Int64,1}
  eliminated::Bool
  potentialused::Bool
  edgeIDs::Array{Int64,1}
  fnc::T
  FunctionNodeData() = new()
  FunctionNodeData(x...) = new(x[1],x[2],x[3],x[4],x[5])
end

function convert(::Type{PackedVariableNodeData}, d::VariableNodeData)
  return PackedVariableNodeData(d.initval[:],size(d.initval,1),
                              d.initstdev[:],size(d.initstdev,1),
                              d.val[:],size(d.val,1),
                              d.bw[:],size(d.bw,1),
                              d.BayesNetOutVertIDs,
                              d.dimIDs, d.dims, d.eliminated,
                              d.BayesNetVertID, d.separator)
end
function convert(::Type{VariableNodeData}, d::PackedVariableNodeData)
  r1 = d.diminitval
  c1 = floor(Int,length(d.vecinitval)/r1)
  M1 = reshape(d.vecinitval,r1,c1)

  r2 = d.diminitdev
  c2 = floor(Int,length(d.vecinitstdev)/r2)
  M2 = reshape(d.vecinitstdev,r2,c2)

  r3 = d.dimval
  c3 = floor(Int,length(d.vecval)/r3)
  M3 = reshape(d.vecval,r3,c3)

  r4 = d.dimbw
  c4 = floor(Int,length(d.vecbw)/r4)
  M4 = reshape(d.vecbw,r4,c4)

  return VariableNodeData(M1,M2,M3,M4, d.BayesNetOutVertIDs,
    d.dimIDs, d.dims, d.eliminated, d.BayesNetVertID, d.separator)
end
function VNDencoder(d::VariableNodeData)
  return convert(PackedVariableNodeData, d)
end
function VNDdecoder(d::PackedVariableNodeData)
  return convert(VariableNodeData, d)
end

function compare(a::VariableNodeData,b::VariableNodeData)
    TP = true
    TP = TP && a.initval == b.initval
    TP = TP && a.initstdev == b.initstdev
    TP = TP && a.val == b.val
    TP = TP && a.bw == b.bw
    TP = TP && a.BayesNetOutVertIDs == b.BayesNetOutVertIDs
    TP = TP && a.dimIDs == b.dimIDs
    TP = TP && a.dims == b.dims
    TP = TP && a.eliminated == b.eliminated
    TP = TP && a.BayesNetVertID == b.BayesNetVertID
    TP = TP && a.separator == b.separator
    return TP
end

function ==(a::VariableNodeData,b::VariableNodeData, nt::Symbol=:var)
  return compare(a,b)
end

function addGraphsVert!(fgl::FactorGraph, exvert::Graphs.ExVertex)
  Graphs.add_vertex!(fgl.g, exvert)
end

function getVertNode(fgl::FactorGraph, id::Int64, nt::Symbol=:var)
  return fgl.g.vertices[id] # check equivalence between fgl.v/f[i] and fgl.g.vertices[i]
  # return nt == :var ? fgl.v[id] : fgl.f[id]
end
function getVertNode(fgl::FactorGraph, lbl::AbstractString, nt::Symbol=:var)
  return getVertNode(fgl, (nt == :var ? fgl.IDs[lbl] : fgl.fIDs[lbl]) , nt)
end

# function addNewVarVertInGraph!(fgl::FactorGraph, vert::Graphs.ExVertex, id::Int64, lbl::AbstractString)
#   vert.attributes = Graphs.AttributeDict() #fg.v[fg.id]
#   vert.attributes["label"] = lbl #fg.v[fg.id]
#   fgl.v[id] = vert # TODO -- this is likely not required, but is used in subgraph methods
#   fgl.IDs[lbl] = id # fg.id, to help find it
#   nothing
# end

# function addNewFncVertInGraph!(fgl::FactorGraph, vert::Graphs.ExVertex, id::Int64, lbl::AbstractString)
#   vert.attributes = Graphs.AttributeDict() #fg.v[fg.id]
#   vert.attributes["label"] = lbl #fg.v[fg.id]
#   fgl.f[id] = vert # TODO -- not sure if this is required
#   fgl.fIDs[lbl] = id # fg.id
#   nothing
# end

# not currently used
# function updateVertData!(fgl::FactorGraph,
#     id::Int64,
#     updlist::Dict{UTF8String,Any})
#     #Array{ASCIIString,1}([string(fn) for fn in fieldnames(VariableNodeData)]))
#
#   vdata = getVertNode(fgl, id).attributes["data"]
#   for item in updlist
#     eval(:(vdata.$(parse(item[1]))=$(item[2])))
#   end
#   nothing
# end

# excessive function, needs refactoring
function updateFullVertData!(fgl::FactorGraph,
    nv::Graphs.ExVertex)

  # not required, since we using reference -- placeholder function CloudGraphs interface
  # getVertNode(fgl, nv.index).attributes["data"] = nv.attributes["data"]
  nothing
end

function makeAddEdge!(fgl::FactorGraph, v1::Graphs.ExVertex, v2::Graphs.ExVertex; saveedgeID::Bool=true)
  edge = Graphs.make_edge(fgl.g, v1, v2)
  Graphs.add_edge!(fgl.g, edge)
  if saveedgeID push!(v2.attributes["data"].edgeIDs,edge.index) end
  edge
end

function graphsOutNeighbors(fgl::FactorGraph, vert::Graphs.ExVertex)
  Graphs.out_neighbors(vert, fgl.g)
end

function graphsGetEdge(fgl::FactorGraph, id::Int64)
  nothing
end

function graphsDeleteVertex!(fgl::FactorGraph, vert::Graphs.ExVertex)
  warn("graphsDeleteVertex! -- not deleting Graphs.jl vertex id=$(vert.index)")
  nothing
end

#


text:
# Relaxation of the TSP, just a toy

module TSP

using JuMP, Gurobi, SDDiP, Combinatorics, GLPKMathProgInterface, Ipopt, PyPlot

function getdistances(x::Vector{Float64}, y::Vector{Float64})
    n = min(length(x), length(y))
    mat = zeros(n, n)
    @inbounds for j=1:n, i=1:j-1
        mat[i, j] = norm([x[i]; y[i]] - [x[j]; y[j]])
    end
    mat
end

srand(32)

const ncities = 12
const x_coords = rand(ncities)
const y_coords = rand(ncities)
const distance_matrix = getdistances(x_coords, y_coords)
const blocked_roads = Tuple{Int, Int}[]

function plottour(tour::Vector{Tuple{Int,Int}}, s::AbstractString)
    lines = Vector[]
    for t in tour
        xs = x_coords[[t...]]
        ys = y_coords[[t...]]
        push!(lines, collect(zip(xs, ys)))
    end

    line_segments = matplotlib[:collections][:LineCollection](lines)

    fig = figure(s)
    ax = axes()
    ax[:add_collection](line_segments)
    axis("image")
end

function nCx(n::Int, x::Int)
    n < x && return 0
    ret = 1
    for i=1:x
        ret *= (n - i + 1)
    end
    ret = div(ret, factorial(x))
end
function strict_subsets(x::Vector{T}) where T
    n = length(x)
    n <= 1 && error("Vector length $n has no strict subsets.")
    y = Array{Array}(n-2)
    @inbounds for len = 2:n-1
        y[len-1] = collect(combinations(x, len))
    end
    y
end

function naivemodel()
    m = Model(solver=GLPKSolverMIP())
    @variable(m, edges[i=1:ncities, j=i+1:ncities], Bin)

    @constraints(m, begin
        balance[i=1:ncities], sum(edges[i, k] for k=i+1:ncities) + sum(edges[k, i] for k=1:i-1) == 2
        blockedroads[r=blocked_roads], edges[r] <= 0
    end)

    @objective(m, :Min, sum(edges[i,j] * distance_matrix[i, j] for i=1:ncities, j=i+1:ncities))

    # Not being realistic here...
    subsets = strict_subsets(collect(1:ncities))
    for len = 1:ncities-2
        for subset in subsets[len]
            @constraint(m, sum(edges[pair[1], pair[2]] for pair in combinations(subset, 2)) <= len)
        end
    end
    m
end

function very_naive_solve(;relax=false)
    m = naivemodel()

    if relax
        π0 = rand(length(m[:balance]))
        dualbound = 100.
        relaxed_bound = ncities * ones(length(m[:balance]))

        method  = LevelMethod(initialbound = dualbound, quadsolver=GurobiSolver(OutputFlag=0))
        # method  = SubgradientMethod(dualbound)
        TSPdata = LinearProgramData(m.obj,
                                    m[:balance],
                                    relaxed_bound,
                                    method=method)

        status, bestvalue = lagrangiansolve!(TSPdata, m, π0)
    else
        solve(m)
    end

    println("The cost is ", getobjectivevalue(m))
    tour = Tuple{Int, Int}[]
    for i=1:ncities
        for j = i+1:ncities
            if getvalue(m[:edges][i, j]) ≈ 1.0
                println((i, j))
                push!(tour, (i, j))
            end
        end
    end
    plottour(tour, "Naive tour")

end

function kruskals(costs::Vector{Float64}, edges::Vector{Tuple{Int,Int}}, nnodes::Int)
    nedges = length(edges)
    @assert nedges == length(costs)

    # The order in which edges will be checked
    order = sortperm(costs)
    ret = zeros(Int, nedges)

    # How many edges we added so far
    count = 1

    # Build up an incidence matrix as we go
    incmat = zeros(Int, nnodes, nedges)

    # Add arcs one at a time
    for k in order
        # Incidence matrix so far
        temp = view(incmat, :, 1:count)
        # Try add kth cheapest edge
        temp[edges[k][1], count] = 1
        temp[edges[k][2], count] = -1
        # Check for cycles
        V = nullspace(temp)
        if isempty(V)
            # Lock in the edge
            count += 1
            ret[k] = 1
            # Stop if we have added enough edges
            count == nnodes && return ret
        else
            # Edge didn't work out
            temp[edges[k][1], count] = 0
            temp[edges[k][2], count] = 0
        end
    end
    error("Something went wrong in Kruskal's. Perhaps you specified the wrong number of nodes.")
end

struct SpanningTree <: Lagrangian.AbstractProblemClass end

# This could just be a solvehook with the current forumlation.
# But if we get away from having to formulate the primal as a maths programming model altogether, even better...
function Lagrangian.solve_primal(m::JuMP.Model, d::LinearProgramData{M, C}, π::Vector{Float64}) where {M<:AbstractLagrangianMethod, C<:SpanningTree}
    # we arbitrarily chose to leave out the last city, we could leave out
    # any city or even better, try leave out one city at a time and find the worst case
    arcs = [(i, j) for i=1:ncities-2 for j=i+1:ncities-1]

    # Prepare an array of costs
    costs = [distance_matrix[a...] for a in arcs][:]

    # Costs include Lagrangian penalties
    for (i, a) in enumerate(arcs)
        costs[i] += π[a[1]] + π[a[2]]
    end

    # Fix n-1 arcs to Kruskal's algorithm's output
    fixed_vals = kruskals(costs, arcs, ncities-1)
    for (i, a) in enumerate(arcs)
        JuMP.setRHS(m[:fixvals][a], fixed_vals[i])
    end

    # Note: we don't just find the final two arcs by picking the cheapest ones
    # because the final two arcs affect the degree of the first n-1 nodes

    @objective(m, :Min, d.obj + dot(π, d.slacks))
    @assert solve(m, ignore_solve_hook=true) == :Optimal

    getobjectivevalue(m), getvalue(d.slacks)

end

# ============================================================================

function less_naive_relaxed()

    # Represent the TSP as a MIP, although this could just be some network logic

    m = Model(solver=GLPKSolverMIP())
    @variable(m, edges[i=1:ncities-1, j=i+1:ncities], Bin)

    @constraints(m, begin
        # Each node has a degree of two- this will be relaxed
        balance[i=1:ncities-1], sum(edges[i, k] for k=i+1:ncities) + sum(edges[k, i] for k=1:i-1) == 2
        # We do require exactly 2 arcs at the final node
        ensure1tree, sum(edges[k, ncities] for k=1:ncities-1) == 2
        # Just for fun
        blockedroads[r=blocked_roads], edges[r] <= 0
    end)

    # Min cost tour
    @objective(m, :Min, sum(edges[i,j] * distance_matrix[i, j] for i=1:ncities-1, j=i+1:ncities))

    # =========================================================================
    # Prepare a dummy constraint, we will choose the RHS while solving

    # Arcs in our one tree (a tree with all nodes except the final node)
    arcs = [(i, j) for i=1:ncities-2 for j=i+1:ncities-1]
    # Edges = whatever value Kruskal's algorithm says they should be
    @constraint(m,fixvals[a in arcs], edges[a...] == 0)

    # =========================================================================
    # The actual Lagrangian solving:

    π0 = rand(length(m[:balance]))                          # random duals to start with
    dualbound = 200.                                        # upper bound for the dual problem
    relaxed_bound = ncities * ones(length(m[:balance]))     # upper bound for the constraint wer are relaxing (something > 2, like ncities)

    # Method:
    method  = LevelMethod(initialbound = dualbound, quadsolver=GurobiSolver(OutputFlag=0))
    # method  = SubgradientMethod(dualbound, wait=20)

    # Linear program data
    TSPdata = LinearProgramData(m.obj,                  # objective
                                m[:balance],            # constraints being relaxed
                                relaxed_bound,          # a large number for RHS of relaxed constraints
                                method=method,
                                problem_class=SpanningTree()
                                )

    # Solve
    status, bestvalue = lagrangiansolve!(TSPdata, m, π0)

    println("The cost is ", getobjectivevalue(m))
    println("The duals are ", getdual(m[:balance]))
    tour = Tuple{Int, Int}[]
    for i=1:ncities
        for j = i+1:ncities
            if getvalue(m[:edges][i, j]) ≈ 1.0
                println((i, j))
                push!(tour, (i, j))
            end
        end
    end
    plottour(tour, "Relaxation tour")
end

end

@time TSP.very_naive_solve(relax=false)
# @time TSP.very_naive_solve(relax=true)
@time TSP.less_naive_relaxed()

using Base.Test
@test TSP.kruskals([1.; 2.; 3.], [(1,2), (2, 3), (1, 3)], 3) == [1, 1, 0]
@test TSP.kruskals([1.; 2.; 3.], [(1,2), (2, 3), (1, 3)], 3) == [1, 1, 0]
@test TSP.kruskals([1.; 0; 2.; 3.], [(1,2), (2, 1), (2, 3), (1, 3)], 3) == [0, 1, 1, 0]
@test TSP.kruskals([5.; 3.; 4.; 1.; 2.], [(1,2), (2, 3), (1, 3), (3, 4), (2, 4)], 4) == [0, 0, 1, 1, 1]


text:
# ---
# jupyter:
#   jupytext:
#     formats: ipynb,jl:hydrogen
#     text_representation:
#       extension: .jl
#       format_name: hydrogen
#       format_version: '1.3'
#       jupytext_version: 1.11.2
#   kernelspec:
#     display_name: Julia 1.6.3
#     language: julia
#     name: julia-1.6
# ---

# %%
using StaticArrays
struct Point{T} <: FieldVector{2, T} x::T; y::T end

# %%
p = Point(1, 2)

# %%
p[2], p.y

# %%
q = Point(3, 4)

# %%
q - p

# %%
3p

# %%
using LinearAlgebra
dot(p, q), cross(p, q)

# %%
struct PointPlain{T} x::T; y::T end
methodswith(PointPlain; supertypes=true)

# %%
struct PointFieldVector{T} <: FieldVector{2, T} x::T; y::T end
methodswith(PointFieldVector; supertypes=true)

# %%

max_stars_repo_name: genkuroki/public

max_issues_repo_name: genkuroki/public

max_forks_repo_name: genkuroki/public


text:
@testset "Databases" begin
    server = InfluxServer("http://localhost:8086")

    dbs, = list_databases(server)
    @test "NOAA_water_database" in dbs[!, :name]
    @test !("foofoo" in dbs[!, :name])

    create_database(server, "foofoo")
    dbs, = list_databases(server)
    @test "NOAA_water_database" in dbs[!, :name]
    @test "foofoo" in dbs[!, :name]
end


text:
# Helpers for wrapping iterate* methods like
# hsa_iterate_agents
# hsa_agent_iterate_regions

type IterState
    inner_cb::Function
    err::Nullable{Exception}

    IterState(cb) = new(cb, Nullable{Exception}())
end

function iterate_cb(x, state_ptr::Ptr{Void})
    # common initialization
    if state_ptr == C_NULL
        return HSA_STATUS_ERROR_INVALID_ARGUMENT
    else
        state = unsafe_pointer_to_objref(state_ptr)

        if !isa(state, IterState)
            return HSA_STATUS_ERROR_INVALID_ARGUMENT
        end
    end

    callback = state.inner_cb
    #end init

    wrapped_cb = () -> callback(x)

    return iterate_cb_common(wrapped_cb, state)
end

function iterate_cb(x,y, state_ptr::Ptr{Void})
    # common initialization
    if state_ptr == C_NULL
        return HSA_STATUS_ERROR_INVALID_ARGUMENT
    else
        state = unsafe_pointer_to_objref(state_ptr)

        if !isa(state, IterState)
            return HSA_STATUS_ERROR_INVALID_ARGUMENT
        end
    end

    callback = state.inner_cb
    #end init

    wrapped_cb = () -> callback(x,y)

    return iterate_cb_common(wrapped_cb, state)
end

function iterate_cb_common(callback::Function, state)
    local cont

    try
        cont = callback()
        if !isa(cont, Bool)
            cont = true
        end
    catch err
        state.err = err
        cont = false
    end

    if cont
        return HSA_STATUS_SUCCESS
    else
        return HSA_STATUS_INFO_BREAK
    end
end


text:
#Constant mean function

@doc """
# Description
Constructor for the constant mean function

m(x) = β
# Arguments:
* `β::Float64`: Constant
""" ->
type MeanConst <: Mean
    β::Float64
    MeanConst(β::Float64) = new(β)
end

@doc """
# Description
Constructor for the zero mean function

m(x) = 0
""" ->
MeanZero() = MeanConst(0.0)

mean(mConst::MeanConst,x::Matrix{Float64}) =  fill(mConst.β, size(x,2))

get_params(mConst::MeanConst) = Float64[mConst.β]
get_param_names(::MeanConst) = [:β]
num_params(mConst::MeanConst) = 1
function set_params!(mConst::MeanConst, hyp::Vector{Float64})
    length(hyp) == 1 || throw(ArgumentError("Constant mean function only has 1 parameter"))
    mConst.β = hyp[1]
end
function grad_mean(mConst::MeanConst, x::Vector{Float64})
    dM_theta = ones(size(x,2))
    return dM_theta
end


text:
"""
agents.jl
Functions for agent-level model components
"""

function AgentDB(cohorts, AgentAssumptions::AgentAssumptions, reduced::Bool)
  """
  A function which will create an empty agent_db for the specified simulation length
  """
  sub_agent_db = DataFrame(cohort = DataFrame(stage=Int[], location=Int[], alive=Int[], dead_natural=Int[], dead_risk=Int[]))
  int_agent_db = hcat(sub_agent_db, sub_agent_db)
  if reduced
    columns = length(AgentAssumptions.growth)
  else
    columns = 104
  end
  for i = 1:(columns-2)
    int_agent_db=hcat(int_agent_db, sub_agent_db)
  end
  if reduced
    names!(int_agent_db, [symbol("stage_$i") for i in 1:columns])
  else
    names!(int_agent_db, [symbol("week_$i") for i in 1:columns])
  end
  agent_db = vcat(int_agent_db, int_agent_db)
  for i = 1:(cohorts-2)
    agent_db = vcat(agent_db, int_agent_db)
  end
  return agent_db
#   return int_agent_db
end

function kill!(agent_db::DataFrame, EnvironmentAssumptions::EnvironmentAssumptions, AgentAssumptions::AgentAssumptions, cohort::Int, week::Int)
  """
  This function will kill agents based on all stage and location specific risk factors described in a `EnvironmentAssumptions`
  """
  for i = 1:length(agent_db[cohort, week][:alive])
    if agent_db[cohort, week][:alive][i] > 0
      killed = rand(Binomial(agent_db[cohort, week][:alive][i], AgentAssumptions.naturalmortality[EnvironmentAssumptions.habitat[agent_db[cohort, week][:location][i]],agent_db[cohort, week][:stage][i]][1]))
      agent_db[cohort, week][:dead_natural][i] += killed
      agent_db[cohort, week][:alive][i] -= killed
      if agent_db[cohort, week][:alive][i] > 0
        if EnvironmentAssumptions.risk[agent_db[cohort, week][:location][i]]
          killed = rand(Binomial(agent_db[cohort, week][:alive][i], AgentAssumptions.extramortality[agent_db[cohort, week][:stage][i]][1]))
          agent_db[cohort, week][:dead_risk][i] += killed
          agent_db[cohort, week][:alive][i] -= killed
        end
      end
    end
  end
end

function localmove(location::Int, stage::Int, AgentAssumptions::AgentAssumptions, EnvironmentAssumptions::EnvironmentAssumptions)
  """
  A function which generates movement to a neighbouring location based on movement weights
  """
  @assert(0.<= AgentAssumptions.autonomy[stage] <=1., "Autonomy level must be between 0 and 1")
  # location id to coordinates
  id=ind2sub(size(EnvironmentAssumptions.habitat), location)
  # Select surrounding block of IDs, match up with weights
  choices = [sub2ind(size(EnvironmentAssumptions.habitat), [id[1]-1,id[1],id[1]+1,id[1]-1,id[1],id[1]+1,id[1]-1,id[1],id[1]+1], [id[2]-1, id[2]-1, id[2]-1, id[2], id[2], id[2], id[2]+1, id[2]+1, id[2]+1]) [AgentAssumptions.movement[stage][:]]]
  # If habitat type is 0, remove row
  choices = choices[EnvironmentAssumptions.habitat[choices[:,1]] .> 0, :]
  # Match locations with natural mortality rates
  choices = hcat(choices, 1-AgentAssumptions.naturalmortality[EnvironmentAssumptions.habitat[choices[:,1]], stage])
  # Normalize into probabilities
  choices[:,2]=choices[:,2]/sum(choices[:,2])
  choices[:,3]=choices[:,3]/sum(choices[:,3])
  # Weight options by autonomy
  return int(choices[findfirst(rand(Multinomial(1, choices[:,2]*(1-AgentAssumptions.autonomy[stage]) + choices[:,3]*(AgentAssumptions.autonomy[stage])))), 1])
end

function move!(agent_db::DataFrame, AgentAssumptions::AgentAssumptions, EnvironmentAssumptions::EnvironmentAssumptions, cohort::Int, week::Int)
  """
  This function will move agents based on stage and location
  """
  for i = 1:length(agent_db[cohort, week][:alive])
    if agent_db[cohort, week][:alive][i] > 0
      agent_db[cohort, week][:location][i] = localmove(agent_db[cohort, week][:location][i], agent_db[cohort, week][:stage][i], AgentAssumptions, EnvironmentAssumptions)
    end
  end
end

function injectagents!(agent_db::DataFrame, location::Int, size::Int, cohort::Int, week::Int)
  """
  This function will inject agents into an `agent_db` to simulate stocking efforts. These stocked agents will take their stage information from the `agent_db`
  """
  push!(agent_db[cohort,week], [maximum(agent_db[cohort,week][:stage]), location, size, 0, 0])
end


text:
#came from GLInfo.jl

const GLSL_COMPATIBLE_NUMBER_TYPES = (GLfloat, GLint, GLuint, GLdouble)
const NATIVE_TYPES = Union{
    GLSL_COMPATIBLE_NUMBER_TYPES...,
    Buffer, GPUArray, Shader, Program
}
isa_gl_struct(x::NATIVE_TYPES) = false

opengl_prefix(T)  = @error "Object $T is not a supported uniform element type"
opengl_postfix(T) = @error "Object $T is not a supported uniform element type"

opengl_prefix(x::Type{T}) where {T <: Union{FixedPoint, Float32, Float16}} = ""
opengl_prefix(x::Type{T}) where {T <: Float64} = "d"
opengl_prefix(x::Type{Cint}) = "i"
opengl_prefix(x::Type{T}) where {T <: Union{Cuint, UInt8, UInt16}} = "u"

opengl_postfix(x::Type{Float64}) = "dv"
opengl_postfix(x::Type{Float32}) = "fv"
opengl_postfix(x::Type{Cint})    = "iv"
opengl_postfix(x::Type{Cuint})   = "uiv"

#Came from GLUniforms or GLInfo.jl

glsl_type(::Type{T}) where {T <: AbstractFloat} = Float32
glsl_type(::UniformBuffer{T}) where T = T
glsl_type(::Texture) where {T, N} = gli.GLTexture{glsl_type(T), N}
glsl_typename(x::T) where {T} = glsl_typename(T)
glsl_typename(t::Type{Nothing})     = "Nothing"
glsl_typename(t::Type{GLfloat})  = "float"
glsl_typename(t::Type{GLdouble}) = "double"
glsl_typename(t::Type{GLuint})   = "uint"
glsl_typename(t::Type{GLint})    = "int"
function glsl_typename(t::Type{T}) where {T}
    glasserteltype(T)
    string(opengl_prefix(eltype(T)), "vec", length(T))
end
glsl_typename(t::Type{TextureBuffer{T}}) where {T} = string(opengl_prefix(eltype(T)), "samplerBuffer")

function glsl_typename(t::Texture{T, D}) where {T, D}
    str = string(opengl_prefix(eltype(T)), "sampler", D, "D")
    t.texturetype == GL_TEXTURE_2D_ARRAY && (str *= "Array")
    str
end
function glsl_typename(t::Type{T}) where T <: Matrix

    M, N = size(t)
    string(opengl_prefix(eltype(t)), "mat", M==N ? M : string(M, "x", N))
end
toglsltype_string(x::T) where {T<:Union{Real, Texture, TextureBuffer, Nothing}} = "uniform $(glsl_typename(x))"
#Handle GLSL structs, which need to be addressed via single fields
function toglsltype_string(x::T) where T
    if isa_gl_struct(x)
        string("uniform ", T.name.name)
    else
        @error "can't splice $T into an OpenGL shader. Make sure all fields are of a concrete type and isbits(FieldType)-->true"
    end
end
# Gets used to access a
function glsl_variable_access(keystring, t::Texture{T, D}) where {T,D}
    fields = SubString("rgba", 1, length(T))
    if t.texturetype == GL_TEXTURE_BUFFER
        return string("texelFetch(", keystring, "index).", fields, ";")
    end
    return string("getindex(", keystring, "index).", fields, ";")
end

function glsl_variable_access(keystring, t::Any)
    @error "no glsl variable calculation available for : $(keystring) of type $(typeof(t))"
end

function glsl_version_string()
    glsl = split(unsafe_string(glGetString(GL_SHADING_LANGUAGE_VERSION)), ['.', ' '])
    if length(glsl) >= 2
        glsl = VersionNumber(parse(Int, glsl[1]), parse(Int, glsl[2]))
        glsl.major == 1 && glsl.minor <= 2 && (@error "OpenGL shading Language version too low. Try updating graphic driver!")
        glsl_version = string(glsl.major) * rpad(string(glsl.minor),2,"0")
        return "#version $(glsl_version)\n"
    else
        @error "could not parse GLSL version: $glsl"
    end
end


text:
using Test
import Slicer
import Slicer: Plane, Vertex, Triangle, AABB, LineSegment, Polygon

@testset "Load STL" begin
    stl = joinpath("data", "nist.stl")
    triangles = Slicer.load(stl)

    @test length(triangles) == 7392
end

@testset "Point-plane distance" begin
    plane = Plane((0, 0, 1), (0, 0, 0))

    @test Slicer.distance(Vertex(0, 0, 1), plane) == 1
    @test Slicer.distance(Vertex(1, 1, 1), plane) == 1
    @test Slicer.distance(Vertex(-1, -1, -1), plane) == -1
    @test Slicer.distance(Vertex(0, 0, 0), plane) == 0
end

@testset "Line-plane intersection" begin
    plane = Plane((0, 0, 1), (0, 0, 0))

    @test Slicer.intersect(Vertex(1, 1, 0), Vertex(-1, -1, 0), plane) == [Vertex(1, 1, 0), Vertex(-1, -1, 0)]
    @test Slicer.intersect(Vertex(1, 1, 1), Vertex(-1, -1, -1), plane) == [Vertex(0, 0, 0)]
    @test Slicer.intersect(Vertex(1, 1, 1), Vertex(-1, -1, 1), plane) == []
    @test Slicer.intersect(Vertex(0, 0, 0), Vertex(0, 0, 1), plane) == [Vertex(0, 0, 0)]
end

@testset "Triangle-plane intersection" begin
    plane = Plane((0, 0, 1), (0, 0, 0))
    triangle1 = Triangle((1, 0, 0), (0, 0, 0), (0, 1, 0), (0, 0, 1))
    triangle2 = Triangle((1, 0, 0), (0, 0, -.5), (0, 1, -.5), (0, 0, .5))

    @test Slicer.intersect(triangle1, plane) == LineSegment([0, 0, 0], [0, 1, 0])
    @test Slicer.intersect(triangle2, plane) == LineSegment([0, 0, 0], [0, .5, 0])
    @test Slicer.intersect(triangle1, Plane((0, 0, 1), (0, 0, 5))) == nothing
    @test Slicer.intersect(triangle1, Plane((0, 0, 1), (0, 0, 1))) == nothing
end

@testset "Triangles-plane intersection" begin
    triangle1 = Triangle((1, 0, 0), (0, 0, 0), (0, 1, 0), (0, 0, 1))
    triangle2 = Triangle((1, 0, 0), (0, 0, -.5), (0, 1, -.5), (0, 0, .5))
    triangle3 = Triangle((1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 1, 1))

    @test Slicer.intersect([triangle1, triangle2], Plane((0, 0, 1), (0, 0, 0))) ==
            [LineSegment([0, 0, 0], [0, 1, 0]), LineSegment([0, 0, 0], [0, .5, 0])]
    @test Slicer.intersect([triangle1, triangle3], Plane((0, 0, 1), (0, 0, 0))) ==
            [LineSegment([0, 0, 0], [0, 1, 0])]
    @test Slicer.intersect([triangle1, triangle3], Plane((0, 0, 1), (0, 0, .5))) ==
            [LineSegment([0, .5, .5], [0, 0, .5]), LineSegment([0, .5, .5], [0, 1, .5])]
    @test Slicer.intersect([triangle1, triangle3], Plane((0, 0, 1), (0, 0, 1))) ==
            [LineSegment([0, 1, 1], [0, 0, 1])]
    @test Slicer.intersect([triangle1, triangle3], Plane((1, 0, 0), (0, 0, 0))) == []
end

@testset "Axis-aligned bounding box" begin
    triangle1 = Triangle((1, 0, 0), (0, 0, 0), (0, 1, 0), (0, 0, 1))
    triangle2 = Triangle((1, 0, 0), (0, 0, -.5), (0, 1, -.5), (0, 0, .5))

    @test Slicer.boundingbox(Triangle((1, 0, 0), (0, 0, 0), (0, 1, 0), (0, 0, 1))) == AABB(0, 0, 0, 1, 0, 1)
    @test AABB(0, 0, 0, 1, 0, 42) + AABB(-1, 1, 0, .5, -.5, 1) == AABB(-1, 1, 0, 1, -.5, 42)
    @test Slicer.boundingbox([triangle1, triangle2]) == AABB(0, 0, 0, 1, -.5, 1)

    @test Slicer.boundingbox(Polygon([(1, 0, 1), (0, 1, 1), (0, 0, 1)])) == AABB(0, 1, 0, 1, 1, 1)

    @test issubset(AABB(0, 1, 0, 1, 0, 0), AABB(0, 1, 0, 1, 0, 0))
    @test issubset(AABB(0, .5, 0, .5, 0, 0), AABB(0, 1, 0, 1, 0, 0))
    @test issubset(AABB(.1, .5, 0, .5, 0, 0), AABB(0, 1, 0, 1, 0, 0))
    @test !issubset(AABB(-.1, .5, 0, .5, 0, 0), AABB(0, 1, 0, 1, 0, 0))
end

@testset "End matching" begin
    @test Slicer.match([
        LineSegment((0, 0, 0), (1, 0, 0)),
        LineSegment((1, 0, 0), (0, 1, 0)),
        LineSegment((0, 1, 0), (0, 0, 0)),
    ]) == [
        Polygon([(0, 0, 0), (0, 1, 0), (1, 0, 0)])
    ]

    @test Slicer.match([
        LineSegment((0, 0, 0), (1, 0, 0)),
        LineSegment((1, 0, 0), (0, 1, 0)),
        LineSegment((0, 1, 0), (0, 0, 0)),
        LineSegment((0, 0, 1), (1, 0, 1)),
        LineSegment((1, 0, 1), (0, 1, 1)),
        LineSegment((0, 1, 1), (0, 0, 1)),
    ]) == [
        Polygon([(0, 0, 0), (0, 1, 0), (1, 0, 0)]),
        Polygon([(1, 0, 1), (0, 1, 1), (0, 0, 1)]),
    ]

    @test Slicer.match([
        LineSegment((0, 0, 0), (1, 0, 0)),
        LineSegment((1, 0, 0), (1, 1, 0)),
        LineSegment((1, 1, 0), (0, 1, 0)),
        LineSegment((0, 1, 0), (0, 0, 0)),
    ]) == [
        Polygon([(1, 1, 0), (0, 1, 0), (0, 0, 0), (1, 0, 0)]),
    ]

    @test Slicer.correct([
        Polygon([(1, 2, 0), (2, 2, 0), (2, 1, 0), (1, 1, 0)]),
        Polygon([(3, 0, 0), (3, 3, 0), (0, 3, 0), (0, 0, 0)]),
    ]) == [
        Polygon([(1, 1, 0), (2, 1, 0), (2, 2, 0), (1, 2, 0)]),
        Polygon([(0, 0, 0), (0, 3, 0), (3, 3, 0), (3, 0, 0)]),
    ]

    @test Slicer.simplify(Polygon([(0, 0, 0), (1, 1, 0), (2, 2, 0), (0, 2, 0)])) ==
                          Polygon([(2, 2, 0), (0, 2, 0), (0, 0, 0)])
end

@testset "Clockwise vs. counter-clockwise" begin
    @test Slicer.isclockwise(Polygon([(0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0)]))
    @test !Slicer.isclockwise(Polygon([(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]))
end


text:
function SeisProcessHeaders(in, out, functions, parameters;
                            group="some", key=[], ntrace=1000000,
                            update_tracenum=true)

    if (group=="all")
	h1 = SeisReadHeaders(in,group=group,key=key,itrace=1,ntrace=ntrace)
	for ifunc = 1 : length(functions)
	    f = functions[ifunc]
	    p = parameters[ifunc]
	    h2 = f(h1;p...)
	    h1 = copy(h2)
	end
	SeisWriteHeaders(out,h1)
    else
	itrace_in = 1
	itrace_out = 1
	NX = GetNumTraces(in)

	while itrace_in <= NX
	    nx = NX - itrace_in + 1
	    ntrace = nx > ntrace ? ntrace : nx
	    h1 = SeisReadHeaders(in, group=group, key=key, itrace=itrace_in,
                                 ntrace=ntrace)
	    num_traces_in = length(h1)

	    for ifunc = 1 : length(functions)
		f = functions[ifunc]
		p = parameters[ifunc]

		h2 = f(h1;p...)
		h1 = copy(h2)
	    end
	    num_traces_out = length(h1)

	    SeisWriteHeaders(out, h1, itrace=itrace_out,
                             update_tracenum=update_tracenum)
	    itrace_in += num_traces_in
	    itrace_out += num_traces_out
	end
    end
end

max_stars_repo_name: fercarozzi/myseismicjulia

max_issues_repo_name: fercarozzi/myseismicjulia

max_forks_repo_name: fercarozzi/myseismicjulia


text:
#############################################
# Trie string approximate implementation
#############################################

# here we create a tree where each node is a letter, and the child nodes are the next letter in the string
# to find the UID for a string, we traverse the tree one letter at a time until we find the UID (or not!)

immutable TrieChar
  byte::UInt8
end
TrieChar() = TrieChar(0x00)

# Base.string(c::TrieChar) = ascii([c.byte])
Base.print(io::IO, c::TrieChar) = print(io, string(c))
Base.show(io::IO, c::TrieChar) = show(io, string(c))
Base.hash(c::TrieChar) = c.byte
==(c1::TrieChar, c2::TrieChar) = c1.byte == c2.byte

type TrieNode{T}
    children::Dict{TrieChar,TrieNode{T}}
    # parentChain::String
    # istail::Bool
    data::Nullable{T}  # note: this will be undefined except for tail nodes

    # TrieNode{T}(::Type{T}) = new(Dict{TrieChar,TrieNode{T}}(), "", false)
    # TrieNode{T}(::Type{T}, parentChain::String) = new(Dict{TrieChar,TrieNode{T}}(), parentChain, false)
    TrieNode() = new(Dict{TrieChar,TrieNode{T}}(), Nullable{T}())
end
# TrieNode{T}(::Type{T}) = TrieNode{T}(T)

function TrieNode{K}(::Type{K}, strings::Vector{String})
    rootNode = TrieNode{K}()
    for (i,s) in enumerate(strings)
        get!(rootNode, s, K(i))
    end
    rootNode
end

# function maketail!{T}(node::TrieNode{T}, data::T)
#     node.istail = true
#     node.data = data
#     return
# end

function Base.get{T<:Union{String,FixedLengthSymbol}, K}(rootNode::TrieNode{K}, s::T, default::K)
    local node::TrieNode{K}
    node = rootNode

    for i in 1:sizeof(T)
        b = getfield(s, i)
        if b == 0x00 || b == 0x20
            break
        end

        c = TrieChar(b)
        if haskey(node.children, c)
            node = node.children[TrieChar(b)]
        else
            return default
        end
        # node = get(node.children, TrieChar(b)) do
        #   return default
        # end
    end

    # if node.istail
    if isnull(node.data)
        return default
    else
        return get(node.data)
    end
end

function Base.get!{T<:Union{String,FixedLengthSymbol}, K}(rootNode::TrieNode{K}, s::T, default::K)
    node = rootNode
    for b in s.data
        # we're done if null char or space
        if b == 0x00 || b == 0x20
            break
        end

        # set node to be the next node in the tree (add one if needed)
        c = TrieChar(b)
        if haskey(node.children, c)
            node = node.children[c]
        else
            newnode = TrieNode{K}()
            node.children[c] = newnode
            node = newnode
        end

        # node = get!(node.children, TrieChar(b), TrieNode(K))

    end

    # add the tail
    if isnull(node.data)
        node.data = Nullable(default)
    end
    get(node.data)

    # maketail!(node, default)

    # node
end


text:
# Autogenerated wrapper script for libplist_jll for aarch64-linux-gnu-cxx03
export libplist, plistutil

JLLWrappers.@generate_wrapper_header("libplist")
JLLWrappers.@declare_library_product(libplist, "libplist-2.0.so.3")
JLLWrappers.@declare_executable_product(plistutil)
function __init__()
    JLLWrappers.@generate_init_header()
    JLLWrappers.@init_library_product(
        libplist,
        "lib/libplist-2.0.so",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_executable_product(
        plistutil,
        "bin/plistutil",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


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

using Markdown
using InteractiveUtils

# ╔═╡ 927bee40-2493-11eb-365b-bbd027f30802
begin
	import Pkg
	Pkg.add("Images")
	Pkg.add("ColorTypes")
	using Images
	using ColorTypes
end

# ╔═╡ 6f413930-2493-11eb-289e-d7b31dc10797
md"""http://blog.robindeits.com/2017/01/18/Chromesthesia/"""

# ╔═╡ c2e4f770-2493-11eb-309d-e589e348cecd

# ╔═╡ 92633620-2493-11eb-092f-1db008e4f2cf
img = "D:\\MyGit\\Colors\\Images\\3by3_Black&white.jpg"

# ╔═╡ 924a7e00-2493-11eb-1a2b-edcdfea00ba7
img1 = load(img)

# ╔═╡ 92303f40-2493-11eb-3aed-53ea36194900
show(img1)

# ╔═╡ 9218bfa2-2493-11eb-1eca-dbbe5e5e785c
R1M = red.(img1)

# ╔═╡ 91fdbd90-2493-11eb-0173-87763bb4bbca
B1M = blue.(img1)

# ╔═╡ 6ec6a010-2495-11eb-2fed-ef6e43d5e732
 G1M = green.(img1)

# ╔═╡ 6e93f750-2495-11eb-29b5-b91a48421361
RGB_SUM = R1M + B1M + G1M

# ╔═╡ 6e7aca00-2495-11eb-0951-351d318562c5

# ╔═╡ 6dda6b50-2495-11eb-24d5-6fe85c9d186a

# ╔═╡ Cell order:
# ╟─6f413930-2493-11eb-289e-d7b31dc10797
# ╠═c2e4f770-2493-11eb-309d-e589e348cecd
# ╠═927bee40-2493-11eb-365b-bbd027f30802
# ╠═92633620-2493-11eb-092f-1db008e4f2cf
# ╠═924a7e00-2493-11eb-1a2b-edcdfea00ba7
# ╠═92303f40-2493-11eb-3aed-53ea36194900
# ╠═9218bfa2-2493-11eb-1eca-dbbe5e5e785c
# ╠═91fdbd90-2493-11eb-0173-87763bb4bbca
# ╠═6ec6a010-2495-11eb-2fed-ef6e43d5e732
# ╠═6e93f750-2495-11eb-29b5-b91a48421361
# ╠═6e7aca00-2495-11eb-0951-351d318562c5
# ╠═6dda6b50-2495-11eb-24d5-6fe85c9d186a


text:
abstract type NodeDistribution end
struct Uniform <: NodeDistribution end
struct NonUniform <: NodeDistribution end

distribution(::AbstractRange) = Uniform()
distribution(::AbstractVector) = NonUniform()


text:
include("task_func.jl")

function drawKrest(r)
    putmarker!(r)
    for side = (Nord, Ost, Sud, West)
        listOfShags = []
        while true
            push!(listOfShags, goToSide!(r, side, save = true, mark = true))
            if isRect(r, side)
                append!(listOfShags, aroundBorder!(r, side, save = true))
                putmarker!(r)
            else
                break
            end
        end
        goToStart!(r, listOfShags)
    end
end

max_stars_repo_name: Trilonka/MireaAl

max_issues_repo_name: Trilonka/MireaAl

max_forks_repo_name: Trilonka/MireaAl