text:
#== # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Description
#
#   Functions related to the analysis of the Right Ascension of the Ascending
#   Node (RAAN).
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ==#

export compute_RAAN_lt, sim_RAAN_J2

"""
    compute_RAAN_lt(JD::Number, asc_node_lt::Number)

Compute the RAAN (0,2π) \\[rad] so that the orbit plane local time is
`asc_node_lt` [hour] at the Julian day `JD`.

"""
function compute_RAAN_lt(JD::Number, asc_node_lt::Number)
    # Get the sun position at noon (UT) represented in the Inertial ref. frame.
    s_i = sun_position_i(JD)

    # Get the desired angle between the Sun and the ascending node [deg].
    alpha = (asc_node_lt-12)*π/12

    # Get the right ascension of the Sun in the Inertial ref. frame. This is the
    # Sun apparent local time.
    SALT = atan(s_i[2],s_i[1])

    # Get the equation of time to compute the Sun mean local time [rad].
    eot = equation_of_time(JD)

    # Compute the Sun mean local time.
    SMLT = SALT + eot

    # Compute the desired RAAN in the interval 0, 2*pi.
    RAAN = mod(SMLT+alpha, 2π)
end

"""
    sim_RAAN_J2(a::Number, e::Number, i::Number, RAAN_0::Number, numDays::Integer)

Simulate the RAAN of an orbit with semi-major axis `a` [m], eccentricity `e`,
inclination `i` [rad], and initial RAAN `RAAN_0` [rad] considering J2
perturbations. The analysis is performed for `numDays` days.

# Returns

A `numDays` × 2 matrix in which the i-th line is:

    | day | RAAN (0,2π) [rad] |

"""
function sim_RAAN_J2(a::Number,
                     e::Number,
                     i::Number,
                     RAAN_0::Number,
                     numDays::Integer)

    # Initialization of variables.
    days = collect(0:1:numDays-1) # Vector of the days in which the RAAN will be
                                  # simulated.

    # RAAN rotation rate [rad/day].
    dOmega = dRAAN(a, e, i, :J2)*24*3600

    # Simulate the RAAN for each day considering just the J2 perturbations.
    RAAN = mod.(RAAN_0 .+ dOmega.*days, 2π)

    [days RAAN]
end


text:
# This file plots two dimensional interpolation with irregular data

using FractalTools
using GeometryBasics
using Makie

# Construct interpolation data
f = FractalTools.ackley
α = 10
ngon = [BigFloat.([-1., -1.]), BigFloat.([1., -1]), BigFloat.([0., 1.])] * α
npts = 100
pts = getdata(f, ngon, npts)

# Construct interpolant
freevar = 0.001
interp = interpolate(pts, Interp2D(freevar))

# Define error function
erf(x, y) = abs(f(x, y) - interp(x, y))

# Construct test data
tpts = getdata(ngon, 7 * npts)

# Plots
fig = Figure()
ls1 = fig[1, 1] = LScene(fig)
ls2 = fig[1, 2] = LScene(fig)
trisurf!(ls1, tpts, f, meshcolor3=:red)
trisurf!(ls1, tpts, interp, meshcolor3=:blue)
scatter!(ls1, tpts)
trisurf!(ls2, tpts, erf, meshcolor3=:green)

ext: jl


text:
using Documenter, ImageCore

format = Documenter.HTML(edit_link = "master",
                         prettyurls = get(ENV, "CI", nothing) == "true")

makedocs(modules  = [ImageCore],
         format   = format,
         sitename = "ImageCore",
         pages    = ["index.md", "views.md", "map.md", "traits.md", "reference.md"])

deploydocs(repo   = "github.com/JuliaImages/ImageCore.jl.git")


text:
mutable struct LatLonAccelDirection
    a_lat::Float64
    a_lon::Float64
    direction::Int
end
Base.show(io::IO, a::LatLonAccelDirection) = @printf(io, "LatLonAccelDirection(%6.3f, %6.3f, %d)", a.a_lat, a.a_lon, a.direction)
Base.length(::Type{LatLonAccelDirection}) = 3
Base.convert(::Type{LatLonAccelDirection}, v::Vector{Float64}) = LatLonAccel(v[1], v[2],convert(Int,v[3]))
function Base.copyto!(v::Vector{Float64}, a::LatLonAccelDirection)
    v[1] = a.a_lat
    v[2] = a.a_lon
    v[3] = convert(Float64,a.direction)
    v
end
function AutomotiveDrivingModels.propagate(veh::Entity{VehicleState, D, Int}, action::LatLonAccelDirection,  roadway::Roadway, Δt::Float64) where {D<:Union{VehicleDef, BicycleModel}}
    previousInd = veh.state.posF.roadind
    a_lat = action.a_lat
    a_lon = action.a_lon

     v = veh.state.v
     ϕ = veh.state.posF.ϕ
    ds = v*cos(ϕ)
     t = veh.state.posF.t
    dt = v*sin(ϕ)

    ΔT = Δt
    ΔT² = ΔT*ΔT
    Δs = ds*ΔT + 0.5*a_lon*ΔT²
    Δt = dt*ΔT + 0.5*a_lat*ΔT²

    ds₂ = ds + a_lon*ΔT
    dt₂ = dt + a_lat*ΔT
    speed₂ = sqrt(dt₂*dt₂ + ds₂*ds₂)
    v₂ = sign(ds₂)*speed₂
    ϕ₂ = atan(dt₂, ds₂) + (v₂ < 0.0)*π # handle negative speeds
    roadind = move_along_with_direction(veh.state.posF.roadind, roadway, Δs, direction = action.direction)
    if t+Δt <= roadway[roadind.tag].width/2.0
        posF = Frenet(roadind, roadway, t=t+Δt, ϕ = ϕ₂)
        return VehicleState(posF, roadway, v₂)
    else
        footpoint = roadway[roadind]
        posG = convert(VecE2, footpoint.pos) + polar(t + Δt, footpoint.pos.θ + π/2)
        posG = VecSE2(posG.x, posG.y, footpoint.pos.θ + ϕ₂)

        state = VehicleState(posG, roadway, v₂)
        projections = in_lanes(posG, roadway)
        if length(roadway[previousInd.tag].exits)>0
            for projection in projections
                dir = clamp(action.direction,1,length(roadway[previousInd.tag].exits))
                if roadway[previousInd.tag].exits[dir].target.tag.segment == projection.tag.segment && !isempty(roadway[previousInd.tag].exits)
                    posF = Frenet(projection, roadway)
                    state = VehicleState(posG, posF, v₂)
                    #println(posF)
                    return state
                end
            end
        end

        for projection in projections
            dir = clamp(action.direction,1,length(roadway[previousInd.tag].exits))
            if  previousInd.tag.segment == projection.tag.segment
                posF = Frenet(projection, roadway)
                state = VehicleState(posG, posF, v₂)
                #println(posF)
                return state
            end
        end
        return state
    end
end

function Base.get(::Type{LatLonAccelDirection}, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)
    accel_lat = get(ACCFT, rec, roadway, vehicle_index, pastframe)
    accel_lon = get(ACCFS, rec, roadway, vehicle_index, pastframe)
    LatLonAccelDirection(accel_lat, accel_lon,1)
end
function pull_action!(::Type{LatLonAccelDirection}, a::Vector{Float64}, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)
    a[1] = get(ACCFT, rec, roadway, vehicle_index, pastframe)
    a[2] = get(ACCFS, rec, roadway, vehicle_index, pastframe)
    a
end

mutable struct AccelSteeringDirection
    a::Float64 # accel [m/s²]
    δ::Float64 # steering angle [rad]
    direction::Int64 # turning direction
end
Base.show(io::IO, a::AccelSteeringDirection) = @printf(io, "AccelSteeringDirection(%6.3f,%6.3f,%d)", a.a, a.δ,a.direction)
Base.length(::Type{AccelSteeringDirection}) = 3
Base.convert(::Type{AccelSteeringDirection}, v::Vector{Float64}) = AccelSteeringDirection(v[1], v[2], convert(Int,v[3]))
function Base.copyto!(v::Vector{Float64}, a::AccelSteeringDirection)
    v[1] = a.a
    v[2] = a.δ
    v[3] = convert(Float64,a.direction)
    v
