text:
"""
    Base.rand(randomwalk::RandomWalk{<:AbstractArray{<:DataType}, <:AbstractArray{<:Real},
                                     <:Sampleable}, ntimesteps::Integer) -> Matrix{Int}

Simulate `randomwalk` for `ntimesteps` time-steps over an integer lattice, returning one
sample path (i.e. trajectory) of length `ntimesteps`.

The time steps represented in the sample path are `0, 1, ..., ntimesteps-1`, for we start
with an initial state.

##### Complexity
- Time complexity: `O(n)`.
"""
function Base.rand(randomwalk::RandomWalk{<:AbstractArray{<:DataType},
                                          <:AbstractArray{<:Real},
                                          <:Sampleable}, ntimesteps::Integer)
    # allocate memory
    realizationmatrix = Matrix{Int}(undef, ntimesteps,
                                                   length(randomwalk.initialstate))
    realizationmatrix[1,:] = randomwalk.initialstate
    # draw a random step
    change = rand(randomwalk.stepsampler)
    for step in 2:ntimesteps
        realizationmatrix[step,:] = realizationmatrix[step-1,:] + change
        change = rand(randomwalk.stepsampler)
    end
    return realizationmatrix
end

"""
    Base.rand(randomwalk::RandomWalk{<:DataType, <:Real, <:Sampleable,
              ntimesteps::Integer) -> Vector{Int}

Simulate a one-dimensional `randomwalk` for `ntimesteps` time-steps, returning one sample
path (i.e. trajectory) of length `ntimesteps`.

The time steps represented in the sample path are `0, 1, ..., ntimesteps-1`, for we start
with an initial state.

##### Complexity
- Time complexity: `O(n)`.
"""
function Base.rand(randomwalk::RandomWalk{<:DataType, <:Real, <:Sampleable},
                   ntimesteps::Integer)
    # allocate memory
    realizationvec = Vector{eltype(randomwalk)}(undef, ntimesteps)
    realizationvec[1] = randomwalk.initialstate
    # draw a random step
    change = rand(randomwalk.stepsampler)[1]
    for step in 2:ntimesteps
        realizationvec[step] = realizationvec[step-1] + change
        change = rand(randomwalk.stepsampler)[1]
    end
    return realizationvec
end

"""
    Base.rand(randomwalk::RandomWalk{<:AbstractGraph, <:Integer, <:Sampleable},
              ntimesteps::Integer) -> Vector{Int}

Simulate `randomwalk` for `ntimesteps` time-steps over a graph, returning one sample path
(i.e. trajectory) of length `ntimesteps`.

The time steps represented in the sample path are `0, 1, ..., ntimesteps-1`, for we start
with an initial state.

##### Complexity
- Time complexity: `O(n)`.
"""
function Base.rand(randomwalk::RandomWalk{<:AbstractGraph, <:Integer, <:Sampleable},
                   ntimesteps::Integer)
    # allocate memory
    realizationvec = Vector{eltype(randomwalk)}(undef, ntimesteps)
    realizationvec[1] = randomwalk.initialstate
    for step in 2:ntimesteps
        # draw a neighbor at random
        realizationvec[step] = NeighborSampler(randomwalk.statespace,
                                               realizationvec[step-1]) |> rand
    end
    return realizationvec
end

max_stars_repo_name: LoganDGraham/StochasticProcesses

max_issues_repo_name: LoganDGraham/StochasticProcesses

max_forks_repo_name: LoganDGraham/StochasticProcesses


text:
using RipQP, LinearOperators, LLSModels, NLPModelsModifiers, QPSReader, QuadraticModels, Quadmath
using DelimitedFiles, LinearAlgebra, MatrixMarket, SparseArrays, Test

qps1 = readqps("QAFIRO.SIF") #lower bounds
qps2 = readqps("HS21.SIF") # low/upp bounds
qps3 = readqps("HS52.SIF") # free bounds
qps4 = readqps("AFIRO.SIF") # LP
qps5 = readqps("HS35MOD.SIF") # fixed variables

Q = [
  6.0 2.0 1.0
  2.0 5.0 2.0
  1.0 2.0 4.0
]
c = [-8.0; -3; -3]
A = [
  1.0 0.0 1.0
  0.0 2.0 1.0
]
b = [0.0; 3]
l = [0.0; 0; 0]
u = [Inf; Inf; Inf]

include("solvers/test_augmented.jl")
include("solvers/test_newton.jl")
include("solvers/test_normal.jl")

include("test_multi.jl")
include("test_alternative_methods.jl")
include("test_alternative_problems.jl")

ext: jl


text:
# vim:set ft=julia ts=4 sw=4 sts=4 autoindent:

# Syntacto-semantic dependency graph and associated functions.
#
#   http://en.wikipedia.org/wiki/Dependency_grammar
#
# Author:   Pontus Stenetorp    <pontus stenetorp se>
# Version:  2014-05-03

module DepGraph

# Dependency graph.
export
    Vertex, Graph, dgraph, sentence,
    edge!, deledge!,
    lmostdep, rmostdep,
    NULLVERT, ROOTID

# String to ID encoder/decoder.
export Coder, encode, decode

require("conllx.jl")

using Base.Collections
using Base.Order

using CoNLLX

type Vertex
    id::Uint
    form::Uint
    postag::Uint
    head::Uint
    deprel::String
    # TODO: Should be an ordered set.
    ldependents::Vector{Vertex}
    rdependents::Vector{Vertex}
    function Vertex(id, form, postag)
        new(id, form, postag, NOHEAD, NOVAL, Vertex[], Vertex[])
    end
end

function Vertex(id, form, postag, head, deprel)
    v = Vertex(id, form, postag)
    v.head = head
    v.deprel = deprel
    return v
end

function Vertex(t::Token, coder)
    Vertex(t.id, encode(t.form, coder), encode(t.cpostag, coder),
        t.head, t.deprel)
end

import CoNLLX: Token
function Token(v::Vertex, coder)
    return Token(v.id, decode(v.form, coder), NOVAL, decode(v.postag, coder),
        NOVAL, NOVAL, v.head, v.deprel, NOHEAD, NOVAL)
end

import Base: isequal
function isequal(a::Vertex, b::Vertex)
    (a.id == b.id && a.form == b.form && a.postag == b.postag
        && a.head == b.head && isequal(a.deprel, b.deprel)
        && length(a.ldependents) == length(b.ldependents)
        && length(a.rdependents) == length(b.rdependents)
        # Only check the IDs to avoid infinite recursion.
        && all([ae.id == be.id
            for (ae, be) in zip(a.ldependents, b.ldependents)])
        && all([ae.id == be.id
            for (ae, be) in zip(a.rdependents, b.rdependents)]))
end

import Base: show
function show(io::IO, v::Vertex)
    ldeps = join([d.id for d in v.ldependents], ", ")
    rdeps = join([d.id for d in v.rdependents], ", ")
    print(io, string("Vertex(id=$(v.id),form=$(v.form),postag=$(v.postag),",
        "head=$(v.head),deprel=$(v.deprel),ldependents=[$ldeps],",
        "rdependents=[$rdeps])"))
end

const NULLID = 0
const ROOTID = 1
# All codes are [1...], we can thus use 0 for the form and postag.
const NULLFORM = 0
const NULLPOS = 0
# Vertex to represent the absence of a vertex.
const NULLVERT = Vertex(NULLID, NULLFORM, NULLPOS)

ROOTTOK = Token(ROOTID, "<ROOT>", NOVAL, NOVAL, NOVAL, NOVAL, NOHEAD, NOVAL,
    NOHEAD, NOVAL)

typealias Graph Vector{Vertex}

import Base: isequal
function isequal(a::Graph, b::Graph)
    length(a) == length(b) && all([isequal(ae, be) for (ae, be) in zip(a, b)])
end

# We encode the vocabulary and PoS-tags as integers for faster featurisation.
type Coder
    enc::Dict{String, Uint}
    dec::Dict{Uint, String}
end

Coder() = Coder(Dict{String, Uint}(), Dict{Uint, String}())

function encode(str, coder)
    code = get!(coder.enc, str, length(coder.enc) + 1)
    coder.dec[code] = str
    return code
end

function decode(code, coder)
    str = get(coder.dec, code, nothing)
    if str == nothing
        error("Unable to decode \"$code\"")
    end
    return str
end

# TODO: Rename as Graph?
function dgraph(sent::Sentence, coder; blind=false)
    graph = Vertex[]
    push!(graph, Vertex(ROOTTOK, coder))
    for tok in sent
        push!(graph, Vertex(tok, coder))
    end

    # Do not add any edges (for training).
    if blind
        return graph
    end

    # Add existing information (if any).
    for i in 2:length(graph)
        vert = graph[i]
        if vert.head != NOHEAD
            head = graph[vert.head]
            if vert.deprel == NOVAL
                edge!(graph, vert, head)
            else
                edge!(graph, vert, head, vert.deprel)
            end
        end
    end

    return graph
end

function sentence(graph::Graph, coder)
    sent = Token[]
    for i in 2:length(graph)
        push!(sent, Token(graph[i], coder))
    end

    return sent
end

# Ordering for the left/right dependents.
const LDEP_ORD = By(v->v.id)
const RDEP_ORD = ReverseOrdering(LDEP_ORD)

lmostdep(v) = !isempty(v.ldependents) ? v.ldependents[1] : NULLVERT
rmostdep(v) = !isempty(v.rdependents) ? v.rdependents[1] : NULLVERT

function adddep(head, dependent)
    if dependent.id < head.id
        heappush!(head.ldependents, dependent, LDEP_ORD)
    else
        heappush!(head.rdependents, dependent, RDEP_ORD)
    end
end

# TODO: More efficient to use a binary tree? O(n) + O(n)?
function rmdep(head, dependent)
    if dependent.id < head.id
        ldeps = head.ldependents
        deleteat!(ldeps, findfirst(ldeps, dependent))
        heapify!(ldeps, LDEP_ORD)
    else
        rdeps = head.rdependents
        deleteat!(rdeps, findfirst(rdeps, dependent))
        heapify!(rdeps, RDEP_ORD)
    end
end

# Add an unlabelled edge.
function edge!(graph::Graph, dependent::Vertex, head::Vertex)
    dependent.head = head.id
    adddep(head, dependent)
end

# Add a labelled edge.
function edge!(graph::Graph, dependent::Vertex, head::Vertex, deprel)
    edge!(graph, dependent, head)
    dependent.deprel = deprel
end

function deledge!(graph::Graph, dependent::Vertex, head::Vertex)
    dependent.head = NOHEAD
    dependent.deprel = NOVAL
    rmdep(head, dependent)
end

end

max_stars_repo_name: ninjin/allen

max_issues_repo_name: ninjin/allen

max_forks_repo_name: ninjin/allen


text:
push!(LOAD_PATH,"../src")
using Documenter, ComplexValues

makedocs(sitename="ComplexValues.jl",
    format = Documenter.HTML(),
    authors = "Toby Driscoll",
    pages = [
        "Home" => "index.md",
        "Polar" => "polar.md",
        "Spherical" => "spherical.md"
		],
	modules = [ComplexValues],
    doctest = true
    )

deploydocs(
    repo = "github.com/complexvariables/ComplexValues.jl.git"
#    versions = ["v#.#"],
#    make = nothing
    )


text:
using Optim
using DataFrames

const nruns = 10
nthreads = Threads.nthreads()

res, params = optim_params(; optimoptions=Optim.Options(iterations=nruns, show_trace=false))
@test Optim.iterations(res) == nruns

df = optim_params_threads(nthreads, optimoptions=Optim.Options(iterations=nruns))
@test df isa DataFrame


text:
export AbstractPolyhedron

"""
    AbstractPolyhedron{N<:Real} <: LazySet{N}

Abstract type for polyhedral sets, i.e., sets with finitely many flat facets, or
equivalently, sets defined as an intersection of a finite number of half-spaces.

### Notes

Every concrete `AbstractPolyhedron` must define the following functions:
- `constraints_list(::AbstractPolyhedron{N})` -- return a list of all facet
    constraints

```jldoctest
julia> subtypes(AbstractPolyhedron)
6-element Array{Any,1}:
 AbstractPolytope
 HPolyhedron
 HalfSpace
 Hyperplane
 Line
 Universe
```
"""
abstract type AbstractPolyhedron{N<:Real} <: LazySet{N} end

# --- common AbstractPolyhedron functions ---

# To account for the compilation order, functions are defined in the file
# AbstractPolyhedron_functions.jl


text:
#!/usr/bin/env julia
#
# Called with no arguments will create the system image
#     ClimateMachine.so
# in the `@__DIR__` directory.
#
# Called with a single argument the system image will be placed in the path
# specified by the argument (relative to the callers path)
#
# Called with a specified systemimg path and `true`, the system image will
# compile the climate machine package module (useful for CI)

sysimage_path =
    isempty(ARGS) ? joinpath(@__DIR__, "ClimateMachine.so") : abspath(ARGS[1])

climatemachine_pkg = get(ARGS, 2, "false") == "true"

@info "Creating system image object file at: '$(sysimage_path)'"
@info "Building ClimateMachine into system image: $(climatemachine_pkg)"

start_time = time()

using Pkg
Pkg.add("PackageCompiler")

Pkg.activate(joinpath(@__DIR__, "..", ".."))
Pkg.instantiate(verbose = true)

