text:
module TestExtras

using Base.Test
using CategoricalArrays
using NullableArrays
using Compat

# == currently throws an error for Nullables
const ==  = isequal

# Test cut

for (A, CA) in zip((Array, NullableArray, Array{Nullable}),
                    (CategoricalArray, NullableCategoricalArray, NullableCategoricalArray))
    x = @inferred cut(A([2, 3, 5]), [1, 3, 6])
    @test x == A(["[1, 3)", "[3, 6)", "[3, 6)"])
    @test isa(x, CA{String, 1})
    @test isordered(x)
    @test levels(x) == ["[1, 3)", "[3, 6)"]

    err = @test_throws ArgumentError cut(A([2, 3, 5]), [3, 6])
    if A === Array
        @test err.value.msg == "value 2 (at index 1) does not fall inside the breaks: adapt them manually, or pass extend=true"
    else
        @test err.value.msg == "value 2 (at index 1) does not fall inside the breaks: adapt them manually, or pass extend=true or nullok=true"
    end

    err = @test_throws ArgumentError cut(A([2, 3, 5]), [2, 5])
    if A === Array
        @test err.value.msg == "value 5 (at index 3) does not fall inside the breaks: adapt them manually, or pass extend=true"
    else
        @test err.value.msg == "value 5 (at index 3) does not fall inside the breaks: adapt them manually, or pass extend=true or nullok=true"
    end

    if A === Array
        err = @test_throws ArgumentError cut(A([2, 3, 5]), [2, 5], nullok=true)
        @test err.value.msg == "value 5 (at index 3) does not fall inside the breaks: adapt them manually, or pass extend=true"
    else
        x = @inferred cut(A([2, 3, 5]), [2, 5], nullok=true)
        @test x == A(["[2, 5)", "[2, 5)", Nullable()])
        @test isa(x, CA{String, 1})
        @test isordered(x)
        @test levels(x) == ["[2, 5)"]
    end

    x = @inferred cut(A([2, 3, 5]), [3, 6], extend=true)
    @test x == A(["[2, 3)", "[3, 6]", "[3, 6]"])
    @test isa(x, CA{String, 1})
    @test isordered(x)
    @test levels(x) == ["[2, 3)", "[3, 6]"]

    x = @inferred cut(A([2, 3, 5, 6]), [3, 6], extend=true)
    @test x == A(["[2, 3)", "[3, 6]", "[3, 6]", "[3, 6]"])
    @test isordered(x)
    @test levels(x) == ["[2, 3)", "[3, 6]"]

    x = @inferred cut(A([1, 2, 4]), [1, 3, 6])
    @test x == A(["[1, 3)", "[1, 3)", "[3, 6)"])
    @test isa(x, CA{String, 1})
    @test isordered(x)
    @test levels(x) == ["[1, 3)", "[3, 6)"]

    x = @inferred cut(A([1, 2, 4]), [3, 6], extend=true)
    @test x == A(["[1, 3)", "[1, 3)", "[3, 6]"])
    @test isa(x, CA{String, 1})
    @test isordered(x)
    @test levels(x) == ["[1, 3)", "[3, 6]"]

    x = @inferred cut(A([1, 2, 4]), [3], extend=true)
    @test x == A(["[1, 3)", "[1, 3)", "[3, 4]"])
    @test isa(x, CA{String, 1})
    @test isordered(x)
    @test levels(x) == ["[1, 3)", "[3, 4]"]

    x = @inferred cut(A([1, 5, 7]), [3, 6], extend=true)
    @test x == A(["[1, 3)", "[3, 6)", "[6, 7]"])
    @test isa(x, CA{String, 1})
    @test isordered(x)
    @test levels(x) == ["[1, 3)", "[3, 6)", "[6, 7]"]

    ages = [20, 22, 25, 27, 21, 23, 37, 31, 61, 45, 41, 32]
    breaks = [18, 25, 35, 60, 100]
    x = @inferred cut(A(ages), breaks)
    @test x == A(["[18, 25)", "[18, 25)", "[25, 35)", "[25, 35)", "[18, 25)", "[18, 25)",
                  "[35, 60)", "[25, 35)", "[60, 100)", "[35, 60)", "[35, 60)", "[25, 35)"])
    @test isa(x, CA{String, 1})
    @test isordered(x)
    @test levels(x) == ["[18, 25)", "[25, 35)", "[35, 60)", "[60, 100)"]

    breaks = [1, 6, 3] # Unsorted breaks
    labels = ["b", "a"] # Differs from lexical ordering
    x = @inferred cut(A([2, 3, 5]), breaks, labels=labels)
    @test x == A(["b", "a", "a"])
    @test isa(x, CA{String, 1})
    @test isordered(x)
    @test breaks == [1, 6, 3] # Check that breaks are copied before sorting
    labels[1] = "c" # Check that labels are copied
    @test levels(x) == ["b", "a"]

    x = @inferred cut(A([-1.1 3.0; 1.456 10.394]), [-2.134, 3.0, 12.5])
    @test x == A(["[-2.134, 3.0)" "[3.0, 12.5)"; "[-2.134, 3.0)" "[3.0, 12.5)"])
    @test isa(x, CA{String, 2})
    @test isordered(x)
    @test levels(x) == ["[-2.134, 3.0)", "[3.0, 12.5)"]
end

# TODO: test on nullable arrays once a quantile() method is provided for them
x = @inferred cut([5, 4, 3, 2], 2)
@test x == ["[3.5, 5.0]", "[3.5, 5.0]", "[2.0, 3.5)", "[2.0, 3.5)"]
@test isa(x, CategoricalArray)
@test isordered(x)
@test levels(x) == ["[2.0, 3.5)", "[3.5, 5.0]"]

end


text:
# model
T = Float64

verbose = false
opts_ilqr = iLQRSolverOptions{T}(verbose=verbose,live_plotting=:off)
opts_al = AugmentedLagrangianSolverOptions{T}(verbose=verbose,opts_uncon=opts_ilqr,iterations=50,penalty_scaling=10.0)
opts_altro = ALTROSolverOptions{T}(verbose=verbose,opts_al=opts_al,R_minimum_time=15.0,dt_max=0.15,dt_min=1.0e-3)

int_schemes = [:midpoint, :rk3, :rk4, :rk3_implicit, :midpoint_implicit]
model = TrajectoryOptimization.Dynamics.pendulum
n = model.n; m = model.m
xf = Problems.pendulum.xf
N = Problems.pendulum.N

# Make sure Ipopt will solve a discrete problem by converting it
prob = copy(Problems.pendulum)
opts_ipopt = DIRCOLSolverOptions(verbose=false)
res, = solve(prob, opts_ipopt)
@test prob isa Problem{T,Discrete}
@test res isa Problem{T,Continuous}

for is in int_schemes
    prob = update_problem(copy(Problems.pendulum),model=discretize_model(model,is))
    TrajectoryOptimization.solve!(prob, opts_altro)
    @test TrajectoryOptimization.max_violation(prob) < opts_al.constraint_tolerance
end

# Test undefined integration
@test_throws ArgumentError TrajectoryOptimization.Problem(model, Problems.pendulum.obj, integration=:bogus, N=N)

# Test different solve methods
prob = copy(Problems.pendulum)
solver_al = TrajectoryOptimization.AugmentedLagrangianSolver(prob, opts_al)
out = solve!(prob, solver_al)
@test out isa AugmentedLagrangianSolver

prob = copy(Problems.pendulum)
out = solve!(prob, opts_al)
@test out isa AugmentedLagrangianSolver

prob = copy(Problems.pendulum)
solver_al = TrajectoryOptimization.AugmentedLagrangianSolver(prob, opts_al)
out = solve(prob, solver_al)
@test out isa Tuple{Problem, AugmentedLagrangianSolver}
@test isnan(cost(prob))

out = solve(prob, opts_al)
@test out isa Tuple{Problem, AugmentedLagrangianSolver}
@test isnan(cost(prob))

ext: jl

max_issues_repo_name: MehrdadZareian/GMARA

max_forks_repo_name: MehrdadZareian/GMARA


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

mutable struct IoK8sApiAutoscalingV2beta2MetricSpec <: SwaggerModel
    external::Any # spec type: Union{ Nothing, IoK8sApiAutoscalingV2beta2ExternalMetricSource } # spec name: external
    object::Any # spec type: Union{ Nothing, IoK8sApiAutoscalingV2beta2ObjectMetricSource } # spec name: object
    pods::Any # spec type: Union{ Nothing, IoK8sApiAutoscalingV2beta2PodsMetricSource } # spec name: pods
    resource::Any # spec type: Union{ Nothing, IoK8sApiAutoscalingV2beta2ResourceMetricSource } # spec name: resource
    type::Any # spec type: Union{ Nothing, String } # spec name: type

    function IoK8sApiAutoscalingV2beta2MetricSpec(;external=nothing, object=nothing, pods=nothing, resource=nothing, type=nothing)
        o = new()
        validate_property(IoK8sApiAutoscalingV2beta2MetricSpec, Symbol("external"), external)
        setfield!(o, Symbol("external"), external)
        validate_property(IoK8sApiAutoscalingV2beta2MetricSpec, Symbol("object"), object)
        setfield!(o, Symbol("object"), object)
        validate_property(IoK8sApiAutoscalingV2beta2MetricSpec, Symbol("pods"), pods)
        setfield!(o, Symbol("pods"), pods)
        validate_property(IoK8sApiAutoscalingV2beta2MetricSpec, Symbol("resource"), resource)
        setfield!(o, Symbol("resource"), resource)
        validate_property(IoK8sApiAutoscalingV2beta2MetricSpec, Symbol("type"), type)
        setfield!(o, Symbol("type"), type)
        o
    end
end # type IoK8sApiAutoscalingV2beta2MetricSpec

const _property_map_IoK8sApiAutoscalingV2beta2MetricSpec = Dict{Symbol,Symbol}(Symbol("external")=>Symbol("external"), Symbol("object")=>Symbol("object"), Symbol("pods")=>Symbol("pods"), Symbol("resource")=>Symbol("resource"), Symbol("type")=>Symbol("type"))
const _property_types_IoK8sApiAutoscalingV2beta2MetricSpec = Dict{Symbol,String}(Symbol("external")=>"IoK8sApiAutoscalingV2beta2ExternalMetricSource", Symbol("object")=>"IoK8sApiAutoscalingV2beta2ObjectMetricSource", Symbol("pods")=>"IoK8sApiAutoscalingV2beta2PodsMetricSource", Symbol("resource")=>"IoK8sApiAutoscalingV2beta2ResourceMetricSource", Symbol("type")=>"String")
Base.propertynames(::Type{ IoK8sApiAutoscalingV2beta2MetricSpec }) = collect(keys(_property_map_IoK8sApiAutoscalingV2beta2MetricSpec))
Swagger.property_type(::Type{ IoK8sApiAutoscalingV2beta2MetricSpec }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiAutoscalingV2beta2MetricSpec[name]))}
Swagger.field_name(::Type{ IoK8sApiAutoscalingV2beta2MetricSpec }, property_name::Symbol) =  _property_map_IoK8sApiAutoscalingV2beta2MetricSpec[property_name]