end
#function propagate(veh::Entity{VehicleState, BicycleModel, Int}, action::AccelSteeringAngle, roadway::Roadway, Δt::Float64)
function AutomotiveDrivingModels.propagate(veh::Entity{VehicleState, D, Int}, action::AccelSteeringDirection, roadway::Roadway, Δt::Float64) where {D<:Union{VehicleDef, BicycleModel}}
    previousInd = veh.state.posF.roadind

    L = veh.def.a + veh.def.b
    l = -veh.def.b

    a = action.a # accel [m/s²]
    δ = action.δ # steering wheel angle [rad]

    x = veh.state.posG.x
    y = veh.state.posG.y
    θ = veh.state.posG.θ
    v = veh.state.v

    s = v*Δt + a*Δt*Δt/2 # distance covered
    v′ = v + a*Δt

    posG = nothing
    if abs(δ) < 0.01 # just drive straight
        posG = veh.state.posG + polar(s, θ)
    else # drive in circle

        R = L/tan(δ) # turn radius

        β = s/R
        xc = x - R*sin(θ) + l*cos(θ)
        yc = y + R*cos(θ) + l*sin(θ)

        θ′ = mod(θ+β, 2π)
        x′ = xc + R*sin(θ+β) - l*cos(θ′)
        y′ = yc - R*cos(θ+β) - l*sin(θ′)

        posG = VecSE2(x′, y′, θ′)
    end

    #VehicleState(posG, roadway, v′)
    state = VehicleState(posG, roadway, v′)
    projections = in_lanes(posG, roadway)
    if length(roadway[previousInd.tag].exits)>0
        for projection in projections
            dir = clamp(action.direction,1,length(roadway[previousInd.tag].exits))
            if roadway[previousInd.tag].exits[dir].target.tag.segment == projection.tag.segment && !isempty(roadway[previousInd.tag].exits)
                posF = Frenet(projection, roadway)
                state = VehicleState(posG, posF, v′)
                #println(posF)
                return state
            end
        end
    end

    for projection in projections
        dir = clamp(action.direction,1,length(roadway[previousInd.tag].exits))
        if  previousInd.tag.segment == projection.tag.segment
            posF = Frenet(projection, roadway)
            state = VehicleState(posG, posF, v′)
            #println(posF)
            return state
        end
    end
    return state
end

mutable struct NextState
    x::Float64
    y::Float64
    theta::Float64
    speed::Float64
    direction::Int
end

function NextState()
    return NextState(0.0,0.0,0.0,0.0,1)
end

function AutomotiveDrivingModels.propagate(veh::Entity{VehicleState, D, Int}, action::NextState,  roadway::Roadway, Δt::Float64) where {D<:Union{VehicleDef, BicycleModel}}
    previousInd = veh.state.posF.roadind

    posG = VecSE2(action.x, action.y, action.theta)
    v′ = action.speed

    state = VehicleState(posG, roadway, v′)
    projections = in_lanes(posG, roadway)
    if length(roadway[previousInd.tag].exits)>0
        for projection in projections
            dir = clamp(action.direction,1,length(roadway[previousInd.tag].exits))
            if roadway[previousInd.tag].exits[dir].target.tag.segment == projection.tag.segment && !isempty(roadway[previousInd.tag].exits)
                posF = Frenet(projection, roadway)
                state = VehicleState(posG, posF, v′)
                #println(posF)
                return state
            end
        end
    end

    for projection in projections
        dir = clamp(action.direction,1,length(roadway[previousInd.tag].exits))
        if  previousInd.tag.segment == projection.tag.segment
            posF = Frenet(projection, roadway)
            state = VehicleState(posG, posF, v′)
            #println(posF)
            return state
        end
    end
    return state
end


text:
struct Stage{P}
    parameters::P

    function Stage()
        return new{Nothing}(nothing)
    end

    function Stage(parameters::P) where P
        return new{P}(parameters)
    end
end
parameter_type(stage::Stage{P}) where P = P

struct StageParameters{NT <: NamedTuple}
    names::Vector{Symbol}
    defaults::NT

    function StageParameters(; kw...)
        defaults = values(kw)
        names = collect(keys(defaults))
        NT = typeof(defaults)
        return new{NT}(names, defaults)
    end

    function StageParameters(names::Vector{Symbol}; kw...)
        defaults = values(kw)
        NT = typeof(defaults)
        return new{NT}(names, defaults)
    end
end

function parameters(stage_params::StageParameters; kw...)
    d = Dict(kw)
    params = if isempty(d)
        stage_params.defaults
    else
        filter!(p -> p.first ∈ stage_params.names, d)
        merge(stage_params.defaults, d)
    end
    if length(params) != length(stage_params.names)
        missing = filter(n -> !(n ∈ keys(params)), stage_params.names)
        isare = length(missing) == 1 ? "is" : "are"
        error("Not enough parameters specified. $(join(missing, ',')) $isare missing.")
    end
    return params
end


text:
"""
    @not_implemented(info)

Create a tangent that indicates that the derivative is not implemented.

The `info` should be useful information about the missing tangent for debugging.

!!! note
    This macro should be used only if the automatic differentiation would error
    otherwise. It is mostly useful if the function has multiple inputs or outputs,
    and one has worked out analytically and implemented some but not all tangents.

!!! note
    It is good practice to include a link to a GitHub issue about the missing
    tangent in the debugging information.
"""
macro not_implemented(info)
    return :(NotImplemented($__module__, $(QuoteNode(__source__)), $(esc(info))))
end

"""
    NotImplemented

This tangent indicates that the derivative is not implemented.

It is generally best to construct this using the [`@not_implemented`](@ref) macro,
which will automatically insert the source module and file location.
"""
struct NotImplemented <: AbstractTangent
    mod::Module
    source::LineNumberNode
    info::String
end

# required for `@scalar_rule`
# (together with `conj(x::AbstractTangent) = x` and the definitions in
# tangent_arithmetic.jl)
Base.Broadcast.broadcastable(x::NotImplemented) = Ref(x)

# throw error with debugging information for other standard information
# (`+`, `-`, `*`, and `dot` are defined in tangent_arithmetic.jl)
Base.:/(x::NotImplemented, ::Any) = throw(NotImplementedException(x))
Base.:/(::Any, x::NotImplemented) = throw(NotImplementedException(x))
Base.:/(x::NotImplemented, ::NotImplemented) = throw(NotImplementedException(x))

Base.zero(x::NotImplemented) = throw(NotImplementedException(x))
function Base.zero(::Type{<:NotImplemented})
    return throw(
        NotImplementedException(
            @not_implemented(
                "`zero` is not defined for missing tangents of type `NotImplemented`"
            )
        ),
    )
end

Base.iterate(x::NotImplemented) = throw(NotImplementedException(x))
Base.iterate(x::NotImplemented, ::Any) = throw(NotImplementedException(x))

Base.adjoint(x::NotImplemented) = throw(NotImplementedException(x))
Base.transpose(x::NotImplemented) = throw(NotImplementedException(x))

Base.convert(::Type{<:Number}, x::NotImplemented) = throw(NotImplementedException(x))

function Base.show(io::IO, x::NotImplemented)
    return print(io, "NotImplemented(", x.mod, ", ", x.source, ", ", x.info, ")")
end

struct NotImplementedException <: Exception
    mod::Module
    source::LineNumberNode
    info::String
end

function NotImplementedException(x::NotImplemented)
    return NotImplementedException(x.mod, x.source, x.info)
end

function Base.showerror(io::IO, e::NotImplementedException)
    print(io, "tangent not implemented @ ", e.mod, " ", e.source)
    if e.info !== nothing
        print(io, "\nInfo: ", e.info)
    end
    return nothing
end


text:
using DiffEqDevTools
import DiffEqDevTools: recursive_mean
import ConstrainedSystems: @unpack, _l2norm

dts = 1 ./ 2 .^(9:-1:5)
testTol = 0.2
const TOL = 1e-13

@inline compute_l2err(sol,t,sol_analytic) = _l2norm(sol-sol_analytic.(t))

function compute_error(solutions,idx,sol_analytic)
  l2err = [compute_l2err(_sol[idx,:],_sol.t,sol_analytic) for _sol in solutions]
  error = Dict(:l2 => l2err)
end

function compute𝒪est(solutions,idx,sol_analytic)
  #l2err = [compute_l2err(_sol[idx,:],_sol.t,sol_analytic) for _sol in solutions]
  #error = Dict(:l2 => l2err)
  error = compute_error(solutions,idx,sol_analytic)
  𝒪est = Dict((DiffEqDevTools.calc𝒪estimates(p) for p = pairs(error)))
end

@testset "Convergence test" begin

### In place ###

# Unconstrained
prob, xexact = ConstrainedSystems.basic_unconstrained_problem(iip=true)

# For now, do this quick and dirty until we figure out how to separate
# state from constraint in sol structure
solutions1 = [solve(prob,LiskaIFHERK();dt=dts[i]) for i=1:length(dts)]
solutions2 = [solve(prob,IFHEEuler();dt=dts[i]) for i=1:length(dts)]

𝒪est1 = compute𝒪est(solutions1,1,xexact)
𝒪est2 = compute𝒪est(solutions2,1,xexact)

@test 𝒪est1[:l2][1] ≈ 3 atol=testTol
@test 𝒪est2[:l2][1] ≈ 1 atol=testTol

# Unconstrained problem with only an integrating factor. Should achieve machine
# precision
prob, xexact = ConstrainedSystems.basic_unconstrained_if_problem(iip=true)

# For now, do this quick and dirty until we figure out how to separate
# state from constraint in sol structure
solutions1 = [solve(prob,LiskaIFHERK();dt=dts[i]) for i=1:length(dts)]
solutions2 = [solve(prob,IFHEEuler();dt=dts[i]) for i=1:length(dts)]

error1 = compute_error(solutions1,1,xexact)
error2 = compute_error(solutions2,1,xexact)
@test all(error1[:l2] .< TOL)
@test all(error2[:l2] .< TOL)