pkgs = Symbol[]
if climatemachine_pkg
    push!(pkgs, :ClimateMachine)
else
    # TODO: reorg project structure (Project.toml) to use
    # Pkg.dependencies() with PackageCompiler
    #if VERSION >= v"1.4"
    #    append!(pkgs, [Symbol(v.name) for v in values(Pkg.dependencies())])
    #end
    append!(pkgs, [Symbol(name) for name in keys(Pkg.installed())])
end

# use package compiler
using PackageCompiler
PackageCompiler.create_sysimage(
    pkgs,
    sysimage_path = sysimage_path,
    precompile_execution_file = joinpath(
        @__DIR__,
        "..",
        "..",
        "test",
        "Numerics",
        "DGMethods",
        "Euler",
        "isentropicvortex.jl",
    ),
)

tot_secs = Int(floor(time() - start_time))
@info "Created system image object file at: $(sysimage_path)"
@info "System image build time: $tot_secs sec"

max_stars_repo_name: leios/CLIMA

max_issues_repo_name: leios/CLIMA

max_forks_repo_name: leios/CLIMA


text:
using StructuresKit

shape_name = "W14X90"
#define discretization along member
zcoords = 0:1:20
n=(4, 4, 4, 4, 4)

shape_info = StructuresKit.CrossSection.AISC(shape_name)

#A Ix Iy J Cw xc yc xs ys
section_properties = [(shape_info.A, shape_info.Ix, shape_info.Iy, shape_info.J, shape_info.Cw, shape_info.d/2, 0.0, shape_info.d/2, 0.0)]

#E  ν
material_properties = [(29000,0.30)]

#kx ky kϕ hx hy
springs = [0.0, 0.0, 0.0, 0.0, 0.0]

#member information
#L dL SectionProperties MaterialProperties Springs
member_definitions = [(13.0*12, (13*12)/12,1,1,1)]

num_nodes = Int(member_definitions[1][1]/member_definitions[1][2]) + 1

#P qx qy ax ay
loads = [(1000.0 * ones(num_nodes)),(0.0 * ones(num_nodes)), (0.0 * ones(num_nodes)),(0.0 * ones(num_nodes)),(0.0 * ones(num_nodes))]

#end boundary conditions
#type=1 u''=v''=ϕ''=0 (simply supported), type=2 u'=v'=ϕ'=0  (fixed), type=3 u''=v''=ϕ''=u'''=v'''=ϕ'''=0 (free end, e.g., a cantilever)
end_boundary_conditions = [1 1]

#supports
#location where u=v=ϕ=0
supports = [0.0 13.0*12]

#imperfections
L = member_definitions[1][1]
dL = member_definitions[1][2]
z = 0: dL :L
Δo = L / 1000 * sin.(π*z/L)
uo = Δo
vo = zeros(Float64, num_nodes)
ϕo = zeros(Float64, num_nodes)

imperfections = [uo, vo, ϕo]

u, v, ϕ, properties = BeamColumn.solve(member_definitions, section_properties, material_properties, loads, springs, end_boundary_conditions, supports)

using Plots
plot(properties.z, u)
plot!(properties.z, Δo)


text:
using OpenImageIO

OIIO = OpenImageIO

input = ImageInput_open("image.jpg")

spec = OIIO.spec(input)
display(spec)

data = read_image(input)

using PyPlot
imshow(data)
#imshow(permutedims(data, [2,3,1]))


text:
# Uses the same optimiser as the base instance. Only works if that solver
# understands lazy constraints and SOCP.
mutable struct OSSBExactSmart <: OSSBOptimisationAlgorithm
  silent_solver::Bool
  instance

  # Separation subproblem (built once, when need be, hence mutability of this struct).
  sub_m
  sub_vars
  sub_r
  sub_z
end

OSSBExactSmart() = OSSBExactSmart(true, nothing, nothing, nothing, nothing, nothing)
OSSBExactSmart(silent_solver::Bool) = OSSBExactSmart(silent_solver, nothing, nothing, nothing, nothing, nothing)

function _ossb_exact_cg_separation(instance::CombinatorialInstance{T},
                                   algo::OSSBExactSmart,
                                   t::Dict{T, Float64},
                                   θ::Dict{T, Float64},
                                   r_max::Float64) where T
  if algo.instance === nothing
    algo.instance = instance
  elseif algo.instance != instance
    error("The OSSBExactSmart has already been used with another combinatorial instance.")
  end

  # If the separation subproblem has not yet been created, do it right now.
  if algo.sub_m === nothing
    # For a given t, solve the following (quadratic) separation problem:
    #    max_{x ∈ X} ∑_{i \in I} x_i / t_i - Δ_x^2
    # Return a solution x such that the objective function is positive (i.e. a
    # constraint that is violated), or nothing.
    m, _, vars = get_lp_formulation(copy(instance), t) # t is ignored, as it's only used
    # in the objective. It has all required arms, so that's enough.

    # Make a conic formulation for z == Δ_x^2 where Δ_x = r_max - θ^T x:
    #    z >= (θ^T x)^2    ⟺    1 >= (θ^T x)^2 / z
    # This is equivalent to:
    #    Δx == θ^T x
    #    (z + 1, z - 1, 2 * Δx) ∈ SOC
    @variable(m, Δx, lower_bound=0.0)
    @variable(m, z, lower_bound=0.0)
    @constraint(m, Δx == r_max - sum(θ[i] * vars[i] for i in keys(t)))
    @constraint(m, [1 + z, 1 - z, 2 * Δx] in SecondOrderCone())

    # Store the model in the OSSB object.
    algo.sub_m = m
    algo.sub_vars = vars
    algo.sub_r = Δx
    algo.sub_z = z
  end

  I = _ossb_confusing_arms(instance, θ)
  # I = all_arm_indices(instance)

  # Create the objective function.
  obj_linear = sum(algo.sub_vars[arm] / t[arm] for arm in keys(t))# if arm in I)
  obj_Δx² = algo.sub_z
  # obj_Δx² = r_max^2 - 2 * r_max * algo.sub_r + algo.sub_z # Δx² = (θ^T x^\star - θ^T x)^2
  # #                                                                \_ r_max _/   \ r /, with z ≥ r²
  @objective(algo.sub_m, Max, obj_linear - obj_Δx²)

  # println(algo.sub_m)
  # @show r_max

  optimize!(algo.sub_m)

  if termination_status(algo.sub_m) != MOI.OPTIMAL
    @show termination_status(algo.sub_m)
    println(algo.sub_m)
    error(termination_status(algo.sub_m))
  end

  # # println(algo.sub_m)
  # @show value(algo.sub_r)
  # @show value(algo.sub_z)
  # @show objective_value(algo.sub_m)
  # @show result_count(algo.sub_m)

  status = termination_status(algo.sub_m)
  return if status == MOI.OPTIMAL && objective_value(algo.sub_m) > 1.0e-5 # TODO: \Delta_min?
    Vector{T}[T[arm for arm in keys(t) if value(algo.sub_vars[arm], result=i) > 0.5] for i in 1:result_count(algo.sub_m)]
    # T[arm for arm in keys(t) if value(algo.sub_vars[arm]) > 0.5]
  else
    Vector{T}[]
  end
end

function optimise_graves_lai(instance::CombinatorialInstance{T},
                             algo::OSSBExactSmart,
                             θ::Dict{T, Float64}; with_trace::Bool=true) where T
  # Must be able to get a LP formulation.
  if ! has_lp_formulation(instance)
    # TODO: with the inexact algorithm, the instance's algorithm will no more be forced to be LP-based! But still, the convex decomposition step requires an LP formulation.
    error("The exact formulation for OSSB relies on a LP formulation, " *
          "which the solver associated to this instance cannot provide.")
  end

  # This function deals with copying the instance as many times as necessary.
  # Called functions should not deal with these details.
  # TODO: rework the interface so that get_lp_formulation always returns a *new* formulation? Currently, these functions always return the same model...
  t0 = time_ns()

  # Precompute useful results.
  d = dimension(instance)
  x_max = solve_linear(copy(instance), θ)
  r_max = sum(θ[arm] for arm in x_max)

  arm_to_idx = Dict(arm => idx for (idx, arm) in enumerate(all_arm_indices(instance)))
  idx_to_arm = Dict(idx => arm for (idx, arm) in enumerate(all_arm_indices(instance)))

  I = _ossb_confusing_arms(instance, θ)

  # Reduced formulation:
  #   min   v (θ^T x^\star) - θ^T t
  #   s.t.  A t ≤ v b
  #         ∑ x_i / t_i ≤ Δ_x^2     ∀ x ∈ X    (constraint generation)
  # v could be removed if the polytope is described as A t = b, but that would require fiddling
  # with the formulation quite a lot if that is not the case.

  instance = copy(instance)
  m, _, vars = get_lp_formulation(instance, θ) # A t ≤ b
  @variable(m, v >= 0)
  @variable(m, 0 <= t[arm in keys(θ)] <= 100) # TODO: param for this upper bound, if it is really needed.
  @variable(m, 0 <= inv_t[arm in keys(θ)] <= 100) # TODO: param for this upper bound, if it is really needed.

  # From "A t ≤ b" to "A t - v b ≤ 0".
  # Multiply the right-hand side by v, for all constraints.
  for (F, S) in JuMP.list_of_constraint_types(m)
    # Remove integrality constraints. (In this case, F is a single variable.)
    # This could be replaced by relax_integrality() of newer JuMP versions, but it would be slower
    # (relax_integrality is reversible, which is not needed here).
    if S in [MOI.ZeroOne, S == MOI.Integer]
      for c in all_constraints(m, F, S)
        JuMP.delete(m, c)
      end
    end
    # Ignore the case where this is a simple bounds.
    if F == JuMP.VariableRef || F == MOI.SingleVariable
      continue
    end

    # If there is a RHS (JuMP normalises everything so that the RHS has only
    # constants), multiply by v. Due to normalisation, this term goes to the
    # LHS, and must see its sign reversed.
    for c in all_constraints(m, F, S)
      if ! iszero(normalized_rhs(c))
        coeff = normalized_rhs(c)
        set_normalized_rhs(c, 0.0)
        set_normalized_coefficient(c, v, -coeff)
      end
    end
  end

  # Define the inv_t variable (only used for the added constraints).
  for arm in keys(θ) # I
    @constraint(m, [vars[arm], inv_t[arm], sqrt(2)] in RotatedSecondOrderCone())
  end

  # Set the objective function.
  obj_best = v * r_max
  obj_actual = sum(θ[arm] * vars[arm] for arm in keys(θ))
  @objective(m, Min, obj_best - obj_actual)
  @constraint(m, obj_best - obj_actual >= 0) # Avoid numerical problems with some polytopes.

  if algo.silent_solver
    set_silent(m)
  else
    unset_silent(m)
  end

  # And go for constraint generation!
  prev_sols = Set{Vector{T}}() # Safety net. Should not be triggered (otherwise, the test on the objective value
  # in _ossb_exact_cg_separation may need to be loosened).
  println("=> Starting constraint generation")
  while true
    optimize!(m)

    if termination_status(m) != MOI.OPTIMAL
      @show termination_status(m)
      println(m)
      error(termination_status(m))
    end

    # Use the separation oracle. Only care for values in I, and not all arms.
    # t_val = Dict{T, Float64}(arm => value(vars[arm]) for arm in I)
    t_val = Dict{T, Float64}(arm => value(vars[arm]) for arm in keys(θ))
    x_vecs = _ossb_exact_cg_separation(instance, algo, t_val, θ, r_max)

    if length(x_vecs) == 0 # No more constraint to add!
      break
    end

    added_constraint = false
    for x_vec in x_vecs
      if x_vec in prev_sols # || all(!(arm in I) for arm in x_vec)
        continue
      end
      push!(prev_sols, x_vec)

      # Found a violated constraint!
      Δx² = (r_max - sum(θ[arm] for arm in x_vec))^2
      if Δx² >= 1.0e-5 # TODO: rather use \Delta_min?
        lhs = sum(inv_t[arm] for arm in x_vec if arm in I)
        # lhs = sum(inv_t[arm] for arm in x_vec)
        c = @constraint(m, lhs <= Δx²)
        added_constraint = true
      end
    end

    if ! added_constraint
      println(":: No constraint to add")
      break
    end

    println(":: Did one iteration of constraint generation")
  end
  println("=> Done with constraint generation")

  # Retrieve the solution and normalise with respect to v.
  # value. doesn't broadcast on dictionaries.
  v_val = value(v)
  t_val = Dict{T, Float64}(arm => value(vars[arm]) / v_val for arm in keys(θ))

  # If the solution t_val is zero, there is not much to do. This should never happen, unless there is a serious
  # bug in the rest of the function.
  if iszero(collect(values(t_val)))
    println("Uh ho...")
    return solve_linear(instance, θ) # Perform pure exploitation.
  end

  # Return the solution that has been found.
  res = GravesLaiResults(instance, t_val, objective_value(m))
  if with_trace
    return res, GravesLaiDetails((time_ns() - t0) / 1_000_000, objective_value(m))
  else
    return res
  end
end


text:
module ConnectionPools

# manage the connection to the DB when there are more user access to it
# and incase they use the expensive operation that take long time
# to minimize the impact and improve user exprience

export withconnection

