text:
# License for this file: MIT (expat)
# Copyright 2017-2018, DLR Institute of System Dynamics and Control
#
# This file is part of module
#   Modia3D.ContactDetectionMPR (Modia3D/contactDetection/ContactDetectionMPR/_module.jl)
#
using LinearAlgebra
EYE3() = Matrix(1.0I,3,3)

# returns true, if AABB's are touching
AABB_touching(aabb1::Basics.BoundingBox, aabb2::Basics.BoundingBox) = aabb1.x_max >= aabb2.x_min && aabb1.x_min <= aabb2.x_max &&
    aabb1.y_max >= aabb2.y_min && aabb1.y_min <= aabb2.y_max &&
    aabb1.z_max >= aabb2.z_min && aabb1.z_min <= aabb2.z_max

function Composition.initializeContactDetection!(world::Composition.Object3D, scene::Composition.Scene)::Nothing
    if typeof(scene.options.contactDetection) == Modia3D.ContactDetectionMPR_handler
        ch::Modia3D.ContactDetectionMPR_handler = scene.options.contactDetection
        ch.contactPairs = Composition.ContactPairs(world, scene.AABB, scene.superObjs, scene.allowedToMove,
            scene.options.visualizeBoundingBox,
            scene.options.nVisualContSupPoints, ch.visualizeContactPoints,
            ch.visualizeSupportPoints, ch.defaultContactSphereDiameter)
        if ch.contactPairs.nz == 0
            Composition.closeContactDetection!(ch)
            scene.collide = false
                @warn "... From Modia3D collision handler: Collision handling switched off, since no contacts can take place (nz=0).\n" *
                    "... You might need to set canCollide=true at joints.\n"
            return
        end
        @assert(ch.contactPairs.ne > 0)
        @assert(ch.contactPairs.nz > 0)
    end
end

function Composition.setComputationFlag(ch::Composition.ContactDetectionMPR_handler)
    ch.distanceComputed = false
end

# This function performs (a) a broad phase to determine which
# shapes are potentially in contact to each other, (b) computes
# the distances of these shapes in a narrow phase and (c) selects
# the nz shape pairs with the smallest distances and orders them
# according to their distances in O(n_n log(n_z)) operations.
# This function is called after initialization and after state events.
function Composition.selectContactPairsWithEvent!(sim, scene::Composition.Scene, ch::Composition.ContactDetectionMPR_handler, world::Composition.Object3D)
    empty!(ch.contactDict)
    ch.noContactMinVal =  42.0
    selectContactPairs!(sim,scene,ch,world,true)
    ch.contactPairs.nzContact = length(ch.contactDict)
    return nothing
end

# This function performs (a) a broad phase to determine which
# shapes are potentially in contact to each other, (b) computes
# the distances of these shapes in a narrow phase and (c) selects
# the nz shape pairs with the smallest distances and orders them
# according to their distances in O(n_n log(n_z)) operations.
# This function is called for contact detection during simulation.
# It also checks if the contact pairs (contact == true), from a previous call of selectContactPairsWithEvent!(...)
# are still true.
function Composition.selectContactPairsNoEvent!(sim, scene::Composition.Scene, ch::Composition.ContactDetectionMPR_handler, world::Composition.Object3D)
    ch.noContactMinVal =  42.0
    selectContactPairs!(sim,scene,ch,world,false)
    return nothing
end

function selectContactPairs!(sim, scene::Composition.Scene, ch::Composition.ContactDetectionMPR_handler, world::Composition.Object3D, hasEvent::Bool)
    if !ch.distanceComputed
        computeDistances(scene, ch, world, false, hasEvent)
    end

    # Store z in simulation engine
    if !isnothing(sim)
        simh = sim.eventHandler
        # z[1] ... zero crossing function from contact to no contact
        # max. distance (= min. penetration) of active contact pairs
        if isempty(ch.contactDict)
            @inbounds simh.z[1] = -42.0
        else
            (pair, key)  = findmax(ch.contactDict)
            @inbounds simh.z[1] = pair.distanceWithHysteresis
        end
        # z[2] ... zero crossing function from no contact to contact
        # min. distance of inactive contact pairs
        @inbounds simh.z[2] = ch.noContactMinVal
    end
    ch.distanceComputed = true
    return nothing
end

# This function performs (a) a broad phase to determine which
# shapes are potentially in contact to each other, (b) computes
# the distances of these shapes in a narrow phase and (c)
# stores the distances of the contact pairs selected by the last
# call of function selectContactPairsWithEvent!(C) in z in O(n log(nz))
# operations. This function is called whenever the integrator
# requests a new zero-crossing function evaluation
function Composition.getDistances!(scene::Composition.Scene, ch::Composition.ContactDetectionMPR_handler, world::Composition.Object3D)
    if !ch.distanceComputed
        computeDistances(scene, ch, world, true, false)
        ch.distanceComputed = true
        #println("Abstand wird berechnet, ", length(ch.contactDict) )
    end
    return nothing
end

function computeDistances(scene::Composition.Scene, ch::Composition.ContactDetectionMPR_handler, world::Composition.Object3D, phase2::Bool, hasEvent::Bool=true)
    noCPairs  = scene.noCPairs
    superObjs = scene.superObjs
    AABB = scene.AABB
    if length(superObjs) > 1
        k = 0
        @inbounds for i = 1:length(superObjs)
            superObj = superObjs[i].superObjCollision.superObj
            for j = 1:length(superObj)
                k = k +1
                obj = superObj[j]
                AABB[i][j] = Modia3D.boundingBox!(obj,
                    AABB[i][j]; tight=false, scaleFactor=0.01)
                if scene.options.visualizeBoundingBox
                    updateVisualBoundingBox!(world.AABBVisu[k], AABB[i][j])
                end
            end
        end

        # counter
        # is: actual super - object
        # js: subsequent super - object
        # i: Object3D of is_th super - object
        # j: Object3D of js_th super - object
        n = 0
        @inbounds for is = 1:length(superObjs)
            actSuperObj = superObjs[is].superObjCollision.superObj
            if !isempty(actSuperObj)
                actSuperAABB = AABB[is]
                for i = 1:length(actSuperObj)
                    actObj = actSuperObj[i]       # determine contact from this Object3D with all Object3Ds that have larger indices
                    actAABB = actSuperAABB[i]
                    for js = is+1:length(superObjs)
                        if !(js in noCPairs[is])    # PairID is not in objects which cant collide
                            nextSuperObj = superObjs[js].superObjCollision.superObj
                            nextSuperAABB = AABB[js]
                            for j = 1:length(nextSuperObj)
                                n += 1
                                nextObj  = nextSuperObj[j]
                                nextAABB = nextSuperAABB[j]
                                pairID = computePairID(scene, actObj, nextObj, is,i,js,j)

                                storeDistancesForSolver!(world, pairID, ch, actObj, nextObj,
                                actAABB, nextAABB, phase2, hasEvent)
    end; end; end; end; end; end; end
    return nothing
end

const zEps  = 1.e-8
const zEps2 = 2*zEps

function pushCollisionPair!(ch, contact, distanceWithHysteresis, pairID, contactPoint1,
    contactPoint2, contactNormal, actObj, nextObj, hasevent, supportPointsDefined, support1A, support2A,
    support3A, support1B, support2B, support3B)::Nothing
    if contact
        push!(ch.contactDict, pairID => Modia3D.ContactPair(contactPoint1,contactPoint2,
            contactNormal, actObj, nextObj, distanceWithHysteresis, supportPointsDefined,
            support1A, support2A, support3A, support1B, support2B, support3B))
    else
        if ch.noContactMinVal > distanceWithHysteresis
            ch.noContactMinVal = distanceWithHysteresis
    end; end
    return nothing
end

function storeDistancesForSolver!(world::Composition.Object3D, pairID::Composition.PairID,
    ch::Composition.ContactDetectionMPR_handler, actObj::Composition.Object3D, nextObj::Composition.Object3D, actAABB::Basics.BoundingBox, nextAABB::Basics.BoundingBox, phase2::Bool, hasEvent::Bool)

    # If object pairs are already in contact, always perform narrow phase!!
    hasContact = haskey(ch.contactDict, pairID)

    # Broad phase
    if hasContact || AABB_touching(actAABB, nextAABB) # AABB's are overlapping
        # narrow phase
        (distanceOrg, contactPoint1, contactPoint2, contactNormal, supportPointsDefined,
        support1A, support1B, support2A, support2B, support3A, support3B) =
            mpr(ch, actObj, nextObj)

    else # AABB's are not overlapping
        (distanceOrg, contactPoint1, contactPoint2, contactNormal, supportPointsDefined,
        support1A, support1B, support2A, support2B, support3A, support3B) =
            computeDistanceBetweenAABB(actAABB, nextAABB)
      #  println("AABB not overlapping")
    end

    contact                = hasEvent ? distanceOrg < -zEps : hasContact
    distanceWithHysteresis = contact  ? distanceOrg : distanceOrg + zEps2
    #  println("mpr dist: ", distanceWithHysteresis, " ", Modia3D.fullName(actObj), " ", Modia3D.fullName(nextObj))

    if hasEvent
        # At event instant
        pushCollisionPair!(ch, contact, distanceWithHysteresis, pairID,
            contactPoint1, contactPoint2, contactNormal, actObj,nextObj, hasEvent,
            supportPointsDefined, support1A, support2A, support3A, support1B, support2B, support3B)

    elseif !phase2
        # Integrator requires zero crossing function
        if contact
            # Collision pair had contact since the last event
            Modia3D.updateContactPair!(ch.contactDict[pairID], contactPoint1, contactPoint2,
                contactNormal, actObj, nextObj, distanceWithHysteresis, supportPointsDefined,
                support1A, support2A, support3A, support1B, support2B, support3B)
        else
            # Collision pair did not have contact since the last event
            pushCollisionPair!(ch, contact, distanceWithHysteresis, pairID,
                contactPoint1, contactPoint2, contactNormal, actObj, nextObj, hasEvent,
                supportPointsDefined, support1A, support2A, support3A, support1B, support2B, support3B)
        end

    else
        # Other model evaluation (only getDistances!())
        if contact
            # Collision pair had contact since the last event
            Modia3D.updateContactPair!(ch.contactDict[pairID], contactPoint1, contactPoint2,
                contactNormal, actObj, nextObj, distanceWithHysteresis, supportPointsDefined,
                support1A, support2A, support3A, support1B, support2B, support3B)
        else
            if ch.noContactMinVal > distanceWithHysteresis
                ch.noContactMinVal = distanceWithHysteresis
    end; end; end
    return nothing
end

function computeDistanceBetweenAABB(actAABB::Basics.BoundingBox, nextAABB::Basics.BoundingBox)
    xd = computeDistanceOneAxisAABB(actAABB.x_min, actAABB.x_max, nextAABB.x_min, nextAABB.x_max)
    yd = computeDistanceOneAxisAABB(actAABB.y_min, actAABB.y_max, nextAABB.y_min, nextAABB.y_max)
    zd = computeDistanceOneAxisAABB(actAABB.z_min, actAABB.z_max, nextAABB.z_min, nextAABB.z_max)
    distance = sqrt(xd^2 + yd^2 + zd^2)
    return (distance, Modia3D.ZeroVector3D, Modia3D.ZeroVector3D, Modia3D.ZeroVector3D, false, Modia3D.ZeroVector3D, Modia3D.ZeroVector3D, Modia3D.ZeroVector3D, Modia3D.ZeroVector3D, Modia3D.ZeroVector3D, Modia3D.ZeroVector3D)
end

function computeDistanceOneAxisAABB(A_min, A_max, B_min, B_max)
    if A_max < B_min
        return B_min - A_max
    elseif A_min > B_max
        return A_min - B_max
    else
        return 0.0