# Constrained
prob, xexact, yexact = ConstrainedSystems.basic_constrained_problem(iip=true)

# For now, do this quick and dirty until we figure out how to separate
# state from constraint in sol structure
solutions1 = [solve(prob,LiskaIFHERK();dt=dts[i]) for i=1:length(dts)]
solutions2 = [solve(prob,IFHEEuler();dt=dts[i]) for i=1:length(dts)]

𝒪est1 = compute𝒪est(solutions1,1,xexact)
𝒪est2 = compute𝒪est(solutions2,1,xexact)

@test 𝒪est1[:l2][1] ≈ 2 atol=testTol
@test 𝒪est2[:l2][1] ≈ 1 atol=testTol

prob, xexact, yexact = ConstrainedSystems.cartesian_pendulum_problem(iip=true)

solutions1 = [solve(prob,LiskaIFHERK();dt=dts[i]) for i=1:length(dts)]
solutions2 = [solve(prob,IFHEEuler();dt=dts[i]) for i=1:length(dts)]

𝒪est1 = compute𝒪est(solutions1,1,xexact)
𝒪est2 = compute𝒪est(solutions2,1,xexact)

@test 𝒪est1[:l2][1] ≈ 2 atol=testTol
@test 𝒪est2[:l2][1] ≈ 1 atol=testTol

prob, xexact, yexact = ConstrainedSystems.partitioned_problem(iip=true)

solutions1 = [solve(prob,LiskaIFHERK();dt=dts[i]) for i=1:length(dts)]
solutions2 = [solve(prob,IFHEEuler();dt=dts[i]) for i=1:length(dts)]

𝒪est1 = compute𝒪est(solutions1,1,xexact)
𝒪est2 = compute𝒪est(solutions2,1,xexact)

@test 𝒪est1[:l2][1] ≈ 2 atol=testTol
@test 𝒪est2[:l2][1] ≈ 1 atol=testTol

### out of place ###

# Unconstrained
prob, xexact = ConstrainedSystems.basic_unconstrained_problem(iip=false)

# For now, do this quick and dirty until we figure out how to separate
# state from constraint in sol structure
solutions1 = [solve(prob,LiskaIFHERK();dt=dts[i]) for i=1:length(dts)]
solutions2 = [solve(prob,IFHEEuler();dt=dts[i]) for i=1:length(dts)]

𝒪est1 = compute𝒪est(solutions1,1,xexact)
𝒪est2 = compute𝒪est(solutions2,1,xexact)

@test 𝒪est1[:l2][1] ≈ 3 atol=testTol
@test 𝒪est2[:l2][1] ≈ 1 atol=testTol

# Unconstrained problem with only an integrating factor. Should achieve machine
# precision
prob, xexact = ConstrainedSystems.basic_unconstrained_if_problem(iip=false)

# For now, do this quick and dirty until we figure out how to separate
# state from constraint in sol structure
solutions1 = [solve(prob,LiskaIFHERK();dt=dts[i]) for i=1:length(dts)]
solutions2 = [solve(prob,IFHEEuler();dt=dts[i]) for i=1:length(dts)]

error1 = compute_error(solutions1,1,xexact)
error2 = compute_error(solutions2,1,xexact)

@test all(error1[:l2] .< TOL)
@test all(error2[:l2] .< TOL)

# Constrained

prob, xexact, yexact = ConstrainedSystems.basic_constrained_problem(iip=false)

solutions1 = [solve(prob,LiskaIFHERK();dt=dts[i]) for i=1:length(dts)]
solutions2 = [solve(prob,IFHEEuler();dt=dts[i]) for i=1:length(dts)]

𝒪est1 = compute𝒪est(solutions1,1,xexact)
𝒪est2 = compute𝒪est(solutions2,1,xexact)

@test 𝒪est1[:l2][1] ≈ 2 atol=testTol
@test 𝒪est2[:l2][1] ≈ 1 atol=testTol

prob, xexact, yexact = ConstrainedSystems.cartesian_pendulum_problem(iip=false)

solutions1 = [solve(prob,LiskaIFHERK();dt=dts[i]) for i=1:length(dts)]
solutions2 = [solve(prob,IFHEEuler();dt=dts[i]) for i=1:length(dts)]

𝒪est1 = compute𝒪est(solutions1,1,xexact)
𝒪est2 = compute𝒪est(solutions2,1,xexact)

@test 𝒪est1[:l2][1] ≈ 2 atol=testTol
@test 𝒪est2[:l2][1] ≈ 1 atol=testTol

prob, xexact, yexact = ConstrainedSystems.partitioned_problem(iip=false)

solutions1 = [solve(prob,LiskaIFHERK();dt=dts[i]) for i=1:length(dts)]
solutions2 = [solve(prob,IFHEEuler();dt=dts[i]) for i=1:length(dts)]

𝒪est1 = compute𝒪est(solutions1,1,xexact)
𝒪est2 = compute𝒪est(solutions2,1,xexact)

@test 𝒪est1[:l2][1] ≈ 2 atol=testTol
@test 𝒪est2[:l2][1] ≈ 1 atol=testTol

end


text:
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
#  Niccolò Antonello <nantonel@idiap.ch>

function ChainRulesCore.rrule(::typeof(nlogML), Nt, a, A, y)
  alpha, c = forward(Nt,a,A,y)
  function nlogML_pullback(delta)
    grada, gradA, grady = get_grad(Nt,a,A,y,alpha,c)
    return NoTangent(), NoTangent(), grada, gradA, grady
  end
  return nlogML(Nt,c), nlogML_pullback
end

function ChainRulesCore.rrule(::typeof(nlogMLlog), Nt, a, A, y)
  alpha, logML = logforward(Nt,a,A,y)
  function nlogMLlog_pullback(delta)
    grada, gradA, grady = get_loggrad(Nt,a,A,y,alpha,logML)
    return NoTangent(), NoTangent(), grada, gradA, grady
  end
  return -sum(logML), nlogMLlog_pullback
end


text:
@eval function DataFrames.DataFrame(job_queue::Vector{Job})
    fs = $(fieldnames(Job))
    d = DataFrame()
    for f in fs
        d[!, f] = getfield.(job_queue, f)
    end
    select!(d, :state, :id, :name, :user, :ncpu, :mem, :create_time, :)
end

function queue(;all=false)
    global JOB_QUEUE
    global JOB_QUEUE_OK
    if all
        DataFrame([JOB_QUEUE..., JOB_QUEUE_OK...])
    else
        DataFrame(JOB_QUEUE)
    end
end
all_queue() = queue(all=true)

function queue(state::Symbol)
    if state == :all
        queue(all=true)
    elseif state in [QUEUING, RUNNING, DONE, FAILED, CANCELLED]
        q = queue(all=true)
        q[q.state .== state, :]
    elseif state == PAST
        DataFrame(JOB_QUEUE_OK)
    else
        queue(all=true)
        @warn "state::Symbol is omitted because it is not one of QUEUING, RUNNING, DONE, FAILED, CANCELLED, or :all."
    end
end
queue(id::Int64) = job_query(id)

@eval function Base.display(job::Job)
    fs = $(fieldnames(Job))
    fs_string = $(map(string, fieldnames(Job)))
    max_byte = $(maximum(length, map(string, fieldnames(Job))))
    println("Job:")
    for (i,f) in enumerate(fs)
        print("  ", f, " " ^ (max_byte - length(fs_string[i])), " → ")
        display(getfield(job, f))
    end
end

@eval function Base.Dict(job::Job)
    fs = $(fieldnames(Job))
    d = Dict{Symbol, Any}()
    for f in fs
        f === :task && continue
        d[f] = getfield(job, f)
    end
    d
end

#TODO: update new fields. Check compatibility with existing programs
function JSON.Writer.json(job::Job)
    """
    {"id":$(job.id),"state":"$(job.state)","name":"$(job.name)","user":"$(job.user)","ncpu":$(job.ncpu),"create_time":"$(job.create_time)","start_time":"$(job.start_time)","stop_time":"$(job.stop_time)","wall_time":"$(job.wall_time)","priority":$(job.priority),"stdout_file":"$(job.stdout_file)","stderr_file":"$(job.stderr_file)"}"""
end

function json_queue(;all=false)
    global JOB_QUEUE
    global JOB_QUEUE_OK
    res = "["
    if all
        if !isempty(JOB_QUEUE)
            res *= join(JOB_QUEUE .|> json, ",")
        end
        if !isempty(JOB_QUEUE_OK)
            if res[end] == '}'
                res *= ","
            end
            res *= join(JOB_QUEUE_OK .|> json, ",")
        end
    else
        if !isempty(JOB_QUEUE)
            res *= join(JOB_QUEUE .|> json, ",")
        end
    end
    res *= "]"
    return res
end


text:
mutable struct ins_t <: LCMType
    utime::Int64
    device_time::Int64

    gyro::SVector{3, Float64}
    mag::SVector{3, Float64}
    accel::SVector{3, Float64}
    quat::SVector{4, Float64}

    pressure::Float64
    rel_alt::Float64
end

@lcmtypesetup(ins_t)


