text:
# These functions do most of the work in the package.
# They are all type-stable recusive methods for performance and extensibility.

"""
    dimsmatch([f], dim, lookup) => Bool
    dimsmatch([f], dims::Tuple, lookups::Tuple) => Bool

Compare 2 dimensions or `Tuple` of `Dimension` are of the same base type,
or are at least rotations/transformations of the same type.

`f` is `<:` by default, but can be `>:` to match abstract types to concrete types.
"""
@inline dimsmatch(dims, lookups) = dimsmatch(<:, dims, lookups)
@inline function dimsmatch(f::Function, dims::Tuple, lookups::Tuple)
    all(map((d, l) -> dimsmatch(f, d, l), dims, lookups))
end
@inline dimsmatch(f::Function, dim, lookup) = dimsmatch(f, typeof(dim), typeof(lookup))
@inline dimsmatch(f::Function, dim::Type, lookup) = dimsmatch(f, dim, typeof(lookup))
@inline dimsmatch(f::Function, dim, lookup::Type) = dimsmatch(f, typeof(dim), lookup)
@inline dimsmatch(f::Function, dim::Nothing, lookup::Type) = false
@inline dimsmatch(f::Function, dim::Type, ::Nothing) = false
@inline dimsmatch(f::Function, dim, lookup::Nothing) = false
@inline dimsmatch(f::Function, dim::Nothing, lookup) = false
@inline dimsmatch(f::Function, dim::Nothing, lookup::Nothing) = false
@inline function dimsmatch(f::Function, dim::Type{D}, match::Type{M}) where {D,M}
    # Compare regular dimension types
    f(basetypeof(unwrap(D)), basetypeof(unwrap(M))) ||
    # Compare the transformed dimensions, if they exist
    f(basetypeof(unwrap(D)), basetypeof(transformdim(lookuptype(unwrap(M))))) ||
    f(basetypeof(transformdim(lookuptype(unwrap(D)))), basetypeof(unwrap(M)))
end

"""
    key2dim(s::Symbol) => Dimension
    key2dim(dims...) => Tuple{Dimension,Vararg}
    key2dim(dims::Tuple) => Tuple{Dimension,Vararg}

Convert a symbol to a dimension object. `:X`, `:Y`, `:Ti` etc will be converted.
to `X()`, `Y()`, `Ti()`, as with any other dims generated with the [`@dim`](@ref) macro.

All other `Symbol`s `S` will generate `Dim{S}()` dimensions.
"""
@inline key2dim(t::Tuple) = map(key2dim, t)
@inline key2dim(s::Symbol) = key2dim(Val{s}())
# Allow other things to pass through
@inline key2dim(d::Val{<:Dimension}) = d
@inline key2dim(d) = d

# key2dim is defined for concrete instances in dimensions.jl

"""
    dim2key(dim::Dimension) => Symbol
    dim2key(dims::Type{<:Dimension}) => Symbol

Convert a dimension object to a simbol. `X()`, `Y()`, `Ti()` etc will be converted.
to `:X`, `:Y`, `:Ti`, as with any other dims generated with the [`@dim`](@ref) macro.

All other `Dim{S}()` dimensions will generate `Symbol`s `S`.
"""
@inline dim2key(dim::Dimension) = dim2key(typeof(dim))
@inline dim2key(dim::Val{D}) where D <: Dimension = dim2key(D)
@inline dim2key(dt::Type{<:Dimension}) = Symbol(Base.nameof(dt))

# dim2key is defined for concrete instances in dimensions.jl

"""
    sortdims([f], tosort, order) => Tuple

Sort dimensions `tosort` by `order`. Dimensions
in `order` but missing from `tosort` are replaced with `nothing`.

`tosort` and `order` can be `Tuple`s or `Vector`s or Dimension
or dimension type. Abstract supertypes like [`TimeDim`](@ref)
can be used in `order`.

`f` is `<:` by default, but can be `>:` to sort abstract types by concrete types.
"""
@inline sortdims(args...) = _call(_sortdims, MaybeFirst(), args...)

@inline _sortdims(f, tosort, order::Tuple{<:Integer,Vararg}) = map(p -> tosort[p], order)
@inline _sortdims(f, tosort, order) = _sortdims_gen(f, tosort, order)

@generated _sortdims_gen(f, tosort::Tuple, order::Tuple) = begin
    expr = Expr(:tuple)
    allreadyfound = Int[]
    for (i, ord) in enumerate(order.parameters)
        # Make sure we don't find the same dim twice
        found = 0
        while true
            found = findnext((tosort.parameters...,), found + 1) do s
                dimsmatch(_asfunc(f), s, ord)
            end
            if found == nothing
                push!(expr.args, :(nothing))
                break
            elseif !(found in allreadyfound)
                push!(expr.args, :(tosort[$found]))
                push!(allreadyfound, found)
                break
            end
        end
    end
    return expr
end

"""
    dims(x, lookup) => Tuple{Vararg{<:Dimension}}
    dims(x, lookup...) => Tuple{Vararg{<:Dimension}}

Get the dimension(s) matching the type(s) of the lookup dimension.

LookupArray can be an Int or an Dimension, or a tuple containing
any combination of either.

## Arguments
- `x`: any object with a `dims` method, or a `Tuple` of `Dimension`.
- `lookup`: Tuple or a single `Dimension` or `Dimension` `Type`.

## Example
```jldoctest
julia> using DimensionalData

julia> A = DimArray(ones(2, 3, 2), (X, Y, Z))
2×3×2 DimArray{Float64,3} with dimensions: X , Y , Z
[:, :, 1]
 1.0  1.0  1.0
 1.0  1.0  1.0
[and 1 more slices...]

julia> dims(A, (X, Y))
X , Y

```
"""
@inline dims(args...) = _call(_dims, MaybeFirst(), args...)

@inline _dims(f, dims, lookup) = _remove_nothing(_sortdims(f, dims, lookup))

"""
    commondims([f], x, lookup) => Tuple{Vararg{<:Dimension}}

This is basically `dims(x, lookup)` where the order of the original is kept,
unlike [`dims`](@ref) where the lookup tuple determines the order

Also unlike `dims`,`commondims` always returns a `Tuple`, no matter the input.
No errors are thrown if dims are absent from either `x` or `lookup`.

`f` is `<:` by default, but can be `>:` to sort abstract types by concrete types.

```jldoctest
julia> using DimensionalData, .Dimensions

julia> A = DimArray(ones(10, 10, 10), (X, Y, Z));

julia> commondims(A, X)
X

julia> commondims(A, (X, Z))
X , Z

julia> commondims(A, Ti)
()

```
"""
@inline commondims(args...) = _call(_commondims, AlwaysTuple(), args...)

_commondims(f, ds, lookup) = _dims(f, ds, _dims(_flip_subtype(f), lookup, ds))

"""
    dimnum(x, lookup::Tuple) => NTuple{Int}
    dimnum(x, lookup) => Int

Get the number(s) of `Dimension`(s) as ordered in the dimensions of an object.

## Arguments
- `x`: any object with a `dims` method, a `Tuple` of `Dimension` or a single `Dimension`.
- `lookup`: Tuple, Array or single `Dimension` or dimension `Type`.

The return type will be a Tuple of `Int` or a single `Int`,
depending on wether `lookup` is a `Tuple` or single `Dimension`.

## Example

```jldoctest
julia> using DimensionalData

julia> A = DimArray(ones(10, 10, 10), (X, Y, Z));

julia> dimnum(A, (Z, X, Y))
(3, 1, 2)

julia> dimnum(A, Y)
2
```
"""
@inline function dimnum(args...)
    all(hasdim(args...)) || _errorextradims()
    _call(_dimnum, MaybeFirst(), args...)
end

@inline function _dimnum(f::Function, ds::Tuple, lookups::Tuple{Vararg{Int}})
    lookups
end
@inline function _dimnum(f::Function, ds::Tuple, lookups::Tuple)
    numbered = map(ds, ntuple(identity, length(ds))) do d, i
        rebuild(d, i)
    end
    map(val, _dims(f, numbered, lookups))
end

"""
    hasdim([f], x, lookup::Tuple) => NTUple{Bool}
    hasdim([f], x, lookups...) => NTUple{Bool}
    hasdim([f], x, lookup) => Bool

Check if an object `x` has dimensions that match or inherit from the `lookup` dimensions.

## Arguments
- `x`: any object with a `dims` method, a `Tuple` of `Dimension` or a single `Dimension`.
- `lookup`: Tuple or single `Dimension` or dimension `Type`.
- `f`: `<:` by default, but can be `>:` to match abstract types to concrete types.

Check if an object or tuple contains an `Dimension`, or a tuple of dimensions.

## Example
```jldoctest
julia> using DimensionalData

julia> A = DimArray(ones(10, 10, 10), (X, Y, Z));

julia> hasdim(A, X)
true

julia> hasdim(A, (Z, X, Y))
(true, true, true)

julia> hasdim(A, Ti)
false
```
"""
@inline hasdim(args...) = _call(_hasdim, MaybeFirst(), args...)

@inline _hasdim(f, dims, lookup) =
    map(d -> !(d isa Nothing), _sortdims(f, _commondims(f, dims, lookup), lookup))
@inline _hasdim(f, dims, lookup::Tuple{Vararg{Int}}) =
    map(l -> l in 1:length(dims), lookup)

"""
    otherdims(x, lookup) => Tuple{Vararg{<:Dimension,N}}

Get the dimensions of an object _not_ in `lookup`.

## Arguments
- `x`: any object with a `dims` method, a `Tuple` of `Dimension`.
- `lookup`: Tuple or single `Dimension` or dimension `Type`.
- `f`: `<:` by default, but can be `>:` to match abstract types to concrete types.

A tuple holding the unmatched dimensions is always returned.

## Example
```jldoctest
julia> using DimensionalData, DimensionalData.Dimensions

julia> A = DimArray(ones(10, 10, 10), (X, Y, Z));

julia> otherdims(A, X)
Y , Z

julia> otherdims(A, (Y, Z))
X

julia>

```
"""
@inline otherdims(args...) = _call(_otherdims_presort, AlwaysTuple(), args...)

