text:
using Test
using Random
using PyCall
using HMMBase
using Distributions

np = pyimport("numpy")
pyhsmm = pyimport("pyhsmm")
pyhsmmi = pyimport("pyhsmm.internals.hmm_messages_interface")

Random.seed!(2019)

function rand_hmm(K)
    A = randtransmat(K)
    B = [Normal(rand() * 100, rand() * 10) for _ = 1:K]
    HMM(A, B)
end

@testset "Messages #$k" for k = 2:10
    hmm = rand_hmm(k)
    y = rand(hmm, 2500)
    LL = likelihoods(hmm, y, logl = true)

    ref = pyhsmm.internals.hmm_states.HMMStatesPython._messages_forwards_normalized(
        hmm.A,
        hmm.a,
        LL,
    )
    res = forward(hmm.a, hmm.A, LL, logl = true)

    @test all(res[1] .≈ ref[1])
    @test res[2] ≈ ref[2]

    ref = pyhsmm.internals.hmm_states.HMMStatesPython._messages_backwards_normalized(
        hmm.A,
        hmm.a,
        LL,
    )
    res = backward(hmm.a, hmm.A, LL, logl = true)

    @test all(res[1] .≈ ref[1])
    @test res[2] ≈ ref[2]
end

@testset "Viterbi #$k" for k = 2:10
    hmm = rand_hmm(k)
    y = rand(hmm, 2500)

    L = likelihoods(hmm, y)
    LL = likelihoods(hmm, y, logl = true)

    ref = pyhsmmi.viterbi(
        PyReverseDims(permutedims(hmm.A)),
        PyReverseDims(permutedims(LL)),
        hmm.a,
        zeros(Int32, size(LL, 1)),
    )

    res1 = viterbi(hmm.a, hmm.A, L, logl = false)
    res2 = viterbi(hmm.a, hmm.A, LL)

    # Python indices are off by 1
    @test res1 == (ref .+ 1)
    @test res2 == (ref .+ 1)
end


text:
module Helpers

export @abstractmethod
export @notimplemented
export @notimplementedif
export @unreachable

macro abstractmethod()
  quote
    error("This function belongs to an interface definition and cannot be used.")
  end
end

macro notimplemented()
  quote
    error("This function is not yet implemented")
  end
end

macro notimplementedif(condition)
  quote
    if $(esc(condition))
      @notimplemented
    end
  end
end

macro unreachable()
  quote
    error("This line of code cannot be reached")
  end
end

end # module Helpers

ext: jl


text:
using ClimateMachine
using ClimateMachine.Atmos
using ClimateMachine.BalanceLaws
using ClimateMachine.ConfigTypes
using ClimateMachine.DGMethods
using ClimateMachine.DGMethods.NumericalFluxes
using ClimateMachine.GenericCallbacks
using ClimateMachine.Mesh.Geometry
using ClimateMachine.Mesh.Grids
using ClimateMachine.Mesh.Topologies
using ClimateMachine.MPIStateArrays
using ClimateMachine.ODESolvers
using ClimateMachine.Orientations
using ClimateMachine.SystemSolvers
using Thermodynamics
using ClimateMachine.TurbulenceClosures
using Thermodynamics.TemperatureProfiles
using ClimateMachine.VariableTemplates
using ClimateMachine.VTK

using CLIMAParameters
using CLIMAParameters.Planet: kappa_d
struct EarthParameterSet <: AbstractEarthParameterSet end
const param_set = EarthParameterSet()

using MPI, Logging, StaticArrays, LinearAlgebra, Printf, Dates, Test

include("isentropicvortex_setup.jl")

if !@isdefined integration_testing
    const integration_testing = parse(
        Bool,
        lowercase(get(ENV, "JULIA_CLIMA_INTEGRATION_TESTING", "false")),
    )
end

const output_vtk = false

function main()
    ClimateMachine.init(parse_clargs = true)
    ArrayType = ClimateMachine.array_type()

    mpicomm = MPI.COMM_WORLD

    polynomialorder = 4
    numlevels = integration_testing ? 4 : 4

    expected_error = Dict()

    # just to make it shorter and aligning
    LMARS = LMARSNumericalFlux()

    @testset "$(@__FILE__)" begin
        for FT in (Float64,), dims in (2, 3), polynomialorder in (4,)
            for NumericalFlux in (LMARS,)
                @info @sprintf """Configuration
                                  ArrayType     = %s
                                  FT        = %s
                                  NumericalFlux = %s
                                  dims          = %d
                                  N_poly        = %d
                                  """ ArrayType "$FT" "$NumericalFlux" dims polynomialorder

                setup = IsentropicVortexSetup{FT}()
                errors = Vector{FT}(undef, numlevels)

                for level in 1:numlevels
                    numelems =
                        ntuple(dim -> dim == 3 ? 1 : 2^(level - 1) * 5, dims)
                    errors[level] = test_run(
                        mpicomm,
                        ArrayType,
                        polynomialorder,
                        numelems,
                        NumericalFlux,
                        setup,
                        FT,
                        dims,
                        level,
                    )

                    @test isapprox(errors[level], FT(1.0); rtol = 1e-5)

                end

            end
        end
    end
end

function test_run(
    mpicomm,
    ArrayType,
    polynomialorder,
    numelems,
    NumericalFlux,
    setup,
    FT,
    dims,
    level,
)
    brickrange = ntuple(dims) do dim
        range(
            -setup.domain_halflength;
            length = numelems[dim] + 1,
            stop = setup.domain_halflength,
        )
    end

    topology = BrickTopology(
        mpicomm,
        brickrange;
        periodicity = ntuple(_ -> true, dims),
    )

    grid = DiscontinuousSpectralElementGrid(
        topology,
        FloatType = FT,
        DeviceArray = ArrayType,
        polynomialorder = polynomialorder,
    )

    problem =
        AtmosProblem(boundaryconditions = (), init_state_prognostic = setup)
    if NumericalFlux isa RoeNumericalFluxMoist
        moisture = EquilMoist()
    else
        moisture = DryModel()
    end

    if NumericalFlux isa LMARSNumericalFlux
        ref_state = NoReferenceState()
    end

    physics = AtmosPhysics{FT}(
        param_set;
        ref_state = ref_state,
        turbulence = ConstantDynamicViscosity(FT(0)),
        moisture = moisture,
    )

    model = AtmosModel{FT}(
        AtmosLESConfigType,
        physics;
        problem = problem,
        orientation = NoOrientation(),
        source = (),
    )

    dg = DGModel(
        model,
        grid,
        NumericalFlux,
        CentralNumericalFluxSecondOrder(),
        CentralNumericalFluxGradient(),
    )

    timeend = FT(2 * setup.domain_halflength / 10 / setup.translation_speed)

    # determine the time step
    elementsize = minimum(step.(brickrange))
    dt = elementsize / soundspeed_air(param_set, setup.T∞) / polynomialorder^2
    nsteps = ceil(Int, timeend / dt)
    dt = timeend / nsteps

    Q = init_ode_state(dg, FT(0))
    lsrk = LSRK54CarpenterKennedy(dg, Q; dt = dt, t0 = 0)

    eng0 = norm(Q)
    dims == 2 && (numelems = (numelems..., 0))
    @info @sprintf """Starting refinement level %d
                      polyorder = %d
                      numelems  = (%d, %d, %d)
                      dt        = %.16e
                      norm(Q₀)  = %.16e
                      FT        = %s
                      """ level polynomialorder numelems... dt eng0 FT

    # Set up the information callback
    starttime = Ref(now())
    cbinfo = EveryXWallTimeSeconds(60, mpicomm) do (s = false)
        if s
            starttime[] = now()
        else
            energy = norm(Q)
            runtime = Dates.format(
                convert(DateTime, now() - starttime[]),
                dateformat"HH:MM:SS",
            )
            @info @sprintf """Update
                              simtime = %.16e
                              runtime = %s
                              norm(Q) = %.16e
                              """ gettime(lsrk) runtime energy
        end
    end
    callbacks = (cbinfo,)

    if output_vtk
        # create vtk dir
        vtkdir =
            "vtk_isentropicvortex" *
            "$(typeof(NumericalFlux))" *
            "_poly$(polynomialorder)_dims$(dims)_$(ArrayType)_$(FT)_level$(level)"
        mkpath(vtkdir)

        vtkstep = 0
        # output initial step
        do_output(mpicomm, vtkdir, vtkstep, dg, Q, Q, model)

        # setup the output callback
        outputtime = timeend / 10
        cbvtk = EveryXSimulationSteps(floor(outputtime / dt)) do
            vtkstep += 1
            Qe = init_ode_state(dg, gettime(lsrk), setup)
            do_output(mpicomm, vtkdir, vtkstep, dg, Q, Qe, model)
        end
        callbacks = (callbacks..., cbvtk)
    end

    solve!(Q, lsrk; timeend = timeend, callbacks = callbacks)

    # final statistics
    Qe = init_ode_state(dg, timeend, setup)
    engf = norm(Q)
    engfe = norm(Qe)
    errf = euclidean_distance(Q, Qe)
    @info @sprintf """Finished refinement level %d
    norm(Q)                 = %.16e
    norm(Q) / norm(Q₀)      = %.16e
    norm(Q) - norm(Q₀)      = %.16e
    norm(Q - Qe)            = %.16e
    norm(Q - Qe) / norm(Qe) = %.16e
    """ level engf engf / eng0 engf - eng0 errf errf / engfe
    engf / eng0
end

function do_output(
    mpicomm,
    vtkdir,
    vtkstep,
    dg,
    Q,
    Qe,
    model,
    testname = "isentropicvortex_lmars",
)
    ## name of the file that this MPI rank will write
    filename = @sprintf(
        "%s/%s_mpirank%04d_step%04d",
        vtkdir,
        testname,
        MPI.Comm_rank(mpicomm),
        vtkstep
    )

    statenames = flattenednames(vars_state(model, Prognostic(), eltype(Q)))
    exactnames = statenames .* "_exact"

    writevtk(filename, Q, dg, statenames, Qe, exactnames)

    ## Generate the pvtu file for these vtk files
    if MPI.Comm_rank(mpicomm) == 0
        ## name of the pvtu file
        pvtuprefix = @sprintf("%s/%s_step%04d", vtkdir, testname, vtkstep)

        ## name of each of the ranks vtk files
        prefixes = ntuple(MPI.Comm_size(mpicomm)) do i
            @sprintf("%s_mpirank%04d_step%04d", testname, i - 1, vtkstep)
        end

        writepvtu(
            pvtuprefix,
            prefixes,
            (statenames..., exactnames...),
            eltype(Q),
        )

        @info "Done writing VTK: $pvtuprefix"
    end
end

main()


text:
"""
    StartPairSystem(F)

A system which consider the system `F(x, p)` as a system `F([x p])`, i.e., variable and
parameter space are considered together.
"""
struct StartPairSystem{S<:AbstractSystem,C<:FiniteDiff.JacobianCache} <: AbstractSystem
    F::S
    # it's a little bit unnecessary to have these here, since views are theoretically
    # sufficient. However, we want to avoid any unnecessary recompilation
    # of the potential expensive evaluate! and evaluate_and_jacobian! functions.
    # So we give exactly the same types as in the tracking
    x::Vector{ComplexF64}
    p::Vector{ComplexF64}
    J::Matrix{ComplexF64}
    fd_cache::C
end

StartPairSystem(F::System; compile::Union{Bool,Symbol} = COMPILE_DEFAULT[]) =
    StartPairSystem(fixed(F; compile = compile))
function StartPairSystem(F::AbstractSystem)
    x = zeros(ComplexF64, size(F, 2))
    p = zeros(ComplexF64, nparameters(F))
    J = zeros(ComplexF64, size(F))
    fd_cache = FiniteDiff.JacobianCache(similar(p), zeros(ComplexF64, size(F, 1)))
    StartPairSystem(F, x, p, J, fd_cache)
end
Base.size(F::StartPairSystem) = (size(F.F, 1), size(F.F, 2) + nparameters(F.F))

function ModelKit.evaluate!(u, F::StartPairSystem, xp, ::Nothing = nothing)
    N, m = length(F.x), length(F.p)
    F.x .= view(xp, 1:N)
    F.p .= view(xp, N+1:N+m)
    evaluate!(u, F.F, F.x, F.p)
end

function ModelKit.evaluate_and_jacobian!(u, U, F::StartPairSystem, xp, ::Nothing = nothing)
    n, N, m = size(F.F, 1), length(F.x), length(F.p)
    F.x .= view(xp, 1:N)
    F.p .= view(xp, N+1:N+m)

    evaluate_and_jacobian!(u, F.J, F.F, F.x, F.p)
    view(U, :, 1:N) .= F.J

    fx = (v, q) -> evaluate!(v, F.F, F.x, q)
    FiniteDiff.finite_difference_jacobian!(view(U, :, N+1:N+m), fx, F.p, F.fd_cache)
end


text:
# ---
# title: 753. Cracking the Safe
# id: problem753
# author: Tian Jun
# date: 2020-10-31
# difficulty: Hard
# categories: Math, Depth-first Search
# link: <https://leetcode.com/problems/cracking-the-safe/description/>
# hidden: true
# ---
#
# There is a box protected by a password. The password is a sequence of `n`
# digits where each digit can be one of the first `k` digits `0, 1, ..., k-1`.
#
# While entering a password, the last `n` digits entered will automatically be
# matched against the correct password.
#
# For example, assuming the correct password is `"345"`, if you type `"012345"`,
# the box will open because the correct password matches the suffix of the
# entered password.
#
# Return any password of **minimum length** that is guaranteed to open the box
# at some point of entering it.
#
#
#
# **Example 1:**
#
#
#
#     Input: n = 1, k = 2
#     Output: "01"
#     **Note:** "10" will be accepted too.
#
#
# **Example 2:**
#
#
#
#     Input: n = 2, k = 2
#     Output: "00110"
#     **Note:** "01100", "10011", "11001" will be accepted too.
#
#
#
#
# **Note:**
#
#   1. `n` will be in the range `[1, 4]`.
#   2. `k` will be in the range `[1, 10]`.
#   3. `k^n` will be at most `4096`.
#
#
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
using Documenter
using BLIS

makedocs(modules=[BLIS],
            sitename = "BLIS.jl",
            authors = "RuQing G. Xu (This Wrapper)",
            pages = [
                "Home" => [
                    "index.md",
                    "interface_linalg.md",
                    "backend_object.md",
                    "backend_typed.md",
                    "performance.md"
                ]
            ]
        )

deploydocs(
    repo = "github.com/JuliaLinearAlgebra/BLIS.jl.git",
    devbranch = "master"
)


text:
module ArgCheck

using Base.Meta
export @argcheck, @check, CheckError

include("checks.jl")
end


text:
####
#### Defines list of tutorials given `GENERATED_DIR`
####

generate_tutorials =
    parse(Bool, get(ENV, "CLIMATEMACHINE_DOCS_GENERATE_TUTORIALS", "true"))

tutorials = []