text:
"""
    fpw(X, r)

ntrols the random number generator used for initialising the starting point of the optimisation.

# Example
```julia-repl
julia> X = spiraldata(300)
julia> mix = fpw(X, 0.05)
julia> x = rand(mix, 1000)'
julia> plot(X[:,1], X[:,2], "bo", label="data")
julia> plot(x[:,1], x[:,2], ".r", label="generated", alpha=0.7)
julia> legend()
```
"""
fpw(X, r, gamma = 1e-6) = fastparzenwindows(X, r, gamma)

function fastparzenwindows(X, r, gamma=1e-6)

  centres_ind = partition(X, r)

  Q, mu, C = softparzen(X, centres_ind, r, gamma)

  getmixturemodel(Q, mu, C)

end


text:
using SimpleDiffEq, StaticArrays, OrdinaryDiffEq, Test

function loop(u, p, t)
    @inbounds begin
        σ = p[1]; ρ = p[2]; β = p[3]
        du1 = σ*(u[2]-u[1])
        du2 = u[1]*(ρ-u[3]) - u[2]
        du3 = u[1]*u[2] - β*u[3]
        return SVector{3}(du1, du2, du3)
    end
end
function liip(du, u, p, t)
    σ = p[1]; ρ = p[2]; β = p[3]
    du[1] = σ*(u[2]-u[1])
    du[2] = u[1]*(ρ-u[3]) - u[2]
    du[3] = u[1]*u[2] - β*u[3]
    return nothing
end

u0 = 10ones(3)
dt = 0.01
oop = SimpleDiffEq.simpletsit5_init(loop, false, SVector{3}(u0), 0.0, dt, [10, 28, 8/3])
step!(oop)
for i in 1:10000;
    step!(oop);
    if isnan(oop.u[1]) || isnan(oop.u[2]) || isnan(oop.u[3])
        error("oop nan")
    end
end

iip = SimpleDiffEq.simpletsit5_init(liip, true, copy(u0), 0.0, dt, [10, 28, 8/3])
step!(iip)
for i in 1:10000;
    step!(iip);
    if isnan(iip.u[1]) || isnan(iip.u[2]) || isnan(iip.u[3])
        error("iip nan")
    end
end

u0 = 10ones(3)
dt = 0.01

odeoop = ODEProblem{false}(loop, SVector{3}(u0), (0.0, 100.0),  [10, 28, 8/3])
odeiip = ODEProblem{true}(liip, u0, (0.0, 100.0),  [10, 28, 8/3])

oop = init(odeoop,SimpleTsit5(),dt=dt)
step!(oop); step!(oop)

iip = init(odeiip,SimpleTsit5(),dt=dt)
step!(iip); step!(iip)

deoop = DiffEqBase.init(odeoop, Tsit5(); adaptive = false,
                        save_everystep = false, dt = dt)
step!(deoop); step!(deoop)
@test oop.u == deoop.u

deiip = DiffEqBase.init(odeiip, Tsit5();
                        adaptive = false, save_everystep = false,
                        dt = dt)
step!(deiip); step!(deiip)
@test iip.u ≈ deiip.u atol=1e-14

sol = solve(odeoop,SimpleTsit5(),dt=dt)

#=
using BenchmarkTools

function bench()
    u0 = 10ones(3)
    dt = 0.01

    oop = SimpleDiffEq.simpletsit5_init(loop, false, SVector{3}(u0), 0.0, dt, [10, 28, 8/3])
    step!(oop)

    iip = SimpleDiffEq.simpletsit5_init(liip, true, u0, 0.0, dt, [10, 28, 8/3])
    step!(iip)

    odeoop = ODEProblem{false}(loop, SVector{3}(u0), (0.0, Inf),  [10, 28, 8/3])
    deoop = DiffEqBase.init(odeoop, Tsit5();
    adaptive = false, save_everystep = false, dt = dt, maxiters = Inf)
    step!(deoop)

    odeiip = ODEProblem{true}(liip, u0, (0.0, Inf),  [10, 28, 8/3])
    deiip = DiffEqBase.init(odeiip, Tsit5();
    adaptive = false, save_everystep = false, dt = dt, maxiters = Inf)

    step!(deiip)

    println("Minimal integrator times")
    println("In-place time")
    @btime step!($iip)

    println("Out of place time")
    @btime step!($oop)

    println("Standard Tsit5 times")
    println("In-place time")
    @btime step!($deiip)

    println("Out of place time")
    @btime step!($deoop)

end

bench()

function bench_only_step()
  u0 = 10ones(3)
  dt = 0.01
  oop = SimpleDiffEq.simpletsit5_init(loop, false, SVector{3}(u0), 0.0, dt, [10, 28, 8/3])
  DiffEqBase.step!(oop)
  iip = SimpleDiffEq.simpletsit5_init(liip, true, u0, 0.0, dt, [10, 28, 8/3])
  DiffEqBase.step!(iip)
  odeoop = ODEProblem{false}(loop, SVector{3}(u0), (0.0, Inf),  [10, 28, 8/3])
  deoop = DiffEqBase.init(odeoop, Tsit5();
  adaptive = false, save_everystep = false, dt = dt, maxiters = Inf)
  DiffEqBase.step!(deoop)
  odeiip = ODEProblem{true}(liip, u0, (0.0, Inf),  [10, 28, 8/3])
  deiip = DiffEqBase.init(odeiip, Tsit5();
  adaptive = false, save_everystep = false, dt = dt, maxiters = Inf)
  DiffEqBase.step!(deiip)
  println("Only Step times")
  println("In-place time")
  @btime DiffEqBase.step!($iip)
  println("Out of place time")
  @btime DiffEqBase.step!($oop)
  println("Standard Tsit5 times")
  println("In-place time")
  @btime OrdinaryDiffEq.perform_step!($deiip,$(deiip.cache))
  println("Out of place time")
  @btime OrdinaryDiffEq.perform_step!($deoop,$(deoop.cache))
end
bench_only_step()
=#


text:
using ConstrainedDynamics
using LinearAlgebra
using StaticArrays

# Parameters
h = 0.06
r = 0.08
b1 = Cylinder(r*0.4, h, h*(r*0.4)^2*500, color = RGBA(0.8, 0.2, 0.))
b2 = Cylinder(r*0.8, h, h*(r*0.8)^2*500, color = RGBA(0.8, 0.2, 0.))
b3 = Cylinder(r, h, h*r^2*500, color = RGBA(0.8, 0.2, 0.))

# Links
origin = Origin{Float64}()
link1 = Body(b1)
link2 = Body(b2)
link3 = Body(b3)
link4 = Body(b2)
link5 = Body(b1)

# Constraints
joint1 = EqualityConstraint(Fixed(link2, link1; p1=-[0;0;0.03], p2=[0;0;0.03]))
joint2 = EqualityConstraint(Fixed(link3, link2; p1=-[0;0;0.03], p2=[0;0;0.03]))
joint3 = EqualityConstraint(Floating(origin, link3))
joint4 = EqualityConstraint(Fixed(link3, link4; p1=[0;0;0.03], p2=-[0;0;0.03]))
joint5 = EqualityConstraint(Fixed(link4, link5; p1=[0;0;0.03], p2=-[0;0;0.03]))
fr1 = InequalityConstraint(Friction(link1, [0;0;1.0], 0.6))
fr2 = InequalityConstraint(Friction(link2, [0;0;1.0], 0.6))
fr3 = InequalityConstraint(Friction(link3, [0;0;1.0], 0.6))
fr4 = InequalityConstraint(Friction(link4, [0;0;1.0], 0.6))
fr5 = InequalityConstraint(Friction(link5, [0;0;1.0], 0.6))

links = [link1;link2;link3;link4;link5]
constraints = [joint1;joint2;joint3;joint4;joint5]
fr = [fr1;fr2;fr3;fr4;fr5]
shapes = [b1;b2;b3]

mech = Mechanism(origin, links, constraints, fr, shapes = shapes)
setPosition!(link3,x = [0.;-10.0;1.5],q=UnitQuaternion(RotX(pi/2)))
setPosition!(link3,link2,Δx = -[0.;0.;0.03])
setPosition!(link2,link1,Δx = -[0.;0.;0.03])
setPosition!(link3,link4,Δx = [0.;0.;0.03])
setPosition!(link4,link5,Δx = [0.;0.;0.03])

spin = 0.35

function football_control!(mechanism, k)
    if k<25
        setForce!(link3, F = SA[0.;25.;25.] * 0, τ=spin*SA[0.2;0.2;1.] * 0)
    elseif k==40
        setForce!(link3, τ = SA[0.;0.3;0.] * 0)
    else
        setForce!(link3)
    end
    return
end


text:
@testset "properties" begin

@testset "topology" begin
    cubane = smilestomol("C12C3C4C1C1C4C3C12")
    @test smallestsssr(cubane)[4] == 4
    @test sssrcount(cubane)[6] == 3
    biphenyl = smilestomol("C1CCCCC1C1CCCCC1")
    @test isringatom(biphenyl)[6]
    @test isringatom(biphenyl)[7]
    @test !isringbond(biphenyl)[7]
end