macro v1_3(expr, elses=nothing)
    esc(quote
        @static if VERSION >= v"1.3"
            $expr
        else
            $elses
        end
    end)
end

mutable struct Pod{T}
    conns::Channel{T}
    numactive::Int
    max::Int
    idle::Int
    reuse::Int
    new::Base.Callable
end

mutable struct Connection{T}
    conn::T
    pod::Pod{Connection{T}}
    idle::Float64
    count::Int
end

Pod(T, max, idle, reuse, new) = Pod(Channel{Connection{T}}(Inf), 0, max, idle, reuse, new)

function decr!(pod::Pod)
    @v1_3 @assert(islocked(pod.conns.cond_take))
    pod.numactive -= 1
    return
end

function incr!(pod::Pod)
    @v1_3 @assert(islocked(pod.conns.cond_take))
    pod.numactive += 1
    return
end

function Base.acquire(pod::Pod, args...; kw...)
    @v1_3 lock(pod.conns)
    try
        while isready(pod.conns)
            conn = take!(pod.conns)
            if (time() - conn.idle) > pod.idle
                close(conn.conn)
            elseif conn.count >= pod.reuse
                close(conn.conn)
            elseif !isopen(conn.conn)
                close(conn.conn)
            else
                conn.count += 1
                incr!(pod)
                return conn
            end
        end
        # If there are not too many connections, create new
        if pod.numactive < pod.max
            incr!(pod)
            return Connection(pod.new(args...; kw...), pod, time(), 1)
        end
        # otherwise, wait for a connection to be released
        while true
            conn = take!(pod.conns)
            if (time() - conn.idle) > pod.idle
                close(conn.conn)
            elseif conn.count >= pod.reuse
                close(conn.conn)
            elseif !isopen(conn.conn)
                close(conn.conn)
            else
                conn.count += 1
                incr!(pod)
                return conn
            end
            if pod.numactive < pod.max
                incr!(pod)
                return Connection(pod.new(args...; kw...), pod, time(), 1)
            end
        end
    finally
        @v1_3 unlock(pod.conns)
    end
end

function Base.release(conn::Connection)
    pod = conn.pod
    @v1_3 lock(pod.conns)
    try
        decr!(pod)
        conn.idle = time()
        put!(conn.pod.conns, conn)
    finally
        @v1_3 unlock(pod.conns)
    end
    return
end

function withconnection(f, pod::Pod, args...; kw...)
    conn = Base.acquire(pod, args...; kw...)
    try
        return f(conn.conn)
    finally
        Base.release(conn)
    end
end

struct Pool{K, C}
    lock::ReentrantLock
    pods::Dict{K, Pod{Connection{C}}}
    max::Int
    idle::Int
    reuse::Int
    new::Base.Callable
end

Pool(K, C, max, idle, reuse, new) = Pool{K, C}(ReentrantLock(), Dict{K, Pod{Connection{C}}}(), max, idle, reuse, new)
Pod(pool::Pool{K, C}) where {K, C} = Pod(C, pool.max, pool.idle, pool.reuse, pool.new)

function Base.acquire(pool::Pool{K, C}, key, args...; kw...) where {K, C}
    pod = lock(pool.lock) do
        get!(() -> Pod(pool), pool.pods, key)
    end
    return Base.acquire(pod, key, args...; kw...)
end

function withconnection(f, pool::Pool, key, args...; kw...)
    pod = lock(pool.lock) do
        get!(() -> Pod(pool), pool.pods, key)
    end
    return withconnection(f, pod, key, args...; kw...)
end

end # module

max_stars_repo_name: vanhp/MicroServiceJulia

max_issues_repo_name: vanhp/MicroServiceJulia

max_forks_repo_name: vanhp/MicroServiceJulia


text:
using HetaSimulator, Plots

p = load_platform(".")

scenarios = read_scenarios("data-mumenthaler-2000/scenarios.csv")
add_scenarios!(p, scenarios)

data = read_measurements("data-mumenthaler-2000/data.csv")
add_measurements!(p, data)

# initial plot
sim(p) |> plot
sim(p, parameters_upd = [:Vmax=>0.3, :ke=>0., :k_a=>5.]) |> plot

# fitting 1 best -63.45
params_df_1 = read_parameters("./julia/parameters-1.csv")
res_fit_1 = fit(p, params_df_1; scenarios=[:scn1], ftol_abs=1e-6, ftol_rel=0.)
res_fit_1 = fit(p, optim(res_fit_1); scenarios=[:scn1], ftol_abs=1e-6, ftol_rel=0.)
fig = sim(p, scenarios=[:scn1], parameters_upd=optim(res_fit_1)) |> plot
# savefig(fig, "diagnostics/scn1_best.png")

# fitting 2 best -63.64
params_df_2 = read_parameters("./julia/parameters-2.csv")
res_fit_2 = fit(p, params_df_2; scenarios=[:scn2], ftol_abs=1e-6, ftol_rel=0.)
res_fit_2 = fit(p, optim(res_fit_2); scenarios=[:scn2], ftol_abs=1e-6, ftol_rel=0.)
fig = sim(p, scenarios=[:scn2], parameters_upd=optim(res_fit_2)) |> plot
# savefig(fig, "diagnostics/scn2_best.png")

# fitting 3 best -63.92
params_df_3 = read_parameters("./julia/parameters-3.csv")
res_fit_3 = fit(p, params_df_3; scenarios=[:scn3], ftol_abs=1e-6, ftol_rel=0.)
res_fit_3 = fit(p, optim(res_fit_3); scenarios=[:scn3], ftol_abs=1e-6, ftol_rel=0.)
fig = sim(p, scenarios=[:scn3], parameters_upd=optim(res_fit_3)) |> plot
# savefig(fig, "diagnostics/scn3_best.png")

############################## Identification ##########################

using LikelihoodProfiler

chi_level = 3.84

p_optim_1 = optim(res_fit_1)
p_optim_2 = optim(res_fit_2)
p_optim_3 = optim(res_fit_3)

sim_scn1 = sim(p.scenarios[:scn1], parameters_upd=p_optim_1)
sim_scn2 = sim(p.scenarios[:scn2], parameters_upd=p_optim_2)
sim_scn3 = sim(p.scenarios[:scn3], parameters_upd=p_optim_3)

p_names = Dict(
  :scn1 => first.(p_optim_1),
  :scn2 => first.(p_optim_2),
  :scn3 => first.(p_optim_3),
)

function loss_func(params::Vector{P}, scen) where P<: Pair
  sim_vec = sim(p; parameters_upd=params, scenarios=[scen])
  sim_res = last(sim_vec[1])
  return loss(sim_res, sim_res.scenario.measurements)
end

function loss_func(pvals::Vector{N}, scen) where N <: Number
  @assert length(p_names[scen]) == length(pvals) "Number of params values doesn't match params names"
  params = [pn => pv for (pn,pv) in zip(p_names[scen],pvals)]
  loss_func(params,scen)
end

loss_scn1(params) = loss_func(params, :scn1)
loss_scn2(params) = loss_func(params, :scn2)
loss_scn3(params) = loss_func(params, :scn3)

function scan_func(params::Vector{P}, timepoint, scen) where P<: Pair
  sim_vec = sim(p; parameters_upd=params, scenarios=[scen])
  return last(sim_vec[1])(timepoint)[:BrAC]
end

function scan_func(pvals::Vector{N}, timepoint, scen) where N <: Number
  @assert length(p_names[scen]) == length(pvals) "Number of params values doesn't match params names"
  params = [pn => pv for (pn,pv) in zip(p_names[scen],pvals)]
  scan_func(params, timepoint, scen)
end

scan_scn1(params, timepoint) = scan_func(params, timepoint, :scn1)
scan_scn2(params, timepoint) = scan_func(params, timepoint, :scn2)
scan_scn3(params, timepoint) = scan_func(params, timepoint, :scn3)

saveat_1 = saveat(p.scenarios[:scn1])
saveat_2 = saveat(p.scenarios[:scn2])
saveat_3 = saveat(p.scenarios[:scn3])

p_ident_1 = [get_interval(
  last.(p_optim_1),
  i,
  loss_scn1,
  :CICO_ONE_PASS,
  scale = fill(:log, length(p_names[:scn1])),
  loss_crit = loss_scn1(p_optim_1) + chi_level
  ) for i in eachindex(p_names[:scn1])]

p_ident_2 = [get_interval(
  last.(p_optim_2),
  i,
  loss_scn2,
  :CICO_ONE_PASS,
  scale = fill(:log, length(p_names[:scn2])),
  loss_crit = loss_scn2(p_optim_2) + chi_level
) for i in eachindex(p_names[:scn2])]

p_ident_3 = [get_interval(
  last.(p_optim_3),
  i,
  loss_scn3,
  :CICO_ONE_PASS,
  scale = fill(:log, length(p_names[:scn3])),
  loss_crit = loss_scn3(p_optim_3) + chi_level
) for i in eachindex(p_names[:scn3])]

BrAC_ident_1 = [get_interval(
  last.(p_optim_1),
  params->scan_scn1(params,t),
  loss_scn1,
  :CICO_ONE_PASS,
  scale = fill(:log, length(p_names[:scn1])),
  loss_crit = loss_scn1(p_optim_1) + chi_level
) for t in saveat_1]

BrAC_ident_2 = [get_interval(
  last.(p_optim_2),
  params->scan_scn2(params,t),
  loss_scn2,
  :CICO_ONE_PASS,
  scale = fill(:log, length(p_names[:scn2])),
  loss_crit = loss_scn2(p_optim_2) + chi_level
) for t in saveat_2]

BrAC_ident_3 = [get_interval(
  last.(p_optim_3),
  params->scan_scn3(params,t),
  loss_scn3,
  :CICO_ONE_PASS,
  scale = fill(:log, length(p_names[:scn3])),
  loss_crit = loss_scn3(p_optim_3) + chi_level
) for t in saveat_3]

lb_1 = [iv.result[1].value for iv in BrAC_ident_1]
ub_1 = [iv.result[2].value for iv in BrAC_ident_1]
BrAC_1 = sim_scn1.(saveat_1, :BrAC)
plot(sim_scn1, show_measurements=false, ribbon = (BrAC_1-lb_1,ub_1-BrAC_1), fc=:orange, fa=0.7)
#savefig("BrAC_ident_scn1.png")

lb_2 = [iv.result[1].value for iv in BrAC_ident_2]
ub_2 = [iv.result[2].value for iv in BrAC_ident_2]
BrAC_2 = sim_scn2.(saveat_2, :BrAC)
plot(sim_scn2, show_measurements=false, ribbon = (BrAC_2-lb_1,ub_2-BrAC_2), fc=:orange, fa=0.7)

lb_3 = [iv.result[1].value for iv in BrAC_ident_3]
ub_3 = [iv.result[2].value for iv in BrAC_ident_3]
BrAC_3 = sim_scn3.(saveat_3, :BrAC)
plot(sim_scn3, show_measurements=false, ribbon = (BrAC_3-lb_3,ub_3-BrAC_3), fc=:orange, fa=0.7)

max_stars_repo_name: insysbio/alco

max_issues_repo_name: insysbio/alco

max_forks_repo_name: insysbio/alco


text:
export gmres, gmres!

#One Arnoldi iteration
#Optionally takes a truncation parameter l
function arnoldi!(K::KrylovSubspace, w; l=K.order)
    v = nextvec(K)
    w = copy(v)
    n = min(length(K.v), l)
    h = zeros(eltype(v), n+1)
    v, h[1:n] = orthogonalize(v, K, n)
    h[n+1] = norm(v)
    (h[n+1]==0) && error("Arnoldi iteration terminated")
    append!(K, v/h[n+1]) #save latest Arnoldi vector, i.e. newest column of Q in the AQ=QH factorization
    h #Return current Arnoldi coefficients, i.e. newest column of in the AQ=QH factorization
end

function apply_givens!(H, J, j)
    for k = 1:(j-1)
        temp     =       J[k,1]  * H[k,j] + J[k,2] * H[k+1,j]
        H[k+1,j] = -conj(J[k,2]) * H[k,j] + J[k,1] * H[k+1,j]
        H[k,j]   = temp
    end
end

function compute_givens(a, b, i, j)
    T = eltype(a)
    p = abs(a)
    q = abs(b)

    if q == zero(T)
        return [one(T), zero(T), a]
    elseif p == zero(T)
        return [zero(T), sign(conj(b)), q]
    else
        m      = hypot(p,q)
        temp   = sign(a)
        return [p / m, temp * conj(b) / m, temp * m]
    end
end

gmres(A, b, Pl=1, Pr=1;
      tol=sqrt(eps(typeof(real(b[1])))), maxiter::Int=1, restart::Int=min(20,length(b))) =
    gmres!(zerox(A,b), A, b, Pl, Pr; tol=tol, maxiter=maxiter, restart=restart)

function gmres!(x, A, b, Pl=1, Pr=1;
        tol=sqrt(eps(typeof(real(b[1])))), maxiter::Int=1, restart::Int=min(20,length(b)))

    history = ConvergenceHistory(restart=restart)
    history[:tol] = tol
    reserve!(history,:resnorm, maxiter*restart)
    gmres_method!(history, x, A, b, Pl, Pr; tol=tol, maxiter=maxiter, restart=restart)
    x, history
end