end; end

function Composition.closeContactDetection!(ch::Composition.ContactDetectionMPR_handler)
    empty!(ch.lastContactDict)
    empty!(ch.contactDict)
    ch.noContactMinVal =  42.0
end

function updateVisualBoundingBox!(obj::Composition.Object3D, aabb::Basics.BoundingBox)
    box::Shapes.Box = obj.shape
    box.lengthX = abs(aabb.x_max - aabb.x_min)
    box.lengthY = abs(aabb.y_max - aabb.y_min)
    box.lengthZ = abs(aabb.z_max - aabb.z_min)

    obj.r_abs = SVector((aabb.x_max + aabb.x_min)/2.0,
                        (aabb.y_max + aabb.y_min)/2.0,
                        (aabb.z_max + aabb.z_min)/2.0)
end


text:
export view_specs, bounding_box

import Requests
import FileIO, Images, Colors

const REL_DATA_DIR = joinpath("..", "data")
if !isdir(REL_DATA_DIR)
  mkdir(REL_DATA_DIR)
end
const DATA_DIR = Base.realpath(REL_DATA_DIR)
const BASE_URL = "http://vision.middlebury.edu/mview/data/data/"

const DATA_SETS = Dict{Symbol,Tuple{AbstractString,AbstractString,Bool}}(
    :dino               => ("dino"            , "dino"    , false),
    :dino_ring          => ("dinoRing"        , "dinoR"   , false),
    :dino_sparse_ring   => ("dinoSparseRing"  , "dinoSR"  , false),
    :temple             => ("temple"          , "temple"  , true ),
    :temple_ring        => ("templeRing"      , "templeR" , true ),
    :temple_sparse_ring => ("templeSparseRing", "templeSR", true )
)

function check_dataset(ds_key)
  (fn_base, im_fn_base, is_rgb) = DATA_SETS[ds_key]

  ds_dir = joinpath(DATA_DIR, fn_base)
  if !isdir(ds_dir)
    info("$ds_dir not found.")
    zip_file = joinpath(DATA_DIR, fn_base*".zip")
    zip_url = BASE_URL*fn_base*".zip"

    if !isfile(zip_file)
      info("$zip_file not found. Fetching from $zip_url...")
      Requests.save(Requests.get(zip_url), zip_file)
    end

    run(`unzip $zip_file -d $DATA_DIR`)
  end
end

function view_specs(ds)
  check_dataset(ds)
  data_set = DATA_SETS[ds]
  dir = joinpath(DATA_DIR, data_set[1])
  local lines
  open(joinpath(dir, data_set[2] * "_par.txt")) do f
    readline(f)
    lines = readlines(f)
  end

  function ln_to_spec(ln)
    strs = split(chomp(ln))
    name = strs[1]
    nums = map(s -> parse(Float32, s), strs[2:end])
    K = reshape(nums[1:9],(3,3))'
    R = reshape(nums[10:18],(3,3))'
    T = nums[19:21]
    cam = M34(K * hcat(R,T))
    (joinpath(dir, name), cam, data_set[3])
  end

  map(ln_to_spec, lines)
end

function bounding_box(ds)
  check_dataset(ds)

  function line_to_vec(ln)
    V3(map(float, split(chomp(ln)[2:end-1])))
  end

  data_set = DATA_SETS[ds]
  local lo, hi
  open(joinpath(DATA_DIR, data_set[1], "README.txt")) do f
    while !eof(f)
      ln = readline(f)
      if ismatch(r"^The \(tight\) bounding box", ln)
        lo = line_to_vec(readline(f))
        hi = line_to_vec(readline(f))
        break
      end
    end
  end
  vcat(lo',hi')
end

function View(spec)

  # read in image
  image = FileIO.load(spec[1])
  (nx, ny) = size(image)

  # convert to float array with alpha channel
  local im
  if spec[3]
    im = Array(Float32, (4, nx, ny))
    for i in 1:nx, j in 1:ny
      im[1,i,j] = 1.0
      samp = image[i,j]
      im[2,i,j] = Float32(samp.r)
      im[3,i,j] = Float32(samp.g)
      im[4,i,j] = Float32(samp.b)
    end
  else
    image = convert(Images.Image{Colors.Gray}, image)
    im = Array(Float32, (2, nx, ny))
    for i in 1:nx, j in 1:ny
      im[1,i,j] = 1.0
      im[2,i,j] = Float32(image[i,j])
    end
  end

  View(spec[2], im)
end

ext: jl

max_stars_repo_name: twadleigh/aminda

max_issues_repo_name: twadleigh/aminda

max_forks_repo_name: twadleigh/aminda


text:
# -----------------------------------------------------------
# GridLayout
# -----------------------------------------------------------

"Simple grid, indices are row-major."
immutable GridLayout <: SubplotLayout
    nr::Int
    nc::Int
end

Base.length(layout::GridLayout) = layout.nr * layout.nc
Base.start(layout::GridLayout) = 1
Base.done(layout::GridLayout, state) = state > length(layout)
function Base.next(layout::GridLayout, state)
  r = div(state-1, layout.nc) + 1
  c = mod1(state, layout.nc)
  (r,c), state + 1
end

nrows(layout::GridLayout) = layout.nr
ncols(layout::GridLayout) = layout.nc
ncols(layout::GridLayout, row::Int) = layout.nc

# get the plot index given row and column
Base.getindex(layout::GridLayout, r::Int, c::Int) = (r-1) * layout.nc + c

# -----------------------------------------------------------
# RowsLayout
# -----------------------------------------------------------

"Number of plots per row"
immutable RowsLayout <: SubplotLayout
    numplts::Int
    rowcounts::AbstractVector{Int}
end

Base.length(layout::RowsLayout) = layout.numplts
Base.start(layout::RowsLayout) = 1
Base.done(layout::RowsLayout, state) = state > length(layout)
function Base.next(layout::RowsLayout, state)
  r = 1
  c = 0
  for i = 1:state
    c += 1
    if c > layout.rowcounts[r]
      r += 1
      c = 1
    end
  end
  (r,c), state + 1
end

nrows(layout::RowsLayout) = length(layout.rowcounts)
ncols(layout::RowsLayout, row::Int) = row < 1 ? 0 : (row > nrows(layout) ? 0 : layout.rowcounts[row])

# get the plot index given row and column
Base.getindex(layout::RowsLayout, r::Int, c::Int) = sum(layout.rowcounts[1:r-1]) + c

# -----------------------------------------------------------
# FlexLayout
# -----------------------------------------------------------

"Flexible, nested layout with optional size percentages."
immutable FlexLayout <: SubplotLayout
    n::Int
    grid::Matrix # Nested layouts. Each position
                 # can be a plot index or another FlexLayout
    widths::Vector{Float64}
    heights::Vector{Float64}
end

typealias IntOrFlex Union{Int,FlexLayout}

Base.length(layout::FlexLayout) = layout.n
Base.start(layout::FlexLayout) = 1
Base.done(layout::FlexLayout, state) = state > length(layout)
function Base.next(layout::FlexLayout, state)
    # TODO: change this method to return more info
    # TODO: might consider multiple iterator types.. some backends might have an easier time row-by-row for example
    error()
    r = 1
    c = 0
    for i = 1:state
        c += 1
        if c > layout.rowcounts[r]
            r += 1
            c = 1
        end
    end
    (r,c), state + 1
end

nrows(layout::FlexLayout)           = size(layout.grid, 1)
ncols(layout::FlexLayout, row::Int) = size(layout.grid, 2)

# get the plot index given row and column
Base.getindex(layout::FlexLayout, r::Int, c::Int) = layout.grid[r,c]

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

# we're taking in a nested structure of some kind... parse it out and build a FlexLayout
function subplotlayout(mat::AbstractVecOrMat; widths = nothing, heights = nothing)
    n = 0
    nr, nc = size(mat)
    grid = Array(IntOrFlex, nr, nc)
    for i=1:nr, j=1:nc
        v = mat[i,j]

        if isa(v, Integer)
            grid[i,j] = Int(v)
            n += 1

        elseif isa(v, Tuple)
            warn("need to handle tuples somehow... (idx, sizepct)")
            grid[i,j] = nothing

        elseif v == nothing
            grid[i,j] = nothing

        elseif isa(v, AbstractVecOrMat)
            grid[i,j] = layout(v)
            n += grid[i,j].n

        else
            error("How do we process? $v")
        end
    end

    if widths == nothing
        widths = ones(nc) ./ nc
    end
    if heights == nothing
        heights = ones(nr) ./ nr
    end

    FlexLayout(n, grid, widths, heights)
end

function subplotlayout(sz::Tuple{Int,Int})
  GridLayout(sz...)
end

function subplotlayout(rowcounts::AVec{Int})
  RowsLayout(sum(rowcounts), rowcounts)
end

function subplotlayout(numplts::Int, nr::Int, nc::Int)

  # figure out how many rows/columns we need
  if nr == -1
    if nc == -1
      nr = round(Int, sqrt(numplts))
      nc = ceil(Int, numplts / nr)
    else
      nr = ceil(Int, numplts / nc)
    end
  else
    nc = ceil(Int, numplts / nr)
  end

  # if it's a perfect rectangle, just create a grid
  if numplts == nr * nc
    return GridLayout(nr, nc)
  end

  # create the rowcounts vector
  i = 0
  rowcounts = Int[]
  for r in 1:nr
    cnt = min(nc, numplts - i)
    push!(rowcounts, cnt)
    i += cnt
  end

  RowsLayout(numplts, rowcounts)
end


text:
function define_controlstructures(machine)
    define(machine, ".",        op_print)
    define(machine, "branch",   op_branch)
    define(machine, "?branch",  op_qbranch)
end

function op_print(machine, parent, myidx)
    print(machine.out, pop!(machine.stack))
    return 1
end

function op_branch(machine, parent, myidx)
    return parent.code[myidx + 1]
end

function op_qbranch(machine, parent, myidx)
    if pop!(machine.stack) == 0
        return parent.code[myidx + 1]
    end
    return 2
end

const op_ifthenelse = """
: if immediate
    postpone ?branch
    ' slot ,
    ' mark ,
;

: then immediate
    ' dup ,
    ' mark ,
    ' swap ,
    ' - ,
    ' 2 ,
    ' + ,
    ' store ,
;

: else immediate
    postpone branch
    ' slot ,
    ' then ,
    ' mark ,
;

"""


text:
#Computes the d-th power residue symbol (a/b)_d in F_q
#with d|q-1

@doc Markdown.doc"""
    power_residue(a::PolyElem{T}, b::PolyElem{T}, d::fmpz, q::fmpz) where T<: RingElem

Computes the $d$-th power residue symbol $\left(\frac{a}{b}\right)_d$ in $\mathbb{F}_q$.
$d$ has to divide $q-1$.
"""

function power_residue(a::PolyElem{T}, b::PolyElem{T}, d::fmpz, q::fmpz) where T<: RingElem
    if mod(q-1,d)!=0
        return error("Must have d|q-1")
    end
    e = div(q-1, d)

    if b==0 || a==0
        return error("Must have a,b!=0")
    end

    if gcd(a,b)!=1
        return 0
    end

    a = mod(a,b)

    #top part constant -> formula
    if degree(a)==0
        return powermod( powermod(fmpz(coeff(a,0)), e, q),  degree(b), q)
    end

    #switch top and bottom part -> recursion (general reciprocity law)
    symbol = mod(  mod( powermod(powermod(fmpz(leading_coefficient(a)), e, q), degree(b), q) *
    powermod(powermod(fmpz(leading_coefficient(b)), e, q), -degree(a), q),  q) *
    power_residue(b,a,d,q),   q)

    if isodd(e) && isodd(degree(a)) && isodd(degree(b))
        symbol = mod( (-1) * symbol, q)
    end

    return symbol