@testset "elements" begin
    sodiumsulfate = smilestomol("O=S(=O)([O-])[O-].[Na+].[Na+]")
    @test atomsymbol(sodiumsulfate) == [:O, :S, :O, :O, :O, :Na, :Na]
    @test bondorder(sodiumsulfate) == [2, 2, 1, 1]
    @test charge(sodiumsulfate) == [0, 0, 0, -1, -1, 1, 1]
    @test nodedegree(sodiumsulfate) == [1, 4, 1, 1, 1, 0, 0]

    isocyanurate = smilestomol("ClN1C(=O)N(Cl)C(=O)N(Cl)C1=O")
    @test atomsymbol(isocyanurate) == [
        :Cl, :N, :C, :O, :N, :Cl, :C, :O, :N, :Cl, :C, :O]
    @test bondorder(isocyanurate) == [
        1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 2]
    @test all(charge(isocyanurate) .== 0)
    @test nodedegree(isocyanurate) == [1, 3, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1]
end

@testset "formula" begin
    hexose = smilestomol("OCC(O)C(O)C(O)C(O)C=O")
    @test molecularformula(hexose) == "C6H12O6"
    @test empiricalformula(hexose) == "CH2O"

    sulfalicacid = smilestomol("O=S(=O)(O)O")
    @test molecularformula(sulfalicacid) == "H2O4S"
    @test empiricalformula(sulfalicacid) == "H2O4S"

    order = smilestomol("[Na].[Ba].B.Br.B.[Ar].Br")
    @test molecularformula(order) == "ArB2BaBr2H8Na"
end

@testset "valence" begin
    atoms = smilestomol("B.C.N.O.F.[Si].P.S.Cl.[As].[Se].Br.I")
    @test valence(atoms) == [3, 4, 3, 2, 1, 4, 3, 2, 1, 3, 2, 1, 1]
    @test lonepair(atoms) == [-1, 0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 3]
    @test implicithconnected(atoms) == [3, 4, 3, 2, 1, 4, 3, 2, 1, 3, 2, 1, 1]

    pyridineoxide = smilestomol("[N+]1([O-])=CC=CC=C1")
    @test valence(pyridineoxide) == [4, 1, 4, 4, 4, 4, 4]
    @test lonepair(pyridineoxide) == [0, 3, 0, 0, 0, 0, 0]
    @test implicithconnected(pyridineoxide) == [0, 0, 1, 1, 1, 1, 1]

    trifluoroborate = smilestomol("C[B-](F)(F)F")
    @test valence(trifluoroborate) == [4, 4, 1, 1, 1]
    @test lonepair(trifluoroborate) == [0, 0, 3, 3, 3]
    @test implicithconnected(trifluoroborate) == [3, 0, 0, 0, 0]

    etmacl = smilestomol("[H]C([H])([H])C[Mg][Cl]")
    @test valence(etmacl) == [1, 4, 1, 1, 4, nothing, 1]
    @test lonepair(etmacl) == [0, 0, 0, 0, 0, nothing, 3]
    @test implicithconnected(etmacl) == [0, 0, 0, 0, 2, 0, 0]
    @test explicithconnected(etmacl) == [0, 3, 0, 0, 0, 0, 0]
    @test hydrogenconnected(etmacl) == [0, 3, 0, 0, 2, 0, 0]
    @test heavyatomconnected(etmacl) == [1, 1, 1, 1, 2, 2, 1]
    @test connectivity(etmacl) == [1, 4, 1, 1, 4, 2, 1]
end

@testset "hybridization" begin
    alkyne = smilestomol("CC=CC#C")
    @test pielectron(alkyne) == [0, 1, 1, 2, 2]
    @test hybridization(alkyne) == [:sp3, :sp2, :sp2, :sp, :sp]

    anilinium = smilestomol("C1=CC=CC=C1[N+]")
    @test pielectron(anilinium) == [1, 1, 1, 1, 1, 1, 0]
    @test hybridization(anilinium) == [:sp2, :sp2, :sp2, :sp2, :sp2, :sp2, :sp3]

    azide = smilestomol("CC(=O)N=[N+]=[N-]")
    @test pielectron(azide) == [0, 1, 1, 1, 2, 1]
    @test hybridization(azide) == [:sp3, :sp2, :sp2, :sp2, :sp, :sp2]

    pyrrole = smilestomol("C1=CC=CN1")
    @test pielectron(pyrrole) == [1, 1, 1, 1, 2]
    @test hybridization(pyrrole) == [:sp2, :sp2, :sp2, :sp2, :sp2]

    nacl = smilestomol("[Na+][Cl-]")
    @test pielectron(nacl) == [0, 0]
    @test hybridization(nacl) == [:none, :none]
end

@testset "rotatable" begin
    Phe = smilestomol("N[C@@H](CC1=CC=CC=C1)C(O)=O")
    @test rotatablecount(Phe) == 3
    KCl = smilestomol("[K+].[Cl-]")
    @test rotatablecount(KCl) == 0
    dipyridamole = smilestomol(
        "n3c(nc2c(nc(nc2N1CCCCC1)N(CCO)CCO)c3N4CCCCC4)N(CCO)CCO")
    @test rotatablecount(dipyridamole) == 12
    paclitaxel = smilestomol(
        "CC1=C2[C@@]([C@]([C@H]([C@@H]3[C@]4([C@H](OC4)C[C@@H]([C@]3(C(=O)[C@@H]2OC(=O)C)C)O)OC(=O)C)OC(=O)c5ccccc5)(C[C@@H]1OC(=O)[C@H](O)[C@@H](NC(=O)c6ccccc6)c7ccccc7)O)(C)C"
    )
    @test rotatablecount(paclitaxel) == 15
end

@testset "aromatic" begin
    phenol = smilestomol("C=1C=CC=CC=1O")  # not carbonyl O
    @test count(isaromatic(phenol)) == 6

    furan = smilestomol("o1cccc1")
    @test count(isaromatic(furan)) == 5

    quinone = smilestomol("C1(=O)C=CC(=O)C=C1")
    @test count(isaromatic(quinone)) == 0

    tropone = smilestomol("C1(=O)C=CC=CC=C1")
    @test count(isaromatic(tropone)) == 7

    azepine = smilestomol("N1C=CC=CC=C1")
    @test count(isaromatic(azepine)) == 0

    thiopheneoxide = smilestomol("C1=CC=CS1=O")
    @test count(isaromatic(thiopheneoxide)) == 0

    dihydroazaborine = smilestomol("C1=CC=CBN1")
    @test count(isaromatic(dihydroazaborine)) == 6

    fulvene = smilestomol("C1=CC=CC1=C")
    @test count(isaromatic(fulvene)) == 0

    cyclopropenyl = smilestomol("C1=C[C+]1")
    @test count(isaromatic(cyclopropenyl)) == 3

    hexatriene = smilestomol("C=CC=CC=C")
    @test count(isaromatic(hexatriene)) == 0

    borazine = smilestomol("B1NBNBN1")
    @test count(isaromatic(borazine)) == 6

    methylenedioxybenzene = smilestomol("C1=CC=CC2=C1OCO2")
    @test count(isaromatic(methylenedioxybenzene)) == 6

    naphthalene = smilestomol("C=1C=CC=C2C1C=CC=C2")
    @test count(isaromatic(naphthalene)) == 10

    coumarin = smilestomol("C1=CC(=O)OC2=C1C=CC=C2")
    @test count(isaromatic(coumarin)) == 10

    pyrene = smilestomol("C12=CC=C3C=CC=C4C=CC(C2=C34)=CC=C1")
    @test count(isaromatic(pyrene)) == 16

    caffeine = smilestomol("CN1C=NC2=C1C(=O)N(C)C(=O)N2C")
    @test count(isaromatic(caffeine)) == 9

    # Difficult aromaticities
    quinodimethane = smilestomol("C1=CC=CC(=C)C1=C")
    @test_broken count(isaromatic(azulene)) == 10

    dihydronaphthalene = smilestomol("C=1CCC=C2C1C=CC=C2")
    @test_broken count(isaromatic(dihydronaphthalene)) == 10

    azulene = smilestomol("C=1C=CC=2C1C=CC=CC2")
    @test_broken count(isaromatic(azulene)) == 10

    pyromellitimide = smilestomol("C1(=O)NC(=O)C=2C1=CC=3C(=O)NC(=O)C=3C=2")
    @test count(isaromatic(pyromellitimide)) == 6

    # TODO: how to deal with tautomerism
    isocyanurate = smilestomol("ClN1C(=O)N(Cl)C(=O)N(Cl)C1=O")
end

@testset "properties" begin
    amide = smilestomol("CCC(=O)N")
    @test hacceptorcount(amide) == 2
    @test hdonorcount(amide) == 1
    fluoro = smilestomol("CCN(CO)CF")
    @test hacceptorcount(fluoro) == 3
    @test hdonorcount(fluoro) == 1
end

end # properties


text:
A = ["John", "Bob", "Mary", "Serena"]
B = ["Jim", "Mary", "John", "Bob"]
@show A B symdiff(A, B)

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
include("pkggraph.jl")
include("../example/graph_stats.jl")


text:
export get_config

function get_config(filename::String)
    YAML.load_file(filename)
end


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

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