function gmres_method!(log::ConvergenceHistory, x, A, b, Pl=1, Pr=1;
        tol=sqrt(eps(typeof(real(b[1])))), maxiter::Int=1, restart::Int=min(20,length(b)))
#Generalized Minimum RESidual
#Reference: http://www.netlib.org/templates/templates.pdf
#           2.3.4 Generalized Minimal Residual (GMRES)
#
#           http://www.netlib.org/lapack/lawnspdf/lawn148.pdf
#           Givens rotation based on Algorithm 1
#
#   Solve A*x=b using the Generalized Minimum RESidual Method with restarts
#
#   Effectively solves the equation inv(Pl)*A*inv(Pr)*y=b where x = inv(Pr)*y
#
#   Required Arguments:
#       A: Linear operator
#       b: Right hand side
#
#   Named Arguments:
#       Pl:      Left preconditioner
#       Pr:      Right preconditioner
#       restart: Number of iterations before restart (GMRES(restart))
#       maxiter:  Maximum number of outer iterations
#       tol:     Convergence Tolerance
#
#   The input A (resp. Pl, Pr) can be a matrix, a function returning A*x,
#   (resp. inv(Pl)*x, inv(Pr)*x), or any type representing a linear operator
#   which implements *(A,x) (resp. \(Pl,x), \(Pr,x)).
    n = length(b)
    T = eltype(b)
    H = zeros(T,n+1,restart)       #Hessenberg matrix
    s = zeros(T,restart+1)         #Residual history
    J = zeros(T,restart,3)         #Givens rotation values
    tol = tol * norm(Pl\b)         #Relative tolerance
    matvecs = 0
    K = KrylovSubspace(x->Pl\(A*(Pr\x)), n, restart+1, T)
    for iter = 1:maxiter
        w    = Pl\(b - A*x)
        s[1] = rho = norm(w)
        init!(K, w / rho)

        N = restart
        for j = 1:restart
            nextiter!(log, mvps=1)
            #Calculate next orthonormal basis vector in the Krylov subspace
            H[1:j+1, j] = arnoldi!(K, w)

            #Update QR factorization of H
            #The Q is stored as a series of Givens rotations in J
            #The R is stored in H
            #- Compute Givens rotation that zeros out bottom right entry of H
            apply_givens!(H, J, j)
            J[j,1:3] = compute_givens(H[j,j], H[j+1,j], j, j+1)
            #G = Base.LinAlg.Givens(restart+1, j, j+1, J[j,1], J[j,2], J[j,3])
            #- Zero out bottom right entry of H
            H[j,j]   = J[j,3]
            H[j+1,j] = zero(T)
            #- Apply Givens rotation j to s, given that s[j+1] = 0
            s[j+1] = -conj(J[j,2]) * s[j]
            #-conj(G.s) * s[j]
            s[j]  *= J[j,1] #G.c

            rho = abs(s[j+1])
            push!(log, :resnorm, rho)
            if rho < tol
                N = j
                break
            end
        end

        @eval a = $(VERSION < v"0.4-" ? Triangular(H[1:N, 1:N], :U) \ s[1:N] : UpperTriangular(H[1:N, 1:N]) \ s[1:N])
        w = a[1:N] * K
        update!(x, 1, Pr\w) #Right preconditioner

        if rho < tol
            setconv(log, true)
            break
        end
    end
    shrink!(log)
    x
end


text:
# Force libgit2 to download packages in stead of downloading tarballs
ENV["PYTHON"] = ""

# Force installation of packages
for _ in true
    function lazy_add(pkgsym)
        if !(isdir(joinpath(@__DIR__, "..", "packages", String(pkgsym))))
            @eval using Pkg
            Pkg.add(String(pkgsym))
        end
    end

    lazy_add(:Revise)
    lazy_add(:OhMyREPL)
end

# Force installation and inclusion of packages at REPL
Base.atreplinit() do _
    function add_and_use(pkgsym)
        try
            @eval using $pkgsym
            return true
        catch e
            @eval using Pkg
            Pkg.add(String(pkgsym))
            @eval using $pkgsym
        end
    end

    add_and_use(:Revise)
    add_and_use(:OhMyREPL)
end

max_stars_repo_name: heetbeet/julia-win

max_issues_repo_name: heetbeet/julia-win

max_forks_repo_name: heetbeet/julia-win


text:
module TypeDict

export standardize_type

const type_dict = (;
    :b => Int8,
    :B => UInt8,
    :byte => Int8,
    :Int => Int,
    :int => Int,
    :Int8 => Int8,
    :Int16 => Int16,
    :Int32 => Int32,
    :Int64 => Int64,
    :int8 => Int8,
    :int16 => Int16,
    :int32 => Int32,
    :int64 => Int64,
    :UInt => UInt,
    :uint => UInt,
    :UInt8 => UInt8,
    :UInt16 => UInt16,
    :UInt32 => UInt32,
    :UInt64 => UInt64,
    :i1 => Int8,
    :i2 => Int16,
    :i4 => Int32,
    :i8 => Int64,
    :h => Int16,
    :short => Int16,
    :long => Int64,
    :longlong => Int64,
    :u1 => UInt8,
    :u2 => UInt16,
    :u4 => UInt32,
    :u8 => UInt64,
    :H => UInt16,
    :ushort => UInt16,
    :ulong => UInt64,
    :ulonglong => UInt64,
    :half => Float16,
    :float16 => Float16,
    :single => Float32,
    :float => Float32,
    :float32 => Float32,
    :Float32 => Float32,
    :double => Float64,
    :float64 => Float64,
    :Float64 => Float64,
    :csingle => ComplexF32,
    :cfloat => ComplexF32,
    :cdouble => ComplexF64,
    :complex => ComplexF64,
    :complex16 => ComplexF16,
    :Complex16 => ComplexF16,
    :complex32 => ComplexF32,
    :Complex32 => ComplexF32,
    :complex64 => ComplexF64,
    :Complex64 => ComplexF64,
    :f => Float32,
    :F => ComplexF32,
    :d => Float64,
    :D => ComplexF64,
    :f2 => Float16,
    :f4 => Float32,
    :f8 => Float64,
)

standardize_type(type_name::Symbol) = type_dict[type_name]
standardize_type(type_name::AbstractString) = type_name |> Symbol |> standardize_type
standardize_type(::Type{T}) where {T<:Number} = T

end # module


text:
push!(LOAD_PATH,"../src/")

using SoftComputingFinal
using Base.Test

const TEST_RNG = MersenneTwister(12345678)

@testset "DecisionTree" begin
    forest = [Classification{3, 3}(1),
              Decision(Dict(Variable{3}(1) => 0.1, Variable{3}(2) => 3.0), 1.0,
                       Classification{3, 3}(2),
                       Classification{3, 3}(1)),
              Decision(Dict(Variable{3}(1) => -4.2, Variable{3}(3) => 9.93), 1.16,
                       Decision(Dict(Variable{3}(1) => -0.79, Variable{3}(2) => 2.87), 5.96,
                                Classification{3, 3}(1),
                                Classification{3, 3}(2)),
                       Decision(Dict(Variable{3}(1) => -7.41, Variable{3}(3) => -3.03), 5.16,
                                Classification{3, 3}(2),
                                Classification{3, 3}(1)))]

    printed = ["""{1}""",
               """
               if 0.1 × x₁ + 3.0 × x₂ ≤ 1.0
                 then {2}
                 else {1}""",
               """
               if -4.2 × x₁ + 9.93 × x₃ ≤ 1.16
                 then if -0.79 × x₁ + 2.87 × x₂ ≤ 5.96
                   then {1}
                   else {2}
                 else if -7.41 × x₁ + -3.03 × x₃ ≤ 5.16
                   then {2}
                   else {1}"""]

    depths = [1, 2, 3]
    sizes = [1, 3, 7]
    conditions = [nothing, [0.1, 3.0, 0.0], [-4.2, 0.0, 9.93]]

    for i in eachindex(forest)
        if forest[i] isa Decision
            @test normalize_conditions(forest[i].conditions) == conditions[i]
        end

        @test string(forest[i]) == printed[i]
        @test treedepth(forest[i]) == depths[i]
        s = treesize(forest[i])
        @test s == sizes[i]

        newt, chunk = randsplit(TEST_RNG, forest[i]) do chunk
            Classification{3, 3}(3)
        end
        @test treesize(newt) - 1 == s - treesize(chunk)
    end
end

@testset "Sampling" begin
    # SplitSampler
    split_samples = rand(SplitSampler{10, 3}(5, 1.0, minvars = 2, maxvars = 4), 20)
    @test all(treedepth(t) ≤ 5 for t in split_samples)
    @test all(t isa Classification || 2 ≤ length(t.conditions) ≤ 4 for t in split_samples)

    # RampedSplitSampler
    ramped_split_samples = rand(RampedSplitSampler{10, 3}(5, 0.5, 0.5, minvars = 2, maxvars = 4), 20)
    @test all(treedepth(t) ≤ 5 for t in ramped_split_samples)
    @test all(t isa Classification || 2 ≤ length(t.conditions) ≤ 4 for t in ramped_split_samples)

    #BoltzmannSampler
    boltzmann_samples = rand(BoltzmannSampler{10, 3}(5, 20, minvars = 2, maxvars = 4), 20)
    @test all(5 ≤ treesize(t) ≤ 20 for t in boltzmann_samples)
    @test all(t isa Classification || 2 ≤ length(t.conditions) ≤ 4 for t in boltzmann_samples)
end

@testset "SSGP Integration" begin
    N = 500
    data = load_testdata()
    fitness, accuracy = create_fitness(data, Val{2}, Val{2},
                                       depth_factor = 2.0, depth_baseline = 5,
                                       size_factor = 0.5, size_baseline = 16)

    initializer = RampedSplitSampler{2, 2}(4, 0.5, 0.5, crange = (-2.0, 2.0))
    population, _ = runssgp(fitness, 20, initializer, N, verbose = false)

    best_tree = select(population, 1, by = fitness, rev = true)
    @show α = accuracy(best_tree)
    @test α > 0.7
end

max_stars_repo_name: phipsgabler/soft-computing-final

max_issues_repo_name: phipsgabler/soft-computing-final

max_forks_repo_name: phipsgabler/soft-computing-final


text:
# Util types for testing
mutable struct CalledConvert
    called::Bool
end
CalledConvert() = CalledConvert(false)
function OneDNN.dnnl_convert(x::CalledConvert)
    x.called = true
    return x
end
reset!(x::CalledConvert) = (x.called = false)
wascalled(x::CalledConvert) = x.called

partial_expand(expr) = macroexpand(OneDNN, OneDNN._apicall_partial_impl(expr))

# Testing `dnnl_arg` pipeline
mutable struct MemoryWrapper
    ptr::OneDNN.Lib.dnnl_memory_t
    context::OneDNN.AccessContext
end
MemoryWrapper() = MemoryWrapper(OneDNN.Lib.dnnl_memory_t(), OneDNN.Unknown())
function OneDNN.dnnl_exec_arg(y::MemoryWrapper, context)
    y.context = context
    return y.ptr
end