# Allow flag to skip generated
# tutorials since this is by
# far the slowest part of the
# docs build.
if generate_tutorials

    # generate tutorials

    include("pages_helper.jl")

    tutorials = [
        "Home" => "TutorialList.jl",
        "BalanceLaws" => [
            "Tendency specification" =>
                "BalanceLaws/tendency_specification_layer.jl",
        ],
        "Atmos" => [
            "Dry Idealized GCM (Held-Suarez)" => "Atmos/heldsuarez.jl",
            "Single Element Stack Experiment (Burgers Equation)" =>
                "Atmos/burgers_single_stack.jl",
            "Finite Volume Single Element Stack Experiment (Burgers Equation)" =>
                "Atmos/burgers_single_stack_fvm.jl",
            "HEVI Single Element Stack Experiment (Burgers Equation)" =>
                "Atmos/burgers_single_stack_bjfnk.jl",
            "LES Experiment (Density Current)" => "Atmos/densitycurrent.jl",
            "LES Experiment (Rising Thermal Bubble)" =>
                "Atmos/risingbubble.jl",
            "Linear Hydrostatic Mountain (Topography)" =>
                "Atmos/agnesi_hs_lin.jl",
            "Linear Non-Hydrostatic Mountain (Topography)" =>
                "Atmos/agnesi_nh_lin.jl",
        ],
        "Land" => [
            "Heat" => ["Heat Equation" => "Land/Heat/heat_equation.jl"],
            "Soil" => [
                "Hydraulic Functions" =>
                    "Land/Soil/Water/hydraulic_functions.jl",
                "Soil Heat Equation" =>
                    "Land/Soil/Heat/bonan_heat_tutorial.jl",
                "Richards Equation" =>
                    "Land/Soil/Water/equilibrium_test.jl",
                "Coupled Water and Heat" =>
                    "Land/Soil/Coupled/equilibrium_test.jl",
                "Phase Change I" =>
                    "Land/Soil/PhaseChange/freezing_front.jl",
                "Phase Change II" =>
                    "Land/Soil/PhaseChange/phase_change_analytic_test.jl",
            ],
        ],
        "Ocean" => [
            "One-dimensional geostrophic adjustment" =>
                "Ocean/geostrophic_adjustment.jl",
            "Propagating mode-1 internal wave" => "Ocean/internal_wave.jl",
            "Shear instability" => "Ocean/shear_instability.jl",
        ],
        "Numerics" => [
            "System Solvers" => [
                "Conjugate Gradient" => "Numerics/SystemSolvers/cg.jl",
                "Batched Generalized Minimal Residual" =>
                    "Numerics/SystemSolvers/bgmres.jl",
            ],
            "DG Methods" =>
                ["Filters" => "Numerics/DGMethods/showcase_filters.jl"],
            "Time-Stepping" => [
                "Introduction" => "Numerics/TimeStepping/ts_intro.jl",
                "Explicit Runge-Kutta methods" => [
                    "Numerics/TimeStepping/explicit_lsrk.jl",
                    "Numerics/TimeStepping/tutorial_risingbubble_config.jl",
                ],
                "Implicit-Explicit (IMEX) Additive Runge-Kutta methods" =>
                    [
                        "Numerics/TimeStepping/imex_ark.jl",
                        "Numerics/TimeStepping/tutorial_acousticwave_config.jl",
                    ],
                "Multirate Runge-Kutta methods" => [
                    "Numerics/TimeStepping/multirate_rk.jl",
                    "Numerics/TimeStepping/tutorial_risingbubble_config.jl",
                ],
                "MIS methods" => [
                    "Numerics/TimeStepping/mis.jl",
                    "Numerics/TimeStepping/tutorial_acousticwave_config.jl",
                ],
            ],
        ],
        "Diagnostics" => [
            "Debug" => [
                "State Statistics Regression" =>
                    "Diagnostics/Debug/StateCheck.jl",
            ],
        ],
    ]

    # Prepend tutorials_dir
    tutorials_jl = flatten_to_array_of_strings(get_second(tutorials))
    if run_single_tutorial
        tutorials_jl =
            filter(x -> occursin(tutorial_string_match, x), tutorials_jl)
        tutorials = ["Single tutorial mode" => tutorials_jl[1]]
    end
    println("Building literate tutorials...")

    @everywhere function generate_tutorial(tutorials_dir, tutorial)
        rpath = relpath(dirname(tutorial), tutorials_dir)
        rpath = rpath == "." ? "" : rpath
        gen_dir = joinpath(GENERATED_DIR, rpath)
        mkpath(gen_dir)

        cd(gen_dir) do
            # change the Edit on GitHub link:
            path = relpath(clima_dir, pwd())
            content = """
            # ```@meta
            # EditURL = "https://github.com/CliMA/ClimateMachine.jl/$(path)"
            # ```
            """
            mdpre(str) = content * str
            input = abspath(tutorial)
            Literate.markdown(
                input;
                execute = true,
                documenter = false,
                preprocess = mdpre,
            )
        end
    end

    tutorials_dir = joinpath(@__DIR__, "..", "tutorials")
    tutorials_jl = map(x -> joinpath(tutorials_dir, x), tutorials_jl)
    pmap(t -> generate_tutorial(tutorials_dir, t), tutorials_jl)

    # update list of rendered markdown tutorial output for mkdocs
    ext_jl2md(x) = joinpath(basename(GENERATED_DIR), replace(x, ".jl" => ".md"))
    tutorials = transform_second(x -> ext_jl2md(x), tutorials)
end


text:
#
# This file is part of the DiscreteEvents.jl Julia package, MIT license
#
# Paul Bayer, 2020
#
# This is a Julia package for discrete event simulation
#

const state = Dict(
    Undefined() => :undefined,
    Idle() => :idle,
    Busy() => :busy,
    Halted() => :halted
    )

function c_id(c::Clock)
    if (c.id == 1) && isa(c.ac, Vector{ClockChannel}) && !isempty(c.ac)
        return "Clock 1 (+$(length(c.ac))): "
    else
        return "Clock $(c.id): "
    end
end

function c_info(c::Clock)
    s1 = "state=$(repr(state[c.state])), "
    s2 = "t=$(round(c.time, sigdigits=4))$(c.unit), "
    s3 = "Δt=$(round(c.Δt, sigdigits=4))$(c.unit)"
    return s1*s2*s3
end

function c_info(rtc::RTClock)
    s1 = "state=$(repr(state[rtc.clock.state])), "
    s2 = "t=$(round(rtc.time, sigdigits=4)) s, "
    s3 = "T=$(round(rtc.T, sigdigits=4)) s"
    return s1*s2*s3
end

function sc_info(c::Clock)
    sc1 = "ev:$(length(c.sc.events)), "
    sc2 = "cev:$(length(c.sc.cevents)), "
    sc3 = "sampl:$(length(c.sc.samples))"
    return sc1*sc2*sc3
end

function pretty_print(c::Clock)
    s1 = c_id(c)
    s2 = c_info(c)
    s3 = ", prc:$(length(c.processes))"
    return s1*s2*s3*"\n  scheduled "*sc_info(c)*"\n"
end

function pretty_print(ac::ActiveClock)
    s1 = "Active clock $(ac.id): "
    s2 = c_info(ac.clock)
    s3 = ", prc:$(length(ac.clock.processes))"
    return s1*s2*s3*"\n   scheduled "*sc_info(ac.clock)*"\n"
end

function pretty_print(rtc::RTClock)
    s1 = "RTClock $(rtc.id) on thread $(rtc.thread): "
    s2 = c_info(rtc)
    s3 = ", prc:$(length(rtc.clock.processes))"
    return s1*s2*s3*"\n   scheduled "*sc_info(rtc.clock)*"\n"
end

Base.show(io::IO, c::CLK) where {CLK<:AbstractClock} = print(io, pretty_print(c))

"""
    prettyClock(on::Bool)

Switch pritty printing for clocks on and off.
"""
function prettyClock(on::Bool)
    m = which(show, (IO, AbstractClock))
    if on &&  m.module == Base
        eval(:(Base.show(io::IO, c::CLK) where {CLK<:AbstractClock} = print(io, pretty_print(c))))
    elseif !on && m.module == DiscreteEvents
        Base.delete_method(m)
    else
        nothing
    end
end


text:
using Choices
using Test

# An implementation of this Rosetta Code task:
# http://rosettacode.org/wiki/Amb
function amb_test()
  # the word lattice to traverse
  lattice = [
    ["the", "that", "a"],
    ["frog", "elephant", "thing"],
    ["walked", "treaded", "grows"],
    ["slowly", "quickly"]
  ]
  # the constraint on adjacent words
  words_meet(before, after) = (isempty(before) || before[end] == after[1])
  # build the nondeterministic computation
  comp = choose([[]])
  for options ∈ lattice
    comp =
      (comp |> (before -> begin
	(choose(options...) |> (after ->
	begin
	  isempty(before) || words_meet(before[end], after) || fail()
	  return [before; after]
	end))
      end))
  end
  comp = (comp |> (words -> join(words, " ")))
  # get all the possible answers
  answers = [comp...]
  cut()
  return answers
end
# test that we got the right answer only
@test amb_test() == ["that thing grows slowly"]


text:
# Automatically generated using Clang.jl

const SPV_VERSION = 0x00010000
const SPV_REVISION = 8
const SpvId = UInt32

@cenum SpvSourceLanguage_::UInt32 begin
    SpvSourceLanguageUnknown = 0
    SpvSourceLanguageESSL = 1
    SpvSourceLanguageGLSL = 2
    SpvSourceLanguageOpenCL_C = 3
    SpvSourceLanguageOpenCL_CPP = 4
    SpvSourceLanguageMax = 2147483647
end

const SpvSourceLanguage = SpvSourceLanguage_

@cenum SpvExecutionModel_::UInt32 begin
    SpvExecutionModelVertex = 0
    SpvExecutionModelTessellationControl = 1
    SpvExecutionModelTessellationEvaluation = 2
    SpvExecutionModelGeometry = 3
    SpvExecutionModelFragment = 4
    SpvExecutionModelGLCompute = 5
    SpvExecutionModelKernel = 6
    SpvExecutionModelMax = 2147483647
end

const SpvExecutionModel = SpvExecutionModel_

@cenum SpvAddressingModel_::UInt32 begin
    SpvAddressingModelLogical = 0
    SpvAddressingModelPhysical32 = 1
    SpvAddressingModelPhysical64 = 2
    SpvAddressingModelMax = 2147483647
end

const SpvAddressingModel = SpvAddressingModel_

@cenum SpvMemoryModel_::UInt32 begin
    SpvMemoryModelSimple = 0
    SpvMemoryModelGLSL450 = 1
    SpvMemoryModelOpenCL = 2
    SpvMemoryModelMax = 2147483647
end

const SpvMemoryModel = SpvMemoryModel_

@cenum SpvExecutionMode_::UInt32 begin
    SpvExecutionModeInvocations = 0
    SpvExecutionModeSpacingEqual = 1
    SpvExecutionModeSpacingFractionalEven = 2
    SpvExecutionModeSpacingFractionalOdd = 3
    SpvExecutionModeVertexOrderCw = 4
    SpvExecutionModeVertexOrderCcw = 5
    SpvExecutionModePixelCenterInteger = 6
    SpvExecutionModeOriginUpperLeft = 7
    SpvExecutionModeOriginLowerLeft = 8
    SpvExecutionModeEarlyFragmentTests = 9
    SpvExecutionModePointMode = 10
    SpvExecutionModeXfb = 11
    SpvExecutionModeDepthReplacing = 12
    SpvExecutionModeDepthGreater = 14
    SpvExecutionModeDepthLess = 15
    SpvExecutionModeDepthUnchanged = 16
    SpvExecutionModeLocalSize = 17
    SpvExecutionModeLocalSizeHint = 18
    SpvExecutionModeInputPoints = 19
    SpvExecutionModeInputLines = 20
    SpvExecutionModeInputLinesAdjacency = 21
    SpvExecutionModeTriangles = 22
    SpvExecutionModeInputTrianglesAdjacency = 23
    SpvExecutionModeQuads = 24
    SpvExecutionModeIsolines = 25
    SpvExecutionModeOutputVertices = 26
    SpvExecutionModeOutputPoints = 27
    SpvExecutionModeOutputLineStrip = 28
    SpvExecutionModeOutputTriangleStrip = 29
    SpvExecutionModeVecTypeHint = 30
    SpvExecutionModeContractionOff = 31
    SpvExecutionModeMax = 2147483647
end

const SpvExecutionMode = SpvExecutionMode_

@cenum SpvStorageClass_::UInt32 begin
    SpvStorageClassUniformConstant = 0
    SpvStorageClassInput = 1
    SpvStorageClassUniform = 2
    SpvStorageClassOutput = 3
    SpvStorageClassWorkgroup = 4
    SpvStorageClassCrossWorkgroup = 5
    SpvStorageClassPrivate = 6
    SpvStorageClassFunction = 7
    SpvStorageClassGeneric = 8
    SpvStorageClassPushConstant = 9
    SpvStorageClassAtomicCounter = 10
    SpvStorageClassImage = 11
    SpvStorageClassMax = 2147483647
end

const SpvStorageClass = SpvStorageClass_

@cenum SpvDim_::UInt32 begin
    SpvDim1D = 0
    SpvDim2D = 1
    SpvDim3D = 2
    SpvDimCube = 3
    SpvDimRect = 4
    SpvDimBuffer = 5
    SpvDimSubpassData = 6
    SpvDimMax = 2147483647
end

const SpvDim = SpvDim_

@cenum SpvSamplerAddressingMode_::UInt32 begin
    SpvSamplerAddressingModeNone = 0
    SpvSamplerAddressingModeClampToEdge = 1
    SpvSamplerAddressingModeClamp = 2
    SpvSamplerAddressingModeRepeat = 3
    SpvSamplerAddressingModeRepeatMirrored = 4
    SpvSamplerAddressingModeMax = 2147483647
end

const SpvSamplerAddressingMode = SpvSamplerAddressingMode_

@cenum SpvSamplerFilterMode_::UInt32 begin
    SpvSamplerFilterModeNearest = 0
    SpvSamplerFilterModeLinear = 1
    SpvSamplerFilterModeMax = 2147483647
end

const SpvSamplerFilterMode = SpvSamplerFilterMode_

@cenum SpvImageFormat_::UInt32 begin
    SpvImageFormatUnknown = 0
    SpvImageFormatRgba32f = 1
    SpvImageFormatRgba16f = 2
    SpvImageFormatR32f = 3
    SpvImageFormatRgba8 = 4
    SpvImageFormatRgba8Snorm = 5
    SpvImageFormatRg32f = 6
    SpvImageFormatRg16f = 7
    SpvImageFormatR11fG11fB10f = 8
    SpvImageFormatR16f = 9
    SpvImageFormatRgba16 = 10
    SpvImageFormatRgb10A2 = 11
    SpvImageFormatRg16 = 12
    SpvImageFormatRg8 = 13
    SpvImageFormatR16 = 14
    SpvImageFormatR8 = 15
    SpvImageFormatRgba16Snorm = 16
    SpvImageFormatRg16Snorm = 17
    SpvImageFormatRg8Snorm = 18
    SpvImageFormatR16Snorm = 19
    SpvImageFormatR8Snorm = 20
    SpvImageFormatRgba32i = 21
    SpvImageFormatRgba16i = 22
    SpvImageFormatRgba8i = 23
    SpvImageFormatR32i = 24
    SpvImageFormatRg32i = 25
    SpvImageFormatRg16i = 26
    SpvImageFormatRg8i = 27
    SpvImageFormatR16i = 28
    SpvImageFormatR8i = 29
    SpvImageFormatRgba32ui = 30
    SpvImageFormatRgba16ui = 31
    SpvImageFormatRgba8ui = 32
    SpvImageFormatR32ui = 33
    SpvImageFormatRgb10a2ui = 34
    SpvImageFormatRg32ui = 35
    SpvImageFormatRg16ui = 36
    SpvImageFormatRg8ui = 37
    SpvImageFormatR16ui = 38
    SpvImageFormatR8ui = 39
    SpvImageFormatMax = 2147483647