@inline _otherdims_presort(f, ds, lookup) = _otherdims(f, ds, _sortdims(f, lookup, ds))
# Work with a sorted lookup where the missing dims are `nothing`
@inline _otherdims(f, ds::Tuple, lookup::Tuple) =
    (_dimifmatching(f, first(ds), first(lookup))..., _otherdims(f, tail(ds), tail(lookup))...)
@inline _otherdims(f, dims::Tuple{}, ::Tuple{}) = ()

@inline _dimifmatching(f, dim, lookup) = dimsmatch(f, dim, lookup) ? () : (dim,)

"""
    setdims(X, newdims) => AbstractArray
    setdims(::Tuple, newdims) => Tuple{Vararg{<:Dimension,N}}

Replaces the first dim matching `<: basetypeof(newdim)` with newdim,
and returns a new object or tuple with the dimension updated.

## Arguments
- `x`: any object with a `dims` method, a `Tuple` of `Dimension` or a single `Dimension`.
- `newdim`: Tuple or single `Dimension`, `Type` or `Symbol`.

# Example
```jldoctest
using DimensionalData, DimensionalData.Dimensions, DimensionalData.LookupArrays
A = ones(X(10), Y(10:10:100))
B = setdims(A, Y(Categorical('a':'j'; order=ForwardOrdered())))
lookup(B, Y)
# output
Categorical 'a':1:'j' ForwardOrdered
```
"""
@inline setdims(x, d1, d2, ds...) = setdims(x, (d1, d2, ds...))
@inline setdims(x, newdims::Dimension) = rebuild(x; dims=setdims(dims(x), key2dim(newdims)))
@inline setdims(x, newdims::Tuple) = rebuild(x; dims=setdims(dims(x), key2dim(newdims)))
@inline setdims(dims::Tuple, newdim::Dimension) = setdims(dims, (newdim,))
@inline setdims(dims::Tuple, newdims::Tuple) = swapdims(dims, sortdims(newdims, dims))
@inline setdims(dims::Tuple, newdims::Tuple{}) = dims

"""
    swapdims(x::T, newdims) => T
    swapdims(dims::Tuple, newdims) => Tuple{Vararg{<:Dimension}}

Swap dimensions for the passed in dimensions, in the
order passed.

Passing in the `Dimension` types rewraps the dimension index,
keeping the index values and metadata, while constructed `Dimension`
objectes replace the original dimension. `nothing` leaves the original
dimension as-is.

## Arguments
- `x`: any object with a `dims` method or a `Tuple` of `Dimension`.
- `newdim`: Tuple of `Dimension` or dimension `Type`.

# Example

```jldoctest
using DimensionalData
A = ones(X(2), Y(4), Z(2))
Dimensions.swapdims(A, (Dim{:a}, Dim{:b}, Dim{:c}))

# output
2×4×2 DimArray{Float64,3} with dimensions: Dim{:a} , Dim{:b} , Dim{:c}
[:, :, 1]
 1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0
[and 1 more slices...]
```
"""
@inline swapdims(x, d1, d2, ds...) = swapdims(x, (d1, d2, ds...))
@inline swapdims(x, newdims::Tuple) =
rebuild(x; dims=format(swapdims(dims(x), newdims), x))
@inline swapdims(dims::DimTuple, newdims::Tuple) =
map((d, nd) -> _swapdims(d, nd), dims, newdims)

@inline _swapdims(dim::Dimension, newdim::DimType) = basetypeof(newdim)(val(dim))
@inline _swapdims(dim::Dimension, newdim::Dimension) = newdim
@inline _swapdims(dim::Dimension, newdim::Nothing) = dim

"""
    slicedims(x, I) => Tuple{Tuple,Tuple}
    slicedims(f, x, I) => Tuple{Tuple,Tuple}

Slice the dimensions to match the axis values of the new array.

All methods return a tuple conatining two tuples: the new dimensions,
and the reference dimensions. The ref dimensions are no longer used in
the new struct but are useful to give context to plots.

Called at the array level the returned tuple will also include the
previous reference dims attached to the array.

# Arguments

- `f`: a function `getindex`,  `view` or `dotview`. This will be used for slicing
    `getindex` is the default if `f` is not included.
- `x`: An `AbstractDimArray`, `Tuple` of `Dimension`, or `Dimension`
- `I`: A tuple of `Integer`, `Colon` or `AbstractArray`
"""
function slicedims end
@inline slicedims(args...) = slicedims(getindex, args...)
@inline slicedims(f::Function, x, i1, i2, I...) = slicedims(f, x, (i1, i2, I...))
@inline slicedims(f::Function, x, I::CartesianIndex) = slicedims(f, x, Tuple(I))
@inline slicedims(f::Function, x, I::Tuple) = _slicedims(f, dims(x), refdims(x), I)
@inline slicedims(f::Function, dims::Tuple, I::Tuple) = _slicedims(f, dims, I)
@inline slicedims(f::Function, dims::Tuple, refdims::Tuple, i1, I...) = slicedims(f, dims, refdims, (i1, I...))
@inline slicedims(f::Function, dims::Tuple, refdims::Tuple, I) = _slicedims(f, dims, refdims, I)
@inline slicedims(f::Function, dims::Tuple, refdims::Tuple, I::CartesianIndex) =
    slicedims(f, dims, refdims, Tuple(I))

@inline _slicedims(f, dims::Tuple, refdims::Tuple, I::Tuple) = begin
    newdims, newrefdims = _slicedims(f, dims, I)
    newdims, (refdims..., newrefdims...)
end
@inline _slicedims(f, dims::Tuple, refdims::Tuple, I::Tuple{}) = dims, refdims
@inline _slicedims(f, dims::DimTuple, I::Tuple{}) = dims, ()
@inline _slicedims(f, dims::DimTuple, I::Tuple) = begin
    d = _slicedims(f, first(dims), first(I))
    ds = _slicedims(f, tail(dims), tail(I))
    (d[1]..., ds[1]...), (d[2]..., ds[2]...)
end
@inline _slicedims(f, dims::Tuple{}, I::Tuple) = (), ()
@inline _slicedims(f, dims::Tuple{}, I::Tuple{}) = (), ()
@inline _slicedims(f, d::Dimension, i::Colon) = (d,), ()
@inline _slicedims(f, d::Dimension, i::Integer) = (), (f(d, i:i),)
@inline _slicedims(f, d::Dimension, i) = (f(d, i),), ()

"""
    reducedims(x, dimstoreduce) => Tuple{Vararg{<:Dimension}}

Replace the specified dimensions with an index of length 1.
This is usually to match a new array size where an axis has been
reduced with a method like `mean` or `reduce` to a length of 1,
but the number of dimensions has not changed.

`LookupArray` traits are also updated to correspond to the change in
cell step, sampling type and order.
"""
@inline reducedims(x, dimstoreduce) = _reducedims(x, key2dim(dimstoreduce))

@inline _reducedims(x, dimstoreduce) = _reducedims(x, (dimstoreduce,))
@inline _reducedims(x, dimstoreduce::Tuple) = _reducedims(dims(x), dimstoreduce)
@inline _reducedims(dims::DimTuple, dimstoreduce::Tuple) =
    map(_reducedims, dims, sortdims(dimstoreduce, dims))
# Map numbers to corresponding dims. Not always type-stable
@inline _reducedims(dims::DimTuple, dimstoreduce::Tuple{Vararg{Int}}) =
    map(_reducedims, dims, sortdims(map(i -> dims[i], dimstoreduce), dims))
# Reduce matching dims but ignore nothing vals - they are the dims not being reduced
@inline _reducedims(dim::Dimension, ::Nothing) = dim
@inline _reducedims(dim::Dimension, ::DimOrDimType) = rebuild(dim, reducelookup(lookup(dim)))

"""
    comparedims(A::AbstractDimArray...)
    comparedims(A::Tuple...)
    comparedims(a, b)

Check that dimensions or tuples of dimensions are the same,
and return the first valid dimension. If `AbstractDimArray`s
are passed as arguments their dimensions are compared.

Empty tuples and `nothing` dimension values are ignored,
returning the `Dimension` value if it exists.
"""
function comparedims end
@inline comparedims(x...; kw...) = comparedims(x; kw...)
@inline comparedims(A::Tuple; kw...) = comparedims(map(dims, A)...; kw...)
@inline comparedims(dims::Vararg{<:Tuple{Vararg{<:Dimension}}}; kw...) =
    map(d -> comparedims(first(dims), d), dims; kw...) |> first

@inline comparedims(a::DimTuple, ::Nothing; kw...) = a
@inline comparedims(::Nothing, b::DimTuple; kw...) = b
@inline comparedims(::Nothing, ::Nothing; kw...) = nothing
# Cant use `map` here, tuples may not be the same length
@inline comparedims(a::DimTuple, b::DimTuple; kw...) =
    (comparedims(first(a), first(b); kw...), comparedims(tail(a), tail(b); kw...)...)