end


text:
# Using Base modules.
using Random
# Load a plotting library.
using Plots
# Load the distributions library.
using Distributions

using StatsPlots

mutable struct CAVI <: InferenceAlgorithm
    # n_iters   ::  Int       # maximum number of iterations
    X # Data
    K::Int       # number of iterations
    N::Int
    sigma2
    # tol :: T    # tolerence values for early convergence criteria
    m
    phi
    s2
    # proposals ::  Dict{Symbol,Any}  # Proposals for paramters
    # space     ::  Set{T}    # sampling space, emtpy means all
end

function CAVI(X, num_components::Int, n_samples::Int, sigma2=1)
    K=num_components
    N=n_samples
    # global sigma2 = 1
    rng = RandomDevice()
    phi = rand(Dirichlet(K*N, (rand(rng, Float32,(1))*rand(rng, 1:9))[1]),(3));
    m = rand(rng,floor(minimum(X)):floor(maximum(X)), (1,K))
    m += maximum(X)*rand(rng, Float32, (1,K))
    s2 = rand(rng, Float32, (1, K))
    print("\nInit mean\n")
    println(m)
    print("\nInit s2\n")
    println(s2)
    CAVI(X, num_components, n_samples, sigma2, m, phi, s2)

end

function get_elbo(alg::CAVI)
    t1 = log.(alg.s2) - alg.m./(alg.sigma2)
    t1 = sum(t1)
    t2 = -0.5.*((alg.X).^2 * ones(1, 3) + ones(3000, 1)*((alg.s2)+(alg.m).^2 ))
    t2 .+= (alg.X)*(alg.m)
    t2 .-= log.(alg.phi)
    t2 .+= alg.phi
    t2 = sum(t2)
    return t1 + t2
end

function _update_phi(alg::CAVI)
    t1 = alg.X*alg.m
    t2 = -(0.5*alg.m.^2 + 0.5*alg.s2)
    exponent = t1 .+ t2
    phi = exp.(exponent)
    alg.phi = phi ./ sum(phi,dims=2)
end
function _update_mu(alg::CAVI)
    alg.m = sum((alg.phi.*alg.X),dims=1) .* (1 ./alg.sigma2 .+ sum(alg.phi,dims=1)).^(-1)
    @assert size(alg.m)[2] == alg.K
    #print(self.m)
    alg.s2 = (1 ./alg.sigma2 .+ sum(alg.phi,dims=1)).^(-1)
    @assert size(alg.s2)[2] == alg.K
end

function _cavi_step(alg::CAVI)
    _update_phi(alg)
    _update_mu(alg)
end

function fit(alg::CAVI; max_iter=100, tol=1e-20, print_interval=50)
    # _init(X=X, num_components=num_components, n_samples=n_samples, sigma2=sigma2)
    elbo_values = [get_elbo(alg)]
    m_history = [alg.m]
    s2_history = [alg.s2]
    for iter_ in 1:(max_iter+1)
        _cavi_step(alg)
        append!(m_history, [alg.m])
        append!(s2_history, [alg.s2])
        append!(elbo_values, [get_elbo(alg)])

        if iter_ % print_interval == 0
            println(iter_, " Means: ", m_history[iter_], " ELBO: ", elbo_values[end])
        end
        if abs(elbo_values[end-1] - elbo_values[end]) < tol
            i=iter_
            elbo_val = elbo_values[end]
            println("ELBO converged with $elbo_val at iteration $i")
            break
        end
        if iter_ == max_iter
            elbo_val = elbo_values[end]
            print("ELBO ended with ll $elbo_val")
        end
    end
    elbo_values, m_history ,s2_history
end


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

## promote()

@test promote_type(Some{Int}, Some{Float64}) === Some{Float64}

## convert()

# These conversions must fail to prevent ambiguities
# when a value to wrap is already a Some or a Nothing
@test_throws MethodError convert(Some, 1)
@test_throws MethodError convert(Union{Some, Nothing}, 1)
@test_throws MethodError convert(Some{Int}, 1)
@test_throws MethodError convert(Union{Some{Int}, Nothing}, 1)

@test convert(Some, Some(1)) === convert(Union{Some, Nothing}, Some(1)) === Some(1)
@test convert(Some{Int}, Some(1)) === convert(Union{Some{Int}, Nothing}, Some(1)) === Some(1)
@test convert(Some{Int}, Some(1.0)) === Some(1)
@test convert(Union{Some{Int}, Nothing}, Some(1.0)) === Some(1)

@test_throws MethodError convert(Some, nothing)
@test_throws MethodError convert(Some{Int}, nothing)

@test convert(Some, Some(nothing)) === Some(nothing)
@test convert(Some{Nothing}, Some(nothing)) === Some(nothing)

@test convert(Union{Some, Nothing}, nothing) === nothing
@test convert(Union{Some{Int}, Nothing}, nothing) === nothing

@test convert(Union{Int, Nothing}, nothing) === nothing
@test convert(Union{Int, Nothing}, 1) === 1
@test convert(Union{Int, Nothing}, 1.0) === 1
@test convert(Nothing, nothing) === nothing
@test_throws MethodError convert(Nothing, 1)

## show()

@test sprint(show, Some(1)) == "Some(1)"
@test sprint(show, Some(Some(1))) == "Some(Some(1))"
@test repr([Some(1)]) == "Some{$Int}[1]"
@test repr([Some(Some(1))]) == "Some{Some{$Int}}[Some(1)]"

##  == and isequal nothing

@test Some(1) != nothing
@test Some(nothing) != nothing
@test !isequal(Some(1), nothing)
@test !isequal(Some(nothing), nothing)

# coalesce()

for v in (nothing, missing)
    @test coalesce(1) === 1
    @test coalesce(v) === v
    @test coalesce(v, 1) === 1
    @test coalesce(1, v) === 1
    @test coalesce(v, v) === v
    @test coalesce(v, 1, 2) === 1
    @test coalesce(1, v, 2) === 1
    @test coalesce(v, v, 2) === 2
    @test coalesce(v, v, v) === v

    @test coalesce(Some(1)) === 1
    @test coalesce(Some(v)) === v
    @test coalesce(Some(1), 0) === 1
    @test coalesce(Some(v), 0) === v
    @test coalesce(v, Some(v)) === v
    @test coalesce(Some(1), v) === 1
    @test coalesce(v, Some(1)) === 1
    @test coalesce(v, Some(1), v) === 1
    @test coalesce(v, Some(1), Some(2)) === 1
    @test coalesce(Some(1), v, Some(2)) === 1

    @test coalesce(v, missing) === missing
    @test coalesce(v, nothing) === nothing
    @test coalesce(v, missing, v) === v
    @test coalesce(v, nothing, v) === v
end

# notnothing()

using Base: notnothing
@test notnothing(1) === 1
@test_throws ArgumentError notnothing(nothing)

max_stars_repo_name: djsegal/julia-fork

max_issues_repo_name: djsegal/julia-fork

max_forks_repo_name: djsegal/julia-fork


text:
using Test
using JSON3
using Pinecone

APIKEY = ENV["PINECONE_API_KEY"]
context = Pinecone.init(APIKEY, "us-west1-gcp")

INDEX = "testfetch"
NAMESPACE = "mynamespace"
index = Pinecone.Index(INDEX);

testdict = Dict{String, Any}("genre"=>"documentary", "year"=>2019);
testvector = Pinecone.PineconeVector("testid", [0.3,0.11,0.3,0.3,0.3,0.3,0.3,0.3,0.4,0.3], testdict)
testvector2 = Pinecone.PineconeVector("testid2", [0.3,0.12,0.3,0.3,0.3,0.3,0.3,0.3,0.4,0.3], testdict)
tvraw1 = [0.3,0.12,0.3,0.3,0.3,0.3,0.3,0.3,0.4,0.3]

@testset "Fetch Test" begin
    rv = Pinecone.upsert(context, index, [testvector, testvector2])
    rvjson = JSON3.read(rv)
    @test rvjson["upsertedCount"] == 2

    rv = Pinecone.upsert(context, index, [testvector, testvector2],  NAMESPACE)
    rvjson = JSON3.read(rv)
    @test rvjson["upsertedCount"] == 2

    rv = Pinecone.fetch(context, index, ["testid"], NAMESPACE)
    @JSON3.pretty(rv)

    rvjson = JSON3.read(rv)
    @test haskey(rvjson, "vectors")
    @test haskey(rvjson, "namespace")
    @test rvjson.namespace == NAMESPACE
    @test haskey(rvjson["vectors"], "testid")

    # Fetch with namespace defaulting to "" in the method
    rv = Pinecone.fetch(context, index, ["testid"])
    rvjson = JSON3.read(rv)
    @test haskey(rvjson, "vectors")
    @test haskey(rvjson, "namespace")
    @test rvjson.namespace == ""
    @test haskey(rvjson["vectors"], "testid")

    # Fetch with empty string namespace
    rv = Pinecone.fetch(context, index, ["testid"], "")
    rvjson = JSON3.read(rv)
    @test haskey(rvjson, "vectors")
    @test haskey(rvjson, "namespace")
    @test rvjson.namespace == ""
    @test haskey(rvjson["vectors"], "testid")

    #test exceeded max ids
    @test_throws ArgumentError Pinecone.fetch(context, index, ["testid" for i in 1:1001])

end


text:
abstract type AbstractThermoSolver end
abstract type AbstractHelmholtzSolver <: AbstractThermoSolver end
macro ifverbose(text)
println(typeof(text))
    if typeof(text) == String
    quote
        if verbose == true
            println($text)
        end
    end |> esc
    else
        quote
        if verbose == true
            @show $text
        end
        end |> esc
    end
end
#volume solver
#with P and T, finds a volume that satisfies pressure(v,T) = P
#without falling on the false loop.
#overload this for cubics and consistent EOS
function volume_solver(model::AbstractHelmholtzModel,P,T,x,v0 = nothing;verbose = false)
    p(z) = core_pressure(model,z,T,x)
    fp(z) = p(z)-P
    dfp(z) = ForwardDiff.derivative(fp,z)
    if isnothing(v0)
    min_v = dot(covolumes(model),x)
    max_v = 40*T0/P0 #approx 5 times ideal gas
    #this is to be sure that (min_v,max_v) is a bracketing interval
    while fp(max_v) > 0
        max_v *= 2
    end
    while fp(min_v) < 0
        min_v *=0.5
    end
    vv = find_zeros(fp,min_v,max_v)

    if length(vv) == 1
        return vv[1]
    else length(vv) >= 1
        v1 = vv[1]
        v2 = vv[end]
        g1 = core_gibbs(model,P,v1,T,x)
        g2 = core_gibbs(model,P,v2,T,x)
        if g1 < g2
            return v2
        else
            return v1
        end
    end
else
    try
        return Roots.newton(fp,dfp,v0)
    catch
        return volume_solver(model,P,T,x)
    end
end
end
function core_mol_volume(model::AbstractHelmholtzModel,P0,T0,x0)
    v = volume_solver(model,P0,T0,x0)
    return v
end

function core_mol_volume(model::AbstractHelmholtzModel,P0,v0,T0,x0)
    v = volume_solver(model,P0,T0,x0,v0)
    return v
end
function core_mol_density(model::AbstractHelmholtzModel,P0,T0,x0)
    v = volume_solver(model,P0,T0,x0)
    return inv(v)
end

function core_mol_density(model::AbstractHelmholtzModel,P0,v0,T0,x0)
    return inv(v)
end

function core_mass_volume(model::AbstractHelmholtzModel,P0,T0,x0)
    v = volume_solver(model,P0,T0,x0)
    k = dot(molecular_weight(model),x0)*1e-03 #kg/mol
    return v/k
end