end

const SpvImageFormat = SpvImageFormat_

@cenum SpvImageChannelOrder_::UInt32 begin
    SpvImageChannelOrderR = 0
    SpvImageChannelOrderA = 1
    SpvImageChannelOrderRG = 2
    SpvImageChannelOrderRA = 3
    SpvImageChannelOrderRGB = 4
    SpvImageChannelOrderRGBA = 5
    SpvImageChannelOrderBGRA = 6
    SpvImageChannelOrderARGB = 7
    SpvImageChannelOrderIntensity = 8
    SpvImageChannelOrderLuminance = 9
    SpvImageChannelOrderRx = 10
    SpvImageChannelOrderRGx = 11
    SpvImageChannelOrderRGBx = 12
    SpvImageChannelOrderDepth = 13
    SpvImageChannelOrderDepthStencil = 14
    SpvImageChannelOrdersRGB = 15
    SpvImageChannelOrdersRGBx = 16
    SpvImageChannelOrdersRGBA = 17
    SpvImageChannelOrdersBGRA = 18
    SpvImageChannelOrderABGR = 19
    SpvImageChannelOrderMax = 2147483647
end

const SpvImageChannelOrder = SpvImageChannelOrder_

@cenum SpvImageChannelDataType_::UInt32 begin
    SpvImageChannelDataTypeSnormInt8 = 0
    SpvImageChannelDataTypeSnormInt16 = 1
    SpvImageChannelDataTypeUnormInt8 = 2
    SpvImageChannelDataTypeUnormInt16 = 3
    SpvImageChannelDataTypeUnormShort565 = 4
    SpvImageChannelDataTypeUnormShort555 = 5
    SpvImageChannelDataTypeUnormInt101010 = 6
    SpvImageChannelDataTypeSignedInt8 = 7
    SpvImageChannelDataTypeSignedInt16 = 8
    SpvImageChannelDataTypeSignedInt32 = 9
    SpvImageChannelDataTypeUnsignedInt8 = 10
    SpvImageChannelDataTypeUnsignedInt16 = 11
    SpvImageChannelDataTypeUnsignedInt32 = 12
    SpvImageChannelDataTypeHalfFloat = 13
    SpvImageChannelDataTypeFloat = 14
    SpvImageChannelDataTypeUnormInt24 = 15
    SpvImageChannelDataTypeUnormInt101010_2 = 16
    SpvImageChannelDataTypeMax = 2147483647
end

const SpvImageChannelDataType = SpvImageChannelDataType_

@cenum SpvImageOperandsShift_::UInt32 begin
    SpvImageOperandsBiasShift = 0
    SpvImageOperandsLodShift = 1
    SpvImageOperandsGradShift = 2
    SpvImageOperandsConstOffsetShift = 3
    SpvImageOperandsOffsetShift = 4
    SpvImageOperandsConstOffsetsShift = 5
    SpvImageOperandsSampleShift = 6
    SpvImageOperandsMinLodShift = 7
    SpvImageOperandsMax = 2147483647
end

const SpvImageOperandsShift = SpvImageOperandsShift_

@cenum SpvImageOperandsMask_::UInt32 begin
    SpvImageOperandsMaskNone = 0
    SpvImageOperandsBiasMask = 1
    SpvImageOperandsLodMask = 2
    SpvImageOperandsGradMask = 4
    SpvImageOperandsConstOffsetMask = 8
    SpvImageOperandsOffsetMask = 16
    SpvImageOperandsConstOffsetsMask = 32
    SpvImageOperandsSampleMask = 64
    SpvImageOperandsMinLodMask = 128
end

const SpvImageOperandsMask = SpvImageOperandsMask_

@cenum SpvFPFastMathModeShift_::UInt32 begin
    SpvFPFastMathModeNotNaNShift = 0
    SpvFPFastMathModeNotInfShift = 1
    SpvFPFastMathModeNSZShift = 2
    SpvFPFastMathModeAllowRecipShift = 3
    SpvFPFastMathModeFastShift = 4
    SpvFPFastMathModeMax = 2147483647
end

const SpvFPFastMathModeShift = SpvFPFastMathModeShift_

@cenum SpvFPFastMathModeMask_::UInt32 begin
    SpvFPFastMathModeMaskNone = 0
    SpvFPFastMathModeNotNaNMask = 1
    SpvFPFastMathModeNotInfMask = 2
    SpvFPFastMathModeNSZMask = 4
    SpvFPFastMathModeAllowRecipMask = 8
    SpvFPFastMathModeFastMask = 16
end

const SpvFPFastMathModeMask = SpvFPFastMathModeMask_

@cenum SpvFPRoundingMode_::UInt32 begin
    SpvFPRoundingModeRTE = 0
    SpvFPRoundingModeRTZ = 1
    SpvFPRoundingModeRTP = 2
    SpvFPRoundingModeRTN = 3
    SpvFPRoundingModeMax = 2147483647
end

const SpvFPRoundingMode = SpvFPRoundingMode_

@cenum SpvLinkageType_::UInt32 begin
    SpvLinkageTypeExport = 0
    SpvLinkageTypeImport = 1
    SpvLinkageTypeMax = 2147483647
end

const SpvLinkageType = SpvLinkageType_

@cenum SpvAccessQualifier_::UInt32 begin
    SpvAccessQualifierReadOnly = 0
    SpvAccessQualifierWriteOnly = 1
    SpvAccessQualifierReadWrite = 2
    SpvAccessQualifierMax = 2147483647
end

const SpvAccessQualifier = SpvAccessQualifier_

@cenum SpvFunctionParameterAttribute_::UInt32 begin
    SpvFunctionParameterAttributeZext = 0
    SpvFunctionParameterAttributeSext = 1
    SpvFunctionParameterAttributeByVal = 2
    SpvFunctionParameterAttributeSret = 3
    SpvFunctionParameterAttributeNoAlias = 4
    SpvFunctionParameterAttributeNoCapture = 5
    SpvFunctionParameterAttributeNoWrite = 6
    SpvFunctionParameterAttributeNoReadWrite = 7
    SpvFunctionParameterAttributeMax = 2147483647
end

const SpvFunctionParameterAttribute = SpvFunctionParameterAttribute_

@cenum SpvDecoration_::UInt32 begin
    SpvDecorationRelaxedPrecision = 0
    SpvDecorationSpecId = 1
    SpvDecorationBlock = 2
    SpvDecorationBufferBlock = 3
    SpvDecorationRowMajor = 4
    SpvDecorationColMajor = 5
    SpvDecorationArrayStride = 6
    SpvDecorationMatrixStride = 7
    SpvDecorationGLSLShared = 8
    SpvDecorationGLSLPacked = 9
    SpvDecorationCPacked = 10
    SpvDecorationBuiltIn = 11
    SpvDecorationNoPerspective = 13
    SpvDecorationFlat = 14
    SpvDecorationPatch = 15
    SpvDecorationCentroid = 16
    SpvDecorationSample = 17
    SpvDecorationInvariant = 18
    SpvDecorationRestrict = 19
    SpvDecorationAliased = 20
    SpvDecorationVolatile = 21
    SpvDecorationConstant = 22
    SpvDecorationCoherent = 23
    SpvDecorationNonWritable = 24
    SpvDecorationNonReadable = 25
    SpvDecorationUniform = 26
    SpvDecorationSaturatedConversion = 28
    SpvDecorationStream = 29
    SpvDecorationLocation = 30
    SpvDecorationComponent = 31
    SpvDecorationIndex = 32
    SpvDecorationBinding = 33
    SpvDecorationDescriptorSet = 34
    SpvDecorationOffset = 35
    SpvDecorationXfbBuffer = 36
    SpvDecorationXfbStride = 37
    SpvDecorationFuncParamAttr = 38
    SpvDecorationFPRoundingMode = 39
    SpvDecorationFPFastMathMode = 40
    SpvDecorationLinkageAttributes = 41
    SpvDecorationNoContraction = 42
    SpvDecorationInputAttachmentIndex = 43
    SpvDecorationAlignment = 44
    SpvDecorationMax = 2147483647
end

const SpvDecoration = SpvDecoration_

@cenum SpvBuiltIn_::UInt32 begin
    SpvBuiltInPosition = 0
    SpvBuiltInPointSize = 1
    SpvBuiltInClipDistance = 3
    SpvBuiltInCullDistance = 4
    SpvBuiltInVertexId = 5
    SpvBuiltInInstanceId = 6
    SpvBuiltInPrimitiveId = 7
    SpvBuiltInInvocationId = 8
    SpvBuiltInLayer = 9
    SpvBuiltInViewportIndex = 10
    SpvBuiltInTessLevelOuter = 11
    SpvBuiltInTessLevelInner = 12
    SpvBuiltInTessCoord = 13
    SpvBuiltInPatchVertices = 14
    SpvBuiltInFragCoord = 15
    SpvBuiltInPointCoord = 16
    SpvBuiltInFrontFacing = 17
    SpvBuiltInSampleId = 18
    SpvBuiltInSamplePosition = 19
    SpvBuiltInSampleMask = 20
    SpvBuiltInFragDepth = 22
    SpvBuiltInHelperInvocation = 23
    SpvBuiltInNumWorkgroups = 24
    SpvBuiltInWorkgroupSize = 25
    SpvBuiltInWorkgroupId = 26
    SpvBuiltInLocalInvocationId = 27
    SpvBuiltInGlobalInvocationId = 28
    SpvBuiltInLocalInvocationIndex = 29
    SpvBuiltInWorkDim = 30
    SpvBuiltInGlobalSize = 31
    SpvBuiltInEnqueuedWorkgroupSize = 32
    SpvBuiltInGlobalOffset = 33
    SpvBuiltInGlobalLinearId = 34
    SpvBuiltInSubgroupSize = 36
    SpvBuiltInSubgroupMaxSize = 37
    SpvBuiltInNumSubgroups = 38
    SpvBuiltInNumEnqueuedSubgroups = 39
    SpvBuiltInSubgroupId = 40
    SpvBuiltInSubgroupLocalInvocationId = 41
    SpvBuiltInVertexIndex = 42
    SpvBuiltInInstanceIndex = 43
    SpvBuiltInSubgroupEqMaskKHR = 4416
    SpvBuiltInSubgroupGeMaskKHR = 4417
    SpvBuiltInSubgroupGtMaskKHR = 4418
    SpvBuiltInSubgroupLeMaskKHR = 4419
    SpvBuiltInSubgroupLtMaskKHR = 4420
    SpvBuiltInBaseVertex = 4424
    SpvBuiltInBaseInstance = 4425
    SpvBuiltInDrawIndex = 4426
    SpvBuiltInMax = 2147483647
end

const SpvBuiltIn = SpvBuiltIn_

@cenum SpvSelectionControlShift_::UInt32 begin
    SpvSelectionControlFlattenShift = 0
    SpvSelectionControlDontFlattenShift = 1
    SpvSelectionControlMax = 2147483647
end

const SpvSelectionControlShift = SpvSelectionControlShift_

@cenum SpvSelectionControlMask_::UInt32 begin
    SpvSelectionControlMaskNone = 0
    SpvSelectionControlFlattenMask = 1
    SpvSelectionControlDontFlattenMask = 2
end

const SpvSelectionControlMask = SpvSelectionControlMask_

@cenum SpvLoopControlShift_::UInt32 begin
    SpvLoopControlUnrollShift = 0
    SpvLoopControlDontUnrollShift = 1
    SpvLoopControlMax = 2147483647
end

const SpvLoopControlShift = SpvLoopControlShift_

@cenum SpvLoopControlMask_::UInt32 begin
    SpvLoopControlMaskNone = 0
    SpvLoopControlUnrollMask = 1
    SpvLoopControlDontUnrollMask = 2
end

const SpvLoopControlMask = SpvLoopControlMask_

@cenum SpvFunctionControlShift_::UInt32 begin
    SpvFunctionControlInlineShift = 0
    SpvFunctionControlDontInlineShift = 1
    SpvFunctionControlPureShift = 2
    SpvFunctionControlConstShift = 3
    SpvFunctionControlMax = 2147483647
end

const SpvFunctionControlShift = SpvFunctionControlShift_

@cenum SpvFunctionControlMask_::UInt32 begin
    SpvFunctionControlMaskNone = 0
    SpvFunctionControlInlineMask = 1
    SpvFunctionControlDontInlineMask = 2
    SpvFunctionControlPureMask = 4
    SpvFunctionControlConstMask = 8
end

const SpvFunctionControlMask = SpvFunctionControlMask_

@cenum SpvMemorySemanticsShift_::UInt32 begin
    SpvMemorySemanticsAcquireShift = 1
    SpvMemorySemanticsReleaseShift = 2
    SpvMemorySemanticsAcquireReleaseShift = 3
    SpvMemorySemanticsSequentiallyConsistentShift = 4
    SpvMemorySemanticsUniformMemoryShift = 6
    SpvMemorySemanticsSubgroupMemoryShift = 7
    SpvMemorySemanticsWorkgroupMemoryShift = 8
    SpvMemorySemanticsCrossWorkgroupMemoryShift = 9
    SpvMemorySemanticsAtomicCounterMemoryShift = 10
    SpvMemorySemanticsImageMemoryShift = 11
    SpvMemorySemanticsMax = 2147483647
end

const SpvMemorySemanticsShift = SpvMemorySemanticsShift_

@cenum SpvMemorySemanticsMask_::UInt32 begin
    SpvMemorySemanticsMaskNone = 0
    SpvMemorySemanticsAcquireMask = 2
    SpvMemorySemanticsReleaseMask = 4
    SpvMemorySemanticsAcquireReleaseMask = 8
    SpvMemorySemanticsSequentiallyConsistentMask = 16
    SpvMemorySemanticsUniformMemoryMask = 64
    SpvMemorySemanticsSubgroupMemoryMask = 128
    SpvMemorySemanticsWorkgroupMemoryMask = 256
    SpvMemorySemanticsCrossWorkgroupMemoryMask = 512
    SpvMemorySemanticsAtomicCounterMemoryMask = 1024
    SpvMemorySemanticsImageMemoryMask = 2048
end

const SpvMemorySemanticsMask = SpvMemorySemanticsMask_

@cenum SpvMemoryAccessShift_::UInt32 begin
    SpvMemoryAccessVolatileShift = 0
    SpvMemoryAccessAlignedShift = 1
    SpvMemoryAccessNontemporalShift = 2
    SpvMemoryAccessMax = 2147483647
end

const SpvMemoryAccessShift = SpvMemoryAccessShift_

@cenum SpvMemoryAccessMask_::UInt32 begin
    SpvMemoryAccessMaskNone = 0
    SpvMemoryAccessVolatileMask = 1
    SpvMemoryAccessAlignedMask = 2
    SpvMemoryAccessNontemporalMask = 4