@inline comparedims(a::DimTuple, b::Tuple{}; kw...) = a
@inline comparedims(a::Tuple{}, b::DimTuple; kw...) = b
@inline comparedims(a::Tuple{}, b::Tuple{}; kw...) = ()
@inline comparedims(a::AnonDim, b::AnonDim; kw...) = nothing
@inline comparedims(a::Dimension, b::AnonDim; kw...) = a
@inline comparedims(a::AnonDim, b::Dimension; kw...) = b
@inline function comparedims(a::Dimension, b::Dimension;
    type=true, length=true, lookup=false, val=false, metadata=false
)
    D = Dimensions
    type && basetypeof(a) != basetypeof(b) && _dimsmismatcherror(a, b)
    lookup && typeof(D.lookup(a)) != typeof(D.lookup(b)) && _lookuperror(a, b)
    length && Base.length(a) != Base.length(b) && _dimsizeerror(a, b)
    val && D.val(a) != D.val(b) && _valerror(a, b)
    metadata && D.metadata(a) != D.metadata(b) && _metadataerror(a, b)
    return a
end

"""
    combinedims(xs; check=true)

Combine the dimensions of each object in `xs`, in the order they are found.
"""
function combinedims end
# @inline combinedims(xs::Tuple) = combinedims(xs...)
@inline combinedims(xs...; kw...) = combinedims(map(dims, xs)...; kw...)
@inline combinedims(dt1::DimTuple; kw...) = dt1
@inline combinedims(dt1::DimTuple, dt2::DimTuple, dimtuples::DimTuple...; kw...) =
    reduce((dt2, dimtuples...); init=dt1) do dims1, dims2
        _combinedims(dims1, dims2; kw...)
    end
# Cant use `map` here, tuples may not be the same length
@inline _combinedims(a::DimTuple, b::DimTuple; check=true, kw...) = begin
    if check # Check the matching dims are the same
        common = commondims(a, b)
        comparedims(dims(a, common), dims(b, common); kw...)
    end
    # Take them from a, and add any extras from b
    (a..., otherdims(b, a)...)
end

"""
    dimstride(x, dim) => Int

Get the stride of the dimension relative to the other dimensions.

This may or may not be equal to the stride of the related array,
although it will be for `Array`.

## Arguments

- `x` is any object with a `dims` method, or a `Tuple` of `Dimension`.
- `dim` is a `Dimension`, `Dimension` type, or and `Int`. Using an `Int` is not type-stable.
"""
@inline dimstride(x, n) = dimstride(dims(x), n)
@inline dimstride(::Nothing, n) = _dimsnotdefinederror()
@inline dimstride(dims::DimTuple, d::DimOrDimType) = dimstride(dims, dimnum(dims, d))
@inline dimstride(dims::DimTuple, n::Int) = prod(map(length, dims)[1:n-1])

@inline basedims(x) = basedims(dims(x))
@inline basedims(ds::Tuple) = map(basedims, ds)
@inline basedims(d::Dimension) = basetypeof(d)()
@inline basedims(d::Symbol) = key2dim(d)
@inline basedims(T::Type{<:Dimension}) = basetypeof(T)()

# Utils
struct MaybeFirst end
struct AlwaysTuple end

# Call the function f with stardardised args
# This looks like HELL, but it removes this complexity
# from every other method and makes sure they all behave
# the same way.
@inline _call(f::Function, t, args...) = _call(f, t, <:, _wraparg(args...)...)
@inline _call(f::Function, t, op::Function, args...) = _call1(f, t, op, _wraparg(args...)...)

@inline _call1(f, t, op::Function, x, l1, l2, ls...) = _call1(f, t, op, x, (l1, l2, ls...))
@inline _call1(f, t, op::Function, x, lookup) = _call1(f, t, op, dims(x), lookup)
@inline _call1(f, t, op::Function, x::Nothing, lookup) = _dimsnotdefinederror()
@inline _call1(f, t, op::Function, d::Tuple, lookup) = _call1(f, t, op, d, dims(lookup))
@inline _call1(f, t::AlwaysTuple, op::Function, d::Tuple, lookup::Union{Dimension,DimType,Val,Integer}) =
    _call1(f, t, op, d, (lookup,))
@inline _call1(f, t::MaybeFirst, op::Function, d::Tuple, lookup::Union{Dimension,DimType,Val,Integer}) =
    _call1(f, t, op, d, (lookup,)) |> _maybefirst
@inline _call1(f, t, op::Function, d::Tuple, lookup::Tuple) = map(unwrap, f(op, d, lookup))

_maybefirst(xs::Tuple) = first(xs)
_maybefirst(::Tuple{}) = nothing

@inline kwdims(kw::Base.Iterators.Pairs) = kwdims(values(kw))
# Convert `Symbol` keyword arguments to a `Tuple` of `Dimension`
@inline kwdims(kw::NamedTuple{Keys}) where Keys = kwdims(key2dim(Keys), values(kw))
@inline kwdims(dims::Tuple, vals::Tuple) =
    (rebuild(first(dims), first(vals)), kwdims(tail(dims), tail(vals))...)
@inline kwdims(dims::Tuple{}, vals::Tuple{}) = ()

@inline pairdims(pairs::Pair...) = map(p -> basetypeof(key2dim(first(p)))(last(p)), pairs)

# Remove `nothing` from a `Tuple`
@inline _remove_nothing(xs::Tuple) = _remove_nothing(xs...)
@inline _remove_nothing(x, xs...) = (x, _remove_nothing(xs...)...)
@inline _remove_nothing(::Nothing, xs...) = _remove_nothing(xs...)
@inline _remove_nothing() = ()

# This looks ridiculous, but gives seven arguments with constant-propagation,
# which means type stability using Symbols/types instead of objects.
@inline _wraparg(d1, d2, d3, d4, d5, d6, d7, ds...) =
    (_w(d1), _w(d2), _w(d3), _w(d4), _w(d5), _w(d6), _w(d7), _wraparg(ds...)...)
@inline _wraparg(d1, d2, d3, d4, d5, d6) = _w(d1), _w(d2), _w(d3), _w(d4), _w(d5), _w(d6)
@inline _wraparg(d1, d2, d3, d4, d5) = _w(d1), _w(d2), _w(d3), _w(d4), _w(d5)
@inline _wraparg(d1, d2, d3, d4) = _w(d1), _w(d2), _w(d3), _w(d4)
@inline _wraparg(d1, d2, d3) = _w(d1), _w(d2), _w(d3)
@inline _wraparg(d1, d2) = _w(d1), _w(d2)
@inline _wraparg(d1) = (_w(d1),)
@inline _wraparg() = ()

@inline _w(t::Tuple) = _wraparg(t...)
@inline _w(x) = x
@inline _w(s::Symbol) = key2dim(s)
@inline _w(x::Type{T}) where T = Val{T}()

@inline _asfunc(::Type{typeof(<:)}) = <:
@inline _asfunc(::Type{typeof(>:)}) = >:

@inline _flip_subtype(::typeof(<:)) = >:
@inline _flip_subtype(::typeof(>:)) = <:

# Error methods. @noinline to avoid allocations.

@noinline _dimsnotdefinederror() = throw(ArgumentError("Object does not define a `dims` method"))
@noinline _dimsmismatcherror(a, b) = throw(DimensionMismatch("$(basetypeof(a)) and $(basetypeof(b)) for dims on the same axis"))
@noinline _dimsizeerror(a, b) = throw(DimensionMismatch("Found both lengths $(length(a)) and $(length(b)) for $(basetypeof(a))"))
@noinline _lookuperror(a, b) = throw(DimensionMismatch("Mode $(lookup(a)) and $(lookup(b)) do not match"))
@noinline _metadataerror(a, b) = throw(DimensionMismatch("Metadata $(metadata(a)) and $(madata(b)) do not match"))
@noinline _valerror(a, b) = throw(DimensionMismatch("Dimension index $(val(a)) and $(val(b)) do not match"))
@noinline _warnextradims(extradims) = @warn "$(map(basetypeof, extradims)) dims were not found in object"
@noinline _errorextradims() = throw(ArgumentError("Some dims were not found in object"))


text:
#=
This file is auto-generated. Do not edit.
=#
"""
    mutable struct Source <: StaticInjection
        name::String
        available::Bool
        bus::Bus
        V_R::Float64
        V_I::Float64
        X_th::Float64
        services::Vector{Service}
        ext::Dict{String, Any}
        internal::InfrastructureSystemsInternal
    end

This struct acts as an infinity bus.

# Arguments
- `name::String`
- `available::Bool`
- `bus::Bus`
- `V_R::Float64`: Voltage Source Real Component, validation range: (0, nothing)
- `V_I::Float64`: Voltage Source Imaginary Component, validation range: (0, nothing)
- `X_th::Float64`: Source Thevenin impedance, validation range: (0, nothing)
- `services::Vector{Service}`: Services that this device contributes to
- `ext::Dict{String, Any}`
- `internal::InfrastructureSystemsInternal`: power system internal reference, do not modify
"""
mutable struct Source <: StaticInjection
    name::String
    available::Bool
    bus::Bus
    "Voltage Source Real Component"
    V_R::Float64
    "Voltage Source Imaginary Component"
    V_I::Float64
    "Source Thevenin impedance"
    X_th::Float64
    "Services that this device contributes to"
    services::Vector{Service}
    ext::Dict{String, Any}
    "power system internal reference, do not modify"
    internal::InfrastructureSystemsInternal
end

function Source(name, available, bus, V_R, V_I, X_th, services=Device[], ext=Dict{String, Any}(), )
    Source(name, available, bus, V_R, V_I, X_th, services, ext, InfrastructureSystemsInternal(), )
end

function Source(; name, available, bus, V_R, V_I, X_th, services=Device[], ext=Dict{String, Any}(), )
    Source(name, available, bus, V_R, V_I, X_th, services, ext, )
end

# Constructor for demo purposes; non-functional.
function Source(::Nothing)
    Source(;
        name="init",
        available=false,
        bus=Bus(nothing),
        V_R=0,
        V_I=0,
        X_th=0,
        services=Device[],
        ext=Dict{String, Any}(),
    )
end