@testset "Testing Utils" begin
    @testset "Testing @apicall" begin
        lib = :Lib
        convert = :dnnl_convert
        _convert = :_dnnl_convert
        esca = Expr(:escape, :a)
        escb = Expr(:escape, :b)
        escf = Expr(:escape, :f)

        # Standard Transformation
        expr = partial_expand(:(dnnl_abc(a, b)))
        expected = :($lib.dnnl_abc($convert($esca), $convert($escb)))
        @test expr == expected

        # Does it ignore function calls that don't start with "dnnl"?
        expr = partial_expand(:(f(a, b)))
        expected = :($escf($convert($esca), $convert($escb)))
        @test expr == expected

        # Does it correctly handle varargs
        expr = partial_expand(:(f(a, b...)))
        expected = :($escf($convert($esca), $_convert($escb...)...))
        @test expr == expected

        expr = partial_expand(:(f(a...)))
        expected = :($escf($_convert($esca...)...))
        @test expr == expected

        # Finally, prepend "lib"
        expr = partial_expand(:(dnnl_abc(a, b...)))
        expected = :($lib.dnnl_abc($convert($esca), $_convert($escb...)...))
        @test expr == expected
    end

    @testset "Testing Ancestor" begin
        w = collect(1:10)
        x = view(w, 1:4)
        y = reshape(x, 2, 2)
        z = view(y, :, 1)

        @test OneDNN.ancestor(w) === w
        @test OneDNN.ancestor(x) === w
        @test OneDNN.ancestor(y) === w
        @test OneDNN.ancestor(z) === w
    end

    @testset "Testing Arguments" begin
        @test OneDNN.getsym(:hello) == "hello"
        @test OneDNN.getsym(:(A.B.hello)) == "hello"
        @test OneDNN.getsym(QuoteNode(:hello)) == "hello"

        wrapper = MemoryWrapper()
        @test wrapper.context == OneDNN.Unknown()
        x = OneDNN.dnnl_arg(OneDNN.Lib.DNNL_ARG_SRC, wrapper)
        @test isa(x, OneDNN.Lib.dnnl_exec_arg_t)
        @test wrapper.context == OneDNN.Reading()
        @test length(x) == 1
        @test collect(x) == [x]

        # Construction utilities.
        tuple_no_array = (1,2,3,4)
        @test OneDNN._hasarray(tuple_no_array...) == false
        @test OneDNN._flatcat(tuple_no_array...) == (1,2,3,4)

        tuple_no_array = ((1,3), 2, 3, 4)
        @test OneDNN._hasarray(tuple_no_array...) == false
        @test OneDNN._flatcat(tuple_no_array...) == (1,3,2,3,4)

        tuple_no_array = ((1, 2), 3, (4, (5, 6), 7), 8)
        @test OneDNN._hasarray(tuple_no_array...) == false
        @test OneDNN._flatcat(tuple_no_array...) == (1,2,3,4,5,6,7,8)

        tuple_with_array = ([1,2], 2, 3, 4)
        @test OneDNN._hasarray(tuple_with_array...) == true
        @test OneDNN._vcat(tuple_with_array; init = Int[]) == [1,2,2,3,4]

        tuple_with_array = (1, 2, [3], 4)
        @test OneDNN._hasarray(tuple_with_array...) == true
        @test OneDNN._vcat(tuple_with_array; init = Int[]) == [1,2,3,4]

        tuple_with_array = (1, 2, 3, [4])
        @test OneDNN._hasarray(tuple_with_array...) == true
        @test OneDNN._vcat(tuple_with_array; init = Int[]) == [1,2,3,4]

        tuple_with_array = (1, [2], 3, [4,2])
        @test OneDNN._hasarray(tuple_with_array...) == true
        @test OneDNN._vcat(tuple_with_array; init = Int[]) == [1,2,3,4,2]
    end

    @testset "Testing Conversions" begin
        a = CalledConvert()
        OneDNN.dnnl_convert(a)
        @test wascalled(a)

        x = (CalledConvert(), CalledConvert(), CalledConvert())
        OneDNN._dnnl_convert(x...)
        @test all(wascalled, x)

        # Wrapping and unwrapping.
        x = Ref(10)
        y = 10

        # Equality for "Ref"s doesn't check contents.
        # Define our own notiong of "equality" here to express the semantics that "wrap_ref"
        # should create a "Ref" is the argument is not already a "Ref".
        ref_equal(x::Ref, y::Ref) = x[] === y[]

        @test OneDNN.unwrap_ref(x) === 10
        @test OneDNN.unwrap_ref(y) === 10
        @test ref_equal(OneDNN.wrap_ref(x), Ref(10))
        @test ref_equal(OneDNN.wrap_ref(y), Ref(10))
    end

end # @testset


text:
using Test
using OpenTrick
@testset "open read succeed" begin
    io = opentrick(open, "sometext.txt", "r")
    @test !eof(io)
    @test "hello world!" == String(readline(io))
    @test "你好！\n" == String(read(io, 10))
    @test 0x0a434241 == read(io, UInt32)
    @test "Remains.\n" == String(readavailable(io))
    @test eof(io)
    @test length(OpenTrick.tasks_pending) == 1
    @debug "call close"
    close(io)
    @test !isopen(io)
    @test length(OpenTrick.tasks_pending) == 0
end

@testset "open write succeed" begin
    filename = tempname()
    outstring = "hello world!"
    out = opentrick(open, filename, "w")
    @test write(out, outstring) == length(outstring)
    @test length(OpenTrick.tasks_pending) == 1
    @debug "call finalize"
    close(out)
    @test !isopen(out)
    @test length(OpenTrick.tasks_pending) == 0
    infile = opentrick(open, filename, "r")
    @test String(read(infile)) == outstring
    @test eof(infile)
    close(infile)
    @test !isopen(rawio(infile))
    @test length(OpenTrick.tasks_pending) == 0
end

@testset "unsafe_clear" begin
    w1 = opentrick(open, "sometext.txt", "r")
    w2 = opentrick(open, "sometext.txt", "r")
    @test length(OpenTrick.tasks_pending) == 2
    unsafe_clear();
    @test length(OpenTrick.tasks_pending) == 0
    @test !isopen(w1)
    @test !isopen(w2)
end


text:
using Manopt, Manifolds, ManifoldsBase, LinearAlgebra, Test

@testset "Test primal dual plan" begin
    #
    # Perform an really easy test, just compute a mid point
    #
    pixelM = Sphere(2)
    M = PowerManifold(pixelM, NestedPowerRepresentation(), 2)
    data = [[1.0, 0.0, 0.0], 1 / sqrt(2) .* [1.0, 1.0, 0.0]]
    α = 1
    # known minimizer
    δ = min(α / distance(pixelM, data[1], data[2]), 0.5)
    x_hat = shortest_geodesic(M, data, reverse(data), δ)
    N = TangentBundle(M)
    fidelity(x) = 1 / 2 * distance(M, x, f)^2
    Λ(x) = ProductRepr(x, forward_logs(M, x))
    prior(x) = norm(norm.(Ref(pixelM), x, submanifold_component(N, Λ(x), 2)), 1)
    cost(x) = (1 / α) * fidelity(x) + prior(x)
    prox_F(M, m, λ, x) = prox_distance(M, λ / α, data, x, 2)
    function prox_G_dual(N, n, λ, ξ)
        return ProductRepr(
            submanifold_component(N, ξ, 1),
            project_collaborative_TV(
                base_manifold(N),
                λ,
                submanifold_component(N, n, 1),
                submanifold_component(N, ξ, 2),
                Inf,
                Inf,
                1.0,
            ),
        )
    end
    DΛ(m, X) = ProductRepr(zero_tangent_vector(M, m), differential_forward_logs(M, m, X))
    function adjoint_DΛ(m, ξ)
        return adjoint_differential_forward_logs(M, m, submanifold_component(N, ξ, 2))
    end

    m = fill(mid_point(pixelM, data[1], data[2]), 2)
    n = Λ(m)
    x0 = deepcopy(data)
    ξ0 = ProductRepr(zero_tangent_vector(M, m), zero_tangent_vector(M, m))

    p_exact = PrimalDualProblem(M, N, cost, prox_F, prox_G_dual, Λ, adjoint_DΛ)
    p_linearized = PrimalDualProblem(
        M, N, cost, prox_F, prox_G_dual, DΛ, adjoint_DΛ, missing
    )
    o_exact = ChambollePockOptions(m, n, x0, ξ0; variant=:exact)
    o_linearized = ChambollePockOptions(m, n, x0, ξ0; variant=:linearized)
    n_old = ProductRepr(submanifold_component(N, n, 1), submanifold_component(N, n, 2))
    x_old = copy(x0)
    ξ_old = ProductRepr(submanifold_component(N, ξ0, 1), submanifold_component(N, ξ0, 2))

    @testset "Primal/Dual residual" begin
        p_exact = PrimalDualProblem(M, N, cost, prox_F, prox_G_dual, Λ, adjoint_DΛ)
        p_linearized = PrimalDualProblem(
            M, N, cost, prox_F, prox_G_dual, DΛ, adjoint_DΛ, missing
        )
        o_exact = ChambollePockOptions(m, n, x0, ξ0; variant=:exact)
        o_linearized = ChambollePockOptions(m, n, x0, ξ0; variant=:linearized)
        @test primal_residual(p_exact, o_exact, x_old, ξ_old, n_old) ≈ 0 atol = 1e-16
        @test primal_residual(p_linearized, o_linearized, x_old, ξ_old, n_old) ≈ 0 atol =
            1e-16
        @test dual_residual(p_exact, o_exact, x_old, ξ_old, n_old) ≈ 4.0 atol = 1e-16
        @test dual_residual(p_linearized, o_linearized, x_old, ξ_old, n_old) ≈ 0.0 atol =
            1e-16

        step_solver!(p_exact, o_exact, 1)
        step_solver!(p_linearized, o_linearized, 1)
        @test primal_residual(p_exact, o_exact, x_old, ξ_old, n_old) > 0
        @test primal_residual(p_linearized, o_linearized, x_old, ξ_old, n_old) > 0
        @test dual_residual(p_exact, o_exact, x_old, ξ_old, n_old) > 4.0
        @test dual_residual(p_linearized, o_linearized, x_old, ξ_old, n_old) > 0

        o_err = ChambollePockOptions(m, n, x0, ξ0; variant=:err)
        @test_throws DomainError dual_residual(p_exact, o_err, x_old, ξ_old, n_old)
    end
    @testset "Debug prints" begin
        a = StoreOptionsAction((:x, :ξ, :n, :m))
        update_storage!(a, Dict(:x => x_old, :ξ => ξ_old, :n => n_old, :m => copy(m)))
        io = IOBuffer()

        d1 = DebugDualResidual(a, io)
        d1(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "Dual Residual:")

        d2 = DebugPrimalResidual(a, io)
        d2(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "Primal Residual: ")

        d3 = DebugPrimalDualResidual(a, io)
        d3(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "PD Residual: ")

        d4 = DebugPrimalChange(a, io)
        d4(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "Primal Change: ")

        d5 = DebugPrimalIterate(io)
        d5(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "x:")

        d6 = DebugDualIterate(io)
        d6(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "ξ:")

        d7 = DebugDualChange(a, io)
        d7(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "Dual Change:")

        d7a = DebugDualChange((ξ0, n), a, io)
        d7a(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "Dual Change:")

        d8 = DebugDualBaseIterate(io)
        d8(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "n:")

        d9 = DebugDualBaseChange(a, io)
        d9(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "Dual Base Change:")

        d10 = DebugPrimalBaseIterate(io)
        d10(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "m:")

        d11 = DebugPrimalBaseChange(a, io)
        d11(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "Primal Base Change:")

        d12 = DebugDualResidual((x0, ξ0, n), a, io)
        d12(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "Dual Residual:")

        d13 = DebugPrimalDualResidual((x0, ξ0, n), a, io)
        d13(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "PD Residual:")

        d14 = DebugPrimalResidual((x0, ξ0, n), a, io)
        d14(p_exact, o_exact, 1)
        s = String(take!(io))
        @test startswith(s, "Primal Residual:")
    end
    @testset "Records" begin
        a = StoreOptionsAction((:x, :ξ, :n, :m))
        update_storage!(a, Dict(:x => x_old, :ξ => ξ_old, :n => n_old, :m => copy(m)))
        io = IOBuffer()

        for r in [
            RecordPrimalChange(),
            RecordPrimalIterate(x0),
            RecordDualIterate(ξ0),
            RecordDualChange(),
            RecordDualBaseIterate(n),
            RecordDualBaseChange(),
            RecordPrimalBaseIterate(x0),
            RecordPrimalBaseChange(),
        ]
            r(p_exact, o_exact, 1)
            @test length(get_record(r)) == 1
        end
    end
end


text:
#=
Given a function that generates perfectly random numbers between 1 and k (inclusive), where k is an input, write a function that shuffles a deck of cards represented as an array using only swaps.

It should run in O(N) time.

Hint: Make sure each one of the 52! permutations of the deck is equally likely.
=#

function swap(deck::Array{Int,1}, card1_index::Int, card2_index::Int)
    newdeck = copy(deck)
    newdeck[card1_index] = deck[card2_index]
    newdeck[card2_index] = deck[card1_index]
    return newdeck
end

function randk(k::Int)
    return rand(1:k)
end

function shuffle(deck::Array{Int,1})
    for card_index in 1:52
        new_pos = randk(52)
        deck = swap(deck, card_index, new_pos)
    end
    return deck
end

max_stars_repo_name: DominiqueCaron/daily-coding-problem

max_issues_repo_name: DominiqueCaron/daily-coding-problem

max_forks_repo_name: DominiqueCaron/daily-coding-problem


text:
using Images
using Base.Iterators
using Printf

function n_kakkei(N)
    return function(x, y)
        N_max = floor(N/2)
        result = 0
        for k in 1:N_max
            c1 = 2k*π/N
            result += abs(x*sin(c1) - abs(y)*cos(c1)) - sin(c1)
        end
        result += 1/2 * abs(y*sin(N*π/2)) - 1/2 * x*cot(N_max*π/N) + 1/2 * cot(N_max*π/N)
        return abs(result)
    end
end

function main()
    N::Int64 = 128
    fimg = zeros(N, N)
    X = 1:N
    Y = 1:N
    # 正N角形 -> 正N+1角形へ
    for n in 3:10
        f1 = n_kakkei(n)
        f2 = n_kakkei(n+1)
        for t in 0:0.05:1
            f3 = (x, y) -> f1(x, y)*(1-t) + f2(x, y)*t
            map(x -> fimg[x...] = f3(((x.-N/2)./(N/3))...), product(X, Y))
            # @show max(fimg...)
            fimg = fimg ./ max(fimg...)
            img = Gray.(fimg)
            str = @sprintf "%02d_%.2f" n t
            save("img_henkei_$(str).jpg", img)
        end
    end
end

main()

max_stars_repo_name: Soyukke/julia-image

max_issues_repo_name: Soyukke/julia-image

max_forks_repo_name: Soyukke/julia-image


text:
@testset "ut1tai" begin
    a1, a2 = ut1tai(2453750.5, 0.892104561, -32.6659)
    @test a1 ≈ 2453750.5 atol=1e-6
    @test a2 ≈ 0.8924826385462962963 atol=1e-12
end

@testset "ut1tt" begin
    a1, a2 = ut1tt(2453750.5, 0.892104561, 64.8499)
    @test a1 ≈ 2453750.5 atol=1e-6
    @test a2 ≈ 0.8928551385462962963 atol=1e-15
end