end

const SpvMemoryAccessMask = SpvMemoryAccessMask_

@cenum SpvScope_::UInt32 begin
    SpvScopeCrossDevice = 0
    SpvScopeDevice = 1
    SpvScopeWorkgroup = 2
    SpvScopeSubgroup = 3
    SpvScopeInvocation = 4
    SpvScopeMax = 2147483647
end

const SpvScope = SpvScope_

@cenum SpvGroupOperation_::UInt32 begin
    SpvGroupOperationReduce = 0
    SpvGroupOperationInclusiveScan = 1
    SpvGroupOperationExclusiveScan = 2
    SpvGroupOperationMax = 2147483647
end

const SpvGroupOperation = SpvGroupOperation_

@cenum SpvKernelEnqueueFlags_::UInt32 begin
    SpvKernelEnqueueFlagsNoWait = 0
    SpvKernelEnqueueFlagsWaitKernel = 1
    SpvKernelEnqueueFlagsWaitWorkGroup = 2
    SpvKernelEnqueueFlagsMax = 2147483647
end

const SpvKernelEnqueueFlags = SpvKernelEnqueueFlags_

@cenum SpvKernelProfilingInfoShift_::UInt32 begin
    SpvKernelProfilingInfoCmdExecTimeShift = 0
    SpvKernelProfilingInfoMax = 2147483647
end

const SpvKernelProfilingInfoShift = SpvKernelProfilingInfoShift_

@cenum SpvKernelProfilingInfoMask_::UInt32 begin
    SpvKernelProfilingInfoMaskNone = 0
    SpvKernelProfilingInfoCmdExecTimeMask = 1
end

const SpvKernelProfilingInfoMask = SpvKernelProfilingInfoMask_

@cenum SpvCapability_::UInt32 begin
    SpvCapabilityMatrix = 0
    SpvCapabilityShader = 1
    SpvCapabilityGeometry = 2
    SpvCapabilityTessellation = 3
    SpvCapabilityAddresses = 4
    SpvCapabilityLinkage = 5
    SpvCapabilityKernel = 6
    SpvCapabilityVector16 = 7
    SpvCapabilityFloat16Buffer = 8
    SpvCapabilityFloat16 = 9
    SpvCapabilityFloat64 = 10
    SpvCapabilityInt64 = 11
    SpvCapabilityInt64Atomics = 12
    SpvCapabilityImageBasic = 13
    SpvCapabilityImageReadWrite = 14
    SpvCapabilityImageMipmap = 15
    SpvCapabilityPipes = 17
    SpvCapabilityGroups = 18
    SpvCapabilityDeviceEnqueue = 19
    SpvCapabilityLiteralSampler = 20
    SpvCapabilityAtomicStorage = 21
    SpvCapabilityInt16 = 22
    SpvCapabilityTessellationPointSize = 23
    SpvCapabilityGeometryPointSize = 24
    SpvCapabilityImageGatherExtended = 25
    SpvCapabilityStorageImageMultisample = 27
    SpvCapabilityUniformBufferArrayDynamicIndexing = 28
    SpvCapabilitySampledImageArrayDynamicIndexing = 29
    SpvCapabilityStorageBufferArrayDynamicIndexing = 30
    SpvCapabilityStorageImageArrayDynamicIndexing = 31
    SpvCapabilityClipDistance = 32
    SpvCapabilityCullDistance = 33
    SpvCapabilityImageCubeArray = 34
    SpvCapabilitySampleRateShading = 35
    SpvCapabilityImageRect = 36
    SpvCapabilitySampledRect = 37
    SpvCapabilityGenericPointer = 38
    SpvCapabilityInt8 = 39
    SpvCapabilityInputAttachment = 40
    SpvCapabilitySparseResidency = 41
    SpvCapabilityMinLod = 42
    SpvCapabilitySampled1D = 43
    SpvCapabilityImage1D = 44
    SpvCapabilitySampledCubeArray = 45
    SpvCapabilitySampledBuffer = 46
    SpvCapabilityImageBuffer = 47
    SpvCapabilityImageMSArray = 48
    SpvCapabilityStorageImageExtendedFormats = 49
    SpvCapabilityImageQuery = 50
    SpvCapabilityDerivativeControl = 51
    SpvCapabilityInterpolationFunction = 52
    SpvCapabilityTransformFeedback = 53
    SpvCapabilityGeometryStreams = 54
    SpvCapabilityStorageImageReadWithoutFormat = 55
    SpvCapabilityStorageImageWriteWithoutFormat = 56
    SpvCapabilityMultiViewport = 57
    SpvCapabilitySubgroupBallotKHR = 4423
    SpvCapabilityDrawParameters = 4427
    SpvCapabilityMax = 2147483647
end

const SpvCapability = SpvCapability_

@cenum SpvOp_::UInt32 begin
    SpvOpNop = 0
    SpvOpUndef = 1
    SpvOpSourceContinued = 2
    SpvOpSource = 3
    SpvOpSourceExtension = 4
    SpvOpName = 5
    SpvOpMemberName = 6
    SpvOpString = 7
    SpvOpLine = 8
    SpvOpExtension = 10
    SpvOpExtInstImport = 11
    SpvOpExtInst = 12
    SpvOpMemoryModel = 14
    SpvOpEntryPoint = 15
    SpvOpExecutionMode = 16
    SpvOpCapability = 17
    SpvOpTypeVoid = 19
    SpvOpTypeBool = 20
    SpvOpTypeInt = 21
    SpvOpTypeFloat = 22
    SpvOpTypeVector = 23
    SpvOpTypeMatrix = 24
    SpvOpTypeImage = 25
    SpvOpTypeSampler = 26
    SpvOpTypeSampledImage = 27
    SpvOpTypeArray = 28
    SpvOpTypeRuntimeArray = 29
    SpvOpTypeStruct = 30
    SpvOpTypeOpaque = 31
    SpvOpTypePointer = 32
    SpvOpTypeFunction = 33
    SpvOpTypeEvent = 34
    SpvOpTypeDeviceEvent = 35
    SpvOpTypeReserveId = 36
    SpvOpTypeQueue = 37
    SpvOpTypePipe = 38
    SpvOpTypeForwardPointer = 39
    SpvOpConstantTrue = 41
    SpvOpConstantFalse = 42
    SpvOpConstant = 43
    SpvOpConstantComposite = 44
    SpvOpConstantSampler = 45
    SpvOpConstantNull = 46
    SpvOpSpecConstantTrue = 48
    SpvOpSpecConstantFalse = 49
    SpvOpSpecConstant = 50
    SpvOpSpecConstantComposite = 51
    SpvOpSpecConstantOp = 52
    SpvOpFunction = 54
    SpvOpFunctionParameter = 55
    SpvOpFunctionEnd = 56
    SpvOpFunctionCall = 57
    SpvOpVariable = 59
    SpvOpImageTexelPointer = 60
    SpvOpLoad = 61
    SpvOpStore = 62
    SpvOpCopyMemory = 63
    SpvOpCopyMemorySized = 64
    SpvOpAccessChain = 65
    SpvOpInBoundsAccessChain = 66
    SpvOpPtrAccessChain = 67
    SpvOpArrayLength = 68
    SpvOpGenericPtrMemSemantics = 69
    SpvOpInBoundsPtrAccessChain = 70
    SpvOpDecorate = 71
    SpvOpMemberDecorate = 72
    SpvOpDecorationGroup = 73
    SpvOpGroupDecorate = 74
    SpvOpGroupMemberDecorate = 75
    SpvOpVectorExtractDynamic = 77
    SpvOpVectorInsertDynamic = 78
    SpvOpVectorShuffle = 79
    SpvOpCompositeConstruct = 80
    SpvOpCompositeExtract = 81
    SpvOpCompositeInsert = 82
    SpvOpCopyObject = 83
    SpvOpTranspose = 84
    SpvOpSampledImage = 86
    SpvOpImageSampleImplicitLod = 87
    SpvOpImageSampleExplicitLod = 88
    SpvOpImageSampleDrefImplicitLod = 89
    SpvOpImageSampleDrefExplicitLod = 90
    SpvOpImageSampleProjImplicitLod = 91
    SpvOpImageSampleProjExplicitLod = 92
    SpvOpImageSampleProjDrefImplicitLod = 93
    SpvOpImageSampleProjDrefExplicitLod = 94
    SpvOpImageFetch = 95
    SpvOpImageGather = 96
    SpvOpImageDrefGather = 97
    SpvOpImageRead = 98
    SpvOpImageWrite = 99
    SpvOpImage = 100
    SpvOpImageQueryFormat = 101
    SpvOpImageQueryOrder = 102
    SpvOpImageQuerySizeLod = 103
    SpvOpImageQuerySize = 104
    SpvOpImageQueryLod = 105
    SpvOpImageQueryLevels = 106
    SpvOpImageQuerySamples = 107
    SpvOpConvertFToU = 109
    SpvOpConvertFToS = 110
    SpvOpConvertSToF = 111
    SpvOpConvertUToF = 112
    SpvOpUConvert = 113
    SpvOpSConvert = 114
    SpvOpFConvert = 115
    SpvOpQuantizeToF16 = 116
    SpvOpConvertPtrToU = 117
    SpvOpSatConvertSToU = 118
    SpvOpSatConvertUToS = 119
    SpvOpConvertUToPtr = 120
    SpvOpPtrCastToGeneric = 121
    SpvOpGenericCastToPtr = 122
    SpvOpGenericCastToPtrExplicit = 123
    SpvOpBitcast = 124
    SpvOpSNegate = 126
    SpvOpFNegate = 127
    SpvOpIAdd = 128
    SpvOpFAdd = 129
    SpvOpISub = 130
    SpvOpFSub = 131
    SpvOpIMul = 132
    SpvOpFMul = 133
    SpvOpUDiv = 134
    SpvOpSDiv = 135
    SpvOpFDiv = 136
    SpvOpUMod = 137
    SpvOpSRem = 138
    SpvOpSMod = 139
    SpvOpFRem = 140
    SpvOpFMod = 141
    SpvOpVectorTimesScalar = 142
    SpvOpMatrixTimesScalar = 143
    SpvOpVectorTimesMatrix = 144
    SpvOpMatrixTimesVector = 145
    SpvOpMatrixTimesMatrix = 146
    SpvOpOuterProduct = 147
    SpvOpDot = 148
    SpvOpIAddCarry = 149
    SpvOpISubBorrow = 150
    SpvOpUMulExtended = 151
    SpvOpSMulExtended = 152
    SpvOpAny = 154
    SpvOpAll = 155
    SpvOpIsNan = 156
    SpvOpIsInf = 157
    SpvOpIsFinite = 158
    SpvOpIsNormal = 159
    SpvOpSignBitSet = 160
    SpvOpLessOrGreater = 161
    SpvOpOrdered = 162
    SpvOpUnordered = 163
    SpvOpLogicalEqual = 164
    SpvOpLogicalNotEqual = 165
    SpvOpLogicalOr = 166
    SpvOpLogicalAnd = 167
    SpvOpLogicalNot = 168
    SpvOpSelect = 169
    SpvOpIEqual = 170
    SpvOpINotEqual = 171
    SpvOpUGreaterThan = 172
    SpvOpSGreaterThan = 173
    SpvOpUGreaterThanEqual = 174
    SpvOpSGreaterThanEqual = 175
    SpvOpULessThan = 176
    SpvOpSLessThan = 177
    SpvOpULessThanEqual = 178
    SpvOpSLessThanEqual = 179
    SpvOpFOrdEqual = 180
    SpvOpFUnordEqual = 181
    SpvOpFOrdNotEqual = 182
    SpvOpFUnordNotEqual = 183
    SpvOpFOrdLessThan = 184
    SpvOpFUnordLessThan = 185
    SpvOpFOrdGreaterThan = 186
    SpvOpFUnordGreaterThan = 187
    SpvOpFOrdLessThanEqual = 188
    SpvOpFUnordLessThanEqual = 189
    SpvOpFOrdGreaterThanEqual = 190
    SpvOpFUnordGreaterThanEqual = 191
    SpvOpShiftRightLogical = 194
    SpvOpShiftRightArithmetic = 195
    SpvOpShiftLeftLogical = 196
    SpvOpBitwiseOr = 197
    SpvOpBitwiseXor = 198
    SpvOpBitwiseAnd = 199
    SpvOpNot = 200
    SpvOpBitFieldInsert = 201
    SpvOpBitFieldSExtract = 202
    SpvOpBitFieldUExtract = 203
    SpvOpBitReverse = 204
    SpvOpBitCount = 205
    SpvOpDPdx = 207
    SpvOpDPdy = 208
    SpvOpFwidth = 209
    SpvOpDPdxFine = 210
    SpvOpDPdyFine = 211
    SpvOpFwidthFine = 212
    SpvOpDPdxCoarse = 213
    SpvOpDPdyCoarse = 214
    SpvOpFwidthCoarse = 215
    SpvOpEmitVertex = 218
    SpvOpEndPrimitive = 219
    SpvOpEmitStreamVertex = 220
    SpvOpEndStreamPrimitive = 221
    SpvOpControlBarrier = 224
    SpvOpMemoryBarrier = 225
    SpvOpAtomicLoad = 227
    SpvOpAtomicStore = 228
    SpvOpAtomicExchange = 229
    SpvOpAtomicCompareExchange = 230
    SpvOpAtomicCompareExchangeWeak = 231
    SpvOpAtomicIIncrement = 232
    SpvOpAtomicIDecrement = 233
    SpvOpAtomicIAdd = 234
    SpvOpAtomicISub = 235
    SpvOpAtomicSMin = 236
    SpvOpAtomicUMin = 237
    SpvOpAtomicSMax = 238
    SpvOpAtomicUMax = 239
    SpvOpAtomicAnd = 240
    SpvOpAtomicOr = 241
    SpvOpAtomicXor = 242
    SpvOpPhi = 245
    SpvOpLoopMerge = 246
    SpvOpSelectionMerge = 247
    SpvOpLabel = 248
    SpvOpBranch = 249
    SpvOpBranchConditional = 250
    SpvOpSwitch = 251
    SpvOpKill = 252
    SpvOpReturn = 253
    SpvOpReturnValue = 254
    SpvOpUnreachable = 255
    SpvOpLifetimeStart = 256
    SpvOpLifetimeStop = 257
    SpvOpGroupAsyncCopy = 259
    SpvOpGroupWaitEvents = 260
    SpvOpGroupAll = 261
    SpvOpGroupAny = 262
    SpvOpGroupBroadcast = 263
    SpvOpGroupIAdd = 264
    SpvOpGroupFAdd = 265
    SpvOpGroupFMin = 266
    SpvOpGroupUMin = 267
    SpvOpGroupSMin = 268
    SpvOpGroupFMax = 269
    SpvOpGroupUMax = 270
    SpvOpGroupSMax = 271
    SpvOpReadPipe = 274
    SpvOpWritePipe = 275
    SpvOpReservedReadPipe = 276
    SpvOpReservedWritePipe = 277
    SpvOpReserveReadPipePackets = 278
    SpvOpReserveWritePipePackets = 279
    SpvOpCommitReadPipe = 280
    SpvOpCommitWritePipe = 281
    SpvOpIsValidReserveId = 282
    SpvOpGetNumPipePackets = 283
    SpvOpGetMaxPipePackets = 284
    SpvOpGroupReserveReadPipePackets = 285
    SpvOpGroupReserveWritePipePackets = 286
    SpvOpGroupCommitReadPipe = 287
    SpvOpGroupCommitWritePipe = 288
    SpvOpEnqueueMarker = 291
    SpvOpEnqueueKernel = 292
    SpvOpGetKernelNDrangeSubGroupCount = 293
    SpvOpGetKernelNDrangeMaxSubGroupSize = 294
    SpvOpGetKernelWorkGroupSize = 295
    SpvOpGetKernelPreferredWorkGroupSizeMultiple = 296
    SpvOpRetainEvent = 297
    SpvOpReleaseEvent = 298
    SpvOpCreateUserEvent = 299
    SpvOpIsValidEvent = 300
    SpvOpSetUserEventStatus = 301
    SpvOpCaptureEventProfilingInfo = 302
    SpvOpGetDefaultQueue = 303
    SpvOpBuildNDRange = 304
    SpvOpImageSparseSampleImplicitLod = 305
    SpvOpImageSparseSampleExplicitLod = 306
    SpvOpImageSparseSampleDrefImplicitLod = 307
    SpvOpImageSparseSampleDrefExplicitLod = 308
    SpvOpImageSparseSampleProjImplicitLod = 309
    SpvOpImageSparseSampleProjExplicitLod = 310
    SpvOpImageSparseSampleProjDrefImplicitLod = 311
    SpvOpImageSparseSampleProjDrefExplicitLod = 312
    SpvOpImageSparseFetch = 313
    SpvOpImageSparseGather = 314
    SpvOpImageSparseDrefGather = 315
    SpvOpImageSparseTexelsResident = 316
    SpvOpNoLine = 317
    SpvOpAtomicFlagTestAndSet = 318
    SpvOpAtomicFlagClear = 319
    SpvOpImageSparseRead = 320
    SpvOpSubgroupBallotKHR = 4421
    SpvOpSubgroupFirstInvocationKHR = 4422
    SpvOpMax = 2147483647