InfrastructureSystems.get_name(value::Source) = value.name
"""Get Source available."""
get_available(value::Source) = value.available
"""Get Source bus."""
get_bus(value::Source) = value.bus
"""Get Source V_R."""
get_V_R(value::Source) = value.V_R
"""Get Source V_I."""
get_V_I(value::Source) = value.V_I
"""Get Source X_th."""
get_X_th(value::Source) = value.X_th
"""Get Source services."""
get_services(value::Source) = value.services
"""Get Source ext."""
get_ext(value::Source) = value.ext
"""Get Source internal."""
get_internal(value::Source) = value.internal

ext: jl


text:
using CPLEX, MathProgBase, Base.Test

@testset "Use loadproblem! twice" begin
    solver = CplexSolver()
    # Check that the env for each model is the same
    m = MathProgBase.LinearQuadraticModel(solver)
    env = m.inner.env
    MathProgBase.loadproblem!(m, [1 0], [1, 1], [1, Inf], [1, 0], [0], [Inf], :Min)
    @test m.inner.env === env
    @test CPLEX.is_valid(env)
    MathProgBase.loadproblem!(m, [0 1], [-Inf, 1], [1, 1], [0, 1], [-Inf], [0], :Min)
    @test m.inner.env === env
    @test CPLEX.is_valid(env)
end


text:
#==============================================================================#
# CognitoSync.jl
#
# This file is generated from:
# https://github.com/aws/aws-sdk-js/blob/master/apis/cognito-sync-2014-06-30.normal.json
#==============================================================================#

__precompile__()

module CognitoSync

using AWSCore

"""
    using AWSSDK.CognitoSync.bulk_publish
    bulk_publish([::AWSConfig], arguments::Dict)
    bulk_publish([::AWSConfig]; IdentityPoolId=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/bulkpublish", arguments::Dict)
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/bulkpublish", IdentityPoolId=)

# BulkPublish Operation

Initiates a bulk publish of all existing datasets for an Identity Pool to the configured stream. Customers are limited to one successful bulk publish per 24 hours. Bulk publish is an asynchronous request, customers can see the status of the request via the GetBulkPublishDetails operation.

This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

# Returns

`BulkPublishResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException`, `InternalErrorException`, `DuplicateRequestException` or `AlreadyStreamedException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/BulkPublish)
"""
@inline bulk_publish(aws::AWSConfig=default_aws_config(); args...) = bulk_publish(aws, args)

@inline bulk_publish(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "POST", "/identitypools/{IdentityPoolId}/bulkpublish", args)

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

"""
    using AWSSDK.CognitoSync.delete_dataset
    delete_dataset([::AWSConfig], arguments::Dict)
    delete_dataset([::AWSConfig]; IdentityPoolId=, IdentityId=, DatasetName=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "DELETE", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}", arguments::Dict)
    cognito_sync([::AWSConfig], "DELETE", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}", IdentityPoolId=, IdentityId=, DatasetName=)

# DeleteDataset Operation

Deletes the specific dataset. The dataset will be deleted permanently, and the action can't be undone. Datasets that this dataset was merged with will no longer report the merge. Any subsequent operation on this dataset will result in a ResourceNotFoundException.

This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `IdentityId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `DatasetName = ::String` -- *Required*
A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).

# Returns

`DeleteDatasetResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException`, `InternalErrorException`, `TooManyRequestsException` or `ResourceConflictException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/DeleteDataset)
"""
@inline delete_dataset(aws::AWSConfig=default_aws_config(); args...) = delete_dataset(aws, args)

@inline delete_dataset(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "DELETE", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}", args)

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

"""
    using AWSSDK.CognitoSync.describe_dataset
    describe_dataset([::AWSConfig], arguments::Dict)
    describe_dataset([::AWSConfig]; IdentityPoolId=, IdentityId=, DatasetName=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}", arguments::Dict)
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}", IdentityPoolId=, IdentityId=, DatasetName=)

# DescribeDataset Operation

Gets meta data about a dataset by identity and dataset name. With Amazon Cognito Sync, each identity has access only to its own data. Thus, the credentials used to make this API call need to have access to the identity data.

This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials. You should use Cognito Identity credentials to make this API call.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `IdentityId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `DatasetName = ::String` -- *Required*
A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).

# Returns

`DescribeDatasetResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException`, `InternalErrorException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/DescribeDataset)
"""
@inline describe_dataset(aws::AWSConfig=default_aws_config(); args...) = describe_dataset(aws, args)

@inline describe_dataset(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}", args)

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

"""
    using AWSSDK.CognitoSync.describe_identity_pool_usage
    describe_identity_pool_usage([::AWSConfig], arguments::Dict)
    describe_identity_pool_usage([::AWSConfig]; IdentityPoolId=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}", arguments::Dict)
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}", IdentityPoolId=)

# DescribeIdentityPoolUsage Operation

Gets usage details (for example, data storage) about a particular identity pool.

This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

# Returns

`DescribeIdentityPoolUsageResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException`, `InternalErrorException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/DescribeIdentityPoolUsage)
"""
@inline describe_identity_pool_usage(aws::AWSConfig=default_aws_config(); args...) = describe_identity_pool_usage(aws, args)

@inline describe_identity_pool_usage(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "GET", "/identitypools/{IdentityPoolId}", args)

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

"""
    using AWSSDK.CognitoSync.describe_identity_usage
    describe_identity_usage([::AWSConfig], arguments::Dict)
    describe_identity_usage([::AWSConfig]; IdentityPoolId=, IdentityId=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}", arguments::Dict)
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}", IdentityPoolId=, IdentityId=)

# DescribeIdentityUsage Operation

Gets usage information for an identity, including number of datasets and data usage.

This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `IdentityId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

# Returns

`DescribeIdentityUsageResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException`, `InternalErrorException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/DescribeIdentityUsage)
"""
@inline describe_identity_usage(aws::AWSConfig=default_aws_config(); args...) = describe_identity_usage(aws, args)

@inline describe_identity_usage(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}", args)

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

"""
    using AWSSDK.CognitoSync.get_bulk_publish_details
    get_bulk_publish_details([::AWSConfig], arguments::Dict)
    get_bulk_publish_details([::AWSConfig]; IdentityPoolId=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/getBulkPublishDetails", arguments::Dict)
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/getBulkPublishDetails", IdentityPoolId=)

# GetBulkPublishDetails Operation

Get the status of the last BulkPublish operation for an identity pool.

This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

# Returns

`GetBulkPublishDetailsResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException` or `InternalErrorException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/GetBulkPublishDetails)
"""
@inline get_bulk_publish_details(aws::AWSConfig=default_aws_config(); args...) = get_bulk_publish_details(aws, args)

@inline get_bulk_publish_details(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "POST", "/identitypools/{IdentityPoolId}/getBulkPublishDetails", args)

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

"""
    using AWSSDK.CognitoSync.get_cognito_events
    get_cognito_events([::AWSConfig], arguments::Dict)
    get_cognito_events([::AWSConfig]; IdentityPoolId=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/events", arguments::Dict)
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/events", IdentityPoolId=)

# GetCognitoEvents Operation

Gets the events and the corresponding Lambda functions associated with an identity pool.

This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
The Cognito Identity Pool ID for the request

# Returns

`GetCognitoEventsResponse`

# Exceptions

`InvalidParameterException`, `ResourceNotFoundException`, `NotAuthorizedException`, `InternalErrorException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/GetCognitoEvents)
"""
@inline get_cognito_events(aws::AWSConfig=default_aws_config(); args...) = get_cognito_events(aws, args)

@inline get_cognito_events(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "GET", "/identitypools/{IdentityPoolId}/events", args)

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

"""
    using AWSSDK.CognitoSync.get_identity_pool_configuration
    get_identity_pool_configuration([::AWSConfig], arguments::Dict)
    get_identity_pool_configuration([::AWSConfig]; IdentityPoolId=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/configuration", arguments::Dict)
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/configuration", IdentityPoolId=)

# GetIdentityPoolConfiguration Operation

Gets the configuration settings of an identity pool.

This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. This is the ID of the pool for which to return a configuration.

# Returns

`GetIdentityPoolConfigurationResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException`, `InternalErrorException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/GetIdentityPoolConfiguration)
"""
@inline get_identity_pool_configuration(aws::AWSConfig=default_aws_config(); args...) = get_identity_pool_configuration(aws, args)

@inline get_identity_pool_configuration(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "GET", "/identitypools/{IdentityPoolId}/configuration", args)

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

"""
    using AWSSDK.CognitoSync.list_datasets
    list_datasets([::AWSConfig], arguments::Dict)
    list_datasets([::AWSConfig]; IdentityPoolId=, IdentityId=, <keyword arguments>)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets", arguments::Dict)
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets", IdentityPoolId=, IdentityId=, <keyword arguments>)

# ListDatasets Operation

Lists datasets for an identity. With Amazon Cognito Sync, each identity has access only to its own data. Thus, the credentials used to make this API call need to have access to the identity data.

ListDatasets can be called with temporary user credentials provided by Cognito Identity or with developer credentials. You should use the Cognito Identity credentials to make this API call.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `IdentityId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `nextToken = ::String`
A pagination token for obtaining the next page of results.

## `maxResults = ::Int`
The maximum number of results to be returned.

# Returns

`ListDatasetsResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `InternalErrorException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/ListDatasets)
"""
@inline list_datasets(aws::AWSConfig=default_aws_config(); args...) = list_datasets(aws, args)

@inline list_datasets(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets", args)

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

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

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "GET", "/identitypools", arguments::Dict)
    cognito_sync([::AWSConfig], "GET", "/identitypools", <keyword arguments>)

# ListIdentityPoolUsage Operation

Gets a list of identity pools registered with Cognito.

ListIdentityPoolUsage can only be called with developer credentials. You cannot make this API call with the temporary user credentials provided by Cognito Identity.