"""

Assess patches on the VM.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachineAssessPatchesResult
"""
function _swaggerinternal_virtualMachinesAssessPatches(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", VirtualMachineAssessPatchesResult, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/assessPatches", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesAssessPatches(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesAssessPatches(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesAssessPatches(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesAssessPatches(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Captures the VM by copying virtual hard disks of the VM and outputs a template that can be used to create similar VMs.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: parameters::VirtualMachineCaptureParameters (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachineCaptureResult
"""
function _swaggerinternal_virtualMachinesCapture(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", VirtualMachineCaptureResult, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/capture", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesCapture(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesCapture(_api, resourceGroupName, vmName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesCapture(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesCapture(_api, resourceGroupName, vmName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Converts virtual machine disks from blob-based to managed disks. Virtual machine must be stop-deallocated before invoking this operation.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualMachinesConvertToManagedDisks(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/convertToManagedDisks", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesConvertToManagedDisks(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesConvertToManagedDisks(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesConvertToManagedDisks(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesConvertToManagedDisks(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: parameters::VirtualMachine (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachine
"""
function _swaggerinternal_virtualMachinesCreateOrUpdate(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PUT", VirtualMachine, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesCreateOrUpdate(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesCreateOrUpdate(_api, resourceGroupName, vmName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesCreateOrUpdate(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesCreateOrUpdate(_api, resourceGroupName, vmName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Shuts down the virtual machine and releases the compute resources. You are not billed for the compute resources that this virtual machine uses.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualMachinesDeallocate(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/deallocate", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesDeallocate(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesDeallocate(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesDeallocate(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesDeallocate(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The operation to delete a virtual machine.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualMachinesDelete(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesDelete(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesDelete(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesDelete(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesDelete(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Sets the OS state of the virtual machine to generalized. It is recommended to sysprep the virtual machine before performing this operation.
For Windows, please refer to [Create a managed image of a generalized VM in Azure](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/capture-image-resource).
For Linux, please refer to [How to create an image of a virtual machine or VHD](https://docs.microsoft.com/en-us/azure/virtual-machines/linux/capture-image).
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualMachinesGeneralize(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/generalize", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesGeneralize(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesGeneralize(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesGeneralize(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesGeneralize(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Retrieves information about the model view or the instance view of a virtual machine.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Param: expand::String
Return: VirtualMachine
"""
function _swaggerinternal_virtualMachinesGet(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; expand=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualMachine, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "\$expand", expand)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesGet(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; expand=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesGet(_api, resourceGroupName, vmName, api_version, subscriptionId; expand=expand, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesGet(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; expand=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesGet(_api, resourceGroupName, vmName, api_version, subscriptionId; expand=expand, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Retrieves information about the run-time state of a virtual machine.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachineInstanceView
"""
function _swaggerinternal_virtualMachinesInstanceView(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualMachineInstanceView, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/instanceView", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesInstanceView(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesInstanceView(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesInstanceView(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesInstanceView(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Lists all of the virtual machines in the specified resource group. Use the nextLink property in the response to get the next page of virtual machines.
Param: resourceGroupName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachineListResult
"""
function _swaggerinternal_virtualMachinesList(_api::VirtualMachinesApi, resourceGroupName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualMachineListResult, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesList(_api::VirtualMachinesApi, resourceGroupName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesList(_api, resourceGroupName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesList(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesList(_api, resourceGroupName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Lists all of the virtual machines in the specified subscription. Use the nextLink property in the response to get the next page of virtual machines.
Param: api_version::String (required)
Param: subscriptionId::String (required)
Param: statusOnly::String
Return: VirtualMachineListResult
"""
function _swaggerinternal_virtualMachinesListAll(_api::VirtualMachinesApi, api_version::String, subscriptionId::String; statusOnly=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualMachineListResult, "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachines", ["azure_auth"])
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_param(_ctx.query, "statusOnly", statusOnly)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesListAll(_api::VirtualMachinesApi, api_version::String, subscriptionId::String; statusOnly=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesListAll(_api, api_version, subscriptionId; statusOnly=statusOnly, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesListAll(_api::VirtualMachinesApi, response_stream::Channel, api_version::String, subscriptionId::String; statusOnly=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesListAll(_api, api_version, subscriptionId; statusOnly=statusOnly, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Lists all available virtual machine sizes to which the specified virtual machine can be resized.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachineSizeListResult
"""
function _swaggerinternal_virtualMachinesListAvailableSizes(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualMachineSizeListResult, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/vmSizes", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesListAvailableSizes(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesListAvailableSizes(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesListAvailableSizes(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesListAvailableSizes(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Gets all the virtual machines under the specified subscription for the specified location.
Param: location::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachineListResult
"""
function _swaggerinternal_virtualMachinesListByLocation(_api::VirtualMachinesApi, location::String, api_version::String, subscriptionId::String; _mediaType=nothing)

    _ctx = Swagger.Ctx(_api.client, "GET", VirtualMachineListResult, "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/virtualMachines", ["azure_auth"])
    Swagger.set_param(_ctx.path, "location", location)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesListByLocation(_api::VirtualMachinesApi, location::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesListByLocation(_api, location, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesListByLocation(_api::VirtualMachinesApi, response_stream::Channel, location::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesListByLocation(_api, location, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The operation to perform maintenance on a virtual machine.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualMachinesPerformMaintenance(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/performMaintenance", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesPerformMaintenance(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesPerformMaintenance(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesPerformMaintenance(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesPerformMaintenance(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The operation to power off (stop) a virtual machine. The virtual machine can be restarted with the same provisioned resources. You are still charged for this virtual machine.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Param: skipShutdown::Bool
Return: Nothing
"""
function _swaggerinternal_virtualMachinesPowerOff(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; skipShutdown=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/powerOff", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "skipShutdown", skipShutdown)  # type Bool
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesPowerOff(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; skipShutdown=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesPowerOff(_api, resourceGroupName, vmName, api_version, subscriptionId; skipShutdown=skipShutdown, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesPowerOff(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; skipShutdown=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesPowerOff(_api, resourceGroupName, vmName, api_version, subscriptionId; skipShutdown=skipShutdown, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The operation to reapply a virtual machine's state.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualMachinesReapply(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/reapply", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesReapply(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesReapply(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesReapply(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesReapply(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Shuts down the virtual machine, moves it to a new node, and powers it back on.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualMachinesRedeploy(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/redeploy", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesRedeploy(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesRedeploy(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesRedeploy(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesRedeploy(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

Reimages the virtual machine which has an ephemeral OS disk back to its initial state.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Param: parameters::VirtualMachineReimageParameters
Return: Nothing
"""
function _swaggerinternal_virtualMachinesReimage(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; parameters=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/reimage", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesReimage(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; parameters=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesReimage(_api, resourceGroupName, vmName, api_version, subscriptionId; parameters=parameters, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesReimage(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; parameters=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesReimage(_api, resourceGroupName, vmName, api_version, subscriptionId; parameters=parameters, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The operation to restart a virtual machine.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualMachinesRestart(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/restart", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesRestart(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesRestart(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesRestart(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesRestart(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The operation to retrieve SAS URIs for a virtual machine's boot diagnostic logs.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Param: sasUriExpirationTimeInMinutes::Int32
Return: RetrieveBootDiagnosticsDataResult
"""
function _swaggerinternal_virtualMachinesRetrieveBootDiagnosticsData(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; sasUriExpirationTimeInMinutes=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", RetrieveBootDiagnosticsDataResult, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/retrieveBootDiagnosticsData", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "sasUriExpirationTimeInMinutes", sasUriExpirationTimeInMinutes)  # type Int32
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesRetrieveBootDiagnosticsData(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; sasUriExpirationTimeInMinutes=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesRetrieveBootDiagnosticsData(_api, resourceGroupName, vmName, api_version, subscriptionId; sasUriExpirationTimeInMinutes=sasUriExpirationTimeInMinutes, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesRetrieveBootDiagnosticsData(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; sasUriExpirationTimeInMinutes=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesRetrieveBootDiagnosticsData(_api, resourceGroupName, vmName, api_version, subscriptionId; sasUriExpirationTimeInMinutes=sasUriExpirationTimeInMinutes, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The operation to simulate the eviction of spot virtual machine. The eviction will occur within 30 minutes of calling the API
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualMachinesSimulateEviction(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/simulateEviction", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesSimulateEviction(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesSimulateEviction(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesSimulateEviction(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesSimulateEviction(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The operation to start a virtual machine.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: Nothing
"""
function _swaggerinternal_virtualMachinesStart(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", Nothing, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/start", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesStart(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesStart(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesStart(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesStart(_api, resourceGroupName, vmName, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

"""

The operation to update a virtual machine.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: parameters::VirtualMachineUpdate (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachine
"""
function _swaggerinternal_virtualMachinesUpdate(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PATCH", VirtualMachine, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", ["azure_auth"], parameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    return _ctx
end

function virtualMachinesUpdate(_api::VirtualMachinesApi, resourceGroupName::String, vmName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesUpdate(_api, resourceGroupName, vmName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function virtualMachinesUpdate(_api::VirtualMachinesApi, response_stream::Channel, resourceGroupName::String, vmName::String, parameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = _swaggerinternal_virtualMachinesUpdate(_api, resourceGroupName, vmName, parameters, api_version, subscriptionId; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

export virtualMachinesAssessPatches, virtualMachinesCapture, virtualMachinesConvertToManagedDisks, virtualMachinesCreateOrUpdate, virtualMachinesDeallocate, virtualMachinesDelete, virtualMachinesGeneralize, virtualMachinesGet, virtualMachinesInstanceView, virtualMachinesList, virtualMachinesListAll, virtualMachinesListAvailableSizes, virtualMachinesListByLocation, virtualMachinesPerformMaintenance, virtualMachinesPowerOff, virtualMachinesReapply, virtualMachinesRedeploy, virtualMachinesReimage, virtualMachinesRestart, virtualMachinesRetrieveBootDiagnosticsData, virtualMachinesSimulateEviction, virtualMachinesStart, virtualMachinesUpdate


text:
using .APIUtils

using CEnum: @cenum

using Printf

import Libdl

const _libcuda = Ref{String}()
function libcuda()
    if !isassigned(_libcuda)
        if Sys.iswindows()
            _libcuda[] = "nvcuda"
        else
            _libcuda[] = Libdl.find_library(["libcuda.so.1", "libcuda.so"])
            if isempty(_libcuda[])
                error("""Could not find the CUDA driver library 'libcuda.so'. Please make sure you have installed the NVIDIA driver for your GPU.
                         If you're sure it's installed, look for `libcuda.so` in your system and make sure it's discoverable by the dynamic linker.
                         Typically, that involves an entry in '/etc/ld.so.conf', or setting LD_LIBRARY_PATH.""")
            end
        end
    end

    # memoized because otherwise each ccall would perform discovery again
    _libcuda[]
end

# low-level wrappers
const CUdeviceptr = CuPtr{Cvoid}
const CUarray = CuArrayPtr{Cvoid}
const GLuint = Cuint    # FIXME: get these from somewhere
const GLenum = Cuint
include("libcuda_common.jl")
include("error.jl")
include("libcuda.jl")
include("libcuda_deprecated.jl")

# high-level wrappers
include("types.jl")
include("version.jl")
include("devices.jl")
include("context.jl")
include("stream.jl")
include("pool.jl")
include("memory.jl")
include("module.jl")
include("events.jl")
include("execution.jl")
include("profile.jl")
include("occupancy.jl")
include("graph.jl")

# TODO: figure out if these wrappers may use the runtime-esque state (stream(), context()).
#       it's inconsitent now: @finalize_in_ctx doesn't, memory.jl does use stream(), etc.


text:
#=
# Format specific functions for writing data output files.
=#

function output_values_raw(vars, file)
    # do one variable/component at a time
    if typeof(vars) <: Array
        for vi=1:length(vars) # each variable
            output_values_raw(vars[vi], file);
        end
    else
        # Here vars is just one variable
        N = size(vars.values, 2); # number of points
        for ci=1:size(vars.values,1) # each component for that variable
            file.write(vars.values[ci,:]); # write the values
        end
    end

end

function output_values_csv(vars, file)
    # columns will be like x, y, z, u1,...
    if typeof(vars) <: Array
        N = size(vars[1].values, 2); # number of points (must be same for all vars)
        if vars[1].location == CELL
            x = fv_info.cellCenters;
        else
            x = grid_data.allnodes;
        end

        # header
        line = "x";
        if dim > 1
            line *= ", y";
        end
        if dim > 2
            line *= ", z";
        end
        for vi=1:length(vars) # each variable
            if size(vars[vi].values,1) > 1
                for ci=1:size(vars[vi].values,1)
                    line *= ", "*string(vars[vi].symbol)*"_"*string(ci);
                end
            else
                line *= ", "*string(vars[vi].symbol);
            end
        end
        println(file, line);

        # data
        for i=1:N
            # x, y, z
            line = string(x[1,i]);
            if dim > 1
                line *= ", "*string(x[2,i]);
            end
            if dim > 2
                line *= ", "*string(x[3,i]);
            end

            # u1, u2, ...
            for vi=1:length(vars) # each variable
                for ci=1:size(vars[vi].values,1)
                    line *= ", "*string(vars[vi].values[ci,i]);
                end
            end
            println(file, line);
        end

    else
        N = size(vars.values, 2); # number of points
        if vars.location == CELL
            x = fv_info.cellCenters;
        else
            x = grid_data.allnodes;
        end
        dim = size(x,1);

        # header
        line = "x";
        if dim > 1
            line *= ", y";
        end
        if dim > 2
            line *= ", z";
        end
        if size(vars.values,1) > 1
            for ci=1:size(vars.values,1)
                line *= ", "*string(vars.symbol)*"_"*string(ci);
            end
        else
            line *= ", "*string(vars.symbol);
        end
        println(file, line);

        # data
        for i=1:N
            # x, y, z
            line = string(x[1,i]);
            if dim > 1
                line *= ", "*string(x[2,i]);
            end
            if dim > 2
                line *= ", "*string(x[3,i]);
            end

            # u1, u2, ...
            for ci=1:size(vars.values,1)
                line *= ", "*string(vars.values[ci,i]);
            end
            println(file, line);
        end
    end
end

function output_values_vtk(vars, file, ascii)
    # Use the WriteVTK package.
    # First build MeshCell array
    nel = size(grid_data.loc2glb,2);
    if config.dimension == 1
        np_to_type = Dict([(2,3)]); # line
    elseif config.dimension == 2
        np_to_type = Dict([(3,5),(4,9)]); # triangle, quad
    else
        np_to_type = Dict([(4,10),(8,12)]); # tet, hex
    end

    cells = Array{WriteVTK.MeshCell,1}(undef, nel);
    for ei=1:nel
        nvertex = 0;
        for vi=1:length(grid_data.glbvertex[:,ei])
            if grid_data.glbvertex[vi,ei] > 0
                nvertex = nvertex+1;
            else
                break;
            end
        end
        if nvertex < 2
            printerr("Found element with too few vertices when writing VTK output: el="*string(ei)*", vertexmap="*string(grid_data.glbvertex[:,ei]));
            return;
        end
        cell_type = np_to_type[nvertex];
        cells[ei] = WriteVTK.MeshCell(VTKCellType(cell_type), grid_data.glbvertex[:,ei]);
    end

    # Initialize the file
    vtkfile = vtk_grid(file, grid_data.allnodes, cells, ascii=ascii);

    # Add values
    if typeof(vars) <: Array
        for vi=1:length(vars)
            if length(vars[vi].symvar) > 1
                for ci=1:length(vars[vi].symvar)
                    compname = string(vars[vi].symbol) * "_" * string(ci);
                    vtkfile[compname] = vars[vi].values[ci,:];
                end
            else
                vtkfile[string(vars[vi].symbol)] = vars[vi].values;
            end
        end
    else
        if length(vars.symvar) > 1
            for ci=1:length(vars.symvar)
                compname = string(vars.symbol) * "_" * string(ci);
                vtkfile[compname] = vars.values[ci,:];
            end
        else
            vtkfile[string(vars.symbol)] = vars.values;
        end
    end

    return vtk_save(vtkfile);
end


text:
# Unit test functions
function unit_test_rmheap_empty()
    r = RMHeap{Int}()
    @test r.N == 0

    return nothing
end

function unit_test_rmheap_empty_isheap()
    r = RMHeap{Int}()
    @test isheap(r)

    return nothing
end

function unit_test_rmheap_add()
    r = RMHeap{Int}()
    val1 = 1
    val2 = 2
    val3 = 3
    val4 = 4
    val5 = 5
    add!(r, val1)
    add!(r, val2)
    @test r.root.key == val1
    @test r.root.right.key == val2

    return nothing
end

function unit_test_rmheap_remove()
    n = 10^4
    r = RMHeap{Int}()

    @time for i = 1:n
        add!(r, i)
    end

    remove!(r)

    return true
end

function unit_test_minpq_size()
    r = RMHeap{Int}()
    @test size(r) == 0
    val1 = 5
    val2 = 4
    add!(r, val1)
    @test size(r) == 1
    add!(r, val2)
    @test size(r) == 2

    remove!(r)
    @test size(r) == 1

    remove!(r)
    @test size(r) == 0

    return nothing
end

function unit_test_minpq_getmin()
    r = RMHeap{Int}()
    val1 = 5
    val2 = 4
    val3 = 3
    val4 = 2
    val5 = 1
    add!(r, val1)
    add!(r, val2)
    add!(r, val3)
    add!(r, val4)
    add!(r, val5)

    @test getmin(r) == 1

    return nothing
end

function unit_test_minpq_isempty()
    r = RMHeap{Int}()
    @test isempty(r)
    val1 = 5
    add!(r, val1)
    @test isempty(r) == false

    return nothing
end

function unit_test_rmheap_example()
    n = 10^3
    r = RMHeap{Int}()

    for i in shuffle(1:n)
        add!(r, i)
        @test isheap(r)
    end

    for i in 1:n
        @test getmin(r) == i
        @test remove!(r) == i
        @test isheap(r)
    end
    @test isempty(r)

    return nothing
end

function unit_test_rmheap_empty_isheap()
    r = RMHeap{Int}()
    @test isheap(r)

    return nothing
end

function unit_test_minpq_empty()
    r = MinPQ{Int}()
    @test r.N == 0

    return nothing
end

function unit_test_minpq_empty_isheap()
    r = MinPQ{Int}()
    @test isheap(r)

    return nothing
end

function unit_test_minpq_add()
    r = MinPQ{Int}()
    val1 = 1
    val2 = 2
    val3 = 3
    val4 = 4
    val5 = 5
    add!(r, val5)
    @test isheap(r)
    add!(r, val4)
    @test isheap(r)
    add!(r, val3)
    @test isheap(r)
    add!(r, val2)
    @test isheap(r)
    add!(r, val1)
    @test isheap(r)
    @test r.root[1] == val1
    @test r.root[2] == val2
    @test r.root[3] == val4
    @test r.root[4] == val5
    @test r.root[5] == val3

    return nothing
end

function unit_test_minpq_greater()
    r = MinPQ{Int}()
    val1 = 1
    val2 = 2
    val3 = 3
    val4 = 4
    val5 = 5
    add!(r, val5)
    add!(r, val4)
    add!(r, val3)
    add!(r, val2)
    add!(r, val1)
    @test greater(r, 2, 1)
    @test greater(r, 1, 2) == false

    return nothing
end

function unit_test_minpq_remove()
    r = MinPQ{Int}()
    val1 = 1
    val2 = 2
    val3 = 3
    val4 = 4
    val5 = 5
    add!(r, val5)
    add!(r, val4)
    add!(r, val3)
    add!(r, val2)
    add!(r, val1)

    @test remove!(r) == val1
    @test isheap(r)
    @test r.root[1] == val2
    @test r.root[2] == val3
    @test r.root[3] == val4
    @test r.root[4] == val5

    @test remove!(r) == val2
    @test isheap(r)
    @test r.root[1] == val3
    @test r.root[2] == val5
    @test r.root[3] == val4

    @test remove!(r) == val3
    @test isheap(r)
    @test r.root[1] == val4
    @test r.root[2] == val5

    @test remove!(r) == val4
    @test isheap(r)
    @test r.root[1] == val5

    @test remove!(r) == val5
    @test isheap(r)

    @test remove!(r) === nothing
    @test isempty(r)
    @test isheap(r)

    return nothing
end

function unit_test_minpq_size()
    r = MinPQ{Int}()
    @test size(r) == 0
    val1 = 5
    val2 = 4
    add!(r, val1)
    @test size(r) == 1
    add!(r, val2)
    @test size(r) == 2

    remove!(r)
    @test size(r) == 1

    remove!(r)
    @test size(r) == 0

    return nothing
end

function unit_test_minpq_getmin()
    r = MinPQ{Int}()
    val1 = 5
    val2 = 4
    val3 = 3
    val4 = 2
    val5 = 1
    add!(r, val1)
    add!(r, val2)
    add!(r, val3)
    add!(r, val4)
    add!(r, val5)

    @test getmin(r) == 1

    return nothing
end

function unit_test_minpq_isempty()
    r = MinPQ{Int}()
    @test isempty(r)
    val1 = 5
    add!(r, val1)
    @test isempty(r) == false

    return nothing
end

function unit_test_minpq_example()
    n = 10^3
    r = MinPQ{Int}()

    for i in shuffle(1:n)
        add!(r, i)
        @test isheap(r)
    end

    for i in 1:n
        @test getmin(r) == i
        @test remove!(r) == i
        @test isheap(r)
    end
    @test isempty(r)

    return nothing
end

# Run the unit tests
@testset "Randomised meldable heaps" begin
    unit_test_rmheap_empty()
    unit_test_rmheap_empty_isheap()
    #unit_test_minpq_add() # bit harder, random
    #unit_test_minpq_remove() # bit harder, random
end

@testset "Minimum priority queue   " begin
    #unit_test_minpq_sink()
    #unit_test_minpq_swim()
end


text:
#Import Turing, Distributions and DataFrames
using Turing, Distributions, DataFrames, Distributed

# Import MCMCChain, Plots, and StatsPlots for visualizations and diagnostics.
using MCMCChains, Plots, StatsPlots

# Set a seed for reproducibility.
using Random
Random.seed!(12);

# Turn off progress monitor.
Turing.setprogress!(false)

theta_noalcohol_meds = 1    # no alcohol, took medicine
theta_alcohol_meds = 3      # alcohol, took medicine
theta_noalcohol_nomeds = 6  # no alcohol, no medicine
theta_alcohol_nomeds = 36   # alcohol, no medicine

# no of samples for each of the above cases
q = 100

#Generate data from different Poisson distributions
noalcohol_meds = Poisson(theta_noalcohol_meds)
alcohol_meds = Poisson(theta_alcohol_meds)
noalcohol_nomeds = Poisson(theta_noalcohol_nomeds)
alcohol_nomeds = Poisson(theta_alcohol_nomeds)

nsneeze_data = vcat(rand(noalcohol_meds, q), rand(alcohol_meds, q), rand(noalcohol_nomeds, q), rand(alcohol_nomeds, q) )
alcohol_data = vcat(zeros(q), ones(q), zeros(q), ones(q) )
meds_data = vcat(zeros(q), zeros(q), ones(q), ones(q) )

df = DataFrame(nsneeze = nsneeze_data, alcohol_taken = alcohol_data, nomeds_taken = meds_data, product_alcohol_meds = meds_data.*alcohol_data)
df[sample(1:nrow(df), 5, replace = false), :]

#Data Plotting

p1 = Plots.histogram(df[(df[:,:alcohol_taken] .== 0) .& (df[:,:nomeds_taken] .== 0), 1], title = "no_alcohol+meds")
p2 = Plots.histogram((df[(df[:,:alcohol_taken] .== 1) .& (df[:,:nomeds_taken] .== 0), 1]), title = "alcohol+meds")
p3 = Plots.histogram((df[(df[:,:alcohol_taken] .== 0) .& (df[:,:nomeds_taken] .== 1), 1]), title = "no_alcohol+no_meds")
p4 = Plots.histogram((df[(df[:,:alcohol_taken] .== 1) .& (df[:,:nomeds_taken] .== 1), 1]), title = "alcohol+no_meds")
plot(p1, p2, p3, p4, layout = (2, 2), legend = false)

# Convert the DataFrame object to matrices.
data = Matrix(df[:,[:alcohol_taken, :nomeds_taken, :product_alcohol_meds]])
data_labels = df[:,:nsneeze]
data

# # Rescale our matrices.
data = (data .- mean(data, dims=1)) ./ std(data, dims=1)

# Bayesian poisson regression (LR)
@model poisson_regression(x, y, n, σ²) = begin
    b0 ~ Normal(0, σ²)
    b1 ~ Normal(0, σ²)
    b2 ~ Normal(0, σ²)
    b3  ~ Normal(0, σ²)
    for i = 1:n
        theta = b0 + b1*x[i, 1] + b2*x[i,2] + b3*x[i,3]
        y[i] ~ Poisson(exp(theta))
    end
end;

# Retrieve the number of observations.
n, _ = size(data)

# Sample using NUTS.

num_chains = 4
chain = mapreduce(
    c -> sample(poisson_regression(data, data_labels, n, 10), NUTS(200, 0.65), 2500, discard_adapt=false),
    chainscat,
    1:num_chains);

gelmandiag(chain)

# Taking the first chain
c1 = chain[:,:,1]

# Calculating the exponentiated means
b0_exp = exp(mean(c1[:b0]))
b1_exp = exp(mean(c1[:b1]))
b2_exp = exp(mean(c1[:b2]))
b3_exp = exp(mean(c1[:b3]))

print("The exponent of the meaned values of the weights (or coefficients are): \n")
print("b0: ", b0_exp, " \n", "b1: ", b1_exp, " \n", "b2: ", b2_exp, " \n", "b3: ", b3_exp, " \n")
print("The posterior distributions obtained after sampling can be visualised as :\n")

plot(chain)

# Note the standard deviation before removing the warmup samples
describe(chain)

# Removing the first 200 values of the chains.
chains_new = chain[201:2500,:,:]
describe(chains_new)

plot(chains_new)

if isdefined(Main, :TuringTutorials)
    Main.TuringTutorials.tutorial_footer(WEAVE_ARGS[:folder], WEAVE_ARGS[:file])
end

max_stars_repo_name: leachim/TuringTutorials

max_issues_repo_name: leachim/TuringTutorials

max_forks_repo_name: leachim/TuringTutorials


text:
# ------------------------------------------------------------------
# Licensed under the ISC License. See LICENCE in the project root.
# ------------------------------------------------------------------

"""
    Record(states)

A geological record of geological `states`.
"""
struct Record{S<:State}
  states::Vector{S}
end

Base.getindex(record::Record, ind) = getindex(record.states, ind)
Base.length(record::Record) = length(record.states)
Base.push!(record::Record, state) = push!(record.states, state)
Base.iterate(record::Record, state=1) = iterate(record.states, state)