function check_required(o::IoK8sApiAutoscalingV2beta2MetricSpec)
    (getproperty(o, Symbol("type")) === nothing) && (return false)
    true
end

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


text: # integersums(n, k) = Multicombinations.integersums(n, k)


text:
# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/FEMBasis.jl/blob/master/LICENSE

code = create_basis_and_eval(
    :Tet4,
    "4 node linear tetrahedral element",
    [
     (0.0, 0.0, 0.0), # N1
     (1.0, 0.0, 0.0), # N2
     (0.0, 1.0, 0.0), # N3
     (0.0, 0.0, 1.0), # N4
    ],
    :(1 + u + v + w),
   )

code = create_basis_and_eval(
    :Tet10,
    "10 node quadratic tetrahedral element",
    [
     (0.0, 0.0, 0.0), # N1
     (1.0, 0.0, 0.0), # N2
     (0.0, 1.0, 0.0), # N3
     (0.0, 0.0, 1.0), # N4
     (0.5, 0.0, 0.0), # N5
     (0.5, 0.5, 0.0), # N6
     (0.0, 0.5, 0.0), # N7
     (0.0, 0.0, 0.5), # N8
     (0.5, 0.0, 0.5), # N9
     (0.0, 0.5, 0.5), # N10
    ],
    :(1 + u + v + w + u*v + v*w + w*u + u^2 + v^2 + w^2),
   )


text:
using LinearAlgebra

include("../models/StochasticProcess.jl")
include("../termstructures/YieldCurve.jl")

# the actual data structure for the model
struct QuasiGaussianModel{T<:AbstractFloat} <: StochasticProcess
    yieldCurve::YieldCurve   # initial yield term structure
    d::Int64                 # specify d-dimensional Brownian motion for x(t)
                             # we do not use stoch vol z(t) for now
    times::Array{T}          # time-grid of left-constant model parameter values
    sigma::Array{T}          # volatility
    slope::Array{T}          # skew
    curve::Array{T}          # smile
    delta::Array{T}          # maturity of benchmark rates f(t,t+delta_i)
    chi::Array{T}            # mean reversion
    Gamma::Array{T,2}        # (benchmark rate) correlation matrix
    # additional model parameters
    DfT::LowerTriangular{Float64,Array{Float64,2}}
    HHfInv::Array{T,2}
end

# constructor

function QuasiGaussianModel(yieldCurve,d,times,sigma,slope,curve,delta,chi,Gamma)
    #
    # run some thorough checks on the input parameters...
    #
    DfT = cholesky(Gamma).L
    Hf_H_inv = [ exp(-chi_ * delta_) for delta_ in delta, chi_ in chi ]  # beware the order of loops!
    HHfInv = inv(Hf_H_inv)
    return QuasiGaussianModel(yieldCurve,d,times,sigma,slope,curve,delta,chi,Gamma,DfT,HHfInv)
end

# time-dependent model parameters are assumed (left-) piece-wise constant
_idx(self::QuasiGaussianModel,t) =
    min(searchsortedfirst(self.times,t), size(self.times)[1])

sigma(self::QuasiGaussianModel, i, t) = self.sigma[i,_idx(self,t)]
slope(self::QuasiGaussianModel, i, t) = self.slope[i,_idx(self,t)]
curve(self::QuasiGaussianModel, i, t) = self.curve[i,_idx(self,t)]

# additional model functions

G(self::QuasiGaussianModel, i, t, T) = (1.0-exp(-self.chi[i]*(T-t)))/self.chi[i]
GPrime(self::QuasiGaussianModel, i, t, T) = exp(-self.chi[i]*(T-t))

# path/payoff interfaces

@views function zeroBond(self::QuasiGaussianModel, t, T, X, alias; G_=nothing)
    if (t==T)
        return 1.0  # short cut
    end
    if (t==0)
        return discount(self.yieldCurve,T)  # short cut, assume x=0, y=0 initial values
    end
    if isnothing(G_)
        G_ = [ G(self, i, t, T) for i=1:self.d ]
    end
    DF1 = discount(self.yieldCurve, t)
    DF2 = discount(self.yieldCurve, T)
    Gx = transpose(G_) * X[begin:self.d]
    GyG = 0.0
    for i = 1:self.d
        y_i = X[self.d + (i-1)*self.d + 1 : self.d + i*self.d]
        tmp = transpose(y_i) * G_  # s.y(i,j) * G[j], j = 1..d
        GyG += G_[i]*tmp
    end
    ZCB = DF2 / DF1 * exp(-Gx - 0.5*GyG)
    return ZCB
end

@views function numeraire(self::QuasiGaussianModel, t, X)
    return exp(X[end]) / discount(self.yieldCurve, t)  # depends on stoch process spec
end

# process simulation interface
# X = [ x, y, s ] (y row-wise)

stateSize(self::QuasiGaussianModel) = self.d + self.d^2 + 1  # dimension of X(t) = [ x, y, s ]

factors(self::QuasiGaussianModel) = self.d  # dimension of W(t)

initialValues(self::QuasiGaussianModel) = zeros(stateSize(self))

# volatility specification is key to model properties

# f - f0 for local volatility calculation
@views function deltaForwardRate(self::QuasiGaussianModel, t, T, X; GPrime_=nothing, G_=nothing)
    # we allow GPrime, G to be provided by user to avoid costly exponentials
    if isnothing(GPrime_)
        GPrime_ = [ GPrime(self, i, t, T) for i = 1:self.d ]
    end
    if isnothing(G_)
        G_ = (1.0 .- GPrime_) ./ self.chi
    end
    df = 0.0
    for i = 1:self.d
        tmp = X[i]  # s.x(i)
        y_i = X[self.d + (i-1)*self.d + 1 : self.d + i*self.d]
        tmp = X[i] + transpose(y_i) * G_  # s.x(i) + sum[ s.y(i,j) * G[j], j = 1..d ]
        df  += GPrime_[i] * tmp
    end
    return df
end

# local volatiity spec, interpreted as diagonal matrix
function sigma_f(self::QuasiGaussianModel, t, X)
    res = zeros(self.d)
    eps = 1.0e-4   # 1bp lower cutoff for volatility
    maxFactor = 10.0  # 10 sigma upper cut-off
    for k = 1:self.d
        df = deltaForwardRate(self, t, t + self.delta[k], X)
        sigma_ = sigma(self,k,t)
        slope_ = slope(self,k,t)
        curve_ = curve(self,k,t)
        vol = sigma_ + slope_*df + curve_*abs(df)
        vol = min(max(vol,eps),maxFactor*sigma_)
        res[k] = vol
    end
    return res
end

function sigma_xT(self, t, X)
    return self.HHfInv * Diagonal(sigma_f(self,t,X)) * self.DfT
end

# simulate Quasi-Gaussian model as Gaussian model with frozen vol matrix
function evolve(self::QuasiGaussianModel, t0, X0, dt, dW, X1)
    # first we may simulate stochastic vol via lognormal approximation (or otherwise)
    # next we need V = z * sigmaxT sigmax
    sigmaxT = sigma_xT(self, t0+0.5*dt, X0)  # assume constant vol on (t0, t0+dt)
    V = sigmaxT * transpose(sigmaxT)   # we need V later for x simulation
    # we also calculate intermediate variables; these do strictly depend on X and could be cached as well
    GPrime_ = [ GPrime(self,i,0,dt) for i = 1:self.d ]
    G_      = (1.0 .- GPrime_) ./ self.chi
    # now we can calculate y
    chi_i_p_chi_j = [ (chi_i + chi_j) for chi_i in self.chi, chi_j in self.chi ]
    b = V ./ chi_i_p_chi_j
    y0 = reshape(X0[self.d+1 : self.d + self.d^2], (self.d,self.d)) # create a view and re-shape as matrix
    a = y0 - b
    # y[i,j] = a[i,j] exp{-(chi_i + chi_j)(T-t)} + b[i,j]
    for i = 1:self.d
        for j = 1:self.d
            X1[self.d + (i-1)*self.d + j] = a[i,j] * GPrime_[i] * GPrime_[j] + b[i,j]
        end
    end
    # finally we calculate x
    for i = 1:self.d  # E[ x1 | x0 ]
        X1[i] = X0[i]
        for j = 1:self.d
            X1[i] += a[i,j] * G_[j]
        end
        X1[i] *= GPrime_[i]
        sumB = sum(b[i,:])
        X1[i] += sumB * G_[i]
    end
    # we overwrite V by the variance; better re-use b and matrix op's
    for i = 1:self.d
        for j = 1:self.d
            V[i,j] *= (1.0 - GPrime_[i] * GPrime_[j]) / (self.chi[i] + self.chi[j])
        end
    end
    L = cholesky(V).L  # maybe better do this in-place

    for i = 1:self.d
        for j = 1:self.d
            X1[i] += L[i,j] * dW[j]  # maybe also exploit that L is lower triangular
        end
    end
    # finally, we need to update s as well
    x0 = sum(X0[begin:self.d])
    x1 = sum(X1[begin:self.d])
    X1[end] = X0[end] + 0.5 * (x0 + x1) * dt
    # all done
    return nothing
end

# the short rate over an integration time period
# this is required for drift calculation in multi-asset and hybrid models
@views function shortRateOverPeriod(self::QuasiGaussianModel, t0, dt, X0, X1)
    B_d = discount(self.yieldCurve,t0) / discount(self.yieldCurve,t0 + dt)  # deterministic drift part for r_d
    x_av = 0.5 * (sum(X0[begin:self.d]) + sum(X1[begin:self.d]))
    return log(B_d) / dt + x_av
end

# bond volatility is used in hybrid model vol adjuster

function zeroBondVolatility(self::QuasiGaussianModel, t, T)
    # sigma_r^T = sigma_x^T sqrt(z)
    # sigma_P^T = G(t,T)^T sigma_x^T sqrt(z)
    G_ = [ G(self, i, t, T) for i = 1:self.d ]
    sigmaxT = sigma_xT(self, 0.5*(t+T), initialValues(self))  # we approximate at x=0
    return transpose(sigmaxT) * G_
end

function zeroBondVolatilityPrime(self::QuasiGaussianModel, t, T)
    # we wrap scalar bond volatility into array to allow
    # for generalisation to multi-factor models
    GPrime_ = [ GPrime(self, i, t, T) for i = 1:self.d ]
    sigmaxT = sigma_xT(self, 0.5*(t+T), initialValues(self))  # we approximate at x=0
    return transpose(sigmaxT) * GPrime_
end

max_stars_repo_name: sschlenkrich/HybridMonteCarlo

max_issues_repo_name: sschlenkrich/HybridMonteCarlo

max_forks_repo_name: sschlenkrich/HybridMonteCarlo


text:
include("utils.jl")

struct CST{T<:AbstractFloat, N} <: AbstractAirfoil{T}
    A₀::T
    Aᵤ::Vector{T}
    Aₗ::Vector{T}
    dz::T
    C₁::T
    C₂::T