function core_mass_volume(model::AbstractHelmholtzModel,P0,v0,T0,x0)
    v = volume_solver(model,P0,T0,x0,v0)
    k = dot(molecular_weight(model),x0)*1e-03 #kg/mol
    return v/k
end

function core_mass_density(model::AbstractHelmholtzModel,P0,T0,x0)
    v = volume_solver(model,P0,T0,x0)
    k = dot(molecular_weight(model),x0)*1e-03 #kg/mol
    return k/v
end

function core_mass_density(model::AbstractHelmholtzModel,P0,v0,T0,x0)
    v = volume_solver(model,P0,T0,x0,v0)
    k = dot(molecular_weight(model),x0)*1e-03
    return k/v
end

function mol_volume(model::AbstractHelmholtzModel,P0,T0,x0)
    P1 = _transform_P(P0)
    T1 = _transform_T(T0)
    return core_mol_volume(model,P1,T1,x0)*1.0u"m^3/mol"
end

function mol_volume(model::AbstractHelmholtzModel,P0,v0,T0,x0)
    P1 = _transform_P(P0)
    T1 = _transform_T(T0)
    v1 = _transform_v(v0,molecular_weight(model),x0)
    return core_mol_volume(model,P1,v1,T1,x0)*1.0u"m^3/mol"
end

function mol_density(model::AbstractHelmholtzModel,P0,T0,x0)
    P1 = _transform_P(P0)
    T1 = _transform_T(T0)
    return core_mol_density(model,P1,T1,x0)*1.0u"mol/m^3"
end

function mol_density(model::AbstractHelmholtzModel,P0,v0,T0,x0)
    P1 = _transform_P(P0)
    T1 = _transform_T(T0)
    v1 = _transform_v(v0,molecular_weight(model),x0)
    return core_mol_density(model,P1,v1,T1,x0)*1.0u"mol/m^3"
end

function mass_volume(model::AbstractHelmholtzModel,P0,T0,x0)
    P1 = _transform_P(P0)
    T1 = _transform_T(T0)
    return core_mass_volume(model,P1,T1,x0)*1.0u"m^3/kg"
end

function mass_volume(model::AbstractHelmholtzModel,P0,v0,T0,x0)
    P1 = _transform_P(P0)
    T1 = _transform_T(T0)
    v1 = _transform_v(v0,molecular_weight(model),x0)
    return core_mass_volume(model,P1,v1,T1,x0)*1.0u"m^3/kg"
end

function mass_density(model::AbstractHelmholtzModel,P0,T0,x0)
    P1 = _transform_P(P0)
    T1 = _transform_T(T0)
    return core_mass_density(model,P1,T1,x0)*1.0u"kg/m^3"
end

function mass_density(model::AbstractHelmholtzModel,P0,v0,T0,x0)
    P1 = _transform_P(P0)
    T1 = _transform_T(T0)
    v1 = _transform_v(v0,molecular_weight(model),x0)
    return core_mass_density(model,P1,v1,T1,x0)*1.0u"kg/m^3"
end

function pt_flash(method::T,
    model::T2,
    P0,
    T0,
    x0,
    options=nothing) where T <: AbstractHelmholtzSolver where T2 <: AbstractHelmholtzModel
    throw(error("this method is not implemented."))
end

function pt_flash(
    model::T2,
    P0::Unitful.Pressure,
    T0::Unitful.Temperature,
    x0,
    method::T,
    options=nothing) where T <: AbstractHelmholtzSolver where T2 <: AbstractHelmholtzModel
    return core_pt_flash(method,
    model,
    _transform_P(P0),
    _transform_T(T0),
    x0,
    options)
end

function pt_flash(model::AbstractHelmholtzModel,
    phase0::HelmholtzPhase,
    method::AbstractHelmholtzSolver,options)
    P0 = core_pressure(model,phase0)
    T0 = temperature(phase0)
    x0 = mol_fraction(model,phase0)
    return core_pt_flash(model,P0,T0,x0,method,options)
end

#spinodal solver
#solves the equation dp/dv = 0 and gives the outer values as a tuple
function spinodal_solver(model::AbstractHelmholtzModel,T,x)
    fp(z) = core_pressure(model,z,T,x)
    dfp(z) = ForwardDiff.derivative(fp,z)
    min_v = dot(covolumes(model),x)
    max_v = 40*T0/100.0 # 0.01 atm

    #this is to be sure that (min_v,max_v) is a bracketing interval
    @show min_v
    @show max_v
    dv = find_zeros(fp,min_v,max_v,n_pts=21)
    dv
end

#function predict_saturation_pressure(model::AbstractHelmholtzModel,T0,x0,method)
function molar_volume_rackett(model::AbstractHelmholtzModel,T,x0)
    Pc = critical_pressure(model)
    Tc = critical_temperature(model)
    vc = critical_volume(model)
    Zc = core_compressibility_factor.(model,Pc,vc,Tc,Ref(1.0))
   # return vc
    return R_GAS .* Tc ./ Pc .* Zc .^ (1.0 .+ (1.0 .- T./ Tc).^(2/7) )
end


text:
# TODO: Use multiple Wordle lists and the UNIX version as well.
function candidate_pool(use_wordle = true)
    path = if use_wordle
        "data/wordle_answers.txt"
    else
        "data/unix_words.txt"
    end
    candidates = Candidate[]
    io = open(path, "r")
    for l in eachline(io)
        # For now, assume any word that's capitalized is bad to use.
        if !isuppercase(l[1])
            candidate = lowercase(chomp(l))
            if length(candidate) == 5
                push!(candidates, Candidate(candidate))
            end
        end
    end
    close(io)
    candidates
end


text:
using DAMMmodel
using Test
using DataFrames
using GLMakie

@testset verbose = true "DAMMmodel" begin
  @testset "DAMM()" begin
    df = DAMMfdata(10)
    @test typeof(DAMM(hcat(df.Tₛ, df.θ), fp)) == Vector{Float64}
  end
  @testset "DAMMfit()" begin
    df = DAMMfdata(10)
    @test typeof(DAMMfit(hcat(df.Tₛ, df.θ), df.Rₛ, 0.7)) == NTuple{7, Float64}
  end
  @testset "DAMMviz()" begin
    @test typeof(DAMMviz()) == Makie.Figure
  end
  @testset "DAMMfdata()" begin
    @test typeof(DAMMfdata(5)) == DataFrames.DataFrame
  end
  @testset "DAMMmat()" begin
    df = DAMMfdata(10)
    @test typeof(DAMMmat(df.Tₛ, df.θ, df.Rₛ, 10)) == sDAMMmat
    @test typeof(DAMMmat(df.Tₛ, df.θ, df.Rₛ, 10, 2)) == sDAMMmatq
  end
  @testset "DAMMplot()" begin
    df = DAMMfdata(10)
    @test typeof(DAMMplot(df.Tₛ, df.θ, df.Rₛ, 10)) == Makie.Figure
  end
  @testset "qbins()" begin
    df = DAMMfdata(10)
    @test typeof(qbins(df.Tₛ, df.θ, df.Rₛ, 2)) == Tuple{Vector{Float64}, Vector{Float64}, Vector{Float64}}
  end
end


text:
#==============================================================================#
# CodePipeline.jl
#
# This file is generated from:
# https://github.com/aws/aws-sdk-js/blob/master/apis/codepipeline-2015-07-09.normal.json
#==============================================================================#

__precompile__()

module CodePipeline

using AWSCore

"""
    using AWSSDK.CodePipeline.acknowledge_job
    acknowledge_job([::AWSConfig], arguments::Dict)
    acknowledge_job([::AWSConfig]; jobId=, nonce=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "AcknowledgeJob", arguments::Dict)
    codepipeline([::AWSConfig], "AcknowledgeJob", jobId=, nonce=)

# AcknowledgeJob Operation

Returns information about a specified job and whether that job has been received by the job worker. Only used for custom actions.

# Arguments

## `jobId = ::String` -- *Required*
The unique system-generated ID of the job for which you want to confirm receipt.

## `nonce = ::String` -- *Required*
A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Get this number from the response of the [PollForJobs](@ref) request that returned this job.

# Returns

`AcknowledgeJobOutput`

# Exceptions

`ValidationException`, `InvalidNonceException` or `JobNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeJob)
"""
@inline acknowledge_job(aws::AWSConfig=default_aws_config(); args...) = acknowledge_job(aws, args)

@inline acknowledge_job(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "AcknowledgeJob", args)

@inline acknowledge_job(args) = acknowledge_job(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.acknowledge_third_party_job
    acknowledge_third_party_job([::AWSConfig], arguments::Dict)
    acknowledge_third_party_job([::AWSConfig]; jobId=, nonce=, clientToken=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "AcknowledgeThirdPartyJob", arguments::Dict)
    codepipeline([::AWSConfig], "AcknowledgeThirdPartyJob", jobId=, nonce=, clientToken=)

# AcknowledgeThirdPartyJob Operation

Confirms a job worker has received the specified job. Only used for partner actions.

# Arguments

## `jobId = ::String` -- *Required*
The unique system-generated ID of the job.

## `nonce = ::String` -- *Required*
A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Get this number from the response to a [GetThirdPartyJobDetails](@ref) request.

## `clientToken = ::String` -- *Required*
The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.

# Returns

`AcknowledgeThirdPartyJobOutput`

# Exceptions

`ValidationException`, `InvalidNonceException`, `JobNotFoundException` or `InvalidClientTokenException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeThirdPartyJob)
"""
@inline acknowledge_third_party_job(aws::AWSConfig=default_aws_config(); args...) = acknowledge_third_party_job(aws, args)

@inline acknowledge_third_party_job(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "AcknowledgeThirdPartyJob", args)

@inline acknowledge_third_party_job(args) = acknowledge_third_party_job(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.create_custom_action_type
    create_custom_action_type([::AWSConfig], arguments::Dict)
    create_custom_action_type([::AWSConfig]; category=, provider=, version=, inputArtifactDetails=, outputArtifactDetails=, <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "CreateCustomActionType", arguments::Dict)
    codepipeline([::AWSConfig], "CreateCustomActionType", category=, provider=, version=, inputArtifactDetails=, outputArtifactDetails=, <keyword arguments>)

# CreateCustomActionType Operation

Creates a new custom action that can be used in all pipelines associated with the AWS account. Only used for custom actions.

# Arguments

## `category = "Source", "Build", "Deploy", "Test", "Invoke" or "Approval"` -- *Required*
The category of the custom action, such as a build action or a test action.

**Note**
> Although Source and Approval are listed as valid values, they are not currently functional. These values are reserved for future use.

## `provider = ::String` -- *Required*
The provider of the service used in the custom action, such as AWS CodeDeploy.

## `version = ::String` -- *Required*
The version identifier of the custom action.

## `settings = [ ... ]`
Returns information about the settings for an action type.
```
 settings = [
        "thirdPartyConfigurationUrl" =>  ::String,
        "entityUrlTemplate" =>  ::String,
        "executionUrlTemplate" =>  ::String,
        "revisionUrlTemplate" =>  ::String
    ]
```

## `configurationProperties = [[ ... ], ...]`
The configuration properties for the custom action.

**Note**
> You can refer to a name in the configuration properties of the custom action within the URL templates by following the format of {Config:name}, as long as the configuration property is both required and not secret. For more information, see [Create a Custom Action for a Pipeline](http://docs.aws.amazon.com/codepipeline/latest/userguide/how-to-create-custom-action.html).
```
 configurationProperties = [[
        "name" => <required> ::String,
        "required" => <required> ::Bool,
        "key" => <required> ::Bool,
        "secret" => <required> ::Bool,
        "queryable" =>  ::Bool,
        "description" =>  ::String,
        "type" =>  "String", "Number" or "Boolean"
    ], ...]
```

## `inputArtifactDetails = [ ... ]` -- *Required*
The details of the input artifact for the action, such as its commit ID.
```
 inputArtifactDetails = [
        "minimumCount" => <required> ::Int,
        "maximumCount" => <required> ::Int
    ]
```

## `outputArtifactDetails = [ ... ]` -- *Required*
The details of the output artifact of the action, such as its commit ID.
```
 outputArtifactDetails = [
        "minimumCount" => <required> ::Int,
        "maximumCount" => <required> ::Int
    ]
```

# Returns

`CreateCustomActionTypeOutput`

# Exceptions

`ValidationException` or `LimitExceededException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreateCustomActionType)
"""
@inline create_custom_action_type(aws::AWSConfig=default_aws_config(); args...) = create_custom_action_type(aws, args)

@inline create_custom_action_type(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "CreateCustomActionType", args)

@inline create_custom_action_type(args) = create_custom_action_type(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.create_pipeline
    create_pipeline([::AWSConfig], arguments::Dict)
    create_pipeline([::AWSConfig]; pipeline=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "CreatePipeline", arguments::Dict)
    codepipeline([::AWSConfig], "CreatePipeline", pipeline=)

# CreatePipeline Operation

Creates a pipeline.

# Arguments

## `pipeline = [ ... ]` -- *Required*
Represents the structure of actions and stages to be performed in the pipeline.
```
 pipeline = [
        "name" => <required> ::String,
        "roleArn" => <required> ::String,
        "artifactStore" => <required> [
            "type" => <required> "S3",
            "location" => <required> ::String,
            "encryptionKey" =>  [
                "id" => <required> ::String,
                "type" => <required> "KMS"
            ]
        ],
        "stages" => <required> [[
            "name" => <required> ::String,
            "blockers" =>  [[
                "name" => <required> ::String,
                "type" => <required> "Schedule"
            ], ...],
            "actions" => <required> [[
                "name" => <required> ::String,
                "actionTypeId" => <required> [
                    "category" => <required> "Source", "Build", "Deploy", "Test", "Invoke" or "Approval",
                    "owner" => <required> "AWS", "ThirdParty" or "Custom",
                    "provider" => <required> ::String,
                    "version" => <required> ::String
                ],
                "runOrder" =>  ::Int,
                "configuration" =>  ::Dict{String,String},
                "outputArtifacts" =>  [["name" => <required> ::String], ...],
                "inputArtifacts" =>  [["name" => <required> ::String], ...],
                "roleArn" =>  ::String
            ], ...]
        ], ...],
        "version" =>  ::Int
    ]
```

# Returns

`CreatePipelineOutput`

# Exceptions

`ValidationException`, `PipelineNameInUseException`, `InvalidStageDeclarationException`, `InvalidActionDeclarationException`, `InvalidBlockerDeclarationException`, `InvalidStructureException` or `LimitExceededException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreatePipeline)
"""
@inline create_pipeline(aws::AWSConfig=default_aws_config(); args...) = create_pipeline(aws, args)