@testset "ut1utc" begin
    a1, a2 = ut1utc(2453750.5, 0.892104561, 0.3341)
    @test a1 ≈ 2453750.5 atol=1e-6
    @test a2 ≈ 0.8921006941018518519 atol=1e-13
end

@testset "utctai" begin
    u1, u2 = utctai(2453750.5, 0.892100694)
    @test u1 ≈ 2453750.5 atol=1e-6
    @test u2 ≈ 0.8924826384444444444 atol=1e-13
    @test_logs (:warn,) utctai(2.4880695e6, 0.0)
    @test_throws ERFAException utctai(typemax(Cdouble), 0.0)
end

@testset "utcut1" begin
    u1, u2 = utcut1(2453750.5, 0.892100694, 0.3341)
    @test u1 ≈ 2453750.5 atol=1e-6
    @test u2 ≈ 0.8921045608981481481 atol=1e-13
end


text:
const N_CYCLES = 6

function count_neighbors(grid::Array{Int,4}, x0::Int, y0::Int, z0::Int, w0::Int)::Int
    count::Int = 0
    for x in x0 - 1:x0 + 1
        for y in y0 - 1:y0 + 1
            for z in z0 - 1:z0 + 1
                for w in w0 - 1:w0 + 1
                    if x == x0 && y == y0 && z == z0 && w == w0
                        continue
                    else
                        count += grid[x, y, z, w]
                    end
                end
            end
        end
    end
    return count
end

function run(s)
    offset = N_CYCLES + 1
    grid = zeros(Int, (8 + 2 * offset, 8 + 2 * offset, 1 + 2 * offset, 1 + 2 * offset))
    for (row, line) in enumerate(eachline(IOBuffer(s)))
        for (col, c) in enumerate(line)
            if c == '#'
                grid[row + offset, col + offset, 1 + offset, 1 + offset] = 1
            end
        end
    end
    old_grid = copy(grid)
    n_neighbors::Int = 0
    for cycle in 1:N_CYCLES
        old_grid .= grid
        for x in offset + 1 - cycle:offset + 8 + cycle
            for y in offset + 1 - cycle:offset + 8 + cycle
                for z in offset + 1 - cycle:offset + 1 + cycle
                    for w in offset + 1 - cycle:offset + 1 + cycle
                        n_neighbors = count_neighbors(old_grid, x, y, z, w)
                        if (old_grid[x, y, z, w] != 0) && (n_neighbors != 2) && (n_neighbors != 3)
                            grid[x, y, z, w] = 0
                        elseif (old_grid[x, y, z, w] == 0) && (n_neighbors == 3)
                            grid[x, y, z, w] = 1
                        end
                    end
                end
            end
        end
    end
    return sum(grid)
end

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

function main()
    res, time, memory = @timed run(ARGS[1])
    println("_duration:$(time * 1000)")
    println(res)
end

main()


text:
export
    dubins_shortest_path, dubins_path,
    dubins_path_length, dubins_segment_length,
    dubins_segment_length_normalized,
    dubins_path_type, dubins_path_sample,
    dubins_path_sample_many, dubins_path_endpoint,
    dubins_extract_subpath

"""
Generate a path from an initial configuration to a target configuration with a specified maximum turning radius

A configuration is given by ``[x, y, \\theta]``, where ``\\theta`` is in radians,

* ``q_0``        - a configuration specified by a 3-element vector ``[x, y, \\theta]``
* ``q_1``        - a configuration specified by a 3-element vector ``[x, y, \\theta]``
* ``\\rho``      - turning radius of the vehicle
* return    - tuple (error code, dubins path). If error code != 0, then `nothing` is returned as the second argument
"""
function dubins_shortest_path(q0::Vector{Float64}, q1::Vector{Float64}, ρ::Float64)

    # input checking
    @assert length(q0) ==  3
    @assert length(q1) == 3
    (ρ <= 0) && (return EDUBBADRHO, nothing)

    path = DubinsPath()

    params = zeros(3)

    best_cost = Inf
    best_word = -1
    intermediate_results = DubinsIntermediateResults(q0, q1, ρ)

    path.qi[1] = q0[1]
    path.qi[2] = q0[2]
    path.qi[3] = q0[3]
    path.ρ = ρ

    for i in 0:5
        path_type = DubinsPathType(i)
        errcode, params = dubins_word(intermediate_results, path_type)
        if errcode == EDUBOK
            cost = sum(params)
            if cost < best_cost
                best_word = i
                best_cost = cost
                path.params[1] = params[1]
                path.params[2] = params[2]
                path.params[3] = params[3]
                path.path_type = path_type
            end
        end
    end

    (best_word == -1) && (return EDUBNOPATH, nothing)
    return EDUBOK, path
end

"""
Generate a path with a specified word from an initial configuratioon to a target configuration, with a specified turning radius

* ``q_0``       - a configuration specified by a 3-element vector ``x``, ``y``, ``\\theta``
* ``q_1``       - a configuration specified by a 3-element vector ``x``, ``y``, ``\\theta``
* ``\\rho``     - turning radius of the vehicle
* path_type - the specified path type to use
* return    - tuple (error code, dubins path). If error code != 0, then `nothing` is returned as the second argument
"""
function dubins_path(q0::Vector{Float64}, q1::Vector{Float64}, ρ::Float64, path_type::DubinsPathType)

    # input checking
    @assert length(q0) ==  3
    @assert length(q1) == 3
    (ρ <= 0) && (return EDUBBADRHO, nothing)

    path = DubinsPath()

    intermediate_results = DubinsIntermediateResults(q0, q1, ρ)

    params = zeros(3)
    errcode, params = dubins_word(intermediate_results, path_type)
    if errcode == EDUBOK
        path.params[1] = params[1]
        path.params[2] = params[2]
        path.params[3] = params[3]
        path.qi[1] = q0[1]
        path.qi[2] = q0[2]
        path.qi[3] = q0[3]
        path.ρ = ρ
        path.path_type = path_type
    end

    (errcode != EDUBOK) && (return errcode, nothing)
    return errcode, path
end

"""
Calculate the length of an initialized path

* path      - path to find the length of
* return    - path length
"""
dubins_path_length(path::DubinsPath) = sum(path.params)*path.ρ

"""
Calculate the length of a specific segment of  an initialized path

* path      - path to find the length of
* ``i``     - the segment for which the length is required (1-3)
* return    - segment length
"""
dubins_segment_length(path::DubinsPath, i::Int) = (i<1 || i>3) ? (return Inf) : (return path.params[i]*path.ρ)

"""
Calculate the normalized length of a specific segment of  an initialized path

* path      - path to find the length of
* ``i``     - the segment for which the length is required (1-3)
* return    - normalized segment length
"""
dubins_segment_length_normalized(path::DubinsPath, i::Int) = (i<1 || i>3) ? (return Inf) : (return path.params[i])

"""
Extract the integer that represents which path type was used

* path      - an initialized path
* return    - one of LSL-0, LSR-1, RSL-2, RSR-3, RLR-4, LRL-5
"""
dubins_path_type(path::DubinsPath) = path.path_type

"""
Operators that transform an arbitrary point ``q_i``, ``[x, y, \\theta]``, into an image point given a parameter ``t`` and segment type

The three operators correspond to ``L``, ``R``, and ``S``

 * ``L(x, y, \\theta, t) = [x, y, \\theta] + [ \\sin(\\theta + t) - \\sin(\\theta), -\\cos(\\theta + t) + \\cos(\\theta),  t]``
 * ``R(x, y, \\theta, t) = [x, y, \\theta] + [-\\sin(\\theta - t) + \\sin(\\theta),  \\cos(\\theta - t) - \\cos(\\theta), -t]``
 * ``S(x, y, \\theta, t) = [x, y, \\theta] + [ \\cos(\\theta) \\cdot t, \\sin(\\theta) \\cdot t, 0]``

 * return    -  the image point as a 3-element vector
"""
function dubins_segment(t::Float64, qi::Vector{Float64}, segment_type::SegmentType)

    qt = zeros(3)
    st = sin(qi[3])
    ct = cos(qi[3])

    if segment_type == L_SEG
        qt[1] = +sin(qi[3]+t) - st
        qt[2] = -cos(qi[3]+t) + ct
        qt[3] = t
    elseif segment_type == R_SEG
        qt[1] = -sin(qi[3]-t) + st
        qt[2] = +cos(qi[3]-t) - ct
        qt[3] = -t
    elseif segment_type == S_SEG
        qt[1] = ct * t
        qt[2] = st * t
        qt[3] = 0.0
    end
    qt[1] = qt[1] + qi[1]
    qt[2] = qt[2] + qi[2]
    qt[3] = qt[3] + qi[3]

    return qt
end

"""
Calculate the configuration along the path, using the parameter t

 * path      - an initialized path
 * ``t``         - length measure where ``0 \\leq t <`` [`dubins_path_length`](@ref)(path)
 * return    - tuple containing non-zero error code if 't' is not in the correct range and the configuration result ``[x, y, \\theta]``
"""
function dubins_path_sample(path::DubinsPath, t::Float64)

    # tprime is the normalized variant of the parameter t
    tprime = t/path.ρ
    qi = zeros(3)
    q = zeros(3)
    segment_types = DIRDATA[Int(path.path_type)]

    (t < 0 || t > dubins_path_length(path)) && (return EDUBPARAM, nothing)

    # initial configuration
    qi = [0.0, 0.0, path.qi[3]]

    # generate target configuration
    p1 = path.params[1]
    p2 = path.params[2]
    q1 = dubins_segment(p1, qi, segment_types[1])
    q2 = dubins_segment(p2, q1, segment_types[2])
    if tprime < p1
        q = dubins_segment(tprime, qi, segment_types[1])
    elseif tprime < (p1+p2)
        q = dubins_segment(tprime-p1, q1, segment_types[2])
    else
        q = dubins_segment(tprime-p1-p2, q2, segment_types[3])
    end

    # scale the target configuration, translate back to the original starting point
    q[1] = q[1] * path.ρ + path.qi[1]
    q[2] = q[2] * path.ρ + path.qi[2]
    q[3] = mod2pi(q[3]);

    return EDUBOK, q
end

"""
Walk along the path at a fixed sampling interval, calling the callback function at each interval

The sampling process continues until the whole path is sampled, or the callback returns a non-zero value

 * path         - the path to sample
 * step_size    - the distance along the path for subsequent samples

 * return       - tuple (error code, configuration vector). If error code != 0, then `nothing` is returned as the second argument
 """
function dubins_path_sample_many(path::DubinsPath, step_size::Float64)

    q = zeros(3)
    configurations = []
    x = 0.0
    length = dubins_path_length(path)

    (step_size < 0 || step_size > length) && (return EDUBPARAM, nothing)

    while x < length
        errcode, q = dubins_path_sample(path, x)
        push!(configurations, q)
        (errcode != 0) && (return errcode, nothing)
        x += step_size
    end

    return EDUBOK, configurations
end

"""
Convenience function to identify the endpoint of a path

 * path          - an initialized path
 * return        - tuple containing (zero on successful completion and the end configuration ``[x,y,\\theta]``)
"""
dubins_path_endpoint(path::DubinsPath) = dubins_path_sample(path, dubins_path_length(path) - TOL)

"""
Convenience function to extract a sub-path

 * path          - an initialized path
 * ``t``             - a length measure, where ``0 < t <`` [`dubins_path_length`](@ref)(path)
 * return        - zero on successful completion and the subpath
"""
function dubins_extract_subpath(path::DubinsPath, t::Float64)

    # calculate the true parameter
    tprime = t / path.ρ;

    ((t < 0) || (t > dubins_path_length(path))) && (return EDUBPARAM, nothing)

    newpath = DubinsPath()

    # copy most of the data
    newpath.qi[1] = path.qi[1]
    newpath.qi[2] = path.qi[2]
    newpath.qi[3] = path.qi[3]
    newpath.ρ = path.ρ
    newpath.path_type = path.path_type

    # fix the parameters
    newpath.params[1] = min(path.params[1], tprime)
    newpath.params[2] = min(path.params[2], tprime - newpath.params[1])
    newpath.params[3] = min(path.params[3], tprime - newpath.params[1] - newpath.params[2])

    return EDUBOK, newpath
end

"""
The function to call the corresponding Dubins path based on the path_type

* return        - tuple (error code, path length as a vector for corresponding path type)
"""
function dubins_word(intermediate_results::DubinsIntermediateResults, path_type::DubinsPathType)

    result::Int = 0
    out = Vector{Float64}(undef,3)
    if path_type == LSL
        result, out = dubins_LSL(intermediate_results)
    elseif path_type == RSL
        result, out = dubins_RSL(intermediate_results)
    elseif path_type == LSR
        result, out = dubins_LSR(intermediate_results)
    elseif path_type == RSR
        result, out = dubins_RSR(intermediate_results)
    elseif path_type == LRL
        result, out = dubins_LRL(intermediate_results)
    elseif path_type == RLR
        result, out = dubins_RLR(intermediate_results)
    else
        result = EDUBNOPATH
    end

    (result == EDUBNOPATH) && (return result, nothing)
    return result, out
end

"""
Reset tolerance value
"""
function set_tolerance(ϵ::Float64)
    TOL = ϵ
    return
end


text:
@deprecate front(x) first(x)
@deprecate back(x) last(x)
@deprecate top(x) first(x)