end

function CST(A::AbstractVector{T}; dz::T=0, c1::T=0.5, c2::T=1.0) where {T<:AbstractFloat}
    n, r = divrem(length(A), 2)
    if (r!=1)
        throw(ArgumentError("length of parameters must be `2N-1`"))
    end
    CST(A[1], A[2:n+1], A[n+2:end]; dz=dz, c1=c1, c2=c2)
end

function CST(A₀::T, Aᵤ::AbstractVector{T}, Aₗ::AbstractVector{T};
             dz::T=0, c1::T=0.5, c2::T=1.0) where {T<:AbstractFloat}
    if length(Aₗ) != length(Aᵤ)
        throw(ArgumentError("length(Aᵤ) != length(Aₗ)"))
    end
    n = length(Aᵤ)
    CST{T,n}(A₀, copy(Aᵤ), copy(Aₗ), dz, c1, c2)
end

function CST(n::Int,
             xᵤ::AbstractVector{T}, yᵤ::AbstractVector{T},
             xₗ::AbstractVector{T}, yₗ::AbstractVector{T},
             opt::OptimizerFactory;
             c1::T=0.5, c2::T=1.0) where {T<:AbstractFloat}
    if length(xᵤ)!=length(yᵤ)
        throw(ArgumentError("imbalanced upper-surface data: length(xᵤ)!=length(yᵤ)"))
    end
    if length(xₗ)!=length(yₗ)
        throw(ArgumentError("imbalanced lower-surface data: length(xₗ)!=length(yₗ)"))
    end
    if !(xᵤ[1] == xₗ[1] == 0)
        throw(ArgumentError("`xᵤ[1]` and `xₗ[1]` must be 0"))
    end
    if !(xᵤ[end] == xₗ[end] == 1)
        throw(ArgumentError("`xᵤ[end]` and `xₗ[end]` must be 0"))
    end
    if !isapprox(yᵤ[1], yₗ[1])
        throw(ArgumentError("`yᵤ[1]` must approximate `yₗ[1]`"))
    end
    # move LE to (0,0)
    oy = (yᵤ[1]+yₗ[1] )/2
    yₗ .-= oy
    yᵤ .-= oy
    #
    dz = (yᵤ[end] - yₗ[end])/2
    if dz < -eps(T)
        throw(ArgumentError("`yᵤ[end]` must be greater than `yₗ[end]`"))
    elseif dz < eps(T)
        dz = zero(T) # set to zero
    end
    A₀, Aᵤ, Aₗ, status = fit_cst(n, dz, xᵤ, yᵤ, xₗ, yₗ, opt; c1=c1, c2=c2)
    CST{T,n}(A₀, Aᵤ, Aₗ, dz, c1, c2)
end

function y_upper(cst::CST{T,N}, x::T)::T where{T<:AbstractFloat,N}
    y = cst.A₀*cst_S(N,0,x)
    for i = 1:N
        y += cst.Aᵤ[i]*cst_S(N,i,x)
    end
    y*cst_C(cst.C₁, cst.C₂, x) + cst.dz*x
end

function y_lower(cst::CST{T,N}, x::T)::T where{T<:AbstractFloat,N}
    y = -cst.A₀*cst_S(N,0,x)
    for i = 1:N
        y += cst.Aₗ[i]*cst_S(N,i,x)
    end
    y*cst_C(cst.C₁, cst.C₂, x)-cst.dz*x
end

function dy_upper(cst::CST{T,N}, x::T)::T where{T<:AbstractFloat,N}
    dy = cst.A₀*cst_dS(N,0,x)
    y = cst.A₀*cst_S(N,0,x)
    for i = 1:N
        y += cst.Aᵤ[i]*cst_S(N,i,x)
        dy += cst.Aᵤ[i]*cst_dS(N,i,x)
    end
    y*cst_dC(cst.C₁, cst.C₂, x)+dy*cst_C(cst.C₁, cst.C₂,x)+cst.dz
end

function dy_lower(cst::CST{T,N}, x::T)::T where{T<:AbstractFloat,N}
    dy = -cst.A₀*cst_dS(N,0,x)
    y = -cst.A₀*cst_S(N,0,x)
    for i = 1:N
        dy += cst.Aₗ[i]*cst_dS(N,i,x)
        y += cst.Aₗ[i]*cst_S(N,i,x)
    end
    y*cst_dC(cst.C₁, cst.C₂, x)+dy*cst_C(cst.C₁, cst.C₂,x)-cst.dz
end

function fy_upper(cst::CST{T,N}, x::T)::Tuple{T,T} where{T<:AbstractFloat,N}
    dy = cst.A₀*cst_dS(N,0,x)
    y = cst.A₀*cst_S(N,0,x)
    for i = 1:N
        y += cst.Aᵤ[i]*cst_S(N,i,x)
        dy += cst.Aᵤ[i]*cst_dS(N,i,x)
    end
    C = cst_C(cst.C₁, cst.C₂, x)
    dC = cst_dC(cst.C₁, cst.C₂, x)
    y*C+cst.dz*x, y*dC+dy*C+cst.dz
end

function fy_lower(cst::CST{T,N}, x::T)::Tuple{T,T} where{T<:AbstractFloat,N}
    dy = -cst.A₀*cst_dS(N,0,x)
    y = -cst.A₀*cst_S(N,0,x)
    for i = 1:N
        dy += cst.Aₗ[i]*cst_dS(N,i,x)
        y += cst.Aₗ[i]*cst_S(N,i,x)
    end
    C = cst_C(cst.C₁, cst.C₂, x)
    dC = cst_dC(cst.C₁, cst.C₂, x)
    y*C-cst.dz*x, y*dC+dy*C-cst.dz
end