end

const SpvOp = SpvOp_


text:
using BinaryBuilder

name = "Julia"
version = v"1.4.1"

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = [
    FreeBSD(:x86_64; compiler_abi=CompilerABI(libgfortran_version=v"4", cxxstring_abi=:cxx11)),
    Linux(:armv7l; libc=:glibc, compiler_abi=CompilerABI(libgfortran_version=v"4", cxxstring_abi=:cxx11)),
    Linux(:aarch64; libc=:glibc, compiler_abi=CompilerABI(libgfortran_version=v"4", cxxstring_abi=:cxx11)),
    Linux(:x86_64; libc=:glibc, compiler_abi=CompilerABI(libgfortran_version=v"4", cxxstring_abi=:cxx11)),
    Linux(:i686; libc=:glibc, compiler_abi=CompilerABI(libgfortran_version=v"4", cxxstring_abi=:cxx11)),
    MacOS(:x86_64; compiler_abi=CompilerABI(libgfortran_version=v"4", cxxstring_abi=:cxx11)),
    Windows(:x86_64; compiler_abi=CompilerABI(libgfortran_version=v"4", cxxstring_abi=:cxx11)),
    Windows(:i686; compiler_abi=CompilerABI(libgfortran_version=v"4", cxxstring_abi=:cxx11)),
]

sources = [
    ArchiveSource("https://julialang2.s3.amazonaws.com/bin/linux/aarch64/1.4/julia-1.4.1-linux-aarch64.tar.gz",
                  "788dc1e79344b52f65358ce4406dc5304bafd82c6af50bfa92a6ee5ea998e678"; unpack_target="aarch64-linux-gnu-libgfortran4-cxx11"),
    ArchiveSource("https://julialang2.s3.amazonaws.com/bin/linux/armv7l/1.4/julia-1.4.1-linux-armv7l.tar.gz",
                  "bdcf24e0365f16092838daf7059bf5c0036bff9dc418511010e79249d9f71e96"; unpack_target="armv7l-linux-gnueabihf-libgfortran4-cxx11"),
    ArchiveSource("https://julialang2.s3.amazonaws.com/bin/linux/x64/1.4/julia-1.4.1-linux-x86_64.tar.gz",
                  "fd6d8cadaed678174c3caefb92207a3b0e8da9f926af6703fb4d1e4e4f50610a"; unpack_target="x86_64-linux-gnu-libgfortran4-cxx11"),
    ArchiveSource("https://julialang2.s3.amazonaws.com/bin/linux/x86/1.4/julia-1.4.1-linux-i686.tar.gz",
                  "765e614b2754b20d50bae475dd9f3b794f445915084afa42523fd1b14e4c91fe"; unpack_target="i686-linux-gnu-libgfortran4-cxx11"),
    ArchiveSource("https://julialang2.s3.amazonaws.com/bin/mac/x64/1.4/julia-1.4.1-mac64.tar.gz",
                  "78afd9c6769d645f7c30ad14dacadfd826cc5b1b3227c46fd7592ecde8af2fc3"; unpack_target="x86_64-apple-darwin14-libgfortran4-cxx11"),
    ArchiveSource("https://julialang2.s3.amazonaws.com/bin/winnt/x64/1.4/julia-1.4.1-win64.tar.gz",
                  "c4c1ae109f7eed5e9791d871b3e29003309d61ffa55a05cfd23184447ec8cfbe"; unpack_target="x86_64-w64-mingw32-libgfortran4-cxx11"),
    ArchiveSource("https://julialang2.s3.amazonaws.com/bin/winnt/x86/1.4/julia-1.4.1-win32.tar.gz",
                  "04d1abb1e28d643c6d049a4b241483ced155aebaf3eea8fb2d995299543645c5"; unpack_target="i686-w64-mingw32-libgfortran4-cxx11"),
    ArchiveSource("https://julialang-s3.julialang.org/bin/freebsd/x64/1.4/julia-1.4.1-freebsd-x86_64.tar.gz",
                  "f7a6545953f8843201acec16ea66ba0d0ced8145439b6cebfcb893e9671cf7af"; unpack_target="x86_64-unknown-freebsd11.1-libgfortran4-cxx11"),
]
script = raw"""
cp -rva ${WORKSPACE}/srcdir/${bb_full_target}/julia-*/* ${prefix}/
install_license /usr/share/licenses/MIT
"""

# The products that we will ensure are always built
products = [
    ExecutableProduct("julia", :julia),
    LibraryProduct("libjulia", :libjulia; dont_dlopen=true),
]

# Dependencies that must be installed before this package can be built/used
dependencies = [
    Dependency("Zlib_jll"),
]

build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)

max_stars_repo_name: tbeason/Yggdrasil

max_issues_repo_name: tbeason/Yggdrasil

max_forks_repo_name: tbeason/Yggdrasil


text:
# immutable RasterDataset
#     dataset::Dataset
#     nrasters::Int
#     RasterDataset(dataset::Dataset) = new(dataset, nraster(dataset))
# end
# Base.eltype(rd::RasterDataset) = RasterBand
# Base.length(rd::RasterDataset) = rd.nrasters
# Base.start(rd::RasterDataset) = 1
# Base.next(rd::RasterDataset, i::Int) = (fetchband(rd.dataset, i), i+1)
# Base.done(rd::RasterDataset, i::Int) = (i > rd.nrasters)

immutable BlockIterator
    rows::Cint
    cols::Cint
    ni::Cint
    nj::Cint
    n::Cint
    xbsize::Cint
    ybsize::Cint
end
function BlockIterator(raster::RasterBand)
    (xbsize, ybsize) = getblocksize(raster)
    rows = height(raster)
    cols = width(raster)
    ni = ceil(Cint, rows/ybsize)
    nj = ceil(Cint, cols/xbsize)
    BlockIterator(rows, cols, ni, nj, ni*nj, xbsize, ybsize)
end
Base.start(obj::BlockIterator) = 0
function Base.next(obj::BlockIterator, iter::Int)
    j = floor(Int, iter / obj.ni)
    i = iter % obj.ni
    nrows = ((i+1)* obj.ybsize < obj.rows) ? obj.ybsize : obj.rows - i* obj.ybsize
    ncols = ((j+1)* obj.xbsize < obj.cols) ? obj.xbsize : obj.cols - j*obj.xbsize
    (((i,j),(nrows,ncols)), iter+1)
end
Base.done(obj::BlockIterator, iter::Int) = (iter == obj.n)

immutable WindowIterator
    blockiter::BlockIterator
end
function WindowIterator(raster::RasterBand)
    WindowIterator(BlockIterator(raster))
end
Base.start(obj::WindowIterator) = Base.start(obj.blockiter)
function Base.next(obj::WindowIterator, iter::Int)
    handle = obj.blockiter
    (((i,j),(nrows,ncols)), iter) = Base.next(handle, iter)
    (((1:ncols)+j*handle.xbsize, (1:nrows)+i*handle.ybsize), iter)
end
Base.done(obj::WindowIterator, iter::Int) = Base.done(obj.blockiter, iter)

type BufferIterator{T <: Real}
    raster::RasterBand
    w::WindowIterator
    buffer::Array{T, 2}
end
function BufferIterator(raster::RasterBand)
    BufferIterator(raster, WindowIterator(raster),
                   Array(getdatatype(raster), getblocksize(raster)...))
end
Base.start(obj::BufferIterator) = Base.start(obj.w)
function Base.next(obj::BufferIterator, iter::Int)
    ((cols,rows), iter) = Base.next(obj.w, iter)
    rasterio!(obj.raster, obj.buffer, rows, cols)
    (obj.buffer[1:length(cols),1:length(rows)], iter)
end
Base.done(obj::BufferIterator, iter::Int) = Base.done(obj.w, iter)

# immutable FeatureDataset
#     dataset::Dataset
#     nlayers::Int
#     FeatureDataset(dataset::Dataset) = new(dataset, nlayer(dataset))
# end
# Base.eltype(rd::FeatureDataset) = FeatureLayer
# Base.length(rd::FeatureDataset) = rd.nlayers
# Base.start(fc::FeatureDataset) = 1
# Base.next(fc::FeatureDataset, i::Int) = (fetchlayer(fc.dataset, i), i+1)
# Base.done(fc::FeatureDataset, i::Int) = (i > fc.nlayers)

Base.start(layer::FeatureLayer) = [Feature(0)]
Base.next(layer::FeatureLayer, state::Vector{Feature}) = (state[1], state)
Base.eltype(layer::FeatureLayer) = Feature
Base.length(layer::FeatureLayer) = nfeature(layer, true)

function Base.done(layer::FeatureLayer, state::Vector{Feature})
    destroy(state[1])
    ptr = ccall((:OGR_L_GetNextFeature,GDAL.libgdal), Feature,(FeatureLayer,),layer)
    state[1] = ptr
    (ptr == C_NULL)
end

immutable DictIterator
    layer::FeatureLayer
end
Base.start(obj::DictIterator) = Base.start(obj.layer)
function Base.next(obj::DictIterator, vf::Vector{Feature})
    f = vf[1]
    properties = Dict{Int, Any}()
    for i in 0:(nfield(f)-1)
        if isfieldset(f, i)
            properties[i] = fetchfield(f, i)
        end
    end
    geometries = Geometry[fetchgeomfield(f, i) for i in 0:(ngeomfield(f)-1)]
    (Dict(:properties => properties, :geom => geometries), vf)
end
Base.done(obj::DictIterator, f::Vector{Feature}) = Base.done(obj.layer, f)


text:
module Agent

const initqvalue = 10000.0  # Q-value の初期値
const actions = [-10.0, 10.0]  # 行動の候補

# 状態分割の下限と上限
const xlimits = [-2.0, 2.0]
const thetalimits = [-pi, pi]
const xdotlimits = [-2.0, 2.0]
const thetadotlimits = [-10.0, 10.0]

# 状態の分割数
const xnum = 4
const thetanum = 40
const xdotnum = 10
const thetadotnum = 50

# 状態分割の bins を生成
const xbins = range(xlimits..., length = xnum - 1)
const thetabins = range(thetalimits..., length = thetanum - 1)
const xdotbins = range(xdotlimits..., length = xdotnum - 1)
const thetadotbins = range(thetadotlimits..., length = thetadotnum - 1)

# 学習に使うパラメータ
mutable struct Params
    α::Float64  # 学習率
    γ::Float64  # 割引率
    ε::Float64  # ランダムに探索する割合
end

const defaultparams = Params(0.1, 0.999, 0.1)
const defaulttestparams = Params(0.0, 0.999, 0.0)

function newqtable()
    qtable = zeros(xnum, thetanum, xdotnum, thetadotnum, length(actions))
    fill!(qtable, initqvalue)
    qtable
end

function action(params, qtable, s)
    if rand() < params.ε
        return rand(actions)
    end
    idx = digitizeall(s)
    maxidx = argmax(qtable[idx..., :])
    actions[maxidx]
end

function learn!(params, qtable, s0, a0, r, s1)
    s0idx = digitizeall(s0)
    a0idx = findfirst(x->x == a0, actions)
    s1idx = digitizeall(s1)

    qtable[s0idx..., a0idx] =
        (1 - params.α) * qtable[s0idx..., a0idx] +
        params.α * (r + params.γ * maximum(qtable[s1idx..., :]))

end

function digitizeall(s)
    xidx = searchsortedfirst(xbins, s[1])
    thetaidx = searchsortedfirst(thetabins, s[2])
    xdotidx = searchsortedfirst(xdotbins, s[3])
    thetadotidx = searchsortedfirst(thetadotbins, s[4])
    xidx, thetaidx, xdotidx, thetadotidx
end

end

max_stars_repo_name: high-moctane/anylang-rl

max_issues_repo_name: high-moctane/anylang-rl

max_forks_repo_name: high-moctane/anylang-rl


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

mutable struct ConnectionMonitorWorkspaceSettings <: SwaggerModel
    workspaceResourceId::Any # spec type: Union{ Nothing, String } # spec name: workspaceResourceId

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

const _property_map_ConnectionMonitorWorkspaceSettings = Dict{Symbol,Symbol}(Symbol("workspaceResourceId")=>Symbol("workspaceResourceId"))
const _property_types_ConnectionMonitorWorkspaceSettings = Dict{Symbol,String}(Symbol("workspaceResourceId")=>"String")
Base.propertynames(::Type{ ConnectionMonitorWorkspaceSettings }) = collect(keys(_property_map_ConnectionMonitorWorkspaceSettings))
Swagger.property_type(::Type{ ConnectionMonitorWorkspaceSettings }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_ConnectionMonitorWorkspaceSettings[name]))}
Swagger.field_name(::Type{ ConnectionMonitorWorkspaceSettings }, property_name::Symbol) =  _property_map_ConnectionMonitorWorkspaceSettings[property_name]

function check_required(o::ConnectionMonitorWorkspaceSettings)
    true
end

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


text:
# Parse parameters
using ArgParse
s = ArgParseSettings()
@add_arg_table s begin
    "--exp"
        help = "Specify the experiment to run (groundstate, stab, conv, adapt)."
        required = true
    "--method"
        help = "Specify the method to use."
        arg_type = String
        required = true
    "--N"
        arg_type = Int
        default = 4
    "--steps"
        help = "Number of steps used in the time interval [0,12]."
        arg_type = Int
        default = 1000
    "--no-ref"
        help = "Don't use reference solution in conv experiment, instead just save resulting wf."
        action = :store_true
    "--tol"
        help = "Tolerance for the adaptivity experiment"
        arg_type = Float64
        default = 1e-5