# Arguments

## `nextToken = ::String`
A pagination token for obtaining the next page of results.

## `maxResults = ::Int`
The maximum number of results to be returned.

# Returns

`ListIdentityPoolUsageResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `InternalErrorException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/ListIdentityPoolUsage)
"""
@inline list_identity_pool_usage(aws::AWSConfig=default_aws_config(); args...) = list_identity_pool_usage(aws, args)

@inline list_identity_pool_usage(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "GET", "/identitypools", args)

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

"""
    using AWSSDK.CognitoSync.list_records
    list_records([::AWSConfig], arguments::Dict)
    list_records([::AWSConfig]; IdentityPoolId=, IdentityId=, DatasetName=, <keyword arguments>)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/records", arguments::Dict)
    cognito_sync([::AWSConfig], "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/records", IdentityPoolId=, IdentityId=, DatasetName=, <keyword arguments>)

# ListRecords Operation

Gets paginated records, optionally changed after a particular sync count for a dataset and identity. With Amazon Cognito Sync, each identity has access only to its own data. Thus, the credentials used to make this API call need to have access to the identity data.

ListRecords can be called with temporary user credentials provided by Cognito Identity or with developer credentials. You should use Cognito Identity credentials to make this API call.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `IdentityId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `DatasetName = ::String` -- *Required*
A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).

## `lastSyncCount = ::Int`
The last server sync count for this record.

## `nextToken = ::String`
A pagination token for obtaining the next page of results.

## `maxResults = ::Int`
The maximum number of results to be returned.

## `syncSessionToken = ::String`
A token containing a session ID, identity ID, and expiration.

# Returns

`ListRecordsResponse`

# Exceptions

`InvalidParameterException`, `NotAuthorizedException`, `TooManyRequestsException` or `InternalErrorException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/ListRecords)
"""
@inline list_records(aws::AWSConfig=default_aws_config(); args...) = list_records(aws, args)

@inline list_records(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "GET", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/records", args)

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

"""
    using AWSSDK.CognitoSync.register_device
    register_device([::AWSConfig], arguments::Dict)
    register_device([::AWSConfig]; IdentityPoolId=, IdentityId=, Platform=, Token=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/identity/{IdentityId}/device", arguments::Dict)
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/identity/{IdentityId}/device", IdentityPoolId=, IdentityId=, Platform=, Token=)

# RegisterDevice Operation

Registers a device to receive push sync notifications.

This API can only be called with temporary credentials provided by Cognito Identity. You cannot call this API with developer credentials.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. Here, the ID of the pool that the identity belongs to.

## `IdentityId = ::String` -- *Required*
The unique ID for this identity.

## `Platform = "APNS", "APNS_SANDBOX", "GCM" or "ADM"` -- *Required*
The SNS platform type (e.g. GCM, SDM, APNS, APNS_SANDBOX).

## `Token = ::String` -- *Required*
The push token.

# Returns

`RegisterDeviceResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException`, `InternalErrorException`, `InvalidConfigurationException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/RegisterDevice)
"""
@inline register_device(aws::AWSConfig=default_aws_config(); args...) = register_device(aws, args)

@inline register_device(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "POST", "/identitypools/{IdentityPoolId}/identity/{IdentityId}/device", args)

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

"""
    using AWSSDK.CognitoSync.set_cognito_events
    set_cognito_events([::AWSConfig], arguments::Dict)
    set_cognito_events([::AWSConfig]; IdentityPoolId=, Events=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/events", arguments::Dict)
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/events", IdentityPoolId=, Events=)

# SetCognitoEvents Operation

Sets the AWS Lambda function for a given event type for an identity pool. This request only updates the key/value pair specified. Other key/values pairs are not updated. To remove a key value pair, pass a empty value for the particular key.

This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
The Cognito Identity Pool to use when configuring Cognito Events

## `Events = ::Dict{String,String}` -- *Required*
The events to configure

# Exceptions

`InvalidParameterException`, `ResourceNotFoundException`, `NotAuthorizedException`, `InternalErrorException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/SetCognitoEvents)
"""
@inline set_cognito_events(aws::AWSConfig=default_aws_config(); args...) = set_cognito_events(aws, args)

@inline set_cognito_events(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "POST", "/identitypools/{IdentityPoolId}/events", args)

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

"""
    using AWSSDK.CognitoSync.set_identity_pool_configuration
    set_identity_pool_configuration([::AWSConfig], arguments::Dict)
    set_identity_pool_configuration([::AWSConfig]; IdentityPoolId=, <keyword arguments>)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/configuration", arguments::Dict)
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/configuration", IdentityPoolId=, <keyword arguments>)

# SetIdentityPoolConfiguration Operation

Sets the necessary configuration for push sync.

This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. This is the ID of the pool to modify.

## `PushSync = [ ... ]`
Options to apply to this identity pool for push synchronization.
```
 PushSync = [
        "ApplicationArns" =>  [::String, ...],
        "RoleArn" =>  ::String
    ]
```

## `CognitoStreams = [ ... ]`
Options to apply to this identity pool for Amazon Cognito streams.
```
 CognitoStreams = [
        "StreamName" =>  ::String,
        "RoleArn" =>  ::String,
        "StreamingStatus" =>  "ENABLED" or "DISABLED"
    ]
```

# Returns

`SetIdentityPoolConfigurationResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException`, `InternalErrorException`, `TooManyRequestsException` or `ConcurrentModificationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/SetIdentityPoolConfiguration)
"""
@inline set_identity_pool_configuration(aws::AWSConfig=default_aws_config(); args...) = set_identity_pool_configuration(aws, args)

@inline set_identity_pool_configuration(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "POST", "/identitypools/{IdentityPoolId}/configuration", args)

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

"""
    using AWSSDK.CognitoSync.subscribe_to_dataset
    subscribe_to_dataset([::AWSConfig], arguments::Dict)
    subscribe_to_dataset([::AWSConfig]; IdentityPoolId=, IdentityId=, DatasetName=, DeviceId=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/subscriptions/{DeviceId}", arguments::Dict)
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/subscriptions/{DeviceId}", IdentityPoolId=, IdentityId=, DatasetName=, DeviceId=)

# SubscribeToDataset Operation

Subscribes to receive notifications when a dataset is modified by another device.

This API can only be called with temporary credentials provided by Cognito Identity. You cannot call this API with developer credentials.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. The ID of the pool to which the identity belongs.

## `IdentityId = ::String` -- *Required*
Unique ID for this identity.

## `DatasetName = ::String` -- *Required*
The name of the dataset to subcribe to.

## `DeviceId = ::String` -- *Required*
The unique ID generated for this device by Cognito.

# Returns

`SubscribeToDatasetResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException`, `InternalErrorException`, `InvalidConfigurationException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/SubscribeToDataset)
"""
@inline subscribe_to_dataset(aws::AWSConfig=default_aws_config(); args...) = subscribe_to_dataset(aws, args)

@inline subscribe_to_dataset(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "POST", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/subscriptions/{DeviceId}", args)

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

"""
    using AWSSDK.CognitoSync.unsubscribe_from_dataset
    unsubscribe_from_dataset([::AWSConfig], arguments::Dict)
    unsubscribe_from_dataset([::AWSConfig]; IdentityPoolId=, IdentityId=, DatasetName=, DeviceId=)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "DELETE", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/subscriptions/{DeviceId}", arguments::Dict)
    cognito_sync([::AWSConfig], "DELETE", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/subscriptions/{DeviceId}", IdentityPoolId=, IdentityId=, DatasetName=, DeviceId=)

# UnsubscribeFromDataset Operation

Unsubscribes from receiving notifications when a dataset is modified by another device.

This API can only be called with temporary credentials provided by Cognito Identity. You cannot call this API with developer credentials.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. The ID of the pool to which this identity belongs.

## `IdentityId = ::String` -- *Required*
Unique ID for this identity.

## `DatasetName = ::String` -- *Required*
The name of the dataset from which to unsubcribe.

## `DeviceId = ::String` -- *Required*
The unique ID generated for this device by Cognito.

# Returns

`UnsubscribeFromDatasetResponse`

# Exceptions

`NotAuthorizedException`, `InvalidParameterException`, `ResourceNotFoundException`, `InternalErrorException`, `InvalidConfigurationException` or `TooManyRequestsException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/UnsubscribeFromDataset)
"""
@inline unsubscribe_from_dataset(aws::AWSConfig=default_aws_config(); args...) = unsubscribe_from_dataset(aws, args)

@inline unsubscribe_from_dataset(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "DELETE", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/subscriptions/{DeviceId}", args)

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

"""
    using AWSSDK.CognitoSync.update_records
    update_records([::AWSConfig], arguments::Dict)
    update_records([::AWSConfig]; IdentityPoolId=, IdentityId=, DatasetName=, SyncSessionToken=, <keyword arguments>)

    using AWSCore.Services.cognito_sync
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}", arguments::Dict)
    cognito_sync([::AWSConfig], "POST", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}", IdentityPoolId=, IdentityId=, DatasetName=, SyncSessionToken=, <keyword arguments>)

# UpdateRecords Operation

Posts updates to records and adds and deletes records for a dataset and user.

The sync count in the record patch is your last known sync count for that record. The server will reject an UpdateRecords request with a ResourceConflictException if you try to patch a record with a new value but a stale sync count.

For example, if the sync count on the server is 5 for a key called highScore and you try and submit a new highScore with sync count of 4, the request will be rejected. To obtain the current sync count for a record, call ListRecords. On a successful update of the record, the response returns the new sync count for that record. You should present that sync count the next time you try to update that same record. When the record does not exist, specify the sync count as 0.

This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials.

# Arguments

## `IdentityPoolId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `IdentityId = ::String` -- *Required*
A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

## `DatasetName = ::String` -- *Required*
A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).