text:
function fast_pca!(X::Matrix{T}, λ::Vector{T}, P::Matrix{T}, n::Int) where T<:AbstractFloat
    r = sum(λ .> 0)
    s = n - r

    if r == 0
        X .= zeros(T, n, n)
    elseif r == n
        return nothing
    elseif r == 1
        X .= (λ[1] * λ[1]) * (P[:,1] * P[:,1]')
    elseif r ≤ s
        P₁   = @view P[:, 1:r]
        λ₁   = sqrt.(λ[1:r])
        P₁λ₁ = P₁ .* λ₁'
        X   .= P₁λ₁ * P₁λ₁'
    else
        P₂   = @view P[:, (r+1):n]
        λ₂   = sqrt.(-λ[(r+1):n])
        P₂λ₂ = P₂ .* λ₂'
        X   .= X .+ P₂λ₂ * P₂λ₂'
    end
    nothing
end

"""
    cor_fastPD!(R::Matrix{<:AbstractFloat}[, τ=1e-6])

Same as [`cor_fastPD`](@ref), but saves space by overwriting the input `R`
instead of creating a copy.

See also: [`cor_fastPD`](@ref), [`cor_nearPD`](@ref)

# Examples
```jldoctest
julia> import LinearAlgebra: isposdef

julia> r = [1.00 0.82 0.56 0.44; 0.82 1.00 0.28 0.85; 0.56 0.28 1.00 0.22; 0.44 0.85 0.22 1.00]
4×4 Array{Float64,2}:
 1.0   0.82  0.56  0.44
 0.82  1.0   0.28  0.85
 0.56  0.28  1.0   0.22
 0.44  0.85  0.22  1.0

julia> isposdef(r)
false

julia> cor_fastPD!(r)

julia> isposdef(r)
true
```
"""
function cor_fastPD!(R::Matrix{<:AbstractFloat}, τ=1e-6)
    n  = size(R, 1)
    τ  = max(eps(eltype(R)), τ)

    R .= Symmetric(R, :U)
    R[diagind(R)] .= (one(eltype(R)) - τ)

    λ, P = eigen(R)
    λ   .= reverse(λ)
    P   .= reverse(P, dims=2)

    fast_pca!(R, λ, P, n)

    R[diagind(R)] .+= τ
    R .= cov2cor(R)
    nothing
end

"""
    cor_fastPD(R::Matrix{<:AbstractFloat}[, τ=1e-6])

Return a positive definite correlation matrix that is close to `R`. `τ` is a
tuning parameter that controls the minimum eigenvalue of the resulting matrix.
`τ` can be set to zero if only a positive semidefinite matrix is needed.

See also: [`cor_fastPD!`](@ref), [`cor_nearPD`](@ref)

# Examples
```jldoctest
julia> import LinearAlgebra: isposdef

julia> r = [1.00 0.82 0.56 0.44; 0.82 1.00 0.28 0.85; 0.56 0.28 1.00 0.22; 0.44 0.85 0.22 1.00]
4×4 Array{Float64,2}:
 1.0   0.82  0.56  0.44
 0.82  1.0   0.28  0.85
 0.56  0.28  1.0   0.22
 0.44  0.85  0.22  1.0

julia> isposdef(r)
false

julia> p = cor_fastPD(r)
4×4 Array{Float64,2}:
 1.0       0.817095  0.559306  0.440514
 0.817095  1.0       0.280196  0.847352
 0.559306  0.280196  1.0       0.219582
 0.440514  0.847352  0.219582  1.0

julia> isposdef(p)
true
```
"""
function cor_fastPD(R::Matrix{<:AbstractFloat}, τ=1e-6)
    X = copy(R)
    cor_fastPD!(X, τ)
    X
end
function cor_fastPD(R::Matrix{Float16}, τ=1e-6)
    X = Matrix{Float32}(R)
    cor_fastPD!(X, τ)
    Matrix{Float16}(X)
end


text:
function test_interp_sky()
    data = [1.  2.  3.  4.;
            5.  6.  7.  8.;
            9. 10. 11. 12]
    xcoords = [0.1, 2.5]
    ycoords = [0.5, 2.5, 4.]
    result = SDSSIO.interp_sky(data, xcoords, ycoords)
    @test size(result) == (2, 3)
    @test_approx_eq result[1, 1] 1.0
    @test_approx_eq result[2, 1] 7.0
    @test_approx_eq result[1, 2] 2.5
    @test_approx_eq result[2, 2] 8.5
    @test_approx_eq result[1, 3] 4.0
    @test_approx_eq result[2, 3] 10.0
end

# test coordinates out of bounds
function test_interp_sky_oob()
    data = [1.  2.  3.  4.;
            5.  6.  7.  8.;
            9. 10. 11. 12]
    xcoords = [-5.0, 4.0]
    ycoords = [-4.0, 5.0]

    result = SDSSIO.interp_sky(data, xcoords, ycoords)
    @test_approx_eq result [1.0 4.0;
                            9.0 12.0]
end

# test that read_photoobj handles missing table extensions.
function test_read_photoobj_missing()

    # get an example of a photoobj file with a missing table
    fname = joinpath(Pkg.dir("Celeste"), "test", "data",
                     "photoObj-006597-4-0025.fits")
    if !isfile(fname)
        run(`wget --quiet -O $(fname) http://data.sdss3.org/sas/dr12/boss/photoObj/301/6597/4/photoObj-006597-4-0025.fits`)
    end

    catalog = SDSSIO.read_photoobj(fname)

end

test_interp_sky()
test_interp_sky_oob()
test_read_photoobj_missing()


text:
################################################################################
#
#   module LatPhysReciprocal
#   -> LatticePhysics_Base
#   -> LinearAlgebra
#
#   --> TYPE DEFINITIONS (Abstract / Concrete)
#           - Point
#           - Path
#           - BrillouinZone
#           - ReciprocalLattice ??
#
#   --> BUILDING FUNCTIONS FOR PATHS IN MOMENTUM SPACE
#           - modification of paths
#           - pre-implemented paths
#           - paths based on Unitcells
#
#   --> BRILLOUIN ZONES
#           - type definition
#           - pre-implemented BZs
#           - construction of default BZs (2D)
#           - construction of default BZs (3D)
#
################################################################################

# module start
module LatPhysReciprocal

# used libraries
using LatPhysBase
using LatPhysLatticeConstruction
using LinearAlgebra
using HDF5

# imports (to overwrite functions)
import LatPhysBase.label
import LatPhysBase.label!
import LatPhysBase.point
import LatPhysBase.point!
import LatPhysBase.newSite
import LatPhysBase.similar
import LatPhysBase.newUnitcell
import LatPhysBase.sites
import LatPhysBase.sites!
import LatPhysBase.bonds
import LatPhysBase.bonds!
import LatPhysBase.latticeVectors
import LatPhysBase.latticeVectors!
import Base.show

# RECIPROCAL POINTS

# abstract type definition
include("reciprocal_points/abstract_rec_point.jl")
# concrete type definition
include("reciprocal_points/concrete_rec_point.jl")

# Default definitions of various points
include("reciprocal_points/default_points.jl")

# Default definitions of various points
include("reciprocal_points/k_space_points.jl")

# RECIPROCAL PATHS

# abstract type definition
include("reciprocal_paths/abstract_rec_path.jl")
# concrete type definition
include("reciprocal_paths/concrete_rec_path.jl")

# RECIPROCAL LATTICE / UNITCELL / BRILLOUIN ZONE

# abstract type definition (unitcell)
include("reciprocal_lattice/abstract_reciprocal_unitcell.jl")
# concrete type definition (unitcell)
include("reciprocal_lattice/concrete_reciprocal_unitcell.jl")

# abstract type definition (Brillouin zone)
include("reciprocal_lattice/abstract_brillouin_zone.jl")
# concrete type definition (Brillouin zone)
include("reciprocal_lattice/concrete_brillouin_zone.jl")

# construction of reciprocal lattices from real space lattices
include("reciprocal_lattice/functions_reciprocal_lattice.jl")

# construction of Brillouin zones
include("reciprocal_lattice/functions_brillouin_zone.jl")

# module end
end


text:
function windowing_test_functional()
    test_windowing_end_to_end()
end

function test_windowing_end_to_end()
    # Goal: Just run a schedule that needs a window and make sure it comes out as expected
    env = {
        "shift_time_min" => 3,
        "shift_time_max" => 8,
        "coverage"  => Array[
            [0, 0, 1, 1, 1, 1, 1, 0, 0],
            [0, 0, 0, 1, 1, 1, 1, 1, 0],
        ],
        "time_between_coverage" => 12,
        "intershift" => 12, # Time periods between shifts   # only serve 1 shift/day
    }

    employees = {
        "Lenny" => {
            "hours_min" => 6, # hours worked over simulation
            "hours_max" => 16, # hours worked over simulation
            "shift_time_min" => 3,
            "shift_time_max" => 8,
            "shift_count_min" => 1,
            "shift_count_max" => 2,
            "availability" => Array[
                [ones(Int, 8)],
                [ones(Int, 8)],
            ],
        },
    }
    ok, s = schedule(employees, env)
    @test ok

    # Check that the offsets weren't goofy :-)
    expected = {"Lenny"=>{{"length"=>5,"day"=>1,"start"=>3},{"length"=>5,"day"=>2,"start"=>4}}}
    @test expected == s
end

max_stars_repo_name: shdann/autoshift

max_issues_repo_name: shdann/autoshift

max_forks_repo_name: shdann/autoshift


text:
using GaPLAC
using AbstractGPs
using KernelFunctions
using Distributions
using CSV
using DataFrames
using Turing
using CairoMakie

spec = GaPLAC.gp_formula("y ~| OU(:x)")

eq, vars = GaPLAC._apply_vars(GaPLAC.formula(spec))
kernels = GaPLAC._walk_kernel(eq)

##

se = CSV.read("mcmc.tsv", DataFrame)
ou = CSV.read("mcmc_ou.tsv", DataFrame)
names(se)

fig = Figure()
se_ax = Axis(fig[1,1])
ou_ax = Axis(fig[1,2])

max_stars_repo_name: biobakery/GaPLAC

max_issues_repo_name: biobakery/GaPLAC

max_forks_repo_name: biobakery/GaPLAC


text:
"""
- `ModuleDocstrings.generate`: Create an API summary docstring for a module.
- `ModuleDocstrings.write`: add an API summary docstring to a package.
"""
module ModuleDocstrings

"""
    ModuleDocstrings.generate(mod::Module)

Return an API summary string for `mod`.

The summary is assembled from all docstrings in the package, picking the first sentence of each docstring.
When added to the package (see [`ModuleDocstrings.write`](@ref)), you should expect to make edits by hand:

- exclude docstrings that shouldn't appear in the API summary
- rephrase summaries for greater clarity or compactness (alternatively, consider making such changes to the
  original docstring)
"""
function generate(mod::Module)
    exported = Set(names(mod))
    docex, docpriv = Pair{String,Vector{String}}[], Pair{String,Vector{String}}[]
    for (bind, doc) in Base.Docs.meta(mod)
        tgt, key = bind.var ∈ exported ? (docex, String(bind.var)) : (docpriv, string(bind))
        push!(tgt, key => firstsentences(doc))
    end
    sort!(docex; by=first)
    sort!(docpriv; by=first)
    io = IOBuffer()
    for doc in (docex, docpriv)
        for (key, methsummaries) in doc
            print(io, "- `", key, "`:")
            if length(methsummaries) == 1
                print(io, ' ', methsummaries[1])
            else
                for msum in methsummaries
                    print(io, "\n  + ", msum)
                end
            end
            print(io, '\n')
        end
    end
    return String(take!(io))
end

firstsentences(docs::Base.Docs.MultiDoc) = String[firstsentences(docstr) for (sig, docstr) in docs.docs]
firstsentences(doc) = firstsentence(doc)
firstsentence(docstr::Base.Docs.DocStr) = firstsentence(docstr.text)
firstsentence(itr) = firstsentence(join(itr))
function firstsentence(d::AbstractDict)
    @assert length(d) == 1 "multiple entries ($(length(itr))) for a given signature"
    return firstsentence(first(d).second)
end
function firstsentence(str::AbstractString)
    # @show str
    io = IOBuffer()
    for line in split(str, '\n')
        startswith(line, "    ") && continue   # code line
        all(isspace, line) && continue
        idx = findfirst(r"\.(\s|$)", line)
        if idx === nothing
            print(io, line, ' ')
            continue
        end
        print(io, line[1:first(idx)])
        return String(take!(io))
    end
    return String(take!(io))
end

"""
    ModuleDocstrings.write(mod, str)

Edit the module-defining file to insert `str` as a docstring for `mod`.

The package should be checked out in `develop` mode before calling `write`.
"""
function write(mod::Module, str)
    path = pathof(mod)
    (path === nothing || !iswritable(path)) && error_write(mod, path)
    modstr = read(path, String)
    idxs = findfirst("module $mod", modstr)
    idxs === nothing && error("could not identify start of module")
    open(path, "w") do io
        print(io, modstr[1:first(idxs)-1], "\"\"\"\n", str, "\"\"\"\n", modstr[first(idxs):end])
    end
end

"""
    ModuleDocstrings.write(mod)

Modify the source file for `mod` to add an API summary docstring.

The docstring is produced by [ModuleDocstrings.generate](@ref).
The package should be checked out in `develop` mode before calling `write`.
"""
write(mod::Module) = write(mod, generate(mod))

# this is replacing, not extending, the Base function of the same name
iswritable(filename::AbstractString) = isfile(filename) && (uperm(filename) & 0x02) != 0x00

error_write(mod, ::Nothing) = error("$mod must be a writable package, but there is no corresponding file, suggesting it wasn't loaded from a package.")
error_write(mod, path::AbstractString) = error("$mod must be a writable package, but the path \"$path\" is not writable.\nDid you forget to `Pkg.develop` the package?")

end

max_stars_repo_name: JuliaDocs/ModuleDocstrings

max_issues_repo_name: JuliaDocs/ModuleDocstrings

max_forks_repo_name: JuliaDocs/ModuleDocstrings


text:
using Microbiome
using DataFrames
using Random
using Test

@testset "Abundances" begin
    # Constructors
    M = rand(100, 10)
    df = hcat(DataFrame(x=collect(1:100)), DataFrame(M))

    a1 = abundancetable(M)
    a2 = abundancetable(df)
    @test typeof(a1) <:AbstractComMatrix
    @test typeof(a2) <:AbstractComMatrix

    abund = abundancetable(
        M, ["sample_$x" for x in 1:10],
        ["feature_$x" for x in 1:100])

    @test a1.occurrences == a2.occurrences == abund.occurrences

    # Normalization functions
    relab_fract = relativeabundance(abund)
    @test typeof(relab_fract) <: AbstractComMatrix

    relab_perc = relativeabundance(abund, kind=:percent)
    @test typeof(relab_perc) <: AbstractComMatrix

    rnorm = rownormalize(abund)
    cnorm = colnormalize(abund)

    @test size(abund) == (nfeatures(abund), nsamples(abund))
    @test size(relab_fract) == (nfeatures(relab_fract), nsamples(relab_fract))
    @test size(relab_perc) == (nfeatures(relab_perc), nsamples(relab_perc))
    @test size(rnorm) == (nfeatures(rnorm), nsamples(rnorm))
    @test size(cnorm) == (nfeatures(cnorm), nsamples(cnorm))

    for j in 1:10
        @test sum(getsample(relab_fract, j)) ≈ 1
        @test sum(getsample(relab_perc, j)) ≈ 100
    end

    for i in 1:nfeatures(rnorm)
        @test maximum(getfeature(rnorm,i)) ≈ 1
    end

    for j in 1:nsamples(cnorm)
        @test maximum(getsample(cnorm, j)) ≈ 1
    end

    # Filtering Functions
    filt = filterabund(relab_fract, 5)
    @test typeof(filt) <: AbstractComMatrix
    @test typeof(filterabund(df, 5)) <: AbstractComMatrix

    @test size(filt) == (6, 10)
    for i in 1:10
        @test sum(getsample(filt, i)) ≈ 1
    end

    @test featurenames(filt)[end] == "other"

    @test present(0.1, 0.001)
    @test !present(0.001, 0.1)
    @test present(rand(), 0.)

    a = zeros(100)
    a[randperm(100)[1:10]] .= rand(10)

    @test prevalence(a, 0.) == 0.1
end

@testset "Distances" begin
    # Constructors
    Random.seed!(1)
    M = rand(100, 10)
    df = hcat(DataFrame(x=collect(1:100)), DataFrame(M))
    abund = abundancetable(
        M, ["sample_$x" for x in 1:10],
        ["feature_$x" for x in 1:100])

    # Diversity indicies
    R = 100
    s1 = rand(R) # high diversity
    s2 = [i % 10 == 0 ? s1[i] : 0 for i in 1:R] # low diversity
    s3 = ones(R) # uniform
    s4 = [1., zeros(R-1)...] # no diversity

    @test shannon(s1) > shannon(s2)
    @test shannon(s3) ≈ log(R)
    @test shannon(s4) ≈ 0.

    @test ginisimpson(s1) > ginisimpson(s2)
    @test ginisimpson(s3) ≈ 1. - 1/R
    @test ginisimpson(s4) ≈ 0.

    @test length(shannon(abund)) == 10
    @test length(ginisimpson(abund)) == 10
end


text:
"""
    DiscreteBelief
A belief specified by a probability vector.
Normalization of `b` is NOT enforced at all times, but the `DiscreteBeleif(pomdp, b)` constructor will warn, and `update(...)` always returns a belief with normalized `b`.
"""
struct DiscreteBelief{P, S}
    pomdp::P
    state_list::Vector{S}       # vector of ordered states
    b::Vector{Float64}
end

function DiscreteBelief(prob::Union{POMDP,IPOMDP,RPOMDP,RIPOMDP}, state_list::AbstractVector, b::AbstractVector{Float64}, check::Bool)
    if check
        if !isapprox(sum(b), 1.0, atol=0.001)
            warn("""
                 b in DiscreteBelief(pomdp, b) does not sum to 1.
                 To suppress this warning use `DiscreteBelief(pomdp, b, check=false)`
                 """)
        end
        if !all(0.0 <= p <= 1.0 for p in b)
            warn("""
                 b in DiscreteBelief(pomdp, b) contains entries outside [0,1].
                 To suppress this warning use `DiscreteBelief(pomdp, b, check=false)`
                 """)
        end
    end
    return DiscreteBelief(prob, state_list, b)
end

function DiscreteBelief(prob::Union{POMDP,IPOMDP,RPOMDP,RIPOMDP}, b::Vector{Float64}; check::Bool=true)
    return DiscreteBelief(prob, ordered_states(prob), b, check)
end

function DiscreteBelief(prob::Union{POMDP,IPOMDP,RPOMDP,RIPOMDP}, b; check::Bool=true)
    # convert b to a vector representation
    state_list = ordered_states(prob)
    bv = Vector{Float64}(n_states(prob))
    for (i, s) in enumerate(state_list)
        bv[i] = pdf(b, s)
    end
    return DiscreteBelief(prob, state_list, bv, check)
end

"""
Return a DiscreteBelief with equal probability for each state.
"""
function uniform_belief(prob::Union{POMDP,IPOMDP,RPOMDP,RIPOMDP})
    state_list = ordered_states(prob)
    ns = length(state_list)
    return DiscreteBelief(prob, state_list, ones(ns) / ns)
end

pdf(b::DiscreteBelief, s) = b.b[state_index(b.pomdp, s)]

function rand(rng::AbstractRNG, b::DiscreteBelief)
    i = sample(rng, Weights(b.b))
    return b.state_list[i]
end

function Base.fill!(b::DiscreteBelief, x::Float64)
    fill!(b.b, x)
    return b
end

Base.length(b::DiscreteBelief) = length(b.b)

iterator(b::DiscreteBelief) = b.state_list

==(b1::DiscreteBelief, b2::DiscreteBelief) = b1.state_list == b2.state_list && b1.b == b2.b

Base.hash(b::DiscreteBelief, h::UInt) = hash(b.b, hash(b.state_list, h))

mutable struct DiscreteUpdater{P} <: Updater
    pomdp::P
end

mutable struct RobustUpdater{R} <: Updater
    rpomdp::R
    alphas::Vector{Vector{Float64}}
end
DiscreteUpdater(pomdp::Union{POMDP,IPOMDP}, alphas::Vector{Vector{Float64}}) = DiscreteUpdater(pomdp)
DiscreteUpdater(rpomdp::Union{RPOMDP,RIPOMDP}, alphas::Vector{Vector{Float64}}) = RobustUpdater(rpomdp, alphas)

uniform_belief(up::DiscreteUpdater) = uniform_belief(up.pomdp)
uniform_belief(up::RobustUpdater) = uniform_belief(up.rpomdp)

function initialize_belief(bu::DiscreteUpdater, dist::Any)
    state_list = ordered_states(bu.pomdp)
    ns = length(state_list)
    b = zeros(ns)
    belief = DiscreteBelief(bu.pomdp, state_list, b)
    for s in iterator(dist)
        sidx = state_index(bu.pomdp, s)
        belief.b[sidx] = pdf(dist, s)
    end
    return belief
end

function initialize_belief(bu::RobustUpdater, dist::Any)
    state_list = ordered_states(bu.rpomdp)
    ns = length(state_list)
    b = zeros(ns)
    belief = DiscreteBelief(bu.rpomdp, state_list, b)
    for s in iterator(dist)
        sidx = state_index(bu.rpomdp, s)
        belief.b[sidx] = pdf(dist, s)
    end
    return belief
end

function update(bu::DiscreteUpdater, b::DiscreteBelief, a, o)
    pomdp = b.pomdp
    state_space = b.state_list
    bp = zeros(length(state_space))
    bp_sum = 0.0   # to normalize the distribution
    for (spi, sp) in enumerate(state_space)
        # po = O(a, sp, o)
        od = observation(pomdp, a, sp)
        po = pdf(od, o)
        # @show po
        (po == 0.0) && continue
        b_sum = 0.0
        for (si, s) in enumerate(state_space)
            td = transition(pomdp, s, a)
            pp = pdf(td, sp)
            # @show pp
            b_sum += pp * b.b[si]
        end
        bp[spi] = po * b_sum
        bp_sum += bp[spi]
        # @show bp_sum
    end
    if bp_sum == 0.0
        error("""
              Failed discrete belief update: new probabilities sum to zero.
              b = $b
              a = $a
              o = $o
              Failed discrete belief update: new probabilities sum to zero.
              """)
    else
        # @show bp
        bp ./= bp_sum
    end

    return DiscreteBelief(pomdp, b.state_list, bp)
end

# Eq. (5) Osogami 2015
# from p[t,z,s,a] to p[t,z,s]
function minutil(prob::Union{RPOMDP,RIPOMDP}, b::Vector{Float64}, a, alphavecs::Vector{Vector{Float64}})
   nz = n_observations(prob)
   ns = n_states(prob)
   nα = length(alphavecs)
   aind = action_index(prob, a)
   plower, pupper = dynamics(prob)
   m = Model(solver = ClpSolver())
   @variable(m, u[1:nz])
   @variable(m, p[1:ns, 1:nz, 1:ns])
   @objective(m, Min, sum(u))
   for zind = 1:nz, αind = 1:nα
       @constraint(m, u[zind] >= sum(b[sind] * p[:,zind,sind]' * alphavecs[αind] for sind = 1:ns))
   end
   @constraint(m, p .<= pupper[:,:,:,aind])
   @constraint(m, p .>= plower[:,:,:,aind])
   for sind = 1:ns
       @constraint(m, sum(p[:,:,sind]) == 1)
   end
   JuMP.solve(m)
   getvalue(u), getvalue(p)
end

function update(bu::RobustUpdater, b::DiscreteBelief, a, o)
    rpomdp = b.pomdp
    state_space = b.state_list
    bp = zeros(length(state_space))
    oi = obs_index(rpomdp, o)
    bp_sum = 0.0   # to normalize the distribution
    umin, pmin = minutil(rpomdp, b.b, a, bu.alphas)
    # @show pmin
    for (spi, sp) in enumerate(state_space)
        (sum(pmin[spi,:,:]) == 0.0) && continue
        po = sum(pmin[spi,oi,:]) / sum(pmin[spi,:,:])
        # @show po
        (po == 0.0) && continue
        b_sum = 0.0
        for (si, s) in enumerate(state_space)
            # pnumer = sum(pmin[spi,:,si])
            # if pnumer < 1e-4
            #     pp = pnumer
            # else
            #     pp = sum(pmin[spi,:,si]) / sum(pmin[:,:,si])
            # end
            pp = sum(pmin[spi,:,si]) / sum(pmin[:,:,si])
            # @show pp
            b_sum += pp * b.b[si]
        end
        bp[spi] = po * b_sum
        bp_sum += bp[spi]
        # @show bp_sum
    end
    if bp_sum == 0.0
        error("""
              Failed discrete belief update: new probabilities sum to zero.
              b = $b
              a = $a
              o = $o
              Failed discrete belief update: new probabilities sum to zero.
              """)
    else
        # @show bp
        bp ./= bp_sum
    end
    return DiscreteBelief(rpomdp, b.state_list, bp)
end

update(bu::Union{RobustUpdater,DiscreteUpdater}, b::Any, a, o) = update(bu, initialize_belief(bu, b), a, o)

# DEPRECATED
@generated function create_belief(bu::DiscreteUpdater)
    Core.println("WARNING: create_belief(up::DiscreteUpdater) is deprecated. Use uniform_belief(up) instead.")
    return :(uniform_belief(bu))
end

# alphas are |A|x|S|
# computes dot product of alpha vectors and belief
# util is array with utility of each alpha vecotr for belief b
@generated function product(alphas::Matrix{Float64}, b::DiscreteBelief)
    Core.println("WARNING: product(alphas, b::DiscreteBelief) is deprecated.")
    quote
        @assert size(alphas, 1) == length(b) "Alpha and belief sizes not equal"
        n = size(alphas, 2)
        util = zeros(n)
        for i = 1:n
            s = 0.0
            for j = 1:length(b)
                s += alphas[j,i]*b.b[j]
            end
            util[i] = s
        end
        return util
    end
end


text:
### Creating driving activity: INPUT is datamatrix, p_min, p_max, e, T, number_zones and OUTPUT is p_drive

function createpdrive(datamatrix, distance_matrix_km, number_zones)
    p_drive = zeros(number_zones, T);
    mean_sum = zeros(number_zones, T);
    min_t = zeros(number_zones,1);
    max_t = zeros(number_zones,1);

    # Calculating the sums, minimum sums and maximum sums of mean travel time out of a zone
    for i=1:number_zones
        for t=1:T
            mean_sum[i, t] = 0;
            counter = 0;
            for j=1:number_zones
                if(datamatrix[i,j,t,1] != 0)
                    mean_sum[i, t] = mean_sum[i, t] + datamatrix[i,j,t,1]/distance_matrix_km[i,j];
                    counter += 1;
                end
            end
            mean_sum[i, t] = mean_sum[i, t]/counter;
        end
        max_t[i] = maximum(mean_sum[i,:]);
        min_t[i] = minimum(mean_sum[i,:]);
    end

    ## Calculating the Bernoulli distributions p_drive
    for i=1:number_zones
        if(max_t[i] > 0) # A zero would lead to infinity given the formula below and create NaN entries.
            for t=1:T
                # A linear function for assigning a value of 10% to p_drive if min_t is given, and a value of 90% if max_t is given.
                p_drive[i,t] = p_min + (p_max - p_min) * ((mean_sum[i,t] - min_t[i]) / (max_t[i] - min_t[i]))^e_drive;
            end
        end
    end

    return p_drive;

end

max_stars_repo_name: ArsamAryandoust/CarParkingMaps

max_issues_repo_name: ArsamAryandoust/CarParkingMaps

max_forks_repo_name: ArsamAryandoust/CarParkingMaps


text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: customer_profiles
using AWS.Compat
using AWS.UUIDs

"""
    add_profile_key(domain_name, key_name, profile_id, values)
    add_profile_key(domain_name, key_name, profile_id, values, params::Dict{String,<:Any})

Associates a new key value with a specific profile, such as a Contact Trace Record (CTR)
ContactId. A profile object can have a single unique key and any number of additional keys
that can be used to identify the profile that it belongs to.

# Arguments
- `domain_name`: The unique name of the domain.
- `key_name`: A searchable identifier of a customer profile.
- `profile_id`: The unique identifier of a customer profile.
- `values`: A list of key values.

"""
function add_profile_key(
    DomainName,
    KeyName,
    ProfileId,
    Values;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/keys",
        Dict{String,Any}(
            "KeyName" => KeyName, "ProfileId" => ProfileId, "Values" => Values
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function add_profile_key(
    DomainName,
    KeyName,
    ProfileId,
    Values,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/keys",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "KeyName" => KeyName, "ProfileId" => ProfileId, "Values" => Values
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_domain(default_expiration_days, domain_name)
    create_domain(default_expiration_days, domain_name, params::Dict{String,<:Any})

Creates a domain, which is a container for all customer data, such as customer profile
attributes, object types, profile keys, and encryption keys. You can create multiple
domains, and each domain can have multiple third-party integrations. Each Amazon Connect
instance can be associated with only one domain. Multiple Amazon Connect instances can be
associated with one domain. Use this API or UpdateDomain to enable identity resolution: set
Matching to true.  To prevent cross-service impersonation when you call this API, see
Cross-service confused deputy prevention for sample policies that you should apply.

# Arguments
- `default_expiration_days`: The default number of days until the data within the domain
  expires.
- `domain_name`: The unique name of the domain.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DeadLetterQueueUrl"`: The URL of the SQS dead letter queue, which is used for reporting
  errors associated with ingesting data from third party applications. You must set up a
  policy on the DeadLetterQueue for the SendMessage operation to enable Amazon Connect
  Customer Profiles to send messages to the DeadLetterQueue.
- `"DefaultEncryptionKey"`: The default encryption key, which is an AWS managed key, is
  used when no specific type of encryption key is specified. It is used to encrypt all data
  before it is placed in permanent or semi-permanent storage.
- `"Matching"`: The process of matching duplicate profiles. If Matching = true, Amazon
  Connect Customer Profiles starts a weekly batch process called Identity Resolution Job. If
  you do not specify a date and time for Identity Resolution Job to run, by default it runs
  every Saturday at 12AM UTC to detect duplicate profiles in your domains.  After the
  Identity Resolution Job completes, use the GetMatches API to return and review the results.
  Or, if you have configured ExportingConfig in the MatchingRequest, you can download the
  results from S3.
- `"Tags"`: The tags used to organize, track, or control access for this resource.
"""
function create_domain(
    DefaultExpirationDays, DomainName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)",
        Dict{String,Any}("DefaultExpirationDays" => DefaultExpirationDays);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_domain(
    DefaultExpirationDays,
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("DefaultExpirationDays" => DefaultExpirationDays),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_profile(domain_name)
    create_profile(domain_name, params::Dict{String,<:Any})

Creates a standard profile. A standard profile represents the following attributes for a
customer profile in a domain.

# Arguments
- `domain_name`: The unique name of the domain.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AccountNumber"`: A unique account number that you have given to the customer.
- `"AdditionalInformation"`: Any additional information relevant to the customer’s
  profile.
- `"Address"`: A generic address associated with the customer that is not mailing,
  shipping, or billing.
- `"Attributes"`: A key value pair of attributes of a customer profile.
- `"BillingAddress"`: The customer’s billing address.
- `"BirthDate"`: The customer’s birth date.
- `"BusinessEmailAddress"`: The customer’s business email address.
- `"BusinessName"`: The name of the customer’s business.
- `"BusinessPhoneNumber"`: The customer’s business phone number.
- `"EmailAddress"`: The customer’s email address, which has not been specified as a
  personal or business address.
- `"FirstName"`: The customer’s first name.
- `"Gender"`: The gender with which the customer identifies.
- `"HomePhoneNumber"`: The customer’s home phone number.
- `"LastName"`: The customer’s last name.
- `"MailingAddress"`: The customer’s mailing address.
- `"MiddleName"`: The customer’s middle name.
- `"MobilePhoneNumber"`: The customer’s mobile phone number.
- `"PartyType"`: The type of profile used to describe the customer.
- `"PersonalEmailAddress"`: The customer’s personal email address.
- `"PhoneNumber"`: The customer’s phone number, which has not been specified as a mobile,
  home, or business number.
- `"ShippingAddress"`: The customer’s shipping address.
"""
function create_profile(DomainName; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_profile(
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_domain(domain_name)
    delete_domain(domain_name, params::Dict{String,<:Any})

Deletes a specific domain and all of its customer data, such as customer profile attributes
and their related objects.

# Arguments
- `domain_name`: The unique name of the domain.

"""
function delete_domain(DomainName; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "DELETE",
        "/domains/$(DomainName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_domain(
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "DELETE",
        "/domains/$(DomainName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_integration(domain_name, uri)
    delete_integration(domain_name, uri, params::Dict{String,<:Any})

Removes an integration from a specific domain.

# Arguments
- `domain_name`: The unique name of the domain.
- `uri`: The URI of the S3 bucket or any other type of data source.

"""
function delete_integration(
    DomainName, Uri; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/integrations/delete",
        Dict{String,Any}("Uri" => Uri);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_integration(
    DomainName,
    Uri,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/integrations/delete",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("Uri" => Uri), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_profile(domain_name, profile_id)
    delete_profile(domain_name, profile_id, params::Dict{String,<:Any})

Deletes the standard customer profile and all data pertaining to the profile.

# Arguments
- `domain_name`: The unique name of the domain.
- `profile_id`: The unique identifier of a customer profile.

"""
function delete_profile(
    DomainName, ProfileId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/delete",
        Dict{String,Any}("ProfileId" => ProfileId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_profile(
    DomainName,
    ProfileId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/delete",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ProfileId" => ProfileId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_profile_key(domain_name, key_name, profile_id, values)
    delete_profile_key(domain_name, key_name, profile_id, values, params::Dict{String,<:Any})

Removes a searchable key from a customer profile.

# Arguments
- `domain_name`: The unique name of the domain.
- `key_name`: A searchable identifier of a customer profile.
- `profile_id`: The unique identifier of a customer profile.
- `values`: A list of key values.

"""
function delete_profile_key(
    DomainName,
    KeyName,
    ProfileId,
    Values;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/keys/delete",
        Dict{String,Any}(
            "KeyName" => KeyName, "ProfileId" => ProfileId, "Values" => Values
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_profile_key(
    DomainName,
    KeyName,
    ProfileId,
    Values,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/keys/delete",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "KeyName" => KeyName, "ProfileId" => ProfileId, "Values" => Values
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_profile_object(domain_name, object_type_name, profile_id, profile_object_unique_key)
    delete_profile_object(domain_name, object_type_name, profile_id, profile_object_unique_key, params::Dict{String,<:Any})

Removes an object associated with a profile of a given ProfileObjectType.

# Arguments
- `domain_name`: The unique name of the domain.
- `object_type_name`: The name of the profile object type.
- `profile_id`: The unique identifier of a customer profile.
- `profile_object_unique_key`: The unique identifier of the profile object generated by the
  service.

"""
function delete_profile_object(
    DomainName,
    ObjectTypeName,
    ProfileId,
    ProfileObjectUniqueKey;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/objects/delete",
        Dict{String,Any}(
            "ObjectTypeName" => ObjectTypeName,
            "ProfileId" => ProfileId,
            "ProfileObjectUniqueKey" => ProfileObjectUniqueKey,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_profile_object(
    DomainName,
    ObjectTypeName,
    ProfileId,
    ProfileObjectUniqueKey,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/objects/delete",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "ObjectTypeName" => ObjectTypeName,
                    "ProfileId" => ProfileId,
                    "ProfileObjectUniqueKey" => ProfileObjectUniqueKey,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_profile_object_type(domain_name, object_type_name)
    delete_profile_object_type(domain_name, object_type_name, params::Dict{String,<:Any})

Removes a ProfileObjectType from a specific domain as well as removes all the
ProfileObjects of that type. It also disables integrations from this specific
ProfileObjectType. In addition, it scrubs all of the fields of the standard profile that
were populated from this ProfileObjectType.

# Arguments
- `domain_name`: The unique name of the domain.
- `object_type_name`: The name of the profile object type.

"""
function delete_profile_object_type(
    DomainName, ObjectTypeName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "DELETE",
        "/domains/$(DomainName)/object-types/$(ObjectTypeName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_profile_object_type(
    DomainName,
    ObjectTypeName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "DELETE",
        "/domains/$(DomainName)/object-types/$(ObjectTypeName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_auto_merging_preview(conflict_resolution, consolidation, domain_name)
    get_auto_merging_preview(conflict_resolution, consolidation, domain_name, params::Dict{String,<:Any})

Tests the auto-merging settings of your Identity Resolution Job without merging your data.
It randomly selects a sample of matching groups from the existing matching results, and
applies the automerging settings that you provided. You can then view the number of
profiles in the sample, the number of matches, and the number of profiles identified to be
merged. This enables you to evaluate the accuracy of the attributes in your matching list.
You can't view which profiles are matched and would be merged.  We strongly recommend you
use this API to do a dry run of the automerging process before running the Identity
Resolution Job. Include at least two matching attributes. If your matching list includes
too few attributes (such as only FirstName or only LastName), there may be a large number
of matches. This increases the chances of erroneous merges.

# Arguments
- `conflict_resolution`: How the auto-merging process should resolve conflicts between
  different profiles.
- `consolidation`: A list of matching attributes that represent matching criteria.
- `domain_name`: The unique name of the domain.

"""
function get_auto_merging_preview(
    ConflictResolution,
    Consolidation,
    DomainName;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/identity-resolution-jobs/auto-merging-preview",
        Dict{String,Any}(
            "ConflictResolution" => ConflictResolution, "Consolidation" => Consolidation
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_auto_merging_preview(
    ConflictResolution,
    Consolidation,
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/identity-resolution-jobs/auto-merging-preview",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "ConflictResolution" => ConflictResolution,
                    "Consolidation" => Consolidation,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_domain(domain_name)
    get_domain(domain_name, params::Dict{String,<:Any})

Returns information about a specific domain.

# Arguments
- `domain_name`: The unique name of the domain.

"""
function get_domain(DomainName; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_domain(
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_identity_resolution_job(domain_name, job_id)
    get_identity_resolution_job(domain_name, job_id, params::Dict{String,<:Any})

Returns information about an Identity Resolution Job in a specific domain.  Identity
Resolution Jobs are set up using the Amazon Connect admin console. For more information,
see Use Identity Resolution to consolidate similar profiles.

# Arguments
- `domain_name`: The unique name of the domain.
- `job_id`: The unique identifier of the Identity Resolution Job.

"""
function get_identity_resolution_job(
    DomainName, JobId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/identity-resolution-jobs/$(JobId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_identity_resolution_job(
    DomainName,
    JobId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/identity-resolution-jobs/$(JobId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_integration(domain_name, uri)
    get_integration(domain_name, uri, params::Dict{String,<:Any})

Returns an integration for a domain.

# Arguments
- `domain_name`: The unique name of the domain.
- `uri`: The URI of the S3 bucket or any other type of data source.

"""
function get_integration(DomainName, Uri; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/integrations",
        Dict{String,Any}("Uri" => Uri);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_integration(
    DomainName,
    Uri,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/integrations",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("Uri" => Uri), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_matches(domain_name)
    get_matches(domain_name, params::Dict{String,<:Any})

Before calling this API, use CreateDomain or UpdateDomain to enable identity resolution:
set Matching to true. GetMatches returns potentially matching profiles, based on the
results of the latest run of a machine learning process.   The process of matching
duplicate profiles. If Matching = true, Amazon Connect Customer Profiles starts a weekly
batch process called Identity Resolution Job. If you do not specify a date and time for
Identity Resolution Job to run, by default it runs every Saturday at 12AM UTC to detect
duplicate profiles in your domains.  After the Identity Resolution Job completes, use the
GetMatches API to return and review the results. Or, if you have configured ExportingConfig
in the MatchingRequest, you can download the results from S3.  Amazon Connect uses the
following profile attributes to identify matches:   PhoneNumber   HomePhoneNumber
BusinessPhoneNumber   MobilePhoneNumber   EmailAddress   PersonalEmailAddress
BusinessEmailAddress   FullName   BusinessName   For example, two or more profiles—with
spelling mistakes such as John Doe and Jhn Doe, or different casing email addresses such as
JOHN_DOE@ANYCOMPANY.COM and johndoe@anycompany.com, or different phone number formats such
as 555-010-0000 and +1-555-010-0000—can be detected as belonging to the same customer
John Doe and merged into a unified profile.

# Arguments
- `domain_name`: The unique name of the domain.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max-results"`: The maximum number of results to return per page.
- `"next-token"`: The token for the next set of results. Use the value returned in the
  previous response in the next request to retrieve the next set of results.
"""
function get_matches(DomainName; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/matches";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_matches(
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/matches",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_profile_object_type(domain_name, object_type_name)
    get_profile_object_type(domain_name, object_type_name, params::Dict{String,<:Any})

Returns the object types for a specific domain.

# Arguments
- `domain_name`: The unique name of the domain.
- `object_type_name`: The name of the profile object type.

"""
function get_profile_object_type(
    DomainName, ObjectTypeName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/object-types/$(ObjectTypeName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_profile_object_type(
    DomainName,
    ObjectTypeName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/object-types/$(ObjectTypeName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_profile_object_type_template(template_id)
    get_profile_object_type_template(template_id, params::Dict{String,<:Any})

Returns the template information for a specific object type. A template is a predefined
ProfileObjectType, such as “Salesforce-Account” or “Salesforce-Contact.” When a
user sends a ProfileObject, using the PutProfileObject API, with an ObjectTypeName that
matches one of the TemplateIds, it uses the mappings from the template.

# Arguments
- `template_id`: A unique identifier for the object template.

"""
function get_profile_object_type_template(
    TemplateId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "GET",
        "/templates/$(TemplateId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_profile_object_type_template(
    TemplateId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "GET",
        "/templates/$(TemplateId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_account_integrations(uri)
    list_account_integrations(uri, params::Dict{String,<:Any})

Lists all of the integrations associated to a specific URI in the AWS account.

# Arguments
- `uri`: The URI of the S3 bucket or any other type of data source.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max-results"`: The maximum number of objects returned per page.
- `"next-token"`: The pagination token from the previous ListAccountIntegrations API call.
"""
function list_account_integrations(Uri; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "POST",
        "/integrations",
        Dict{String,Any}("Uri" => Uri);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_account_integrations(
    Uri, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "POST",
        "/integrations",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("Uri" => Uri), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_domains()
    list_domains(params::Dict{String,<:Any})

Returns a list of all the domains for an AWS account that have been created.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max-results"`: The maximum number of objects returned per page.
- `"next-token"`: The pagination token from the previous ListDomain API call.
"""
function list_domains(; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "GET", "/domains"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_domains(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "GET", "/domains", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    list_identity_resolution_jobs(domain_name)
    list_identity_resolution_jobs(domain_name, params::Dict{String,<:Any})

Lists all of the Identity Resolution Jobs in your domain. The response sorts the list by
JobStartTime.

# Arguments
- `domain_name`: The unique name of the domain.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max-results"`: The maximum number of results to return per page.
- `"next-token"`: The token for the next set of results. Use the value returned in the
  previous response in the next request to retrieve the next set of results.
"""
function list_identity_resolution_jobs(
    DomainName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/identity-resolution-jobs";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_identity_resolution_jobs(
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/identity-resolution-jobs",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_integrations(domain_name)
    list_integrations(domain_name, params::Dict{String,<:Any})

Lists all of the integrations in your domain.

# Arguments
- `domain_name`: The unique name of the domain.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max-results"`: The maximum number of objects returned per page.
- `"next-token"`: The pagination token from the previous ListIntegrations API call.
"""
function list_integrations(DomainName; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/integrations";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_integrations(
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/integrations",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_profile_object_type_templates()
    list_profile_object_type_templates(params::Dict{String,<:Any})

Lists all of the template information for object types.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max-results"`: The maximum number of objects returned per page.
- `"next-token"`: The pagination token from the previous ListObjectTypeTemplates API call.
"""
function list_profile_object_type_templates(;
    aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "GET", "/templates"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_profile_object_type_templates(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "GET", "/templates", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    list_profile_object_types(domain_name)
    list_profile_object_types(domain_name, params::Dict{String,<:Any})

Lists all of the templates available within the service.

# Arguments
- `domain_name`: The unique name of the domain.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max-results"`: The maximum number of objects returned per page.
- `"next-token"`: Identifies the next page of results to return.
"""
function list_profile_object_types(
    DomainName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/object-types";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_profile_object_types(
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "GET",
        "/domains/$(DomainName)/object-types",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_profile_objects(domain_name, object_type_name, profile_id)
    list_profile_objects(domain_name, object_type_name, profile_id, params::Dict{String,<:Any})

Returns a list of objects associated with a profile of a given ProfileObjectType.

# Arguments
- `domain_name`: The unique name of the domain.
- `object_type_name`: The name of the profile object type.
- `profile_id`: The unique identifier of a customer profile.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ObjectFilter"`: Applies a filter to the response to include profile objects with the
  specified index values. This filter is only supported for ObjectTypeName _asset, _case and
  _order.
- `"max-results"`: The maximum number of objects returned per page.
- `"next-token"`: The pagination token from the previous call to ListProfileObjects.
"""
function list_profile_objects(
    DomainName, ObjectTypeName, ProfileId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/objects",
        Dict{String,Any}("ObjectTypeName" => ObjectTypeName, "ProfileId" => ProfileId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_profile_objects(
    DomainName,
    ObjectTypeName,
    ProfileId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/objects",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "ObjectTypeName" => ObjectTypeName, "ProfileId" => ProfileId
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_tags_for_resource(resource_arn)
    list_tags_for_resource(resource_arn, params::Dict{String,<:Any})

Displays the tags associated with an Amazon Connect Customer Profiles resource. In Connect
Customer Profiles, domains, profile object types, and integrations can be tagged.

# Arguments
- `resource_arn`: The ARN of the resource for which you want to view tags.

"""
function list_tags_for_resource(
    resourceArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "GET",
        "/tags/$(resourceArn)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_tags_for_resource(
    resourceArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "GET",
        "/tags/$(resourceArn)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    merge_profiles(domain_name, main_profile_id, profile_ids_to_be_merged)
    merge_profiles(domain_name, main_profile_id, profile_ids_to_be_merged, params::Dict{String,<:Any})

Runs an AWS Lambda job that does the following:   All the profileKeys in the
ProfileToBeMerged will be moved to the main profile.   All the objects in the
ProfileToBeMerged will be moved to the main profile.   All the ProfileToBeMerged will be
deleted at the end.   All the profileKeys in the ProfileIdsToBeMerged will be moved to the
main profile.   Standard fields are merged as follows:   Fields are always \"union\"-ed if
there are no conflicts in standard fields or attributeKeys.   When there are conflicting
fields:   If no SourceProfileIds entry is specified, the main Profile value is always
taken.    If a SourceProfileIds entry is specified, the specified profileId is always
taken, even if it is a NULL value.       You can use MergeProfiles together with
GetMatches, which returns potentially matching profiles, or use it with the results of
another matching system. After profiles have been merged, they cannot be separated
(unmerged).

# Arguments
- `domain_name`: The unique name of the domain.
- `main_profile_id`: The identifier of the profile to be taken.
- `profile_ids_to_be_merged`: The identifier of the profile to be merged into MainProfileId.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FieldSourceProfileIds"`: The identifiers of the fields in the profile that has the
  information you want to apply to the merge. For example, say you want to merge EmailAddress
  from Profile1 into MainProfile. This would be the identifier of the EmailAddress field in
  Profile1.
"""
function merge_profiles(
    DomainName,
    MainProfileId,
    ProfileIdsToBeMerged;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/objects/merge",
        Dict{String,Any}(
            "MainProfileId" => MainProfileId, "ProfileIdsToBeMerged" => ProfileIdsToBeMerged
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function merge_profiles(
    DomainName,
    MainProfileId,
    ProfileIdsToBeMerged,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/objects/merge",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "MainProfileId" => MainProfileId,
                    "ProfileIdsToBeMerged" => ProfileIdsToBeMerged,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    put_integration(domain_name)
    put_integration(domain_name, params::Dict{String,<:Any})

Adds an integration between the service and a third-party service, which includes Amazon
AppFlow and Amazon Connect. An integration can belong to only one domain.

# Arguments
- `domain_name`: The unique name of the domain.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FlowDefinition"`: The configuration that controls how Customer Profiles retrieves data
  from the source.
- `"ObjectTypeName"`: The name of the profile object type.
- `"ObjectTypeNames"`: A map in which each key is an event type from an external
  application such as Segment or Shopify, and each value is an ObjectTypeName (template) used
  to ingest the event. It supports the following event types: SegmentIdentify,
  ShopifyCreateCustomers, ShopifyUpdateCustomers, ShopifyCreateDraftOrders,
  ShopifyUpdateDraftOrders, ShopifyCreateOrders, and ShopifyUpdatedOrders.
- `"Tags"`: The tags used to organize, track, or control access for this resource.
- `"Uri"`: The URI of the S3 bucket or any other type of data source.
"""
function put_integration(DomainName; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "PUT",
        "/domains/$(DomainName)/integrations";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function put_integration(
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "PUT",
        "/domains/$(DomainName)/integrations",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    put_profile_object(domain_name, object, object_type_name)
    put_profile_object(domain_name, object, object_type_name, params::Dict{String,<:Any})

Adds additional objects to customer profiles of a given ObjectType. When adding a specific
profile object, like a Contact Trace Record (CTR), an inferred profile can get created if
it is not mapped to an existing profile. The resulting profile will only have a phone
number populated in the standard ProfileObject. Any additional CTRs with the same phone
number will be mapped to the same inferred profile. When a ProfileObject is created and if
a ProfileObjectType already exists for the ProfileObject, it will provide data to a
standard profile depending on the ProfileObjectType definition. PutProfileObject needs an
ObjectType, which can be created using PutProfileObjectType.

# Arguments
- `domain_name`: The unique name of the domain.
- `object`: A string that is serialized from a JSON object.
- `object_type_name`: The name of the profile object type.

"""
function put_profile_object(
    DomainName, Object, ObjectTypeName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "PUT",
        "/domains/$(DomainName)/profiles/objects",
        Dict{String,Any}("Object" => Object, "ObjectTypeName" => ObjectTypeName);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function put_profile_object(
    DomainName,
    Object,
    ObjectTypeName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "PUT",
        "/domains/$(DomainName)/profiles/objects",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("Object" => Object, "ObjectTypeName" => ObjectTypeName),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    put_profile_object_type(description, domain_name, object_type_name)
    put_profile_object_type(description, domain_name, object_type_name, params::Dict{String,<:Any})

Defines a ProfileObjectType.

# Arguments
- `description`: Description of the profile object type.
- `domain_name`: The unique name of the domain.
- `object_type_name`: The name of the profile object type.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AllowProfileCreation"`: Indicates whether a profile should be created when data is
  received if one doesn’t exist for an object of this type. The default is FALSE. If the
  AllowProfileCreation flag is set to FALSE, then the service tries to fetch a standard
  profile and associate this object with the profile. If it is set to TRUE, and if no match
  is found, then the service creates a new standard profile.
- `"EncryptionKey"`: The customer-provided key to encrypt the profile object that will be
  created in this profile object type.
- `"ExpirationDays"`: The number of days until the data in the object expires.
- `"Fields"`: A map of the name and ObjectType field.
- `"Keys"`: A list of unique keys that can be used to map data to the profile.
- `"SourceLastUpdatedTimestampFormat"`: The format of your sourceLastUpdatedTimestamp that
  was previously set up.
- `"Tags"`: The tags used to organize, track, or control access for this resource.
- `"TemplateId"`: A unique identifier for the object template.
"""
function put_profile_object_type(
    Description,
    DomainName,
    ObjectTypeName;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "PUT",
        "/domains/$(DomainName)/object-types/$(ObjectTypeName)",
        Dict{String,Any}("Description" => Description);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function put_profile_object_type(
    Description,
    DomainName,
    ObjectTypeName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "PUT",
        "/domains/$(DomainName)/object-types/$(ObjectTypeName)",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("Description" => Description), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    search_profiles(domain_name, key_name, values)
    search_profiles(domain_name, key_name, values, params::Dict{String,<:Any})

Searches for profiles within a specific domain name using name, phone number, email
address, account number, or a custom defined index.

# Arguments
- `domain_name`: The unique name of the domain.
- `key_name`: A searchable identifier of a customer profile. The predefined keys you can
  use to search include: _account, _profileId, _assetId, _caseId, _orderId, _fullName,
  _phone, _email, _ctrContactId, _marketoLeadId, _salesforceAccountId, _salesforceContactId,
  _salesforceAssetId, _zendeskUserId, _zendeskExternalId, _zendeskTicketId,
  _serviceNowSystemId, _serviceNowIncidentId, _segmentUserId, _shopifyCustomerId,
  _shopifyOrderId.
- `values`: A list of key values.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"max-results"`: The maximum number of objects returned per page.
- `"next-token"`: The pagination token from the previous SearchProfiles API call.
"""
function search_profiles(
    DomainName, KeyName, Values; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/search",
        Dict{String,Any}("KeyName" => KeyName, "Values" => Values);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function search_profiles(
    DomainName,
    KeyName,
    Values,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/domains/$(DomainName)/profiles/search",
        Dict{String,Any}(
            mergewith(
                _merge, Dict{String,Any}("KeyName" => KeyName, "Values" => Values), params
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    tag_resource(resource_arn, tags)
    tag_resource(resource_arn, tags, params::Dict{String,<:Any})

Assigns one or more tags (key-value pairs) to the specified Amazon Connect Customer
Profiles resource. Tags can help you organize and categorize your resources. You can also
use them to scope user permissions by granting a user permission to access or change only
resources with certain tag values. In Connect Customer Profiles, domains, profile object
types, and integrations can be tagged. Tags don't have any semantic meaning to AWS and are
interpreted strictly as strings of characters. You can use the TagResource action with a
resource that already has tags. If you specify a new tag key, this tag is appended to the
list of tags associated with the resource. If you specify a tag key that is already
associated with the resource, the new tag value that you specify replaces the previous
value for that tag. You can associate as many as 50 tags with a resource.

# Arguments
- `resource_arn`: The ARN of the resource that you're adding tags to.
- `tags`: The tags used to organize, track, or control access for this resource.

"""
function tag_resource(resourceArn, tags; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "POST",
        "/tags/$(resourceArn)",
        Dict{String,Any}("tags" => tags);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function tag_resource(
    resourceArn,
    tags,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "POST",
        "/tags/$(resourceArn)",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tags" => tags), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    untag_resource(resource_arn, tag_keys)
    untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any})

Removes one or more tags from the specified Amazon Connect Customer Profiles resource. In
Connect Customer Profiles, domains, profile object types, and integrations can be tagged.

# Arguments
- `resource_arn`: The ARN of the resource from which you are removing tags.
- `tag_keys`: The list of tag keys to remove from the resource.

"""
function untag_resource(
    resourceArn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "DELETE",
        "/tags/$(resourceArn)",
        Dict{String,Any}("tagKeys" => tagKeys);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function untag_resource(
    resourceArn,
    tagKeys,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "DELETE",
        "/tags/$(resourceArn)",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tagKeys" => tagKeys), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_domain(domain_name)
    update_domain(domain_name, params::Dict{String,<:Any})

Updates the properties of a domain, including creating or selecting a dead letter queue or
an encryption key. After a domain is created, the name can’t be changed. Use this API or
CreateDomain to enable identity resolution: set Matching to true.  To prevent cross-service
impersonation when you call this API, see Cross-service confused deputy prevention for
sample policies that you should apply.

# Arguments
- `domain_name`: The unique name of the domain.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DeadLetterQueueUrl"`: The URL of the SQS dead letter queue, which is used for reporting
  errors associated with ingesting data from third party applications. If specified as an
  empty string, it will clear any existing value. You must set up a policy on the
  DeadLetterQueue for the SendMessage operation to enable Amazon Connect Customer Profiles to
  send messages to the DeadLetterQueue.
- `"DefaultEncryptionKey"`: The default encryption key, which is an AWS managed key, is
  used when no specific type of encryption key is specified. It is used to encrypt all data
  before it is placed in permanent or semi-permanent storage. If specified as an empty
  string, it will clear any existing value.
- `"DefaultExpirationDays"`: The default number of days until the data within the domain
  expires.
- `"Matching"`: The process of matching duplicate profiles. If Matching = true, Amazon
  Connect Customer Profiles starts a weekly batch process called Identity Resolution Job. If
  you do not specify a date and time for Identity Resolution Job to run, by default it runs
  every Saturday at 12AM UTC to detect duplicate profiles in your domains.  After the
  Identity Resolution Job completes, use the GetMatches API to return and review the results.
  Or, if you have configured ExportingConfig in the MatchingRequest, you can download the
  results from S3.
- `"Tags"`: The tags used to organize, track, or control access for this resource.
"""
function update_domain(DomainName; aws_config::AbstractAWSConfig=global_aws_config())
    return customer_profiles(
        "PUT",
        "/domains/$(DomainName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_domain(
    DomainName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "PUT",
        "/domains/$(DomainName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_profile(domain_name, profile_id)
    update_profile(domain_name, profile_id, params::Dict{String,<:Any})

Updates the properties of a profile. The ProfileId is required for updating a customer
profile. When calling the UpdateProfile API, specifying an empty string value means that
any existing value will be removed. Not specifying a string value means that any value
already there will be kept.

# Arguments
- `domain_name`: The unique name of the domain.
- `profile_id`: The unique identifier of a customer profile.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AccountNumber"`: A unique account number that you have given to the customer.
- `"AdditionalInformation"`: Any additional information relevant to the customer’s
  profile.
- `"Address"`: A generic address associated with the customer that is not mailing,
  shipping, or billing.
- `"Attributes"`: A key value pair of attributes of a customer profile.
- `"BillingAddress"`: The customer’s billing address.
- `"BirthDate"`: The customer’s birth date.
- `"BusinessEmailAddress"`: The customer’s business email address.
- `"BusinessName"`: The name of the customer’s business.
- `"BusinessPhoneNumber"`: The customer’s business phone number.
- `"EmailAddress"`: The customer’s email address, which has not been specified as a
  personal or business address.
- `"FirstName"`: The customer’s first name.
- `"Gender"`: The gender with which the customer identifies.
- `"HomePhoneNumber"`: The customer’s home phone number.
- `"LastName"`: The customer’s last name.
- `"MailingAddress"`: The customer’s mailing address.
- `"MiddleName"`: The customer’s middle name.
- `"MobilePhoneNumber"`: The customer’s mobile phone number.
- `"PartyType"`: The type of profile used to describe the customer.
- `"PersonalEmailAddress"`: The customer’s personal email address.
- `"PhoneNumber"`: The customer’s phone number, which has not been specified as a mobile,
  home, or business number.
- `"ShippingAddress"`: The customer’s shipping address.
"""
function update_profile(
    DomainName, ProfileId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return customer_profiles(
        "PUT",
        "/domains/$(DomainName)/profiles",
        Dict{String,Any}("ProfileId" => ProfileId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_profile(
    DomainName,
    ProfileId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return customer_profiles(
        "PUT",
        "/domains/$(DomainName)/profiles",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ProfileId" => ProfileId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end