end

parsed_args = parse_args(s)
const method_string = parsed_args["method"]
const steps = parsed_args["steps"]
const N = parsed_args["N"]
const experiment = parsed_args["exp"]
const adaptive_tol = parsed_args["tol"]

# Run experiment
using TSSM
using JLD

# The following line uses my installation directory, modify if necessary
TSSM_dir = joinpath(homedir(), ".julia/dev/TSSM")
include(joinpath(TSSM_dir, "MCTDHF/mctdhf1d.jl"))
include(joinpath(TSSM_dir, "MCTDHF/check.jl"))
include(joinpath(TSSM_dir, "examples/time_propagators.jl"))

V1(x) = 1. / 32 * (x^2)
V2(x,y) = 1/sqrt((x-y)^2+1/16)
V(x,y) = V1(x) + V1(y) + V2(x,y)

const interval_bound = 20
const nx = Int(512*interval_bound/10)
const t0 = 0
const groundstate_tol=1e-9

SHIFT_B = 0

println("N = ", N, ", nx = ", nx, " on [-", interval_bound, ",", interval_bound, "]")

function method_from_string(variant::String)
    if variant == "yoshidaRK4"
        g = [1.351207191959657634, -1.702414383919315268, 1.351207191959657634] # Yoshida
        a, b = get_coeffs_composition(g)
        method = SplittingRK4BMethod(a,b)
        println("yoshida splitting")
    elseif variant == "yoshidaMP"
        g = [1.351207191959657634, -1.702414383919315268, 1.351207191959657634] # Yoshida
        method = CompositionMethod(g, 3)
        println("yoshida splitting using MP")
    elseif variant == "suzukiRK4"
        g = [1/(4-4^(1/3)),1/(4-4^(1/3)),-4^(1/3)/(4-4^(1/3)), 1/(4-4^(1/3)), 1/(4-4^(1/3))] # Suzuki
        a, b = get_coeffs_composition(g)
        method = SplittingRK4BMethod(a,b)
        println("suzuki splitting")
    elseif variant == "suzukiMP"
        g = [1/(4-4^(1/3)),1/(4-4^(1/3)),-4^(1/3)/(4-4^(1/3)), 1/(4-4^(1/3)), 1/(4-4^(1/3))] # Suzuki
        method = CompositionMethod(g, 3)
        println("suzuki splitting using MP")
    elseif variant == "strang"
        a, b = [0.5, 0.5], [1.0, 0.0]
        method = SplittingRK4BMethod(a, b, secondorder=true)
        println("strang splitting")
    elseif variant == "krogstad"
        method = ExponentialRungeKutta(:krogstad)
        println("krogstad")
    elseif variant == "rk4"
        method = ExponentialRungeKutta(:rk4)
        println("rk4")
    elseif variant == "rklawson"
        method = ExponentialRungeKutta(:lawson)
        println("runge kutta lawson")

    elseif variant == "adamslawson31"
        method = ExponentialMultistep(3, version=2, iters=1, starting_method=ExponentialRungeKutta(:lawson), starting_subdivision=50)
        println("adamslawson 3 + 1it")
    elseif variant == "adamslawson40"
        method = ExponentialMultistep(4, version=2, iters=0, starting_method=ExponentialRungeKutta(:lawson), starting_subdivision=50)
        println("adamslawson 4 + 0it")
    elseif variant == "expmultistep31"
        method = ExponentialMultistep(3, version=1, iters=1, starting_method=ExponentialRungeKutta(:lawson), starting_subdivision=50)
        println("exponential multistep 3 + 1it")
    elseif variant == "expmultistep40"
        method = ExponentialMultistep(4, version=1, iters=0, starting_method=ExponentialRungeKutta(:lawson), starting_subdivision=50)
        println("exponential multistep 4 + 0it")

    elseif variant == "adamslawson51"
        method = ExponentialMultistep(5, version=2, iters=1, starting_method=ExponentialRungeKutta(:lawson), starting_subdivision=50)
        println("adamslawson 5 + 1it")
    elseif variant == "adamslawson60"
        method = ExponentialMultistep(6, version=2, iters=0, starting_method=ExponentialRungeKutta(:lawson), starting_subdivision=50)
        println("adamslawson without 6 + 0it")
    elseif variant == "expmultistep51"
        method = ExponentialMultistep(5, version=1, iters=1, starting_method=ExponentialRungeKutta(:lawson), starting_subdivision=50)
        println("exponential multistep 5 + 1it")
    elseif variant == "expmultistep60"
        method = ExponentialMultistep(6, version=1, iters=0, starting_method=ExponentialRungeKutta(:lawson), starting_subdivision=50)
        println("exponential multistep without 6 + 0it")
    else
        throw(ArgumentError("\""*variant*"\" is not a supported method"))
    end

    try
        s = parse(Int, variant[end-1])
        println(s, " step method needs ", s-1, " additional starting values")
        global SHIFT_B = -(s-1)*4*50
        println("shift COUNT_B by ", SHIFT_B)
    catch ArgumentError
    end
    return method
end

function conv(variant::String, steps::Int)
    #laser field
    E(t) = sin(2*t)
    tend = 12
    dt=tend/steps

    V1_t(x, t) = E(t)*x
    V_t(x,y,t) = E(t)*(x+y)

    m = MCTDHF1D(2, N, nx, -interval_bound, interval_bound, potential1=V1, potential1_t=V1_t, potential2=V2, spin_restricted=true)
    psi = wave_function(m)

    TSSM.load!(psi, "wfquantumdot_f2_n"*string(N)*"_nx"*string(nx)*"_t0_1e-9.h5")
    set_time!(psi, t0)

    method = method_from_string(variant)
    times, energies, norms = propagate_equidistant!(method, psi, t0, dt, steps)

    if !isapprox(times[end], tend)
        println("Method did not converge!")
        return
    end

    TSSM.save(psi, "results_conv/wfquantumdot_conv_f2_n"*string(N)*"_nx"*string(nx)*"_t"*string(tend)*"_"*variant*"_"*string(steps)*".h5")

    if !parsed_args["no-ref"]
        psi_ref = wave_function(m);
        TSSM.load!(psi_ref, "results_conv/wfquantumdot_conv_f2_n"*string(N)*"_nx"*string(nx)*"_t"*string(tend)*"_adamslawson51_12000.h5")
        err = distance(psi, psi_ref)
        println("err:", err)
        JLD.save("results_conv/wfquantumdot_conv_f2_n"*string(N)*"_nx"*string(nx)*"_t"*string(tend)*"_"*variant*"_"*string(steps)*".jld", "times", times, "energies", energies, "dt", dt, "err", err, "B_calls", COUNT_B+SHIFT_B)
    end
end

function stab(variant::String, steps::Int)
    #no laser field
    E(t) = 0
    tend = 70
    dt=tend/steps

    V1_t(x, t) = E(t)*x
    V_t(x,y,t) = E(t)*(x+y)

    m = MCTDHF1D(2, N, nx, -interval_bound, interval_bound, potential1=V1, potential1_t=V1_t, potential2=V2, spin_restricted=true);
    psi = wave_function(m);

    TSSM.load!(psi, "wfquantumdot_f2_n"*string(N)*"_nx"*string(nx)*"_t0_1e-9.h5")
    set_time!(psi, t0)

    method = method_from_string(variant)

    times, energies, norms = propagate_equidistant!(method, psi, t0, dt, steps)

    JLD.save("results_stab/wfquantumdot_stab_f2_n"*string(N)*"_nx"*string(nx)*"_t"*string(tend)*"_"*variant*"_"*string(steps)*".jld", "times", times, "energies", energies, "dt", dt, "norms", norms)
end

function adapt(variant::String, tol::Float64)
    E(t) = sin(2*t)
    tend = 12

    V1_t(x, t) = E(t)*x
    V_t(x,y,t) = E(t)*(x+y)

    m = MCTDHF1D(2, N, nx, -interval_bound, interval_bound, potential1=V1, potential1_t=V1_t, potential2=V2, spin_restricted=true);
    psi = wave_function(m);
    TSSM.load!(psi, "wfquantumdot_f2_n"*string(N)*"_nx"*string(nx)*"_t0_1e-9.h5")
    set_time!(psi, t0)

    times, energies, norms, stepsizes = propagate_adaptive!(psi, t0, tend, variant, tol)

    TSSM.save(psi, "results_adapt/wfquantumdot_adapt_f2_n"*string(N)*"_nx"*string(nx)*"_t"*string(tend)*"_"*variant*"_"*string(tol)*".h5")
    if !parsed_args["no-ref"]
        psi_ref = wave_function(m);
        TSSM.load!(psi_ref, "results_conv/wfquantumdot_conv_f2_n"*string(N)*"_nx"*string(nx)*"_t"*string(tend)*"_adamslawson51_12000.h5")
        err = distance(psi, psi_ref)
        println("err:", err)
        JLD.save("results_adapt/wfquantumdot_adapt_f2_n"*string(N)*"_nx"*string(nx)*"_"*variant*"_"*string(tol)*".jld", "times", times, "energies", energies, "norms", norms, "stepsizes", stepsizes, "B_calls", COUNT_B, "err", err)
    end
end

function propagate_equidistant!(method, psi, t0, dt, steps)
    times = Vector{Float64}()
    energies = Vector{Float64}()
    norms = Vector{Float64}()
    step_counter = 1
    time0 = time()
    for (step, tsi) in EquidistantTimeStepper(method, psi, t0, dt, steps)
        n = norm(psi)
        E_pot = potential_energy(psi)
        E_kin = kinetic_energy(psi)
        E_tot = E_pot+E_kin
        if step_counter % 50 == 0 || step == steps
            @printf("%5i  %14.10f  %14.10f  %14.10f  %14.10f  %14.10f  %14.10f %6i %10.2f\n",
                step_counter, get_time(psi), E_pot, E_kin, E_tot, dt, n, COUNT_B+SHIFT_B, time()-time0)
        end
        append!(times, get_time(psi))
        append!(energies, E_tot)
        append!(norms, n)
        step_counter += 1
        if n > 1e10
            break
        end
    end
    return times, energies, norms
end

function propagate_adaptive!(psi, t0, tend, variant, tol)
    version = 0
    if variant[1:end-1] == "adamslawson"
        version = 2
    elseif variant[1:end-1] == "expmultistep"
        version = 1
    else
        throw(ArgumentError("\""*variant*"\" is not a valid method"))
    end
    method = try
        AdaptiveAdamsLawson(parse(Int, variant[end]), version=version)
    catch ArgumentError
        throw(ArgumentError("The number of steps could not be parsed from \""*variant*"\". Only single digits are supported"))
    end

    times = Vector{Float64}()
    energies = Vector{Float64}()
    stepsizes = Vector{Float64}()
    norms = Vector{Float64}()
    step_counter = 1
    time0 = time()
    told = t0
    for (t, tsi) in AdaptiveTimeStepper(method, psi, t0, tend, tol, 0.00001)
        n = norm(psi)
        E_pot = potential_energy(psi)
        E_kin = kinetic_energy(psi)
        E_tot = E_pot+E_kin
        stepsize = t - told
        if step_counter % 50 == 0
            @printf("%5i  %14.10f  %14.10f  %14.10f  %14.10f  %14.10f  %14.10f  %10.2f\n",
                step_counter, get_time(psi), n, E_pot, E_kin, E_tot, stepsize, time()-time0)
        end
        append!(times, get_time(psi))
        append!(energies, E_tot)
        append!(stepsizes, stepsize)
        append!(norms, n)
        told = t
        step_counter += 1
    end
    return times, energies, norms, stepsizes
end

if experiment == "groundstate"
    println("calculate groundstate with tolerance ", groundstate_tol)
    include(joinpath(TSSM_dir, "MCTDHF/propagators.jl"))
    m = MCTDHF1D(2, N, nx, -interval_bound, interval_bound, potential1=V1, potential2=V2, spin_restricted=true)
    psi = wave_function(m)
    groundstate!(psi, dt=0.1, max_iter=500000, output_step=100, tol=groundstate_tol)
    TSSM.save(psi, "wfquantumdot_f2_n"*string(N)*"_nx"*string(nx)*"_t0_"*string(groundstate_tol)*".h5")
elseif experiment == "conv"
    println("calculate solution using method ", method_string, " with ", steps, " steps")
    conv(method_string, steps)
elseif experiment == "stab"
    stab(method_string, steps)
elseif experiment == "adapt"
    println("calculate solution using adaptive method ", method_string, " with tolerance ", adaptive_tol)
    adapt(method_string, adaptive_tol)
else
    throw(ArgumentError("\"" * experiment * "\" is not an implemented experiment type"))
end


text:
function nextline(pf::IO, c::Char)
    eof(pf) && return "-1"
    s = "\0"
    while s[1] != c
        eof(pf) && return "-1"
        s = chomp(readline(pf))
    end
    return s
end