text:
include("kern_proc.jl")

d = 10
n = [50, 100, 200]

cov_procs = Array(Proc, 0)
push!(cov_procs, KernelTest(SEIso(1.0, 1.0) + RQIso(1.0, 1.0, 1.0), d, GaussianProcesses.cov))
push!(cov_procs, KernelTest(SEIso(1.0, 1.0) * RQIso(1.0, 1.0, 1.0), d, GaussianProcesses.cov))
cov_table = run(cov_procs, n)

grad_stack_procs = Array(Proc, 0)
push!(grad_stack_procs, KernelTest(SEIso(1.0, 1.0) + RQIso(1.0, 1.0, 1.0), d, GaussianProcesses.grad_stack))
push!(grad_stack_procs, KernelTest(SEIso(1.0, 1.0) * RQIso(1.0, 1.0, 1.0), d, GaussianProcesses.grad_stack))
grad_stack_table = run(grad_stack_procs, n)

println("\ncov calculations")
show(cov_table)

println("\grad_stack calculations")
show(grad_stack_table)


text:
using Pkg
Pkg.activate(@__DIR__)

using Dates
using HTTP
using MySQL
using JSON3
using StructTypes

struct jsonObj
    id::Int
    randomNumber::Int
end

StructTypes.StructType(::Type{jsonObj}) = StructTypes.Struct()

HTTP.listen("0.0.0.0" , 8080, reuseaddr = true) do http
    target = http.message.target

    HTTP.setstatus(http, 200)
    HTTP.setheader(http, "Server" => "Julia-HTTP")
    HTTP.setheader(http, "Date" => Dates.format(Dates.now(), Dates.RFC1123Format) * " GMT")

    if endswith(target, "/plaintext")
        HTTP.setheader(http, "Content-Type" => "text/plain")
        HTTP.startwrite(http)
        write(http, "Hello, World!")

    elseif endswith(target, "/json")
        HTTP.setheader(http, "Content-Type" => "application/json")
        startwrite(http)
        JSON3.write(http, (;message = "Hello, World!"))

    elseif endswith(target, "/db")
        HTTP.setheader(http, "Content-Type" => "application/json")
        randNum = rand(1:10000)

        conn = DBInterface.connect(MySQL.Connection, "tfb-database", "benchmarkdbuser", "benchmarkdbpass", db="hello_world")
        sqlQuery = "SELECT * FROM World WHERE id = $randNum"
        results = DBInterface.execute(conn, sqlQuery)
        row = first(results)
        dbNumber = row[2]
        jsonString = "{\"id\":$randNum,\"randomNumber\":$dbNumber}"

        startwrite(http)
        JSON3.write(http, (JSON3.read(jsonString)))

        DBInterface.close!(conn)

    elseif occursin("/queries", target)
        HTTP.setheader(http, "Content-Type" => "application/json")
        numQueries = -1

        try
            numQueries = parse(Int64, (split(target, "="))[2])

        catch ArgumentError
            numQueries = 1

        finally
            if numQueries > 500
                numQueries = 500
            end

            if numQueries < 1
                numQueries = 1
            end
        end

        conn = DBInterface.connect(MySQL.Connection, "tfb-database", "benchmarkdbuser", "benchmarkdbpass", db="hello_world")

        responseArray = Array{jsonObj}(undef, numQueries)
        for i in 1:numQueries
            # randNum = randNumList[i]
            randNum = rand(1:10000)
            sqlQuery = "SELECT * FROM World WHERE id = $randNum"
            results = DBInterface.execute(conn, sqlQuery)
            row = first(results)
            dbNumber = row[2]
            responseArray[i] = JSON3.read("{\"id\":$randNum,\"randomNumber\":$dbNumber}", jsonObj)
        end

        startwrite(http)
        JSON3.write(http, responseArray)

        DBInterface.close!(conn)

    elseif occursin("/updates", target)
        HTTP.setheader(http, "Content-Type" => "application/json")
        numQueries = -1

        try
            numQueries = parse(Int64, (split(target, "="))[2])

        catch ArgumentError
            numQueries = 1

        finally
            if numQueries > 500
                numQueries = 500
            end

            if numQueries < 1
                numQueries = 1
            end
        end

        conn = DBInterface.connect(MySQL.Connection, "tfb-database", "benchmarkdbuser", "benchmarkdbpass", db="hello_world")

        responseArray = Array{jsonObj}(undef, numQueries)
        for i in 1:numQueries
            randId = rand(1:10000)
            randNum = rand(1:10000)
            sqlQuery = "SELECT * FROM World WHERE id = $randId"
            results = DBInterface.execute(conn, sqlQuery)
            row = first(results)
            dbNumber = row[2]

            sqlQuery = "UPDATE World SET randomnumber = $randNum WHERE id = $randId"
            results = DBInterface.execute(conn, sqlQuery)
            responseArray[i] = JSON3.read("{\"id\":$randId,\"randomNumber\":$randNum}", jsonObj)
        end

        startwrite(http)
        JSON3.write(http, responseArray)

        DBInterface.close!(conn)

    elseif endswith(target, "/fortunes")
        HTTP.setheader(http, "Content-Type" => "text/html; charset=utf-8")

        fortunesList = []
        sqlQuery = "SELECT * FROM fortune"
        output = "<!DOCTYPE html><title>Fortunes</title>