@inline create_pipeline(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "CreatePipeline", args)

@inline create_pipeline(args) = create_pipeline(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.delete_custom_action_type
    delete_custom_action_type([::AWSConfig], arguments::Dict)
    delete_custom_action_type([::AWSConfig]; category=, provider=, version=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "DeleteCustomActionType", arguments::Dict)
    codepipeline([::AWSConfig], "DeleteCustomActionType", category=, provider=, version=)

# DeleteCustomActionType Operation

Marks a custom action as deleted. PollForJobs for the custom action will fail after the action is marked for deletion. Only used for custom actions.

**Important**
> To re-create a custom action after it has been deleted you must use a string in the version field that has never been used before. This string can be an incremented version number, for example. To restore a deleted custom action, use a JSON file that is identical to the deleted action, including the original string in the version field.

# Arguments

## `category = "Source", "Build", "Deploy", "Test", "Invoke" or "Approval"` -- *Required*
The category of the custom action that you want to delete, such as source or deploy.

## `provider = ::String` -- *Required*
The provider of the service used in the custom action, such as AWS CodeDeploy.

## `version = ::String` -- *Required*
The version of the custom action to delete.

# Exceptions

`ValidationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeleteCustomActionType)
"""
@inline delete_custom_action_type(aws::AWSConfig=default_aws_config(); args...) = delete_custom_action_type(aws, args)

@inline delete_custom_action_type(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "DeleteCustomActionType", args)

@inline delete_custom_action_type(args) = delete_custom_action_type(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.delete_pipeline
    delete_pipeline([::AWSConfig], arguments::Dict)
    delete_pipeline([::AWSConfig]; name=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "DeletePipeline", arguments::Dict)
    codepipeline([::AWSConfig], "DeletePipeline", name=)

# DeletePipeline Operation

Deletes the specified pipeline.

# Arguments

## `name = ::String` -- *Required*
The name of the pipeline to be deleted.

# Exceptions

`ValidationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeletePipeline)
"""
@inline delete_pipeline(aws::AWSConfig=default_aws_config(); args...) = delete_pipeline(aws, args)

@inline delete_pipeline(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "DeletePipeline", args)

@inline delete_pipeline(args) = delete_pipeline(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.delete_webhook
    delete_webhook([::AWSConfig], arguments::Dict)
    delete_webhook([::AWSConfig]; name=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "DeleteWebhook", arguments::Dict)
    codepipeline([::AWSConfig], "DeleteWebhook", name=)

# DeleteWebhook Operation

Deletes a previously created webhook by name. Deleting the webhook stops AWS CodePipeline from starting a pipeline every time an external event occurs. The API will return successfully when trying to delete a webhook that is already deleted. If a deleted webhook is re-created by calling PutWebhook with the same name, it will have a different URL.

# Arguments

## `name = ::String` -- *Required*
The name of the webhook you want to delete.

# Returns

`DeleteWebhookOutput`

# Exceptions

`ValidationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeleteWebhook)
"""
@inline delete_webhook(aws::AWSConfig=default_aws_config(); args...) = delete_webhook(aws, args)

@inline delete_webhook(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "DeleteWebhook", args)