@doc """
    H, R = uwpf(pf[, v])

Read UW-format seismic pick file `pf` into SeisHdr object `H`, with seismic
source description (focal mechanism) returned in SeisSrc object `R`.

    uwpf!(W, pf[, v::Integer=KW.v])

Read UW-format seismic pick info from pickfile `f` into SeisEvent object `W`.
Overwrites W.source and W.hdr with pickfile information. Keyword `v` controls
verbosity.

!!! caution

    Reader has no safety check to guarantee that `pf` is from the same event.

""" uwpf
function uwpf(pickfile::String; v::Integer=KW.v)
  # Initialize variables that will fill SeisHdr structure
  D   = Dict{String, Any}()
  MAG = -5.0f0
  ID  = ""
  OT  = zero(Float64)
  loc = zeros(Float64, 12)
  sig = ""
  locflags = Array{Char, 1}(undef,8)
  R = SeisSrc()
  fill!(locflags, '0')

  # Read begins
  pf = open(pickfile, "r")

  # ========================================================================
  # Acard line
  A = nextline(pf, 'A')
  (v > 1)  && println(stdout, A)
  c = 0
  if length(A) == 75 || length(A) == 12
    y = zero(Int8)
    c = 1900
  else
    y = Int8(2)
  end
  D["type"] = getindex(A, 2)

  # ACard indices
  #
  # Crosson's notes:
  # Type, Year, Month,  Day,  Hour, Min,  Sec,  LatDeg, NS, Latmin*100, LongDeg,  EW, Lonmin*100, Depth, Fix, Magnitude, Numsta, numphase, Gap, Mindelta, RMS, ERR, Q1, Q2, Velmodel
  # ATYYYYMMDDHHMM SS.SS LLNMMMM LLLWMMMM DD.DD* M.M NN/0NN GGG DD R.RR EE.EQQ VV
  # AF200206291436  4.79 45N2009 121W4118  6.20* 4.5 41/041  37  9 0.27  0.1BB O0
  #
  #        Sec,Lat,Lon,Dep,Fix,Mag,Nst,Nph,Gap, d0,RMS,ERR, Q, mod
  si = Int8[13, 19, 27, 36, 42, 43, 47, 51, 54, 58, 61, 66, 71, 74] .+ y
  ei = Int8[18, 26, 35, 41, 42, 46, 49, 53, 57, 60, 65, 70, 72, 75] .+ y
  L = length(si)

  # Parse reset of Acard line
  ah = Array{String,1}(undef, L)
  for i = 1:L
    setindex!(ah, getindex(A, getindex(si, i):getindex(ei, i)), i)
  end
  v > 2 && println("ah = ", ah)

  # origin time, event depth, and magnitude
  OT            = d2u(DateTime(string(parse(Int64, A[3:4+y]) + c)*A[5+y:12+y],
                      "yyyymmddHHMM")) + parse(Float64, getindex(ah, 1))
  evla          = getindex(ah, 2)
  evlo          = getindex(ah, 3)
  loc[3]        = parse(Float64, getindex(ah, 4))       # depth           :dep
  locflags[3]   = (getindex(ah, 5) == "F") ? '1' : '0'
  MAG           = parse(Float32, getindex(ah, 6))
  nst           = parse(Int64, getindex(ah, 7))
  D["numpha"]   = parse(Int64, getindex(ah, 8))
  loc[10]       = parse(Float64, getindex(ah, 9))       # gap             :gap
  loc[11]       = parse(Float64, getindex(ah, 10))      # min distance    :dmin
  loc[9]        = parse(Float64, getindex(ah, 11))      # rms pick error  :rms
  loc[8]        = parse(Float64, getindex(ah, 12))      # standard error  :se
  D["qual"]     = getindex(ah, 13)
  D["vmod"]     = getindex(ah, 14)

  # Convert lat and lon to decimal degrees
  loc[1] = (parse(Float64, evla[1:3]) +
            parse(Float64, evla[5:6])/60.0 +
            parse(Float64, evla[7:8])/6000.0) * (evla[4] == 'S' ? -1.0 : 1.0)
  loc[2] = (parse(Float64, evlo[1:4]) +
            parse(Float64, evlo[6:7])/60.0 +
            parse(Float64, evlo[8:9])/6000.0) * (evlo[5] == 'W' ? -1.0 : 1.0)

  # ========================================================================
  # Error line
  seekstart(pf)
  eline = nextline(pf, 'E')
  if eline != "-1"
    # E O0  0.27 0.022 0.281 0.281  141.30  38   Z  0.05 0.05 0.11 0.01 4.50 0.000.03
    # Effectively: 10x   MeanRMS    SDabout0    SDaboutMean    SSWRES    NDFR    FIXXYZT    SDx    SDy    SDz    SDt    Mag  5x MeanUncert
    #              10x   f6.3       f6.3        f6.3           f8.2      i4      a4        f5.2   f5.2   f5.2   f5.2   f5.2  5x f4.2
    eline_keys = String["MeanRMS", "SDabout0", "SDaboutMean", "SSWRES", "NDFR", "FIXXYZT", "SDx", "SDy", "SDz", "SDt", "Mag", "MeanUncert"]
    si =           Int8[       11,         17,            23,       29,     37,        42,    46,     51,    56,   61,    66,           76]
    ei =           Int8[       16,         22,            28,       36,     40,        45,    50,     55,    60,   65,    70,           79]
    j = 0

    while j < length(eline_keys)
      j = j + 1
      a = getindex(si, j)
      b = getindex(ei, j)
      s = getindex(eline, a:b)
      if j == 6
        (s[1] == 'X') && (locflags[1] = '1')
        (s[2] == 'Y') && (locflags[2] = '1')
        (s[3] == 'Z') && (locflags[3] = '1')
        (s[4] == 'T') && (locflags[4] = '1')
      elseif j == 7
        loc[4] = parse(Float64, s)
      elseif j == 8
        loc[5] = parse(Float64, s)
      elseif j == 9
        loc[6] = parse(Float64, s)
      elseif j == 10
        if s != "*****"
          loc[7] = parse(Float64, s)
        end
      elseif !isempty(s)
        k = getindex(eline_keys, j)
        D[k] = parse(j == 5 ? Int32 : Float32, s)
      end
    end
    sig = "1σ"
  end
  LOC = EQLoc(loc..., nst, parse(UInt8, join(locflags), base=2), "", "hypocenter", "", "SPONG")

  # ========================================================================
  # Focal mechanism line(s)
  #= Note: planes F and G azimuth and an incidence are NOT in N°E. They're
    measured clockwise from the (N°E) azimuth of the dip vector, because R.
    Crosson wanted to be a unique special snowflake.

    The axes copied to Hdr.axes are therefore P, T, with the last field of
    the 3Tuple set to 0.0.
  =#
  seekstart(pf)
  mline = nextline(pf,'M')
  m = 0
  PAX = Array{Float64,2}(undef, 2 ,2)
  NP = Array{Float64,2}(undef, 2, 2)
  if mline != "-1"
    # Convert first mechanism line
    M = split(mline)

    setindex!(NP, parse(Float64, getindex(M, 3)), 1)
    setindex!(NP, parse(Float64, getindex(M, 4)), 2)
    setindex!(NP, parse(Float64, getindex(M, 6)), 3)
    setindex!(NP, parse(Float64, getindex(M, 7)), 4)

    # Order here is T, P
    setindex!(PAX, parse(Float64, getindex(M, 18)), 1)
    setindex!(PAX, parse(Float64, getindex(M, 19)), 2)
    setindex!(PAX, parse(Float64, getindex(M, 15)), 3)
    setindex!(PAX, parse(Float64, getindex(M, 16)), 4)

    setfield!(R, :pax, PAX)
    setfield!(R, :planes, NP)
    pf_str = abspath(pickfile)
    setfield!(R, :src, pf_str)
    note!(R, "+source ¦ " * pf_str)

    # Add rest to a dictionary
    mech_lines = Array{String, 1}(undef, 0)
    mline = nextline(pf,'M')
    while mline != "-1"
      m += 1
      push!(mech_lines, mline)
      mline = nextline(pf,'M')
    end
    R.gap = getindex(loc, 10)
    if !isempty(mech_lines)
      R.misc["mech_lines"] = mech_lines
    end
    v>0 && println(stdout, "Processed ", m, " focal mechanism lines.")
    note!(R, string("planes are arranged [θ₁ θ₂; ϕ₁ ϕ₂] but θ₁, θ₂ are NOT oriented N°E. ",
                    "They're measured clockwise from the N°E azimuth of the dip vector."))
    note!(R, string("gap is copied from the A-card line; this likely ",
                    "under-represents the true focal mechanism gap."))
  end

  # ========================================================================
  # Comment lines
  seekstart(pf)
  m = 0
  cline = nextline(pf,'C')
  if cline != "-1"
    D["comment"] = Array{String, 1}(undef, 0)
    while cline != "-1"
      m = m + 1
      L = lastindex(cline)
      if occursin("NEAR", cline)
        D["loc_name"] = getindex(cline, 8:L)
      elseif occursin("EVENT ID", cline)
        ID = getindex(cline, 13:L)
      elseif occursin("LOCATED BY", cline)
        setfield!(LOC, :src, getfield(LOC, :src) * "; " * getindex(cline, 3:L))
      else
        push!(D["comment"], getindex(cline, 3:L))
      end
      cline = nextline(pf,'C')
    end
    v > 0 && println(stdout, "Processed ", m, " comment lines.")
  end

  # ========================================================================
  # Done reading
  close(pf)
  H = SeisHdr()
  src_str = abspath(pickfile)
  setfield!(H, :loc, LOC)
  setfield!(H, :src, src_str)
  note!(H, "+source ¦ " * src_str)
  if MAG != -5.0f0
    setfield!(H, :mag, EQMag(val = MAG, scale = "Md", src = "SPONG"))
  end
  if OT != zero(Float64)
    setfield!(H, :ot, u2d(OT))
  end
  if isempty(ID) == false
    setfield!(H, :id, string(ID))
    setfield!(R, :eid, string(ID))
  end
  if isempty(D) == false
    setfield!(H, :misc, D)
  end

  return H, R
end

@doc (@doc uwpf)
function uwpf!(S::SeisEvent, pickfile::String; v::Integer=KW.v)
  (H, R) = uwpf(pickfile, v=v)

  N   = getfield(getfield(S, :data), :n)
  ID  = getfield(getfield(S, :data), :id)
  PHA = getfield(getfield(S, :data), :pha)
  cha = Array{String,1}(undef, N)
  for i = 1:N
    id = split(getindex(ID, i), ".", keepempty=true)
    setindex!(cha, string(".", getindex(id, 2), ".", getindex(id, 4)), i)
  end
  v > 2 && println("cha = ", cha)

  # Pick lines (requires reopening/rereading file)
  m = 0
  ndur = 0
  npol = 0
  pf = open(pickfile, "r")
  pick_line = nextline(pf, '.')

  while pick_line != "-1"
    v>1 && println(stdout, "pick_line = ", pick_line)
    m += 1
    pdat = split(pick_line, "(")
    pick_cha = getindex(pdat, 1)
    pcat = PhaseCat()
    dur = 0.0

    # Parse picks
    for j = 2:length(pdat)
      pha = split(getindex(pdat, j))
      if getindex(pha, 1) == "P"
        v > 2 && println(pha)
        pol = getindex(pha, 3)[1]
        if pol != '_'
          npol = npol + 1
        end
        pcat[getindex(pha,2)] = SeisPha(
          0.0,                              # amp
          0.0,                              # d
          0.0,                              # inc
          parse(Float64, pha[7][1:end-1]),  # res
          0.0,                              # rp
          0.0,                              # ta
          parse(Float64, pha[4]),           # tt --> relative to file begin; fixed below
          parse(Float64, pha[6]),           # unc
          pol,                              # polarity
          pha[5][1]                         # quality
          )
      elseif getindex(pha, 1) == "D"
        dur = parse(Float64, getindex(pha,2)[1:end-1])
      end
    end

    # Assign to the correct channel
    for i = 1:N
      if startswith(pick_cha, getindex(cha, i))
        for p in keys(pcat)
          PHA[i][p] = pcat[p]
        end
        if dur > 0.0
          ndur = ndur + 1
          S.data.misc[i]["dur"] = dur
        end
        break
      end
    end
    pick_line = nextline(pf, '.')
  end
  v>0 && println(stdout, "Processed ", m, " pick lines.")
  close(pf)

  # Set ndur, npol
  setfield!(getfield(H, :mag), :nst, ndur)
  setfield!(R, :npol, npol)

  # Place hdr, source
  setfield!(S, :hdr, H)
  setfield!(S, :source, R)

  # Done
  return S
end


text:
using Test

include("pascals-triangle.jl")

rows = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]

@testset "$i row(s)" for i in 1:4
    @test triangle(i) == rows[1:i]
end

@testset "special cases" begin
    @test_throws DomainError triangle(-1)
    @test isempty(triangle(0))
end


text:
"""
    repvec(orig, reps)

Repeats the items in the first vector by the corresponding number of
times in the second vector. Essentially the inverse operation of `hist`
"""
function repvec(orig::Vector{T}, reps::Vector{Int}) where T
    (length(orig) != length(reps)) && error("Provided vectors have to be of same length")
    data = Array{T}(undef, sum(reps))
    j = 1
    for i in 1:length(orig)
        if reps[i] > 0
            data[j:(j+reps[i]-1)] .= orig[i]
            j += reps[i]
        end
    end
    data
end

"""
    volume(diameter)

Given the `diameter` of a sphere, return its volume
"""
volume(diameter::Number) = 4/3*π*(diameter/2)^3

"""
    diameter(volume)

Given the `volume` of a sphere, compute its diameter
"""
diameter(volume::Number) = 2*(3/4*volume/π)^(1/3)

"""
    load_folder(folder)

Loads all coulter runs in a folder into a dictionary where the keys are the
first parts of the filenames separated by an underscore.
"""
function load_folder(folder)
    runs = DefaultDict{String, Array{Coulter.CoulterCounterRun}}([])

    files = readdir(folder)
    filter!(x -> splitext(x)[2] == ".=#Z2", files)

    for measurement in files
        catname = split(measurement, "_")[1]
        push!(runs[catname], loadZ2(joinpath(folder, measurement), String(catname)))
    end

    for (catname, samples) in runs
        sort!(samples, by=i->i.timepoint)
    end

    runs
end


text:
using TimeZones.TZData: tzdata_url, tzdata_download, isarchive, LATEST_FILE, read_latest

@test tzdata_url("2016j") == "https://data.iana.org/time-zones/releases/tzdata2016j.tar.gz"
@test tzdata_url("latest") == "https://data.iana.org/time-zones/tzdata-latest.tar.gz"

# Note: Try to keep the number of `tzdata_download` calls low to avoid unnecessary network traffic
mktempdir() do temp_dir
    file_path = ignore_output() do
        tzdata_download("latest", temp_dir)
    end

    @test isfile(file_path)
    @test isarchive(file_path)
    @test basename(file_path) != basename(tzdata_url("latest"))

    last_modified = mtime(file_path)
    last_file_path = file_path

    # No need to ignore output as this should never trigger a download
    file_path = tzdata_download("latest", temp_dir)

    @test file_path == last_file_path
    @test mtime(file_path) == last_modified

    # Validate the contents of the LATEST_FILE which will be automatically created when
    # downloading the latest data.
    @test isfile(LATEST_FILE)
    version, retrieved = read_latest(LATEST_FILE)
    @test occursin(r"\A(?:\d{2}){1,2}[a-z]?\z", version)
    @test isa(retrieved, DateTime)
end


text:
"""
    find_global_maximum_graph(graph::Dict{Int64,Array{Int64,1}})

Find the total global maximum based on a comparsion between the intial vertex
(`global_maximum = 0`), the current dictionary key, and the accesible vertexes from
the array-list (value).

# Arguments
- `graph::Dict{Int64,Array{Int64,1}}`: Graph of the connected nodes
"""
function find_global_maximum_graph(graph::Dict{Int64,Array{Int64,1}})
    global_maximum = 0
    # Going through the dictionary
    for (key, value) in graph
        # Check the keys as new global maximum
        if key > global_maximum
            global_maximum = key
        end

        # Check the values as new local maximum
        local_maximum = maximum(value)

        # Check if new local maximum becomes global maximum
        if local_maximum > global_maximum
            global_maximum = local_maximum
        end
    end
    return global_maximum
end