id	message
"
        conn = DBInterface.connect(MySQL.Connection, "tfb-database", "benchmarkdbuser", "benchmarkdbpass", db="hello_world")
        results = DBInterface.execute(conn, sqlQuery)

        for row in results
            push!(fortunesList, [string(row[1]), row[2]])
        end

        push!(fortunesList, [string(0), "Additional fortune added at request time."])

        sort!(fortunesList, by = x -> x[2])

        for fortune in fortunesList
            id = fortune[1]
            message = HTTP.Strings.escapehtml(fortune[2])
            output = string(output, "
$id	$message
")
        end

        output = string(output, "
")

        write(http, output)

        DBInterface.close!(conn)

    else
        HTTP.setstatus(http, 404)
        startwrite(http)
        write(http, "Not Found")

    end
end

max_stars_repo_name: qballer/FrameworkBenchmarks

max_issues_repo_name: qballer/FrameworkBenchmarks

max_forks_repo_name: qballer/FrameworkBenchmarks


text:
@doc """
A Julia Batch Job.

Runs in a single allocation/container restricted to the specified amount of
CPUs and memory. The Julia process started in the batch job is allowed to
start other worker processes or threads, all within the specified limits.
The upper bound of CPUs/memory is determined by the largest cluster node.

Scenarios:
- non-parallel
- multi-threaded parallelism
- multi-process shared memory parallelism

Required parameters:
- name: name of the job (must be unique in the system, can be random)
- start_script: a Julia script to start the master node with
- run_volume: a persistent volume to use as the master volume

Optional parameters:
- pkg_bundle: a package bundle to set at LOAD_PATH (none by default)
- additional_volumes: more persistent volumes to attach at /mnt/<volume name> (none by default)
- ports: network ports to expose as a Dict{String,Tuple{Int,Int}} of name to container port and service port map (default: nothing)
- external: whether network ports should be exposed to external network (default: false)
- image: the docker image to run (default: julia)
- cpu: CPU share to allocate (default: minimum 0.1 of a core, burstable to 1 core)
- gpu: GPUs to allocate (default: 0)
- memory: RAM to allocate (default: 512 MiB to 1Gi)
- shell: the script to use for startup shell (default: master.sh)
- envvars: additional environment variables to set
""" JuliaBatch

@doc """
A Julia Master-Slave Parallel Batch Job.

A designated master process and an array of worker processes, each of which
runs in a separate allocation/container. All worker processes have a uniform
resource allocation. The master process can have a different allocation.

The job as a whole can use all available CPU/memory in a cluster (within
practical limitations imposed networking and such). The upper bound for each
master/worker process is determined by the largest node in the cluster.

The master and worker processes are initialized for Julia parallel constructs.
The number of workers can be checked and manipulated with the `scale`/`scale!`
APIs. The number of worker processes actually running depends on the available
cluster resources and may be different from the requested scale. The job is
deemed running when the master process starts, and JuliaRun attempts to match
number of worker processes to the requested scale continuously. The master
process may check the number of actual workers with the `nworkers` API and
wait for a minimum number of workers if needed by it.

Scenario:
- multi-process distributed memory parallelism

Required parameters:
- name: name of the job (must be unique in the system, can be random)
- start_script: a Julia script to start the master node with
- run_volume: a persistent volume to use as the master volume

Optional parameters:
- pkg_bundle: a package bundle to set at LOAD_PATH (none by default)
- additional_volumes: more persistent volumes to attach at /mnt/<volume name> (none by default)
- ports: network ports to expose from the master process as a Dict{String,Tuple{Int,Int}} of name to container port and service port map (default: nothing)
- external: whether network ports should be exposed to external network (default: false)
- image: the docker image to run (default: julia)
- cpu: CPU share to allocate to master process (default: 0.1 of a core, burstable to 1 core)
- gpu: GPUs to allocate (default: 0)
- memory: RAM to allocate to master process (default: 512 Mi to 1 Gi)
- shell: the script to use for master shell (default: master.sh)
- envvars: additional environment variables to set for the master
- nworkers: number of worker processes to start (0 by default, can be scaled later)
- worker_cpu: CPU share to allocate to a worker process (default: 0.1 of a core, burstable to 1 core)
- worker_gpu: GPUs to allocate to a worker process(default: 0)
- worker_memory: RAM to allocate to a worker process (default: 512 Mi to 1 Gi)
- worker_shell: the script to use for a worker shell (default: master.sh)
- worker_envvars: additional environment variables to set for the worker
- worker_start_script: a Julia script to start the worker node with (default: worker.sh)
- restart: should workers be restarted (RestartAlways by default, can also be RestartOnFailure or Never)
""" JuliaParBatch

@doc """
A Julia Embarrassingly Parallel Batch Job.

An array of batch jobs that can be scaled as a single unit. Each unit in the job array
can be likened to a JuliaBatch job. Since there is no interlinking between the units,
this can be scaled faster and to much higher levels.

As a whole, the job can use all available CPU/memory in the cluster, but the upper bound
for each worker process is determined by the largest node in the cluster.

Scenarios:
- work queues
- distributed memory parallelism

Required parameters:
- name: name of the job (must be unique in the system, can be random)
- start_script: a Julia script to start each node with
- run_volume: a persistent volume to use as the work volume

Optional parameters:
- pkg_bundle: a package bundle to set at LOAD_PATH (none by default)
- additional_volumes: more persistent volumes to attach at /mnt/<volume name> (none by default)
- ports: network ports to expose as a Dict{String,Tuple{Int,Int}} of name to container port and service port map (default: nothing)
- external: whether network ports should be exposed to external network (default: false)
- image: the docker image to run (default: julia)
- cpu: CPU share to allocate to each process (default: 0.1 of a core, burstable to 1 core)
- gpu: GPUs to allocate to each process (default: 0)
- memory: RAM to allocate to each process (default: 512 Mi to 1Gi)
- shell: the script to use for process shell (default: worker.sh)
- envvars: additional environment variables to set
- nworkers: number of worker processes to start (0 by default, can be scaled later)
- restart: should workers be restarted (RestartAlways by default, can also be RestartOnFailure or Never)
""" JuliaParBatchWorkers

@doc """
A Julia Interactive Notebook.

The notebook is accessible outside the cluster and can be protected by a password (or an external portal/proxy).
The master container runs the Jupyter notebook process and the Julia kernels.

The Julia process running as the kernel is similar to a JuliaBatch.
Workers can be provisioned (optionally) as:
- slaves to a master Julia process (a Jupyter kernel), similar to JuliaParBatch
- a job array, similar to JuliaParBatchWorkers

Scenarios:
- interactive/exploratory tasks
- shell access (through Jupyter shell)
- file transfer (through Jupyter file manager)

Required parameters:
- name: name of the job (must be unique in the system, can be random)
- run_volume: a persistent volume to use as the master volume

Optional parameters:
- pkg_bundle: a package bundle to set at LOAD_PATH (none by default)
- additional_volumes: more persistent volumes to attach at /mnt/<volume name> (none by default)
- image: the docker image to run (default: julia)
- cpu: CPU share to allocate to master process (default: 0.1 of a core, burstable to 1 core)
- gpu: GPUs to allocate to master process (default: 0)
- memory: RAM to allocate to master process (default: 512 Mi to 1 Gi)
- shell: the script to use for master shell (default: notebook.sh)
- envvars: additional environment variables to set for the master
- worker_cpu: CPU share to allocate to a worker process (default: 0.1 of a core, burstable to 1 core)
- worker_gpu: GPUs to allocate to a worker process (default: 0)
- worker_memory: RAM to allocate to a worker process (default: 512 Mi to 1 Gi)
- worker_shell: the script to use for a worker shell (default: master.sh)
- worker_envvars: additional environment variables to set for the worker
- worker_start_script: a Julia script to start the worker node with (default: worker.sh)
- passwd: password to protect the notebook with (default: no password)
- ports: network ports to expose as a Dict{String,Tuple{Int,Int}} of name to container port and service port map (default: Dict("nb"=>(8888,8888)))
- external: whether network ports should be exposed to external network (default: false)
- restart: should workers be restarted (RestartAlways by default, can also be RestartOnFailure or Never)
""" Notebook

@doc """
Build / update a Julia package bundle.

It mounts the volume representing the package folder of the bundle in
read-write mode, and launches a script to build them. It is similar to
a JuilaBatch job.

Package bundles are a way of making Julia packages accessible to JuliaRun jobs.
They are just folders with Julia packages, pre-compiled and along with all their
dependencies. Package bundles can be built and tested separately and attached to
multiple images, providing a way to dissociate their maintenance.

Attaching a package bundle to a JuliaRun job sets the appropriate environment
variables (`LOAD_PATH` and such) so that Julia code can start using them seamlessly.

Required parameters:
- name: name of the job (must be unique in the system, can be random)
- builder_script: a Julia script that builds packages
- run_volume: a persistent volume to use as the master volume
- pkg_bundle: the package bundle to build

Optional parameters:
- additional_volumes: more persistent volumes to attach at /mnt/<volume name> (none by default)
- image: the docker image to run (default: julia)
- cpu: CPU share to allocate (default: 1 core, burstable to 2 cores)
- gpu: GPUs to allocate (default: 0)
- memory: RAM to allocate (default: 4Gi to 8 Gi)
- shell: the script to use for startup shell (default: master.sh)
- envvars: additional environment variables to set for the master
""" PkgBuilder

@doc """
Webserver that can be used to serve API/UI/files for jobs.
Nginx is used as the underlying service.

Scenarios:
- accept inputs (file uploads, API calls, ...)
- serve output/log files created by jobs
- simple user interfaces

Required parameters:
- name: name of the job (must be unique in the system, can be random)
- cfg_file: configuration file to start webserver with
- run_volume: a persistent volume to use as the master volume

Optional parameters:
- additional_volumes: more persistent volumes to attach at /mnt/<volume name> (none by default)
- image: the docker image to run (default: nginx)
- cpu: CPU share to allocate (default: 0.1 core, burstable to 1 core)
- memory: RAM to allocate (default: 512Mi to 1Gi)
- envvars: additional environment variables to set
- ports: network ports to expose as a Dict{String,Tuple{Int,Int}} of name to container port and service port map (default: Dict("http"=>(80,80), "https"=>(443,443)))
- external: whether network ports should be exposed to external network (default: false)
- nworkers: number of webserver containers to start

Logging:
Use Nginx logging configuration to configure logging characteristics. For example:
- log to `/mnt/juliarun/webserver/error.log`: `error_log /mnt/juliarun/webserver/error.log warn;`
- log to stderr (and set level to debug): `error_log stderr debug;`
- send access logs to `/mnt/juliarun/webserver/access.log`: `access_log /mnt/juliarun/webserver/access.log;`

Ensure the target volume for log files is specified in `additional_volumes` parameter.
""" Webserver

@doc """
Message Queue that can be used for communication between processes within or across jobs.
Enables complex routing/broadcast of messages.
Uses RabbitMQ as the message queue provider.

Scenarios:
- inter process communication within / across jobs
- task queue, used by job arrays

Required parameters:
- name: name of the job (must be unique in the system, can be random)
- cfg_file: configuration file to start message queue with
- run_volume: a persistent volume to use as the master volume

Optional parameters:
- additional_volumes: more persistent volumes to attach at /mnt/<volume name> (none by default)
- image: the docker image to run (default: rabbitmq)
- cpu: CPU share to allocate (default: 1 core, burstable to 2 cores)
- memory: RAM to allocate (default: 4Gi)
- envvars: additional environment variables to set
- ports: network ports to expose as a Dict{String,Tuple{Int,Int}} of name to container port and service port map (default: Dict("amqptls"=>(5671,5671), "amqp"=>(5672,5672), "mgmttls"=>(15672,15671), "mgmt"=>(15672,15672)))
- external: whether network ports should be exposed to external network (default: false)

Logging:
Use RabbitMQ logging configuration environment variables to configure logging characteristics.
- by default logs are written on to stdout / stderr
- log to `/mnt/juliarun/mq/rabbit.log`: set environment variable `RABBITMQ_LOGS` to the file for the job
- log SASL activity to `/mnt/juliarun/mq/rabbit_sasl.log`: set environment variable `RABBITMQ_SASL_LOGS` to the file for the job

Ensure the target volume for log files is specified in `additional_volumes` parameter.
""" MessageQ

@doc """
Generic job to run any command in any docker image.

Required parameters:
- name: name of the job (must be unique in the system, can be random)
- image: image to run
- run_volume: a persistent volume to use as the master volume

Optional parameters:
- command: command in the docker to execute (Docker entrypoint by default)
- args: arguments to the command as Vector{String} (none by default)
- additional_volumes: more persistent volumes to attach at /mnt/<volume name> (none by default)
- cpu: CPU share to allocate (default: 0.1 core, burstable to 1 core)
- memory: RAM to allocate (default: 512Mi to 1Gi)
- envvars: additional environment variables to set
- ports: network ports to expose as a Dict{String,Tuple{Int,Int}} of name to container port and service port map (default: none)
- external: whether network ports should be exposed to external network (default: false)
- nworkers: number of containers to start
""" Generic


text:
# Autogenerated wrapper script for ngraph_jll for x86_64-linux-gnu
export libcodegen, libcpu_backend, libdnnl, libeval_backend, libinterpreter_backend, libiomp5, libmklml_intel, libngraph, libnop_backend

using OpenSSL_jll
## Global variables
PATH = ""
LIBPATH = ""
LIBPATH_env = "LD_LIBRARY_PATH"
LIBPATH_default = ""

# Relative path to `libcodegen`
const libcodegen_splitpath = ["lib", "libcodegen.so"]

# This will be filled out by __init__() for all products, as it must be done at runtime
libcodegen_path = ""

# libcodegen-specific global declaration
# This will be filled out by __init__()
libcodegen_handle = C_NULL

# This must be `const` so that we can use it with `ccall()`
const libcodegen = "libcodegen.so"

# Relative path to `libcpu_backend`
const libcpu_backend_splitpath = ["lib", "libcpu_backend.so"]

# This will be filled out by __init__() for all products, as it must be done at runtime
libcpu_backend_path = ""

# libcpu_backend-specific global declaration
# This will be filled out by __init__()
libcpu_backend_handle = C_NULL

# This must be `const` so that we can use it with `ccall()`
const libcpu_backend = "libcpu_backend.so"

# Relative path to `libdnnl`
const libdnnl_splitpath = ["lib", "libdnnl.so"]

# This will be filled out by __init__() for all products, as it must be done at runtime
libdnnl_path = ""

# libdnnl-specific global declaration
# This will be filled out by __init__()
libdnnl_handle = C_NULL

# This must be `const` so that we can use it with `ccall()`
const libdnnl = "libdnnl.so"

# Relative path to `libeval_backend`
const libeval_backend_splitpath = ["lib", "libeval_backend.so"]

# This will be filled out by __init__() for all products, as it must be done at runtime
libeval_backend_path = ""

# libeval_backend-specific global declaration
# This will be filled out by __init__()
libeval_backend_handle = C_NULL

# This must be `const` so that we can use it with `ccall()`
const libeval_backend = "libeval_backend.so"

# Relative path to `libinterpreter_backend`
const libinterpreter_backend_splitpath = ["lib", "libinterpreter_backend.so"]

# This will be filled out by __init__() for all products, as it must be done at runtime
libinterpreter_backend_path = ""

# libinterpreter_backend-specific global declaration
# This will be filled out by __init__()
libinterpreter_backend_handle = C_NULL

# This must be `const` so that we can use it with `ccall()`
const libinterpreter_backend = "libinterpreter_backend.so"

# Relative path to `libiomp5`
const libiomp5_splitpath = ["lib", "libiomp5.so"]

# This will be filled out by __init__() for all products, as it must be done at runtime
libiomp5_path = ""

# libiomp5-specific global declaration
# This will be filled out by __init__()
libiomp5_handle = C_NULL

# This must be `const` so that we can use it with `ccall()`
const libiomp5 = "libiomp5.so"

# Relative path to `libmklml_intel`
const libmklml_intel_splitpath = ["lib", "libmklml_intel.so"]

# This will be filled out by __init__() for all products, as it must be done at runtime
libmklml_intel_path = ""

# libmklml_intel-specific global declaration
# This will be filled out by __init__()
libmklml_intel_handle = C_NULL

# This must be `const` so that we can use it with `ccall()`
const libmklml_intel = "libmklml_intel.so"

# Relative path to `libngraph`
const libngraph_splitpath = ["lib", "libngraph.so"]

# This will be filled out by __init__() for all products, as it must be done at runtime
libngraph_path = ""

# libngraph-specific global declaration
# This will be filled out by __init__()
libngraph_handle = C_NULL

# This must be `const` so that we can use it with `ccall()`
const libngraph = "libngraph.so"

# Relative path to `libnop_backend`
const libnop_backend_splitpath = ["lib", "libnop_backend.so"]

# This will be filled out by __init__() for all products, as it must be done at runtime
libnop_backend_path = ""

# libnop_backend-specific global declaration
# This will be filled out by __init__()
libnop_backend_handle = C_NULL

# This must be `const` so that we can use it with `ccall()`
const libnop_backend = "libnop_backend.so"

"""
Open all libraries
"""
function __init__()
    global artifact_dir = abspath(artifact"ngraph")

    # Initialize PATH and LIBPATH environment variable listings
    global PATH_list, LIBPATH_list
    # From the list of our dependencies, generate a tuple of all the PATH and LIBPATH lists,
    # then append them to our own.
    foreach(p -> append!(PATH_list, p), (OpenSSL_jll.PATH_list,))
    foreach(p -> append!(LIBPATH_list, p), (OpenSSL_jll.LIBPATH_list,))

    global libcodegen_path = normpath(joinpath(artifact_dir, libcodegen_splitpath...))

    # Manually `dlopen()` this right now so that future invocations
    # of `ccall` with its `SONAME` will find this path immediately.
    global libcodegen_handle = dlopen(libcodegen_path)
    push!(LIBPATH_list, dirname(libcodegen_path))

    global libcpu_backend_path = normpath(joinpath(artifact_dir, libcpu_backend_splitpath...))

    # Manually `dlopen()` this right now so that future invocations
    # of `ccall` with its `SONAME` will find this path immediately.
    global libcpu_backend_handle = dlopen(libcpu_backend_path)
    push!(LIBPATH_list, dirname(libcpu_backend_path))

    global libdnnl_path = normpath(joinpath(artifact_dir, libdnnl_splitpath...))

    # Manually `dlopen()` this right now so that future invocations
    # of `ccall` with its `SONAME` will find this path immediately.
    global libdnnl_handle = dlopen(libdnnl_path)
    push!(LIBPATH_list, dirname(libdnnl_path))

    global libeval_backend_path = normpath(joinpath(artifact_dir, libeval_backend_splitpath...))

    # Manually `dlopen()` this right now so that future invocations
    # of `ccall` with its `SONAME` will find this path immediately.
    global libeval_backend_handle = dlopen(libeval_backend_path)
    push!(LIBPATH_list, dirname(libeval_backend_path))

    global libinterpreter_backend_path = normpath(joinpath(artifact_dir, libinterpreter_backend_splitpath...))

    # Manually `dlopen()` this right now so that future invocations
    # of `ccall` with its `SONAME` will find this path immediately.
    global libinterpreter_backend_handle = dlopen(libinterpreter_backend_path)
    push!(LIBPATH_list, dirname(libinterpreter_backend_path))

    global libiomp5_path = normpath(joinpath(artifact_dir, libiomp5_splitpath...))

    # Manually `dlopen()` this right now so that future invocations
    # of `ccall` with its `SONAME` will find this path immediately.
    global libiomp5_handle = dlopen(libiomp5_path)
    push!(LIBPATH_list, dirname(libiomp5_path))

    global libmklml_intel_path = normpath(joinpath(artifact_dir, libmklml_intel_splitpath...))

    # Manually `dlopen()` this right now so that future invocations
    # of `ccall` with its `SONAME` will find this path immediately.
    global libmklml_intel_handle = dlopen(libmklml_intel_path)
    push!(LIBPATH_list, dirname(libmklml_intel_path))

    global libngraph_path = normpath(joinpath(artifact_dir, libngraph_splitpath...))

    # Manually `dlopen()` this right now so that future invocations
    # of `ccall` with its `SONAME` will find this path immediately.
    global libngraph_handle = dlopen(libngraph_path)
    push!(LIBPATH_list, dirname(libngraph_path))

    global libnop_backend_path = normpath(joinpath(artifact_dir, libnop_backend_splitpath...))

    # Manually `dlopen()` this right now so that future invocations
    # of `ccall` with its `SONAME` will find this path immediately.
    global libnop_backend_handle = dlopen(libnop_backend_path)
    push!(LIBPATH_list, dirname(libnop_backend_path))

    # Filter out duplicate and empty entries in our PATH and LIBPATH entries
    filter!(!isempty, unique!(PATH_list))
    filter!(!isempty, unique!(LIBPATH_list))
    global PATH = join(PATH_list, ':')
    global LIBPATH = join(vcat(LIBPATH_list, [joinpath(Sys.BINDIR, Base.LIBDIR, "julia"), joinpath(Sys.BINDIR, Base.LIBDIR)]), ':')
end  # __init__()