## `DeviceId = ::String`
The unique ID generated for this device by Cognito.

## `RecordPatches = [[ ... ], ...]`
A list of patch operations.
```
 RecordPatches = [[
        "Op" => <required> "replace" or "remove",
        "Key" => <required> ::String,
        "Value" =>  ::String,
        "SyncCount" => <required> ::Int,
        "DeviceLastModifiedDate" =>  timestamp
    ], ...]
```

## `SyncSessionToken = ::String` -- *Required*
The SyncSessionToken returned by a previous call to ListRecords for this dataset and identity.

## `*header:* x-amz-Client-Context = ::String`
Intended to supply a device ID that will populate the lastModifiedBy field referenced in other methods. The ClientContext field is not yet implemented.

# Returns

`UpdateRecordsResponse`

# Exceptions

`InvalidParameterException`, `LimitExceededException`, `NotAuthorizedException`, `ResourceNotFoundException`, `ResourceConflictException`, `InvalidLambdaFunctionOutputException`, `LambdaThrottledException`, `TooManyRequestsException` or `InternalErrorException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/UpdateRecords)
"""
@inline update_records(aws::AWSConfig=default_aws_config(); args...) = update_records(aws, args)

@inline update_records(aws::AWSConfig, args) = AWSCore.Services.cognito_sync(aws, "POST", "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}", args)

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

end # module CognitoSync

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


text:
abstract Model

function (::Type{T}){T <: Model}()
    return T(initial_parameters(T))
end

function (::Type{T}){T <: Model}(res::Optim.MultivariateOptimizationResults)
    return T(Optim.minimizer(res))
end


text:
#ランダムフォレストによる予測モデルの構築およびクロスバリデーションの実行

function Estfun(Ytraining,Xtraining,CV_n)
  Ytraining=Ytraining
  Xtraining=Xtraining
  CV_n=CV_n

  # unievalfun(model,inds)
  unievalfun=Unievalfun(Ytraining,Xtraining)

  return function estfun(nfeature,ntree,nrate)
    ## ランダムフォレストによる予測モデルの構築
    function trainfun(inds)
      model = build_forest(Ytraining[inds,1] , Xtraining[inds,:],nfeature,ntree,nrate)
      return model
    end

    n =size(Xtraining)[1]

    ## クロスバリデーションの実行
    scores = cross_validate(
                                            inds -> trainfun(inds),
                                            (model,inds) -> unievalfun(model , setdiff(1:n , inds) ),
                                            n,
                                            Kfold(n,CV_n)
                                          )

    return scores
  end
end

max_stars_repo_name: wakakusa/RFCVGT

max_issues_repo_name: wakakusa/RFCVGT

max_forks_repo_name: wakakusa/RFCVGT


text:
# transfer entropy functions load correctly
@test Inform._transfer_entropy_found
@test Inform._transfer_entropy != C_NULL
@test isa(Inform._transfer_entropy, Ptr{Void})

@test Inform._transfer_entropy_ensemble_found
@test Inform._transfer_entropy_ensemble != C_NULL
@test isa(Inform._transfer_entropy_ensemble, Ptr{Void})


text:
struct ALPSComplex
  data::Array{ComplexF64}
end

function ALPSComplex(g::HDF5.Dataset)
  data = read(g)

  # flip all dimensions since data is stored as row-major
  data = permutedims(data, reverse(1:ndims(data)))
  sz = size(data)

  # interpret last dimension as real/complex
  if haskey(attributes(g), "__complex__")
    @assert sz[end] == 2
    R = CartesianIndices(sz[1:end-1])
    data = data[R,1] + 1.0im * data[R, 2]
  end

  return ALPSComplex(data)
end

Base.read(g::HDF5.Group, ::Type{ALPSComplex}) = ALPSComplex(g)

function Base.write(parent::Union{HDF5.File, HDF5.Group}, name::String, X::ALPSComplex)
  # flip all dimensions since data is stored as row-major
  data = permutedims(X.data, reverse(1:ndims(X.data)))

  # reinterpret real/complex as new axis
  data = reshape(reinterpret(Float64, data), 2, size(data)...)

  parent[name] = data
  attributes(parent[name])["__complex__"] = Int8(1)
end

struct ALPSTimeGrid
  grid
  function ALPSTimeGrid(grid::T) where T <: AbstractTimeGrid
    new(grid)
  end
end

function ALPSTimeGrid(g::HDF5.Group)
  nb = read(g, "contour/size")
  branches = Branch[]

  branches = ntuple(nb) do i
    b = BranchEnum(read(g, "contour/branch$(i-1)/type") + 1)
    l = read(g, "contour/branch$(i-1)/len")
    return Branch(b, l)
  end

  values = ALPSComplex(g["values"]).data
  branch_enums = read(g["branch_enums"])

  npts_fwd = count(branch_enums .== 0)
  npts_back = count(branch_enums .== 1)
  ntau = count(branch_enums .== 2)

  @assert npts_fwd == npts_back
  nt = npts_fwd

  get_branch = domain -> begin
    idx = findfirst(b -> b.domain == domain, branches)
    isnothing(idx) ? nothing : branches[idx]
  end

  if nb == 3
    tmax = length(get_branch(forward_branch))
    β = length(get_branch(imaginary_branch))
    c = FullContour(branches, tmax, β)
    grid = FullTimeGrid(c, nt, ntau)
  elseif nb == 2
    tmax = length(get_branch(forward_branch))
    c = KeldyshContour(branches, tmax)
    grid = KeldyshTimeGrid(c, nt)
  else
    β = length(get_branch(imaginary_branch))
    grid = ImaginaryTimeGrid(c, ntau)
  end

  @assert map(t -> t.bpoint.val, grid) ≈ values

  return ALPSTimeGrid(grid)
end

Base.read(g::HDF5.Group, ::Type{ALPSTimeGrid}) = ALPSTimeGrid(g)

function Base.write(parent::Union{HDF5.File, HDF5.Group}, name::String, X::ALPSTimeGrid)
  g = HDF5.create_group(parent, name)

  grid = X.grid
  c = grid.contour

  g["contour/size"] = UInt(nbranches(c))
  for (i, branch) in enumerate(c.branches)
    g["contour/branch$(i-1)/type"] = Int32(Int(branch.domain) - 1)
    g["contour/branch$(i-1)/len"] = length(branch)
  end

  values = ALPSComplex(map(t -> t.bpoint.val, grid))
  refs = map(t -> t.val.ref, grid)
  branch_enums = map(t -> Int32(Int(t.val.domain) - 1), grid)

  write(g, "values", values)
  write(g, "refs", refs)
  write(g, "branch_enums", branch_enums)
end

struct ALPSTimeGF
  G
  function ALPSTimeGF(G::T) where T <: AbstractTimeGF{ComplexF64, true}
    new(G)
  end
end

function ALPSTimeGF(g::HDF5.Group)
  grid = ALPSTimeGrid(g["mesh/1"]).grid
  data = ALPSComplex(g["data"]).data

  G = GenericTimeGF(grid, 1, true) do t1, t2
    data[t1.cidx, t2.cidx]
  end

  return ALPSTimeGF(G)
end

Base.read(g::HDF5.Group, ::Type{ALPSTimeGF}) = ALPSTimeGF(g)

function Base.write(parent::Union{HDF5.File, HDF5.Group}, name::String, X::ALPSTimeGF)
  G = X.G
  grid = G.grid
  N = length(grid)

  data = Matrix{ComplexF64}(undef, N, N)

  for t1 in grid
    for t2 in grid
      data[t1.cidx, t2.cidx] = G[t1, t2]
    end
  end

  g = HDF5.create_group(parent, name)

  write(g, "data", ALPSComplex(data))
  write(g, "mesh/N", 2)

  for i in 1:2
    write(g, "mesh/$i", ALPSTimeGrid(grid))
  end
end


text:
function should_symbol_recurse(var)
    taboo = [Module, AbstractString, Dict, Array, Tuple, DataType, Function]
    for datatype in taboo
        if isa(var, datatype)
            return false
        end
    end
    return true
end

function module_rewrite(m::Module, name::Symbol, value)
    eval(m, :($name=$value))
end

function switch_mods(vars, mod1, mod2)
    types = extract_types(mod1)
    for var in vars
        var_type = typeof(var)
        if !isa(var_type,    DataType)
            continue
        end
        for (old_type, type_name) in types
            if is_same_type_base(var_type, old_type)
                mod2_raw_type = mod2.(type_name)
                mod2_type = mod2_raw_type{var_type.parameters...}
                if is_identical_type(var_type, mod2_type)
                    unsafe_alter_type!(var, mod2_type)
                else
                    warn("Couldn't alter $var")
                end
            end
        end
    end
end

macro type_strip()
    if VERSION >= v"0.3.0-prerelease+925"
        quote
        end
    else
        esc(quote
            if options[:strip_types]
                e_i = eval_includes(e)
                if name == :Main
                    create_module(m_tmp, e)
                    e_t = strip_types(Main, e_i, Main.(m_tmp))
                else
                    create_module(m_tmp, Expr(:block))
                    info_debug("creating temporary module $m_tmp")
                    create_module(name, e, Main.(m_tmp))
                    info_debug("stripping types")
                    e_t = strip_types(m, e_i, Main.(m_tmp).(name))
                end
            else
                e_t = e
            end
        end)
    end
end

function reload_module(name, e)
    local m_tmp
    info_debug("reloading module $name")
    while true
        m_tmp = symbol("_m_tmp_$(rand(1:100000))") #todo must be better way to do this
        if !(m_tmp in names(Main, true))
            break
        end
    end
    m = nothing
    if name in names(Main, true)
        m = Main.(name)
        if isa(m, Module)
            @type_strip
            # if options[:strip_types]
            #     e_i = eval_includes(e)
            #     if name == :Main
            #         create_module(m_tmp, e)
            #         e_t = strip_types(Main, e_i, Main.(m_tmp))
            #     else
            #         create_module(m_tmp, Expr(:block))
            #         info_debug("creating temporary module $m_tmp")
            #         create_module(name, e, Main.(m_tmp))
            #         info_debug("stripping types")
            #         e_t = strip_types(m, e_i, Main.(m_tmp).(name))
            #     end
            # else
            #     e_t = e
            # end
            e_t = e
            #module_rewrite(Main, name, m)
            if e_t != nothing
                info_debug("evaluating in context of original module")
                for arg in e_t.args
                    eval(m, arg)
                end
                return
            end
        end
        if name == :Main
            warn("Type defined in Main changed. Unavoidable error will occur")
        else
            warn("Recreating module $name because of changed types")
        end
    end
    info_debug("initializing module $name")
    create_module(name, e)
    if m != nothing
        if options[:smart_types]
            info_debug("switching types in $name")
            switch_types(m, Main.(name))
        end
    end
end

function eval_includes(e_block)
    e_list = []
    for e in e_block.args
        if isa(e, Expr) &&
            e.head == :call &&
            e.args[1] == :include
            local f
            if isa(e.args[2], AbstractString)
                f = e.args[2]
            elseif isa(e.args[2], Expr)
                try
                    f = eval(Main, e.args[2]) # dangerous to eval in Main
                catch err
                    warn("include statement could not be processed:\n $err")
                    f = nothing
                end
            end
            if f != nothing
                f_p = parse_file(f)
                for arg in f_p.args
                    push!(e_list, arg)
                end
            else
                push!(e_list, e)
            end
            #push!(e_list, f_p)
        elseif isa(e, Expr) && e.head == :module
            f_p = eval_includes(e.args[3])
            push!(e_list, Expr(:module, e.args[1], e.args[2], f_p))
        else
            push!(e_list, e)
        end
    end
    block_wrap(e_list)
end

block_wrap(e_set::Array) = Expr(:block, e_set...)
block_wrap(e::Expr) = e

function get_type_name(e::Expr)
    if e.head == :type
        name = e.args[2]
    elseif e.head == :abstract
        name = e.args[1]
    else
        error("Name of type could not be extracted: \n$e")
    end
    while isa(name, Expr)
        name = name.args[1]
    end
    name
end

function strip_types(m, e_block, m_new)
    e_stripped = Any[]
    for e in e_block.args
        do_strip = false
        if isa(e, Expr) && e.head in [:type, :abstract]
            name = get_type_name(e) #e.args[2]
            if name in names(m, true)
                t = m.(name)
                if isa(t, DataType)
                    if is_identical_type(t, m_new.(name))
                        do_strip = true
                    else
                        info_debug("Type $t changed")
                        if DEBUG
                            module_rewrite(Main, :old_t, t)
                            module_rewrite(Main, :new_t, m_new.(name))
                        end
                        return nothing
                    end
                end
            end
        end
        if !do_strip
            push!(e_stripped, e)
        end
    end
    block_wrap(e_stripped)
end

function create_module(name, e, base=Main)
    info_debug("creating module")
    if name == :Main
        eval(Main, e)
    else
        eval(base, Expr(:module, true, name, e))
    end
end

function switch_types(m_old, m_new)
    symbols = collect_symbols(Main)
    switch_mods(symbols, m_old, m_new)
end

function extract_modules(e_block)
    modules = Dict{Symbol,Any}()
    in_main = Any[]
    info_debug("beginning module extraction")
    for e in e_block.args
        # isa(e, Expr) || continue
        if isa(e, Expr) && e.head == :module
            name = e.args[2]
            m_e = e.args[3]
            modules[name] = m_e
        else
            push!(in_main, e)
        end
    end
    modules[:Main] = block_wrap(in_main)
    info_debug("finishing module extraction")
    return modules
end

function collect_symbols(m)
    vars = []
    _collect_symbols(m, vars, 1)
    return vars
end

function try_getfield(m, name)
    local var
    try
        var = m.(name)
    catch err
        #warn("Symbol collection warning: \n$err")
        return (nothing, false)
    end
    return (var, true)
end

function _collect_symbols(m, vars, depth)
    # @show depth
    if isa(m, Module)
        name_list = names(m, true)
    else
        name_list = names(m)
    end
    for name in name_list
        var, has_var = try_getfield(m, name)
        has_var || continue
        if var in vars
            continue
        end
        push!(vars, var)
        if should_symbol_recurse(var)
            _collect_symbols(var, vars, depth+1)
        end
        if isa(var, Array) || isa(var, Tuple)
            for item in var
                if should_symbol_recurse(item)
                    _collect_symbols(item, vars, depth+1)
                end
                push!(vars, item)
            end
        end
        if isa(var, Dict) #todo handle keys properly
            for (key, value) in var
                for item in (key, value)
                    if should_symbol_recurse(item)
                        _collect_symbols(item, vars, depth+1)
                    end
                    push!(vars, item)
                end
            end
        end
    end
    vars
end

function unsafe_alter_type!(x, T::DataType)
    ptr = convert(Ptr{@compat UInt64}, pointer_from_objref(x))
    ptr_array = pointer_to_array(ptr, 1)
    ptr_array[1] = pointer_from_objref(T)
    x
end

function alter_type(x, T::DataType, var_name="")
    fields = names(T)
    old_fields = names(typeof(x))
    local x_new
    try
        x_new = T()
        for field in fields
            if field in old_fields
                x_new.(field) = x.(field)
            end
        end
    catch
        args = Any[]
        for field in fields
            if field in old_fields
                arg = x.(field)
                push!(args, arg)
            else
                warn("Type alteration of $(var_name) could not be performed automatically")
                return nothing
            end
        end
        x_new =    T(args...)
    end
    return x_new
end

function extract_types(mod::Module)
    types = Dict{DataType,Symbol}()
    for var_name in names(mod, true)
        var, has_var = try_getfield(mod, var_name)
        has_var || continue
        if typeof(var)==DataType
            types[var] = var_name
        end
    end
    types
end

function is_identical_type(t1, t2; kwargs...)
    t1 == t2
end

function is_identical_type(t1::TypeVar, t2::TypeVar; kwargs...)
    t1.name == t2.name || return false
    if isa(t1.ub, Tuple)
        isa(t2.ub, Tuple) || return false
        length(t1.ub) == length(t2.ub) || return false
        for i in 1:length(t1.ub)
            is_identical_type(t1.ub[i], t2.ub[i]) || return false
        end
    else
        is_identical_type(t1.ub, t2.ub) || return false
    end
    return true
end

function is_identical_type(t1::DataType, t2::DataType; deep_check::Bool=true)
    if !deep_check
        # This is hacky.
        return t1.name.name == t2.name.name
    end
    if t1.name.name == t2.name.name &&
        length(names(t1)) == length(names(t2)) &&
        all(names(t1).==names(t2))
        #sizeof(t1)==sizeof(t2) &&
        # t1.parameters==t2.parameters && #verify this
        # all(fieldoffsets(t1).==fieldoffsets(t2)) &&
        # t1.types == t2.types
        if length(t1.parameters) != length(t2.parameters)
            return false
        end
        for i in 1:length(t1.parameters)
            if !is_identical_type(t1.parameters[i], t2.parameters[i], deep_check=false)
                return false
            end
        end
        for i in 1:length(t1.types)
            if !is_identical_type(t1.types[i], t2.types[i], deep_check=false)
                return false
            end
        end
        return true
    else
        false
    end
end

function is_same_type_base(t1::DataType, t2::DataType)
    if t1.name == t2.name
        true
    else
        false
    end
end


text:
module KhepriBlender
using KhepriBase
using Sockets

# functions that need specialization
include(khepribase_interface_file())
include("Blender.jl")

function __init__()
  add_current_backend(blender)
end
end


text:
# AUTO GENERATED FILE - DO NOT EDIT

export 'feffery'_antdtransfer

"""
    'feffery'_antdtransfer(;kwargs...)

An AntdTransfer component.

Keyword arguments:
- `id` (String; optional)
- `className` (String; optional)
- `dataSource` (optional): . dataSource has the following type: Array of lists containing elements 'key', 'title'.
Those elements have the following types:
  - `key` (String | Real; optional)
  - `title` (String; optional)s
- `disabled` (Bool; optional)
- `height` (String; optional)
- `loading_state` (optional): . loading_state has the following type: lists containing elements 'is_loading', 'prop_name', 'component_name'.
Those elements have the following types:
  - `is_loading` (Bool; optional): Determines if the component is loading or not
  - `prop_name` (String; optional): Holds which property is loading
  - `component_name` (String; optional): Holds the name of the component that is loading
- `locale` (a value equal to: 'zh-cn', 'en-us'; optional)
- `moveDirection` (String; optional)
- `moveKeys` (Array; optional)
- `operations` (Array; optional)
- `pagination` (optional): . pagination has the following type: Bool | lists containing elements 'pageSize'.
Those elements have the following types:
  - `pageSize` (Real; optional)
- `persisted_props` (Array of a value equal to: 'targetKeys's; optional): Properties whose user interactions will persist after refreshing the
component or the page. Since only `value` is allowed this prop can
normally be ignored.
- `persistence` (Bool | String | Real; optional): Used to allow user interactions in this component to be persisted when
the component - or the page - is refreshed. If `persisted` is truthy and
hasn't changed from its previous value, a `value` that the user has
changed while using the app will keep that change, as long as
the new `value` also matches what was given originally.
Used in conjunction with `persistence_type`.
- `persistence_type` (a value equal to: 'local', 'session', 'memory'; optional): Where persisted user changes will be stored:
memory: only kept in memory, reset on page refresh.
local: window.localStorage, data is kept after the browser quit.
session: window.sessionStorage, data is cleared once the browser quit.
- `showSearch` (Bool; optional)
- `showSelectAll` (Bool; optional)
- `style` (Dict; optional)
- `targetKeys` (Array; optional)
- `titles` (Array; optional)
"""
function 'feffery'_antdtransfer(; kwargs...)
        available_props = Symbol[:id, :className, :dataSource, :disabled, :height, :loading_state, :locale, :moveDirection, :moveKeys, :operations, :pagination, :persisted_props, :persistence, :persistence_type, :showSearch, :showSelectAll, :style, :targetKeys, :titles]
        wild_props = Symbol[]
        return Component("'feffery'_antdtransfer", "AntdTransfer", "feffery_antd_components", available_props, wild_props; kwargs...)
end

max_stars_repo_name: ReilYoung/feffery-antd-components

max_issues_repo_name: ReilYoung/feffery-antd-components

max_forks_repo_name: ReilYoung/feffery-antd-components


text:
Base.show(io::IO, r::OneToRange) = print(io, typeof(r).name, "(", last(r), ")")

function Base.show(io::IO, r::AbstractStepRangeLen)
    print(io, typeof(r).name, "(", first(r), ":", step(r), ":", last(r), ")")
end

function Base.show(io::IO, r::StepMRange)
    print(io, "StepMRange(", first(r), ":", step(r), ":", last(r), ")")
end

function Base.show(io::IO, r::StepSRange)
    print(io, "StepSRange(", first(r), ":", step(r), ":", last(r), ")")
end

function Base.show(io::IO, r::StaticUnitRange)
    print(io, typeof(r).name, "(", repr(first(r)), ':', repr(last(r)), ")")
end


text:
"""
    _draw_image(video::Video, actions::Vector, frame::Int, canvas::Gtk.Canvas,
    img_dims::Vector)

Internal function to create an image that is drawn on a Gtk Canvas.
"""
function _draw_image(
    video::Video,
    actions::Vector,
    frame::Int,
    canvas::Gtk.Canvas,
    img_dims::Vector,
)
    @guarded draw(canvas) do widget
        # Gets a specific frame from graphic; transposed due to returned matrix
        frame_mat = transpose(get_javis_frame(video, actions, frame))

        # Gets the correct Canvas context to draw on
        context = getgc(canvas)

        # Uses Cairo to draw on Gtk canvas context
        image(context, CairoImageSurface(frame_mat), 0, 0, img_dims[1], img_dims[2])
    end
end

"""
    _increment(video::Video, widgets::Vector, actions::Vector, dims::Vector,
        canvas::Gtk.Canvas, frames::Int)

Increments a given value and returns the associated frame.
"""
function _increment(
    video::Video,
    widgets::Vector,
    actions::Vector,
    dims::Vector,
    canvas::Gtk.Canvas,
    frames::Int,
)
    # Get current frame from textbox as an Int value
    curr_frame = parse(Int, get_gtk_property(widgets[2], :text, String))
    if frames > curr_frame
        # `widgets[1]` represents the GtkReactive slider widget
        push!(widgets[1], curr_frame + 1)
        _draw_image(video, actions, curr_frame + 1, canvas, dims)
    else
        # `widgets[2]` represents the GtkReactive textboxwidget
        push!(widgets[2], 1) # Sets the first frame shown to one
        _draw_image(video, actions, 1, canvas, dims)
    end
end

"""
    _decrement(video::Video, widgets::Vector, actions::Vector, dims::Vector,
        canvas::Gtk.Canvas, frames::Int)

Decrements a given value and returns the associated frame.
"""
function _decrement(
    video::Video,
    widgets::Vector,
    actions::Vector,
    dims::Vector,
    canvas::Gtk.Canvas,
    frames::Int,
)
    # Get current frame from textbox as an Int value
    curr_frame = parse(Int, get_gtk_property(widgets[2], :text, String))
    if curr_frame > 1
        # `widgets[1]` represents the GtkReactive slider widget
        push!(widgets[1], curr_frame - 1)
        _draw_image(video, actions, curr_frame - 1, canvas, dims)
    else
        # `widgets[2]` represents the GtkReactive textboxwidget
        push!(widgets[2], frames) # Sets the first frame shown to one
        _draw_image(video, actions, frames, canvas, dims)
    end
end

"""
     _javis_viewer(video::Video, frames::Int, action_list::Vector, show::Bool)

Internal Javis Viewer built on Gtk that is called for live previewing.
"""
function _javis_viewer(
    video::Video,
    total_frames::Int,
    action_list::Vector,
    show::Bool = true,
)

    #####################################################################
    # VIEWER WINDOW AND CONFIGURATION
    #####################################################################

    # Determine frame size of animation
    frame_dims = [video.width, video.height]

    # Creates a GTK window for drawing; sized based on frame size
    win = GtkWindow("Javis Viewer", frame_dims[1], frame_dims[2])

    # Sets border size of window
    set_gtk_property!(win, :border_width, 20)

    #####################################################################
    # DISPLAY WIDGETS
    #####################################################################

    # Create GtkScale internal widget
    _slide = GtkScale(false, 1:total_frames)

    # Create GtkReactive slider widget
    slide = slider(1:total_frames, value = 1, widget = _slide)

    #=
    #
    # NOTE: We must provide a named GtkScale widget named `_slide` to the
    # GtkReactive `slider` widget so as to perform asynchronous calls
    # via signal_connect. Otherwise, we will be unable to update the
    # widget that is automatically created by the slider object.
    #
    # It should be stated that a `slider` object is essentially a
    # GtkScale widget coupled with a Reactive object.
    #
    =#

    # Create a textbox
    tbox = GtkReactive.textbox(Int; signal = signal(slide))

    # Button for going forward through animation
    forward = GtkButton("==>")

    # Button for going backward through animation
    backward = GtkButton("<==")

    #=

    TODO: Enable widgets of window to dynamically resize based on user changing the size of a window.

    I think I can use the `configure-event` signal in GTK3 documentation (link: https://developer.gnome.org/gtk3/stable/GtkWidget.html#GtkWidget-configure-event). From there, I can then make a `signal_connect` set-up where I update `set_gtk_property!()` of the windows accordingly using `:width_request` and `height_request`.

    =#

    #####################################################################
    # VIEWER CANVAS AND GRID CONFIGURATION
    #####################################################################

    # Gtk Canvas object upon which to draw image; sized via frame size
    canvas = Gtk.Canvas(frame_dims[1], frame_dims[2])

    # Grid to allocate widgets
    grid = Gtk.Grid()

    # Allocate the widgets in a 3x3 grid
    grid[1:3, 1] = canvas
    grid[1:3, 2] = slide
    grid[1, 3] = backward
    grid[2, 3] = tbox
    grid[3, 3] = forward

    # Center all widgets vertically in grid
    set_gtk_property!(grid, :valign, 3)

    # Center all widgets horizontally in grid
    set_gtk_property!(grid, :halign, 3)

    # Adds grid to previously defined window
    push!(win, grid)

    #####################################################################
    # DISPLAY FIRST FRAME
    #####################################################################

    _draw_image(video, action_list, 1, canvas, frame_dims)

    #####################################################################
    # SIGNAL CONNECTION FUNCTIONS
    #####################################################################

    # When the slider is changed, update currently viewed frame
    signal_connect(_slide, "value-changed") do widget
        # Collects GtkScale as an adjustable bounded value object
        bound_slide = Gtk.GAccessor.adjustment(_slide)

        # Get frame number from bounded value object as Int
        slide_val = Gtk.get_gtk_property(bound_slide, "value", Int)

        _draw_image(video, action_list, slide_val, canvas, frame_dims)
    end

    # When the `Enter` key is pressed, update the frame
    signal_connect(win, "key-press-event") do widget, event
        if event.keyval == 65293
            # Get current frame from textbox as an Int value
            curr_frame = parse(Int, get_gtk_property(tbox, :text, String))
            curr_frame = clamp(curr_frame, 1, total_frames)
            _draw_image(video, action_list, curr_frame, canvas, frame_dims)
        end
    end

    # When the `forward` button is clicked, increment current frame number
    # If at final frame, wrap viewer to first frame
    signal_connect(forward, "clicked") do widget
        _increment(video, [slide, tbox], action_list, frame_dims, canvas, total_frames)
    end

    # When the `Right Arrow` key is pressed, increment current frame number
    # If at final frame, wrap viewer to first frame
    signal_connect(win, "key-press-event") do widget, event
        if event.keyval == 65363
            _increment(video, [slide, tbox], action_list, frame_dims, canvas, total_frames)
        end
    end

    # When the `backward` button is clicked, decrement the current frame number
    # If at first frame, wrap viewer to last frame
    signal_connect(backward, "clicked") do widget
        _decrement(video, [slide, tbox], action_list, frame_dims, canvas, total_frames)
    end

    # When the `Left Arrow` key is pressed, decrement current frame number
    # If at first frame, wrap viewer to last frame
    signal_connect(win, "key-press-event") do widget, event
        if event.keyval == 65361
            _decrement(video, [slide, tbox], action_list, frame_dims, canvas, total_frames)
        end
    end

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

    if show
        # Display image viewer
        Gtk.showall(win)
    else
        return win, frame_dims, slide, tbox, canvas, action_list, total_frames, video
    end

end


text:
abstract type PreallocatedDataAugmented{T <: Real, S} <: PreallocatedData{T, S} end

abstract type PreallocatedDataAugmentedLDL{T <: Real, S} <: PreallocatedDataAugmented{T, S} end

include("K2LDL.jl")
include("K2_5LDL.jl")

abstract type PreallocatedDataAugmentedKrylov{T <: Real, S} <: PreallocatedDataAugmented{T, S} end

include("K2Krylov.jl")
include("K2_5Krylov.jl")