"""
bridge_check(
    graph::Dict{Int64,Array{Int64,1}},
    u::Int64,
    result::Array{Int64,1},
    visited::Array{Bool,1},
    parent::Array{Int64,1},
    low::Array{Int64,1},
    disc::Array{Int64,1},
    time::Int64,
)

For finding a bridge belonging to the current vertex, the algorithm has to remove firstly
one by one all edges. Next, the algorithm has to see if the removal of an edge causes a
disconnected graph. If yes, for the current pair of `u` and `v`, are a bridge between the
endpoints is found.

# Arguments
- `graph::Dict{Int64,Array{Tuple{Int64,Int64},1}}`: Graph of the connected nodes
- `u::Int64`: Next to visit vertex
- `result::Array{Int64,1}`: Results of the graph bridges; start and endpoint of the bridge
- `visited::Array{Bool,1}`: Visited vertex
- `parent::Array{Int64,1}`: Parent vertices in DFS tree'
- `low::Array{Int64,1}`: Lowest vertex reachable from subtree
- `disc::Array{Int64,1}`: Discovery time of the visited vertex
- `time::Int64`: Current time
"""
function bridge_check(
    graph::Dict{Int64,Array{Int64,1}},
    u::Int64,
    result::Array{Int64,1},
    visited::Array{Bool,1},
    parent::Array{Int64,1},
    low::Array{Int64,1},
    disc::Array{Int64,1},
    time::Int64,
)

    # Mark the current node as visited and print it
    visited[u] = true

    # Initialize discovery time
    disc[u] = time

    # Initialize low value
    low[u] = time

    # Update time
    time += 1

    #Recur for all the vertices adjacent to this vertex
    for v in graph[u]
        # If v is not visited yet, then make it a child of u
        # in DFS tree and recur for it
        if visited[v] == false
            parent[v] = u
            time, _ = bridge_check(graph, v, result, visited, parent, low, disc, time)

            # Check if the subtree rooted with v has a connection to
            # one of the ancestors of u
            low[u] = min(low[u], low[v])

            # If the lowest vertex reachable from subtree under v is below u in DFS tree,
            # then u-v is a bridge
            if low[v] > disc[u]
                # This returns goes up to the recursive function
                append!(result, (u, v))
            end
        elseif v != parent[u] # Update low value of u for parent function calls.
            low[u] = min(low[u], disc[v])
        end
    end
    return time, result
end

"""
    graph_bridge_check(graph::Dict{Int64,Array{Int64,1}}))

For finding a bridge or more bridges in an undirect connected graph, the kind of connection
has to be found, which can disconnect the graph by removing it. In case of disconnected
undirected graphs, the bridge is the connection which increases number of disconnected
components by removing it.

# Arguments
- `graph::Dict{Int64,Array{Tuple{Int64,Int64},1}}`: Graph of the connected nodes

# Examples
```julia-repl
julia> import ClassicAlgorithmsCollections
julia> graph_bridge = Dict(1 => [2, 3, 4], 2 => [1, 3], 3 => [1, 2], 4 => [1, 5], 5 => [4])
julia> ClassicAlgorithmsCollections.graph_bridge_check(graph_bridge)
[4 5; 1 4]
```
"""
function graph_bridge_check(graph::Dict{Int64,Array{Int64,1}})

    # Mark all the vertices as not visited and Initialize parent and visited,
    # and ap(articulation point) arrays
    vertex_size = find_global_maximum_graph(graph)

    #Create an array of visited nodes
    visited = zeros(Bool, vertex_size)

    disc = fill(99999, vertex_size)

    low = fill(99999, vertex_size)

    #
    parent = fill(vertex_size, vertex_size)

    # Intialze the time
    time = 0
    # Create a array list for the results
    result = zeros(Int64, false)
    # Call the recursive helper function to find bridges
    # in DFS tree rooted with vertex 'i'
    for i in 1:vertex_size
        time, result = bridge_check(graph, i, result, visited, parent, low, disc, time)
    end

    return adjoint(reshape(result, (2, :)))
end

max_stars_repo_name: Anselmoo/ClassicAlgorithmsCollections

max_issues_repo_name: Anselmoo/ClassicAlgorithmsCollections

max_forks_repo_name: Anselmoo/ClassicAlgorithmsCollections


text:
using Metida
using  Test, CSV, DataFrames, StatsBase, PrettyTables, MixedModels, Distributions
path    = dirname(@__FILE__)
include(joinpath(path, "validation_s1.jl"))
include(joinpath(path, "validation_s2.jl"))
include(joinpath(path, "validation_s3.jl"))


text:
using FlatBuffers
using Test

include("defaults.jl")
include("internals.jl")
CheckByteLayout()
CheckManualBuild()
CheckVtableDeduplication()
CheckNotInObjectError()
CheckStringIsNestedError()
CheckByteStringIsNestedError()
CheckStructIsNotInlineError()
CheckFinishedBytesError()
CheckCreateByteVector()
checkFuzz(100, 100, true)

include("flatc.jl")

include("monster.jl")

vec3 = SmallExample.Vec3(1.0, 2.0, 3.0, 3.0, SmallExample.Color(1), SmallExample.Test(5, 6))
test4 = SmallExample.Test[SmallExample.Test(10, 20), SmallExample.Test(30, 40)]
testArrayOfString = ["test1","test2"]

mon = SmallExample.Monster(vec3, 150, 80, "MyMonster", false, collect(0x00:0x04),
	SmallExample.Blue, test4, testArrayOfString, SmallExample.Monster[],
	UInt8[], SmallExample.Stat("",0,0), false, 0, 0, 0, 0, 0, 0, 0, 0,
	Bool[], 0, 0, 0)
b = FlatBuffers.build!(mon)
monst = FlatBuffers.read(b)
monst2 = FlatBuffers.read(SmallExample.Monster, FlatBuffers.bytes(b))

@test mon.pos == monst.pos
@test mon.pos == monst2.pos

# create test types
# types (Scalar, Enum, struct, T, String, Vector{UInt8})
mutable struct TestInt8T
	x::Int8
end

inst1 = TestInt8T(1)

b = FlatBuffers.Builder(TestInt8T)
FlatBuffers.build!(b, inst1)
t = FlatBuffers.Table(b)
inst1_2 = FlatBuffers.read(t)

@test inst1.x === inst1_2.x

struct TestInt8I
	x::Int8
end

inst2 = TestInt8I(2)

mutable struct TestInt8A
	x::Union{Nothing, Vector{Int8}}
end

inst3 = TestInt8A([1,2,3])

b = FlatBuffers.Builder(TestInt8A)
FlatBuffers.build!(b, inst3)
t = FlatBuffers.Table(b)
inst3_2 = FlatBuffers.read(t)

@test inst3.x == inst3_2.x

mutable struct TestMixT
	x::Int8
	y::String
	z::Union{Nothing, Vector{Int8}}
end

inst4 = TestMixT(10,"singin tooralli ooralli addity",[1,2,3])

b = FlatBuffers.Builder(TestMixT)
FlatBuffers.build!(b, inst4)
t = FlatBuffers.Table(b)
inst4_2 = FlatBuffers.read(t)

@test inst4.x == inst4_2.x && inst4.y == inst4_2.y && inst4.z == inst4_2.z

# simple sub-table/type (Stat)
mutable struct TestSubT
	x::TestInt8T
	y::TestInt8I
	z::TestInt8A
end

inst5 = TestSubT(inst1, inst2, inst3)

b = FlatBuffers.Builder(TestSubT)
FlatBuffers.build!(b, inst5)
t = FlatBuffers.Table(b)
inst5_2 = FlatBuffers.read(t)

@test inst5.x.x == inst5_2.x.x && inst5.y.x == inst5_2.y.x && inst5.z.x == inst5_2.z.x

# vtable duplicates
mutable struct TestDupT
	x::TestInt8T
	y::TestInt8I
	z::TestInt8T
end

inst6 = TestDupT(inst1, inst2, TestInt8T(2))

b = FlatBuffers.Builder(TestDupT)
FlatBuffers.build!(b, inst6)
t = FlatBuffers.Table(b)
inst6_2 = FlatBuffers.read(t)

@test inst6.x.x == inst6_2.x.x && inst6.y.x == inst6_2.y.x && inst6.z.x == inst6_2.z.x

mutable struct TestDup2T
	x::Vector{TestInt8T}
end

inst7 = TestDup2T([inst1, TestInt8T(2), TestInt8T(3), TestInt8T(4)])

b = FlatBuffers.Builder(TestDup2T)
FlatBuffers.build!(b, inst7)
t = FlatBuffers.Table(b)
inst7_2 = FlatBuffers.read(t)

@test all(map(x->x.x, inst7.x) .== map(x->x.x, inst7_2.x))

# self-referential type test (type has subtype of itself)
# type TestCircT
#     x::Int8
#     y::TestCircT
# end
#
# struct TestCircI
#     x::Int8
#     y::TestCircI
# end

# simple Union (Any_)

# fbs
# table TestUnionT {
#     x::TestUnionI
# }

@UNION TestUnionU (Nothing,TestInt8T,TestInt8A)

mutable struct TestUnionT
	x_type::Int8
	x::TestUnionU
end

TestUnionT(x::TestUnionU) = TestUnionT(FlatBuffers.typeorder(TestUnionU, typeof(x)), x)

inst8 = TestUnionT(inst1)

b = FlatBuffers.Builder(TestUnionT)
FlatBuffers.build!(b, inst8)
t = FlatBuffers.Table(b)
inst8_2 = FlatBuffers.read(t)

@test inst8.x_type == inst8_2.x_type && inst8.x.x == inst8_2.x.x

inst9 = TestUnionT(inst3)

b = FlatBuffers.Builder(TestUnionT)
FlatBuffers.build!(b, inst9)
t = FlatBuffers.Table(b)
inst9_2 = FlatBuffers.read(t)

@test inst9.x_type == inst9_2.x_type && inst9.x.x == inst9_2.x.x

const Nachos = String
const Burgers = Int
FlatBuffers.@UNION(Delicious,
	(Burgers, Nachos)
)

FlatBuffers.@with_kw mutable struct TestVecUnionT
	xs_type::Vector{UInt8}
	xs::Vector{TestUnionU}
	ys_type::Vector{UInt8}
	ys::Vector{Delicious}
end

function TestVecUnionT(xs::Vector{A}, ys::Vector{B}) where {A<:TestUnionU, B<:Delicious}
	xs_type = [FlatBuffers.typeorder(TestUnionU, typeof(x)) for x in xs]
	ys_type = [FlatBuffers.typeorder(Delicious, typeof(y)) for y in ys]
	TestVecUnionT(xs_type, xs, ys_type, ys)
end

dinner = "beef"
inst10 = TestVecUnionT(TestUnionU[inst1, inst1, inst1], [dinner])

b = FlatBuffers.Builder(TestVecUnionT)
FlatBuffers.build!(b, inst10)

t = FlatBuffers.Table(b)
inst10_2 = FlatBuffers.read(t)

@test inst10.xs_type == inst10_2.xs_type
@test [x.x for x in inst10.xs] == [x.x for x in inst10_2.xs]

inst11 = TestVecUnionT(TestUnionU[inst3, inst3], [dinner for _ = 1:9])

b = FlatBuffers.Builder(TestVecUnionT)
FlatBuffers.build!(b, inst11)
t = FlatBuffers.Table(b)
inst11_2 = FlatBuffers.read(t)

@test inst11.xs_type == inst11_2.xs_type
@test [x.x for x in inst11.xs] == [x.x for x in inst11_2.xs]
@test inst11.ys_type == inst11_2.ys_type
@test [y for y in inst11.ys] == [y for y in inst11_2.ys]

# test @STRUCT macro
@STRUCT struct A
	a::Int32
end
@test sizeof(A) == 4
@test all(fieldnames(A) .== [:a])
@test A(1) == A(1)

@STRUCT struct B
	a::Int8
	b::Int32
end
@test sizeof(B) == 8
@test all(fieldnames(B) .== [:a, :_pad_a_B_0, :_pad_a_B_1, :b])
@test B(1,2) == B(1,2)

@STRUCT struct C
	a::Int16
	b::Int32
	c::Int16
end
@test sizeof(C) == 12
@test all(fieldnames(C) .== [:a, :_pad_a_C_0, :b, :c, :_pad_c_C_1])
@test C(1,2,3) == C(1,2,3)

@STRUCT struct D
	a::Int8
	b::Int64
end
@test sizeof(D) == 16
@test all(fieldnames(D) .== [:a, :_pad_a_D_0, :_pad_a_D_1, :_pad_a_D_2, :b])
@test D(1,2) == D(1,2)

@STRUCT struct E
	a::Int64
	b::Int32
end
@test sizeof(E) == 16
@test all(fieldnames(E) .== [:a, :b, :_pad_b_E_0])
@test E(1,2) == E(1,2)

@STRUCT struct F
	a::Int32
	b::Int16
	c::Int32
	d::Int32
	e::Int64
end
@test sizeof(F) == 24
@test all(fieldnames(F) .== [:a, :b, :_pad_b_F_0, :c, :d, :e])
@test F(1,2,3,4,5) == F(1,2,3,4,5)

@STRUCT struct G
	a::Float64
	b::Int8
	c::Int16
	d::Int32
end
@test sizeof(G) == 24
@test all(fieldnames(G) .== [:a, :b, :_pad_b_G_0, :c, :_pad_c_G_1, :d])
@test G(1,2,3,4) == G(1,2,3,4)

@STRUCT struct H
	a::Float32
	b::Int8
	c::Int16
end
@test sizeof(H) == 8
@test all(fieldnames(H) .== [:a, :b, :_pad_b_H_0, :c])
@test H(1,2,3) == H(1,2,3)

@STRUCT struct I
	a::Float64
	b::Int8
	c::Int32
end
@test sizeof(I) == 16
@test all(fieldnames(I) .== [:a, :b, :_pad_b_I_0, :_pad_b_I_1, :c])
@test I(1,2,3) == I(1,2,3)

@STRUCT struct J
	a::Int8
	b::A
end
@test sizeof(J) == 8
@test all(fieldnames(J) .== [:a, :_pad_a_J_0, :_pad_a_J_1, :b_a])
@test J(1,A(2)) == J(1,A(2))

@STRUCT struct K
	a::J
	b::I
	c::J
end
@test sizeof(K) == 48
@test all(fieldnames(K) .== [:a_a, :a__pad_a_J_0, :a__pad__pad_a_J_0_J_0, :a__pad_a_J_1, :a__pad__pad_a_J_1_J_1, :a_b_a, :b_a, :b_b, :b__pad_b_I_0, :b__pad__pad_b_I_0_I_0, :b__pad_b_I_1, :b__pad__pad_b_I_1_I_1, :b_c, :c_a, :c__pad_a_J_0, :c__pad__pad_a_J_0_J_0, :c__pad_a_J_1, :c__pad__pad_a_J_1_J_1, :c_b_a])
@test K(J(1,A(2)), I(3.0, 4, 5), J(6, A(7))) == K(J(1,A(2)), I(3.0, 4, 5), J(6, A(7)))


text:
using Test, SumTypes

@sum_type Foo begin
    Bar(::Int)
    Baz(::Float64)
end

@test Bar(1) isa Foo
@test_throws MethodError Foo(1)

@sum_type Either{A, B} begin
    Left{A, B}(::A)
    Right{A, B}(::B)
end

let x = Right{Int, Int}(1)
    @case Either f((x,)::Left)  = x + 1
    @case Either f((x,)::Right) = x - 1
    @test f(x) == 0
    @test SumTypes.iscomplete(f, Either)
end

let x = Left{Int, Int}(1)
    @case Either f((x,)::Left)  = x + 1
    @test f(x) == 2
    @test !(SumTypes.iscomplete(f, Either))
end

@test_throws MethodError Left{Int, String}("hi")
@test_throws MethodError Right{Int, String}(1)
@test_throws MethodError Left{Int, Int}(0x01)

@sum_type List{A, L} begin
    Nil{A, L}()
    Cons{A, L}(::A, ::L)
end

@test Nil{Int, List}() isa List{Int, List}
@test Cons{Int, List}(1, Cons{Int, List}(1, Nil{Int, List}())) isa List{Int, List}