@inline delete_webhook(args) = delete_webhook(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.deregister_webhook_with_third_party
    deregister_webhook_with_third_party([::AWSConfig], arguments::Dict)
    deregister_webhook_with_third_party([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "DeregisterWebhookWithThirdParty", arguments::Dict)
    codepipeline([::AWSConfig], "DeregisterWebhookWithThirdParty", <keyword arguments>)

# DeregisterWebhookWithThirdParty Operation

Removes the connection between the webhook that was created by CodePipeline and the external tool with events to be detected. Currently only supported for webhooks that target an action type of GitHub.

# Arguments

## `webhookName = ::String`
The name of the webhook you want to deregister.

# Returns

`DeregisterWebhookWithThirdPartyOutput`

# Exceptions

`ValidationException` or `WebhookNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeregisterWebhookWithThirdParty)
"""
@inline deregister_webhook_with_third_party(aws::AWSConfig=default_aws_config(); args...) = deregister_webhook_with_third_party(aws, args)

@inline deregister_webhook_with_third_party(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "DeregisterWebhookWithThirdParty", args)

@inline deregister_webhook_with_third_party(args) = deregister_webhook_with_third_party(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.disable_stage_transition
    disable_stage_transition([::AWSConfig], arguments::Dict)
    disable_stage_transition([::AWSConfig]; pipelineName=, stageName=, transitionType=, reason=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "DisableStageTransition", arguments::Dict)
    codepipeline([::AWSConfig], "DisableStageTransition", pipelineName=, stageName=, transitionType=, reason=)

# DisableStageTransition Operation

Prevents artifacts in a pipeline from transitioning to the next stage in the pipeline.

# Arguments

## `pipelineName = ::String` -- *Required*
The name of the pipeline in which you want to disable the flow of artifacts from one stage to another.

## `stageName = ::String` -- *Required*
The name of the stage where you want to disable the inbound or outbound transition of artifacts.

## `transitionType = "Inbound" or "Outbound"` -- *Required*
Specifies whether artifacts will be prevented from transitioning into the stage and being processed by the actions in that stage (inbound), or prevented from transitioning from the stage after they have been processed by the actions in that stage (outbound).

## `reason = ::String` -- *Required*
The reason given to the user why a stage is disabled, such as waiting for manual approval or manual tests. This message is displayed in the pipeline console UI.

# Exceptions

`ValidationException`, `PipelineNotFoundException` or `StageNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DisableStageTransition)
"""
@inline disable_stage_transition(aws::AWSConfig=default_aws_config(); args...) = disable_stage_transition(aws, args)

@inline disable_stage_transition(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "DisableStageTransition", args)

@inline disable_stage_transition(args) = disable_stage_transition(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.enable_stage_transition
    enable_stage_transition([::AWSConfig], arguments::Dict)
    enable_stage_transition([::AWSConfig]; pipelineName=, stageName=, transitionType=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "EnableStageTransition", arguments::Dict)
    codepipeline([::AWSConfig], "EnableStageTransition", pipelineName=, stageName=, transitionType=)

# EnableStageTransition Operation

Enables artifacts in a pipeline to transition to a stage in a pipeline.

# Arguments

## `pipelineName = ::String` -- *Required*
The name of the pipeline in which you want to enable the flow of artifacts from one stage to another.

## `stageName = ::String` -- *Required*
The name of the stage where you want to enable the transition of artifacts, either into the stage (inbound) or from that stage to the next stage (outbound).

## `transitionType = "Inbound" or "Outbound"` -- *Required*
Specifies whether artifacts will be allowed to enter the stage and be processed by the actions in that stage (inbound) or whether already-processed artifacts will be allowed to transition to the next stage (outbound).

# Exceptions

`ValidationException`, `PipelineNotFoundException` or `StageNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/EnableStageTransition)
"""
@inline enable_stage_transition(aws::AWSConfig=default_aws_config(); args...) = enable_stage_transition(aws, args)

@inline enable_stage_transition(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "EnableStageTransition", args)

@inline enable_stage_transition(args) = enable_stage_transition(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.get_job_details
    get_job_details([::AWSConfig], arguments::Dict)
    get_job_details([::AWSConfig]; jobId=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "GetJobDetails", arguments::Dict)
    codepipeline([::AWSConfig], "GetJobDetails", jobId=)

# GetJobDetails Operation

Returns information about a job. Only used for custom actions.

**Important**
> When this API is called, AWS CodePipeline returns temporary credentials for the Amazon S3 bucket used to store artifacts for the pipeline, if the action requires access to that Amazon S3 bucket for input or output artifacts. Additionally, this API returns any secret values defined for the action.

# Arguments

## `jobId = ::String` -- *Required*
The unique system-generated ID for the job.

# Returns

`GetJobDetailsOutput`

# Exceptions

`ValidationException` or `JobNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetJobDetails)
"""
@inline get_job_details(aws::AWSConfig=default_aws_config(); args...) = get_job_details(aws, args)

@inline get_job_details(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "GetJobDetails", args)

@inline get_job_details(args) = get_job_details(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.get_pipeline
    get_pipeline([::AWSConfig], arguments::Dict)
    get_pipeline([::AWSConfig]; name=, <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "GetPipeline", arguments::Dict)
    codepipeline([::AWSConfig], "GetPipeline", name=, <keyword arguments>)

# GetPipeline Operation

Returns the metadata, structure, stages, and actions of a pipeline. Can be used to return the entire structure of a pipeline in JSON format, which can then be modified and used to update the pipeline structure with [UpdatePipeline](@ref).

# Arguments

## `name = ::String` -- *Required*
The name of the pipeline for which you want to get information. Pipeline names must be unique under an Amazon Web Services (AWS) user account.

## `version = ::Int`
The version number of the pipeline. If you do not specify a version, defaults to the most current version.

# Returns

`GetPipelineOutput`

# Exceptions

`ValidationException`, `PipelineNotFoundException` or `PipelineVersionNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipeline)
"""
@inline get_pipeline(aws::AWSConfig=default_aws_config(); args...) = get_pipeline(aws, args)

@inline get_pipeline(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "GetPipeline", args)

@inline get_pipeline(args) = get_pipeline(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.get_pipeline_execution
    get_pipeline_execution([::AWSConfig], arguments::Dict)
    get_pipeline_execution([::AWSConfig]; pipelineName=, pipelineExecutionId=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "GetPipelineExecution", arguments::Dict)
    codepipeline([::AWSConfig], "GetPipelineExecution", pipelineName=, pipelineExecutionId=)

# GetPipelineExecution Operation

Returns information about an execution of a pipeline, including details about artifacts, the pipeline execution ID, and the name, version, and status of the pipeline.

# Arguments

## `pipelineName = ::String` -- *Required*
The name of the pipeline about which you want to get execution details.

## `pipelineExecutionId = ::String` -- *Required*
The ID of the pipeline execution about which you want to get execution details.

# Returns

`GetPipelineExecutionOutput`

# Exceptions

`ValidationException`, `PipelineNotFoundException` or `PipelineExecutionNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineExecution)
"""
@inline get_pipeline_execution(aws::AWSConfig=default_aws_config(); args...) = get_pipeline_execution(aws, args)

@inline get_pipeline_execution(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "GetPipelineExecution", args)

@inline get_pipeline_execution(args) = get_pipeline_execution(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.get_pipeline_state
    get_pipeline_state([::AWSConfig], arguments::Dict)
    get_pipeline_state([::AWSConfig]; name=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "GetPipelineState", arguments::Dict)
    codepipeline([::AWSConfig], "GetPipelineState", name=)

# GetPipelineState Operation

Returns information about the state of a pipeline, including the stages and actions.

# Arguments

## `name = ::String` -- *Required*
The name of the pipeline about which you want to get information.

# Returns

`GetPipelineStateOutput`

# Exceptions

`ValidationException` or `PipelineNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineState)
"""
@inline get_pipeline_state(aws::AWSConfig=default_aws_config(); args...) = get_pipeline_state(aws, args)

@inline get_pipeline_state(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "GetPipelineState", args)

@inline get_pipeline_state(args) = get_pipeline_state(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.get_third_party_job_details
    get_third_party_job_details([::AWSConfig], arguments::Dict)
    get_third_party_job_details([::AWSConfig]; jobId=, clientToken=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "GetThirdPartyJobDetails", arguments::Dict)
    codepipeline([::AWSConfig], "GetThirdPartyJobDetails", jobId=, clientToken=)

# GetThirdPartyJobDetails Operation

Requests the details of a job for a third party action. Only used for partner actions.

**Important**
> When this API is called, AWS CodePipeline returns temporary credentials for the Amazon S3 bucket used to store artifacts for the pipeline, if the action requires access to that Amazon S3 bucket for input or output artifacts. Additionally, this API returns any secret values defined for the action.

# Arguments

## `jobId = ::String` -- *Required*
The unique system-generated ID used for identifying the job.

## `clientToken = ::String` -- *Required*
The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.

# Returns

`GetThirdPartyJobDetailsOutput`

# Exceptions

`JobNotFoundException`, `ValidationException`, `InvalidClientTokenException` or `InvalidJobException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetThirdPartyJobDetails)
"""
@inline get_third_party_job_details(aws::AWSConfig=default_aws_config(); args...) = get_third_party_job_details(aws, args)

@inline get_third_party_job_details(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "GetThirdPartyJobDetails", args)

@inline get_third_party_job_details(args) = get_third_party_job_details(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.list_action_types
    list_action_types([::AWSConfig], arguments::Dict)
    list_action_types([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "ListActionTypes", arguments::Dict)
    codepipeline([::AWSConfig], "ListActionTypes", <keyword arguments>)

# ListActionTypes Operation

Gets a summary of all AWS CodePipeline action types associated with your account.

# Arguments

## `actionOwnerFilter = "AWS", "ThirdParty" or "Custom"`
Filters the list of action types to those created by a specified entity.

## `nextToken = ::String`
An identifier that was returned from the previous list action types call, which can be used to return the next set of action types in the list.

# Returns

`ListActionTypesOutput`

# Exceptions

`ValidationException` or `InvalidNextTokenException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionTypes)
"""
@inline list_action_types(aws::AWSConfig=default_aws_config(); args...) = list_action_types(aws, args)

@inline list_action_types(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "ListActionTypes", args)

@inline list_action_types(args) = list_action_types(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.list_pipeline_executions
    list_pipeline_executions([::AWSConfig], arguments::Dict)
    list_pipeline_executions([::AWSConfig]; pipelineName=, <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "ListPipelineExecutions", arguments::Dict)
    codepipeline([::AWSConfig], "ListPipelineExecutions", pipelineName=, <keyword arguments>)

# ListPipelineExecutions Operation

Gets a summary of the most recent executions for a pipeline.

# Arguments

## `pipelineName = ::String` -- *Required*
The name of the pipeline for which you want to get execution summary information.

## `maxResults = ::Int`
The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned nextToken value. The available pipeline execution history is limited to the most recent 12 months, based on pipeline execution start times. Default value is 100.

## `nextToken = ::String`
The token that was returned from the previous ListPipelineExecutions call, which can be used to return the next set of pipeline executions in the list.

# Returns

`ListPipelineExecutionsOutput`

# Exceptions

`ValidationException`, `PipelineNotFoundException` or `InvalidNextTokenException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelineExecutions)
"""
@inline list_pipeline_executions(aws::AWSConfig=default_aws_config(); args...) = list_pipeline_executions(aws, args)

@inline list_pipeline_executions(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "ListPipelineExecutions", args)

@inline list_pipeline_executions(args) = list_pipeline_executions(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.list_pipelines
    list_pipelines([::AWSConfig], arguments::Dict)
    list_pipelines([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "ListPipelines", arguments::Dict)
    codepipeline([::AWSConfig], "ListPipelines", <keyword arguments>)

# ListPipelines Operation

Gets a summary of all of the pipelines associated with your account.

# Arguments

## `nextToken = ::String`
An identifier that was returned from the previous list pipelines call, which can be used to return the next set of pipelines in the list.

# Returns

`ListPipelinesOutput`

# Exceptions

`ValidationException` or `InvalidNextTokenException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelines)
"""
@inline list_pipelines(aws::AWSConfig=default_aws_config(); args...) = list_pipelines(aws, args)

@inline list_pipelines(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "ListPipelines", args)

@inline list_pipelines(args) = list_pipelines(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.list_webhooks
    list_webhooks([::AWSConfig], arguments::Dict)
    list_webhooks([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "ListWebhooks", arguments::Dict)
    codepipeline([::AWSConfig], "ListWebhooks", <keyword arguments>)

# ListWebhooks Operation

Gets a listing of all the webhooks in this region for this account. The output lists all webhooks and includes the webhook URL and ARN, as well the configuration for each webhook.

# Arguments

## `NextToken = ::String`
The token that was returned from the previous ListWebhooks call, which can be used to return the next set of webhooks in the list.

## `MaxResults = ::Int`
The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned nextToken value.

# Returns

`ListWebhooksOutput`

# Exceptions

`ValidationException` or `InvalidNextTokenException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListWebhooks)
"""
@inline list_webhooks(aws::AWSConfig=default_aws_config(); args...) = list_webhooks(aws, args)

@inline list_webhooks(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "ListWebhooks", args)

@inline list_webhooks(args) = list_webhooks(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.poll_for_jobs
    poll_for_jobs([::AWSConfig], arguments::Dict)
    poll_for_jobs([::AWSConfig]; actionTypeId=, <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "PollForJobs", arguments::Dict)
    codepipeline([::AWSConfig], "PollForJobs", actionTypeId=, <keyword arguments>)

# PollForJobs Operation

Returns information about any jobs for AWS CodePipeline to act upon. PollForJobs is only valid for action types with "Custom" in the owner field. If the action type contains "AWS" or "ThirdParty" in the owner field, the PollForJobs action returns an error.

**Important**
> When this API is called, AWS CodePipeline returns temporary credentials for the Amazon S3 bucket used to store artifacts for the pipeline, if the action requires access to that Amazon S3 bucket for input or output artifacts. Additionally, this API returns any secret values defined for the action.

# Arguments

## `actionTypeId = [ ... ]` -- *Required*
Represents information about an action type.
```
 actionTypeId = [
        "category" => <required> "Source", "Build", "Deploy", "Test", "Invoke" or "Approval",
        "owner" => <required> "AWS", "ThirdParty" or "Custom",
        "provider" => <required> ::String,
        "version" => <required> ::String
    ]
```

## `maxBatchSize = ::Int`
The maximum number of jobs to return in a poll for jobs call.

## `queryParam = ::Dict{String,String}`
A map of property names and values. For an action type with no queryable properties, this value must be null or an empty map. For an action type with a queryable property, you must supply that property as a key in the map. Only jobs whose action configuration matches the mapped value will be returned.

# Returns

`PollForJobsOutput`

# Exceptions

`ValidationException` or `ActionTypeNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PollForJobs)
"""
@inline poll_for_jobs(aws::AWSConfig=default_aws_config(); args...) = poll_for_jobs(aws, args)

@inline poll_for_jobs(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "PollForJobs", args)

@inline poll_for_jobs(args) = poll_for_jobs(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.poll_for_third_party_jobs
    poll_for_third_party_jobs([::AWSConfig], arguments::Dict)
    poll_for_third_party_jobs([::AWSConfig]; actionTypeId=, <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "PollForThirdPartyJobs", arguments::Dict)
    codepipeline([::AWSConfig], "PollForThirdPartyJobs", actionTypeId=, <keyword arguments>)

# PollForThirdPartyJobs Operation

Determines whether there are any third party jobs for a job worker to act on. Only used for partner actions.

**Important**
> When this API is called, AWS CodePipeline returns temporary credentials for the Amazon S3 bucket used to store artifacts for the pipeline, if the action requires access to that Amazon S3 bucket for input or output artifacts.

# Arguments

## `actionTypeId = [ ... ]` -- *Required*
Represents information about an action type.
```
 actionTypeId = [
        "category" => <required> "Source", "Build", "Deploy", "Test", "Invoke" or "Approval",
        "owner" => <required> "AWS", "ThirdParty" or "Custom",
        "provider" => <required> ::String,
        "version" => <required> ::String
    ]
```

## `maxBatchSize = ::Int`
The maximum number of jobs to return in a poll for jobs call.

# Returns

`PollForThirdPartyJobsOutput`

# Exceptions

`ActionTypeNotFoundException` or `ValidationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PollForThirdPartyJobs)
"""
@inline poll_for_third_party_jobs(aws::AWSConfig=default_aws_config(); args...) = poll_for_third_party_jobs(aws, args)

@inline poll_for_third_party_jobs(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "PollForThirdPartyJobs", args)

@inline poll_for_third_party_jobs(args) = poll_for_third_party_jobs(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.put_action_revision
    put_action_revision([::AWSConfig], arguments::Dict)
    put_action_revision([::AWSConfig]; pipelineName=, stageName=, actionName=, actionRevision=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "PutActionRevision", arguments::Dict)
    codepipeline([::AWSConfig], "PutActionRevision", pipelineName=, stageName=, actionName=, actionRevision=)

# PutActionRevision Operation

Provides information to AWS CodePipeline about new revisions to a source.

# Arguments

## `pipelineName = ::String` -- *Required*
The name of the pipeline that will start processing the revision to the source.

## `stageName = ::String` -- *Required*
The name of the stage that contains the action that will act upon the revision.

## `actionName = ::String` -- *Required*
The name of the action that will process the revision.

## `actionRevision = [ ... ]` -- *Required*
Represents information about the version (or revision) of an action.
```
 actionRevision = [
        "revisionId" => <required> ::String,
        "revisionChangeId" => <required> ::String,
        "created" => <required> timestamp
    ]
```

# Returns

`PutActionRevisionOutput`

# Exceptions

`PipelineNotFoundException`, `StageNotFoundException`, `ActionNotFoundException` or `ValidationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutActionRevision)
"""
@inline put_action_revision(aws::AWSConfig=default_aws_config(); args...) = put_action_revision(aws, args)

@inline put_action_revision(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "PutActionRevision", args)

@inline put_action_revision(args) = put_action_revision(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.put_approval_result
    put_approval_result([::AWSConfig], arguments::Dict)
    put_approval_result([::AWSConfig]; pipelineName=, stageName=, actionName=, result=, token=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "PutApprovalResult", arguments::Dict)
    codepipeline([::AWSConfig], "PutApprovalResult", pipelineName=, stageName=, actionName=, result=, token=)

# PutApprovalResult Operation

Provides the response to a manual approval request to AWS CodePipeline. Valid responses include Approved and Rejected.

# Arguments

## `pipelineName = ::String` -- *Required*
The name of the pipeline that contains the action.

## `stageName = ::String` -- *Required*
The name of the stage that contains the action.

## `actionName = ::String` -- *Required*
The name of the action for which approval is requested.

## `result = [ ... ]` -- *Required*
Represents information about the result of the approval request.
```
 result = [
        "summary" => <required> ::String,
        "status" => <required> "Approved" or "Rejected"
    ]
```

## `token = ::String` -- *Required*
The system-generated token used to identify a unique approval request. The token for each open approval request can be obtained using the [GetPipelineState](@ref) action and is used to validate that the approval request corresponding to this token is still valid.

# Returns

`PutApprovalResultOutput`

# Exceptions

`InvalidApprovalTokenException`, `ApprovalAlreadyCompletedException`, `PipelineNotFoundException`, `StageNotFoundException`, `ActionNotFoundException` or `ValidationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutApprovalResult)
"""
@inline put_approval_result(aws::AWSConfig=default_aws_config(); args...) = put_approval_result(aws, args)

@inline put_approval_result(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "PutApprovalResult", args)

@inline put_approval_result(args) = put_approval_result(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.put_job_failure_result
    put_job_failure_result([::AWSConfig], arguments::Dict)
    put_job_failure_result([::AWSConfig]; jobId=, failureDetails=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "PutJobFailureResult", arguments::Dict)
    codepipeline([::AWSConfig], "PutJobFailureResult", jobId=, failureDetails=)

# PutJobFailureResult Operation

Represents the failure of a job as returned to the pipeline by a job worker. Only used for custom actions.

# Arguments

## `jobId = ::String` -- *Required*
The unique system-generated ID of the job that failed. This is the same ID returned from PollForJobs.

## `failureDetails = [ ... ]` -- *Required*
The details about the failure of a job.
```
 failureDetails = [
        "type" => <required> "JobFailed", "ConfigurationError", "PermissionError", "RevisionOutOfSync", "RevisionUnavailable" or "SystemUnavailable",
        "message" => <required> ::String,
        "externalExecutionId" =>  ::String
    ]
```

# Exceptions

`ValidationException`, `JobNotFoundException` or `InvalidJobStateException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobFailureResult)
"""
@inline put_job_failure_result(aws::AWSConfig=default_aws_config(); args...) = put_job_failure_result(aws, args)

@inline put_job_failure_result(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "PutJobFailureResult", args)

@inline put_job_failure_result(args) = put_job_failure_result(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.put_job_success_result
    put_job_success_result([::AWSConfig], arguments::Dict)
    put_job_success_result([::AWSConfig]; jobId=, <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "PutJobSuccessResult", arguments::Dict)
    codepipeline([::AWSConfig], "PutJobSuccessResult", jobId=, <keyword arguments>)

# PutJobSuccessResult Operation

Represents the success of a job as returned to the pipeline by a job worker. Only used for custom actions.

# Arguments

## `jobId = ::String` -- *Required*
The unique system-generated ID of the job that succeeded. This is the same ID returned from PollForJobs.

## `currentRevision = [ ... ]`
The ID of the current revision of the artifact successfully worked upon by the job.
```
 currentRevision = [
        "revision" => <required> ::String,
        "changeIdentifier" => <required> ::String,
        "created" =>  timestamp,
        "revisionSummary" =>  ::String
    ]
```

## `continuationToken = ::String`
A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides to identify a custom action in progress. Future jobs will use this token in order to identify the running instance of the action. It can be reused to return additional information about the progress of the custom action. When the action is complete, no continuation token should be supplied.

## `executionDetails = [ ... ]`
The execution details of the successful job, such as the actions taken by the job worker.
```
 executionDetails = [
        "summary" =>  ::String,
        "externalExecutionId" =>  ::String,
        "percentComplete" =>  ::Int
    ]
```

# Exceptions

`ValidationException`, `JobNotFoundException` or `InvalidJobStateException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobSuccessResult)
"""
@inline put_job_success_result(aws::AWSConfig=default_aws_config(); args...) = put_job_success_result(aws, args)

@inline put_job_success_result(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "PutJobSuccessResult", args)

@inline put_job_success_result(args) = put_job_success_result(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.put_third_party_job_failure_result
    put_third_party_job_failure_result([::AWSConfig], arguments::Dict)
    put_third_party_job_failure_result([::AWSConfig]; jobId=, clientToken=, failureDetails=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "PutThirdPartyJobFailureResult", arguments::Dict)
    codepipeline([::AWSConfig], "PutThirdPartyJobFailureResult", jobId=, clientToken=, failureDetails=)

# PutThirdPartyJobFailureResult Operation

Represents the failure of a third party job as returned to the pipeline by a job worker. Only used for partner actions.

# Arguments

## `jobId = ::String` -- *Required*
The ID of the job that failed. This is the same ID returned from PollForThirdPartyJobs.

## `clientToken = ::String` -- *Required*
The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.

## `failureDetails = [ ... ]` -- *Required*
Represents information about failure details.
```
 failureDetails = [
        "type" => <required> "JobFailed", "ConfigurationError", "PermissionError", "RevisionOutOfSync", "RevisionUnavailable" or "SystemUnavailable",
        "message" => <required> ::String,
        "externalExecutionId" =>  ::String
    ]
```

# Exceptions

`ValidationException`, `JobNotFoundException`, `InvalidJobStateException` or `InvalidClientTokenException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobFailureResult)
"""
@inline put_third_party_job_failure_result(aws::AWSConfig=default_aws_config(); args...) = put_third_party_job_failure_result(aws, args)

@inline put_third_party_job_failure_result(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "PutThirdPartyJobFailureResult", args)

@inline put_third_party_job_failure_result(args) = put_third_party_job_failure_result(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.put_third_party_job_success_result
    put_third_party_job_success_result([::AWSConfig], arguments::Dict)
    put_third_party_job_success_result([::AWSConfig]; jobId=, clientToken=, <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "PutThirdPartyJobSuccessResult", arguments::Dict)
    codepipeline([::AWSConfig], "PutThirdPartyJobSuccessResult", jobId=, clientToken=, <keyword arguments>)

# PutThirdPartyJobSuccessResult Operation

Represents the success of a third party job as returned to the pipeline by a job worker. Only used for partner actions.

# Arguments

## `jobId = ::String` -- *Required*
The ID of the job that successfully completed. This is the same ID returned from PollForThirdPartyJobs.

## `clientToken = ::String` -- *Required*
The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.

## `currentRevision = [ ... ]`
Represents information about a current revision.
```
 currentRevision = [
        "revision" => <required> ::String,
        "changeIdentifier" => <required> ::String,
        "created" =>  timestamp,
        "revisionSummary" =>  ::String
    ]
```

## `continuationToken = ::String`
A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides to identify a partner action in progress. Future jobs will use this token in order to identify the running instance of the action. It can be reused to return additional information about the progress of the partner action. When the action is complete, no continuation token should be supplied.

## `executionDetails = [ ... ]`
The details of the actions taken and results produced on an artifact as it passes through stages in the pipeline.
```
 executionDetails = [
        "summary" =>  ::String,
        "externalExecutionId" =>  ::String,
        "percentComplete" =>  ::Int
    ]
```

# Exceptions

`ValidationException`, `JobNotFoundException`, `InvalidJobStateException` or `InvalidClientTokenException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobSuccessResult)
"""
@inline put_third_party_job_success_result(aws::AWSConfig=default_aws_config(); args...) = put_third_party_job_success_result(aws, args)

@inline put_third_party_job_success_result(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "PutThirdPartyJobSuccessResult", args)

@inline put_third_party_job_success_result(args) = put_third_party_job_success_result(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.put_webhook
    put_webhook([::AWSConfig], arguments::Dict)
    put_webhook([::AWSConfig]; webhook=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "PutWebhook", arguments::Dict)
    codepipeline([::AWSConfig], "PutWebhook", webhook=)

# PutWebhook Operation

Defines a webhook and returns a unique webhook URL generated by CodePipeline. This URL can be supplied to third party source hosting providers to call every time there's a code change. When CodePipeline receives a POST request on this URL, the pipeline defined in the webhook is started as long as the POST request satisfied the authentication and filtering requirements supplied when defining the webhook. RegisterWebhookWithThirdParty and DeregisterWebhookWithThirdParty APIs can be used to automatically configure supported third parties to call the generated webhook URL.

# Arguments

## `webhook = [ ... ]` -- *Required*
The detail provided in an input file to create the webhook, such as the webhook name, the pipeline name, and the action name. Give the webhook a unique name which identifies the webhook being defined. You may choose to name the webhook after the pipeline and action it targets so that you can easily recognize what it's used for later.
```
 webhook = [
        "name" => <required> ::String,
        "targetPipeline" => <required> ::String,
        "targetAction" => <required> ::String,
        "filters" => <required> [[
            "jsonPath" => <required> ::String,
            "matchEquals" =>  ::String
        ], ...],
        "authentication" => <required> "GITHUB_HMAC", "IP" or "UNAUTHENTICATED",
        "authenticationConfiguration" => <required> [
            "AllowedIPRange" =>  ::String,
            "SecretToken" =>  ::String
        ]
    ]
```

# Returns

`PutWebhookOutput`

# Exceptions

`ValidationException`, `LimitExceededException`, `InvalidWebhookFilterPatternException`, `InvalidWebhookAuthenticationParametersException` or `PipelineNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutWebhook)
"""
@inline put_webhook(aws::AWSConfig=default_aws_config(); args...) = put_webhook(aws, args)

@inline put_webhook(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "PutWebhook", args)

@inline put_webhook(args) = put_webhook(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.register_webhook_with_third_party
    register_webhook_with_third_party([::AWSConfig], arguments::Dict)
    register_webhook_with_third_party([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "RegisterWebhookWithThirdParty", arguments::Dict)
    codepipeline([::AWSConfig], "RegisterWebhookWithThirdParty", <keyword arguments>)

# RegisterWebhookWithThirdParty Operation

Configures a connection between the webhook that was created and the external tool with events to be detected.

# Arguments

## `webhookName = ::String`
The name of an existing webhook created with PutWebhook to register with a supported third party.

# Returns

`RegisterWebhookWithThirdPartyOutput`

# Exceptions

`ValidationException` or `WebhookNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/RegisterWebhookWithThirdParty)
"""
@inline register_webhook_with_third_party(aws::AWSConfig=default_aws_config(); args...) = register_webhook_with_third_party(aws, args)

@inline register_webhook_with_third_party(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "RegisterWebhookWithThirdParty", args)

@inline register_webhook_with_third_party(args) = register_webhook_with_third_party(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.retry_stage_execution
    retry_stage_execution([::AWSConfig], arguments::Dict)
    retry_stage_execution([::AWSConfig]; pipelineName=, stageName=, pipelineExecutionId=, retryMode=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "RetryStageExecution", arguments::Dict)
    codepipeline([::AWSConfig], "RetryStageExecution", pipelineName=, stageName=, pipelineExecutionId=, retryMode=)

# RetryStageExecution Operation

Resumes the pipeline execution by retrying the last failed actions in a stage.

# Arguments

## `pipelineName = ::String` -- *Required*
The name of the pipeline that contains the failed stage.

## `stageName = ::String` -- *Required*
The name of the failed stage to be retried.

## `pipelineExecutionId = ::String` -- *Required*
The ID of the pipeline execution in the failed stage to be retried. Use the [GetPipelineState](@ref) action to retrieve the current pipelineExecutionId of the failed stage

## `retryMode = "FAILED_ACTIONS"` -- *Required*
The scope of the retry attempt. Currently, the only supported value is FAILED_ACTIONS.

# Returns

`RetryStageExecutionOutput`

# Exceptions

`ValidationException`, `PipelineNotFoundException`, `StageNotFoundException`, `StageNotRetryableException` or `NotLatestPipelineExecutionException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/RetryStageExecution)
"""
@inline retry_stage_execution(aws::AWSConfig=default_aws_config(); args...) = retry_stage_execution(aws, args)

@inline retry_stage_execution(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "RetryStageExecution", args)

@inline retry_stage_execution(args) = retry_stage_execution(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.start_pipeline_execution
    start_pipeline_execution([::AWSConfig], arguments::Dict)
    start_pipeline_execution([::AWSConfig]; name=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "StartPipelineExecution", arguments::Dict)
    codepipeline([::AWSConfig], "StartPipelineExecution", name=)

# StartPipelineExecution Operation

Starts the specified pipeline. Specifically, it begins processing the latest commit to the source location specified as part of the pipeline.

# Arguments

## `name = ::String` -- *Required*
The name of the pipeline to start.

# Returns

`StartPipelineExecutionOutput`

# Exceptions

`ValidationException` or `PipelineNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/StartPipelineExecution)
"""
@inline start_pipeline_execution(aws::AWSConfig=default_aws_config(); args...) = start_pipeline_execution(aws, args)

@inline start_pipeline_execution(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "StartPipelineExecution", args)

@inline start_pipeline_execution(args) = start_pipeline_execution(default_aws_config(), args)

"""
    using AWSSDK.CodePipeline.update_pipeline
    update_pipeline([::AWSConfig], arguments::Dict)
    update_pipeline([::AWSConfig]; pipeline=)

    using AWSCore.Services.codepipeline
    codepipeline([::AWSConfig], "UpdatePipeline", arguments::Dict)
    codepipeline([::AWSConfig], "UpdatePipeline", pipeline=)

# UpdatePipeline Operation

Updates a specified pipeline with edits or changes to its structure. Use a JSON file with the pipeline structure in conjunction with UpdatePipeline to provide the full structure of the pipeline. Updating the pipeline increases the version number of the pipeline by 1.

# Arguments

## `pipeline = [ ... ]` -- *Required*
The name of the pipeline to be updated.
```
 pipeline = [
        "name" => <required> ::String,
        "roleArn" => <required> ::String,
        "artifactStore" => <required> [
            "type" => <required> "S3",
            "location" => <required> ::String,
            "encryptionKey" =>  [
                "id" => <required> ::String,
                "type" => <required> "KMS"
            ]
        ],
        "stages" => <required> [[
            "name" => <required> ::String,
            "blockers" =>  [[
                "name" => <required> ::String,
                "type" => <required> "Schedule"
            ], ...],
            "actions" => <required> [[
                "name" => <required> ::String,
                "actionTypeId" => <required> [
                    "category" => <required> "Source", "Build", "Deploy", "Test", "Invoke" or "Approval",
                    "owner" => <required> "AWS", "ThirdParty" or "Custom",
                    "provider" => <required> ::String,
                    "version" => <required> ::String
                ],
                "runOrder" =>  ::Int,
                "configuration" =>  ::Dict{String,String},
                "outputArtifacts" =>  [["name" => <required> ::String], ...],
                "inputArtifacts" =>  [["name" => <required> ::String], ...],
                "roleArn" =>  ::String
            ], ...]
        ], ...],
        "version" =>  ::Int
    ]
```

# Returns

`UpdatePipelineOutput`

# Exceptions

`ValidationException`, `InvalidStageDeclarationException`, `InvalidActionDeclarationException`, `InvalidBlockerDeclarationException`, `InvalidStructureException` or `LimitExceededException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UpdatePipeline)
"""
@inline update_pipeline(aws::AWSConfig=default_aws_config(); args...) = update_pipeline(aws, args)

@inline update_pipeline(aws::AWSConfig, args) = AWSCore.Services.codepipeline(aws, "UpdatePipeline", args)

@inline update_pipeline(args) = update_pipeline(default_aws_config(), args)

end # module CodePipeline

#==============================================================================#
# End of file
#==============================================================================#


text:
"""
    LongestPaths

Find the longest simple path in a directed graph or a long path and a
good upper bound. The longest path problem is NP-hard, so the time
needed to find the solution grows quickly with the size of the graph,
unless it has some advantageous structure.

    longest_path(graph; kwargs)

Find the longest simple path in a LightGraphs directed `graph`,
starting with vertex one and ending anywhere.
"""
module LongestPaths

include("longest_path.jl")
include("utils.jl")

end


text:
function transform_norm(norm_in, mode)

    Nbins = size(norm_in, 1)
    norm = Vector{Float64}(undef, Nbins)

    @inbounds for i = 1:Nbins
        if mode == 1
            norm[i] = norm_in[i] * 1.e20
        elseif mode == 2
            norm[i] = norm_in[i] * 1.e-20
        elseif mode == 3
            norm[i] = 10.0^norm_in[i]
        elseif mode == 4
            norm[i] = norm_in[i]
        end
    end

    return norm

end

function construct_bin_centers(par, cut)

    bin = Vector{Float64}(undef, par.Nbins)

    @inbounds for i = 1:par.Nbins

        # beginning of bin
        p_start = par.pmin * 10.0^((i - 1) * par.bin_width)

        p_end = par.pmin * 10.0^(i * par.bin_width)
        if p_end > cut
            p_end = cut
        end

        bin[i] = 10.0^( 0.5 * ( log10(p_start) + log10(p_end) ) )
    end

    return bin
end


text:
"""
    FourierTransform(; modes, even = true)

Constructs a discrete Fourier transform with modes `modes` and style `even` that
operates on the 2nd, 3rd, ...N-modes+1-st dimension of the data.

# Example
```
julia> FourierTransform(modes = (12, 3, 4, 12))
```
"""
Base.@kwdef struct FourierTransform{N, T} <: AbstractTransform
    modes::NTuple{N, T}
    even::Bool = true
end

function forward(::FourierTransform{N}, x) where {N}
    return rfft(x, 2:(N + 1))
end

function inverse(tr::FourierTransform{N}, x) where {N}
    if tr.even
        d = 2 * size(x)[2] - 2
    else
        d = 2 * size(x)[2] - 1
    end
    return irfft(x, d, 2:(N + 1))
end

function truncate_modes(tr::FourierTransform{N}, coeff) where {N}
    # return a low-pass filtered version of coeff assuming
    # that coeff is a tensor of spectral weights.
    # Ex.: tr.modes = (3,)
    # [0, 1, 2, 3, -2, -1] -> [0, 1, 2, -1]
    # [a, b, c, d,  e,  f] -> [a, b, c,  f]

    # indices for the spectral coefficients that we need to retain
    inds = [
        vcat(collect(1:(m)), collect((s - m + 1):s))
        for (s, m) in zip(size(coeff)[2:(end - 1)], tr.modes)
    ]

    # we need to handle the first dimension of the real Fourier transform
    # separately
    inds[1] = collect(1:tr.modes[1])

    coeff_truncated = OperatorFlux.mview(coeff, inds, Val(N))

    return coeff_truncated
end

function pad_modes(
    ::FourierTransform,
    coeff,
    size_pad::NTuple{N, T},
) where {N, T}
    # return a padded-with-zeros version of coeff assuming
    # that coeff is a tensor of spectral weights, thereby inflating coeff.
    size_space = size(coeff)[2:(end - 1)] # sizes of space-like dimensions of coeff

    # generate a zero array and indices that point to the filled-in
    # locations
    size_padded = (size(coeff)[1], size_pad..., size(coeff)[end])
    coeff_padded = zeros(eltype(coeff), size_padded)
    inds = [
        vcat(collect(1:(div(m, 2) + 1)), collect((s - div(m, 2) + 2):s))
        for (s, m) in zip(size_pad, size(coeff)[2:(end - 1)])
    ]

    # we need to handle the first dimension of the real Fourier transform
    # separately
    inds[1] = collect(1:size_space[1])

    coeff_padded_view = OperatorFlux.mview(coeff_padded, inds, Val(N))
    coeff_padded_view .= coeff

    return coeff_padded
end

# Base extensions
Base.ndims(::FourierTransform{N}) where {N} = N
Base.eltype(::FourierTransform) = ComplexF32
Base.size(tr::FourierTransform) = [tr.modes[1]..., 2 * [tr.modes[2:end]...]...]

function Base.show(io::IO, tr::FourierTransform)
    print(io, "FourierTransform(modes = $(tr.modes), dims = $(tr.dims))")
end


text:
using DataFrames
using CSV
using Tables

const year2hour = 8760
const percent = 100

include("types.jl")
include("utils.jl")
include("loadcase.jl")
include("generation.jl")
include("P&C.jl")
include("P&A.jl")
include("I&C.jl")
include("O&M.jl")
include("D&D.jl")

max_stars_repo_name: Thiago-NovaesB/zefiro

max_issues_repo_name: Thiago-NovaesB/zefiro

max_forks_repo_name: Thiago-NovaesB/zefiro


text:
struct AffineIndex
    value::Int
end

mutable struct MOIVariable
    cp_identifier::String
    min::Union{Nothing, Int}
    max::Union{Nothing, Int}
    vi::MOI.VariableIndex
end

struct MOIConstraint{T <: Union{MOI.AbstractSet, SeaPearl.Constraint}}
    type::Type{T}
    args::Tuple
    ci::MOI.ConstraintIndex
end

mutable struct MOIAffineFunction
    cp_identifier::Union{Nothing, String}
    content::MOI.ScalarAffineFunction
end

mutable struct MOIModel
    variables::Array{MOIVariable}
    constraints::Array{MOIConstraint}
    affines::Array{MOIAffineFunction}
    objective_identifier::Union{Nothing, AffineIndex, MOI.VariableIndex}
    MOIModel() = new(MOIVariable[], MOIConstraint[], MOIAffineFunction[], nothing)
end

mutable struct MOIVariableSelectionAttribute <: MOI.AbstractOptimizerAttribute end

mutable struct MOIValueSelectionAttribute <: MOI.AbstractOptimizerAttribute end

mutable struct Optimizer <: MOI.AbstractOptimizer
    cpmodel::CPModel
    moimodel::MOIModel
    variableselection::AbstractVariableSelection
    valueselection::ValueSelection
    options::Dict{String, Any}
    terminationStatus::MOI.TerminationStatusCode
    primalStatus::MOI.ResultStatusCode

    function Optimizer()
        cpmodel = SeaPearl.CPModel(SeaPearl.Trailer())
        new(cpmodel, MOIModel(), MinDomainVariableSelection(), BasicHeuristic(), Dict{String, Any}(), MOI.OPTIMIZE_NOT_CALLED)
    end
end