text:
#
# ResizableArrays.jl --
#
# Implement arrays which are resizable.
#

module ResizableArrays

export
    ResizableArray,
    ResizableMatrix,
    ResizableVector,
    isgrowable,
    maxlength,
    shrink!

using Base: elsize, tail, OneTo, throw_boundserror, @propagate_inbounds

"""

```julia
ResizableArray{T}(undef, dims)
```

yields a resizable array with uninitialized elements of type `T` and dimensions
`dims`.  Dimensions may be a tuple of integers or a a list of integers.  The
number `N` of dimensions may be explicitly specified:

```julia
ResizableArray{T,N}(undef, dims)
```

To create an empty resizable array of given rank and element type, call:

```julia
ResizableArray{T,N}()
```

The dimensions of a resizable array `A` may be changed by calling
`resize!(A,dims)` with `dims` the new dimensions.  The number of dimensions
must remain unchanged but the length of the array may change.  Depending on the
type of the object backing the storage of the array, it may be possible or not
to augment the number of elements of the array.  When array elements are stored
in a regular Julia vector, the number of element can always be augmented.
Changing only the last dimension of a resizable array preserves its contents.

Resizable arrays are designed to re-use storage if possible to avoid calling
the garbage collector.  This may be useful for real-time applications.  As a
consequence, the storage used by a resizable array `A` can only grow unless
`skrink!(A)` is called to reduce the storage to the minimum.  The call
`copy(ResizableArray,A)` yields a copy of `A` which is a resizable array.

To improve performances, call `sizehint!(A,n)` to indicate the minimum number
of elements to preallocate for `A` (`n` can be a number of elements or array
dimensions).

The `ResizableArray` constructor and the `convert` method can be used to to
convert an array `A` to a resizable array:

```julia
ResizableArray(A)
convert(ResizableArray, A)
```

Element type `T` and number of dimensions `N` may be specified:

```julia
ResizableArray{T[,N]}(A)
convert(ResizableArray{T[,N]}, A)
```

`N` must match `ndims(A)` but `T` may be different from `eltype(A)`.  If
possible, the `convert` method returns the input array while the
`ResizableArray` constructor always returns a new instance.

The default storage for the elements of a resizable array is provided by a
regular Julia vector.  To use an object `buf` to store the elements of a
resizable array, use one of the following:

```julia
A = ResizableArray(buf, dims)
A = ResizableArray{T}(buf, dims)
A = ResizableArray{T,N}(buf, dims)
```

The buffer `buf` must store its elements contiguously using linear indexing
style with 1-based indices and have element type `T`, that is
`IndexStyle(typeof(buf))` and `eltype(buf)` must yield `IndexLinear()` and `T`
respectively.  The methods, `IndexStyle`, `eltype`, `length`, `getindex` and
`setindex!` must be applicable for the type of `buf`.  If the method `resize!`
is applicable for `buf`, the number of elements of `A` can be augmented;
otherwise the maximum number of elements of `A` is `length(buf)`.

!!! warning
    When explictely providing a resizable buffer `buf` for backing the
    storage of a resizable array `A`, you have the responsibility to make
    sure that the same buffer is not resized elsewhere.  Otherwise a
    segmentation fault may occur because `A` might assume a wrong buffer
    size.  To avoid this, the best is to make sure that only `A` owns `buf`
    and only `A` manages its size.  In the current implementation, the size
    of the internal buffer is never reduced so the same buffer may be
    safely shared by different resizable arrays.

"""
mutable struct ResizableArray{T,N,B} <: DenseArray{T,N}
    len::Int
    dims::NTuple{N,Int}
    vals::B
    # Inner constructor for provided storage buffer.
    function ResizableArray{T,N}(buf::B,
                                 dims::NTuple{N,Int}) where {T,N,B}
        eltype(B) === T || error("buffer has a different element type")
        IndexStyle(B) === IndexLinear() ||
            error("buffer must have linear indexing style")
        checkdimensions(dims)
        len = prod(dims)
        length(buf) ≥ len || error("buffer is too small")
        return new{T,N,B}(len, dims, buf)
    end
    # Inner constructor using regular Julia's vector to store elements.
    function ResizableArray{T,N}(::UndefInitializer,
                                 dims::NTuple{N,Int}) where {T,N}
        checkdimensions(dims)
        len = prod(dims)
        buf = Vector{T}(undef, len)
        return new{T,N,Vector{T}}(len, dims, buf)
    end

end

# Calling the `ResizableArray` constructor always creates a new instance.

ResizableArray(arg, dims::Integer...) =
    ResizableArray(arg, dims)
ResizableArray(arg, dims::Tuple{Vararg{Integer}}) =
    ResizableArray(arg, map(Int, dims))
ResizableArray(buf::B, dims::NTuple{N,Int}) where {N,B} =
    ResizableArray{eltype(B),N}(buf, dims)

ResizableArray{T}(arg, dims::Integer...) where {T} =
    ResizableArray{T}(arg, dims)
ResizableArray{T}(arg, dims::Tuple{Vararg{Integer}}) where {T} =
    ResizableArray{T}(arg, map(Int, dims))
ResizableArray{T}(arg, dims::NTuple{N,Int}) where {T,N} =
    ResizableArray{T,N}(arg, dims)

ResizableArray{T,N}(arg, dims::Integer...) where {T,N} =
    ResizableArray{T,N}(arg, dims)
function ResizableArray{T,N}(arg, dims::Tuple{Vararg{Integer}}) where {T,N}
    length(dims) == N || _throw_mismatching_number_of_dimensions()
    return ResizableArray{T,N}(arg, map(Int, dims))
end

ResizableArray{T,N,B}(A::AbstractArray) where {T,N,B} =
    (Vector{T} <: B ? ResizableArray{T,N}(A) :
     _throw_invalid_buffer_type(B,T))
ResizableArray{T,N}(A::AbstractArray{<:Any,M}) where {T,N,M} =
    (M == N ? copyto!(ResizableArray{T,N}(undef, size(A)), A) :
     _throw_mismatching_number_of_dimensions())
ResizableArray{T}(A::AbstractArray) where {T} =
    copyto!(ResizableArray{T}(undef, size(A)), A)
ResizableArray(A::AbstractArray{T}) where {T} =
    copyto!(ResizableArray{T}(undef, size(A)), A)

# Constructor for, initially empty, workspace of given rank and element type.
ResizableArray{T,N}() where {T,N} =
    ResizableArray{T,N}(undef, ntuple(i -> 0, Val(N)))

@noinline _throw_mismatching_number_of_dimensions() =
    throw(DimensionMismatch("mismatching number of dimensions"))

# TypeError is more appropriate but we want a specific error message.
@noinline _throw_invalid_buffer_type(::Type{B},::Type{T}) where {B,T} =
    throw(ErrorException("invalid buffer type $B (must be ≥ Vector{$T})"))

# Make a resizable copy.
Base.copy(::Type{ResizableArray}, A::AbstractArray) =
    ResizableArray(A)
Base.copy(::Type{ResizableArray{T}}, A::AbstractArray) where {T} =
    ResizableArray{T}(A)
Base.copy(::Type{ResizableArray{T,N}}, A::AbstractArray) where {T,N} =
    ResizableArray{T,N}(A)
Base.copy(::Type{ResizableArray{T,N,B}}, A::AbstractArray) where {T,N,B} =
    ResizableArray{T,N,B}(A)

# Unlike the `ResizableArray` constructor, calling the `convert` method avoids
# creating a new instance if possible.
Base.convert(::Type{ResizableArray{T,N,B}}, A::ResizableArray{T,N,C}) where {T,N,B,C<:B} = A
Base.convert(::Type{ResizableArray{T,N}}, A::ResizableArray{T,N}) where {T,N} = A
Base.convert(::Type{ResizableArray{T}}, A::ResizableArray{T}) where {T} = A
Base.convert(::Type{ResizableArray}, A::ResizableArray) = A
Base.convert(::Type{ResizableArray{T,N,B}}, A::AbstractArray) where {T,N,B} =
    ResizableArray{T,N,B}(A)
Base.convert(::Type{ResizableArray{T,N}}, A::AbstractArray) where {T,N} =
    ResizableArray{T,N}(A)
Base.convert(::Type{ResizableArray{T}}, A::AbstractArray) where {T} =
    ResizableArray{T}(A)
Base.convert(::Type{ResizableArray}, A::AbstractArray) =
    ResizableArray(A)

"""
```julia
ResizableVector{T}
```

Supertype for one-dimensional resizable arrays with elements of type `T`.
Alias for [`ResizableArray{T,1}`](@ref).

"""
const ResizableVector{T,B} = ResizableArray{T,1,B}

"""
```julia
ResizableMatrix{T}
```

Supertype for two-dimensional resizable arrays with elements of type `T`.
Alias for [`ResizableArray{T,2}`](@ref).

"""
const ResizableMatrix{T,B} = ResizableArray{T,2,B}

"""
```julia
checkdimension(Bool, dim) -> boolean
```

yields whether `dim` is a valid dimension length (that is a nonnegative
integer).

"""
@inline checkdimension(::Type{Bool}, dim::Integer) = (dim ≥ 0)
@inline checkdimension(::Type{Bool}, dim) = false

"""
```julia
checkdimensions(Bool, dims) -> boolean
```

yields whether `dims` is a valid list of dimensions.

```julia
checkdimensions(dims)
```
throws an error if `dims` is not a valid list of dimensions.

"""
@inline checkdimensions(::Type{Bool}, dims::Tuple) =
    checkdimension(Bool, dims[1]) & checkdimensions(Bool, tail(dims))
@inline checkdimensions(::Type{Bool}, ::Tuple{}) = true
@inline checkdimensions(dims::Tuple) =
    checkdimensions(Bool, dims) || throw_invalid_dimensions()

@noinline throw_invalid_dimensions() =
    error("invalid dimension(s)")

"""
```julia
isgrowable(x) -> boolean
```

yields whether `x` is a growable object, that is its size can be augmented.

"""
isgrowable(A::ResizableArray) = isgrowable(A.vals)
isgrowable(A::ResizableArray{T,0}) where {T} = false
isgrowable(::Vector) = true
isgrowable(::Any) = false

"""
```julia
maxlength(A)
```

yields the maximum number of elements which can be stored in resizable
array `A` without resizing its internal buffer.

See also: [`ResizableArray`](@ref).

"""
maxlength(A::ResizableArray) = length(A.vals)

Base.length(A::ResizableArray) = A.len
Base.size(A::ResizableArray) = A.dims
Base.size(A::ResizableArray{T,N}, d::Integer) where {T,N} =
    (d > N ? 1 : d ≥ 1 ? A.dims[d] : error("out of range dimension"))
Base.axes(A::ResizableArray) = map(OneTo, A.dims)
Base.axes(A::ResizableArray, d::Integer) = Base.OneTo(size(A, d))
@inline Base.axes1(A::ResizableArray{<:Any,0}) = OneTo(1)
@inline Base.axes1(A::ResizableArray) = OneTo(A.dims[1])
Base.IndexStyle(::Type{<:ResizableArray}) = IndexLinear()
Base.parent(A::ResizableArray) = A.vals
Base.similar(::Type{ResizableArray{T}}, dims::NTuple{N,Int}) where {T,N} =
    ResizableArray{T,N}(undef, dims)

# Make sizeof() return the number of bytes of the actual contents.
Base.elsize(::Type{ResizableArray{T,N,B}}) where {T,N,B} = elsize(B)
Base.sizeof(A::ResizableArray) = elsize(A)*length(A)

# Make ResizableArray's efficient iterators.
@inline Base.iterate(A::ResizableArray, i=1) =
    ((i % UInt) - 1 < length(A) ? (@inbounds A[i], i + 1) : nothing)

# Equality is false if rank is different.
Base.:(==)(::ResizableArray, ::AbstractArray) = false
Base.:(==)(::AbstractArray,  ::ResizableArray) = false
Base.:(==)(::ResizableArray, ::ResizableArray) = false

Base.:(==)(A::ResizableVector{<:Any}, B::ResizableVector{<:Any}) =
    (length(A) == length(B) && _same_elements(A.vals, B.vals, length(A)))

Base.:(==)(A::ResizableArray{<:Any,N}, B::ResizableArray{<:Any,N}) where {N} =
    (size(A) == size(B) && _same_elements(A.vals, B.vals, length(A)))

Base.:(==)(A::ResizableVector{<:Any}, B::Vector{<:Any}) =
    (length(A) == length(B) && _same_elements(A.vals, B, length(A)))
Base.:(==)(A::Vector{<:Any}, B::ResizableVector{<:Any}) =
    (length(A) == length(B) && _same_elements(A, B.vals, length(A)))

Base.:(==)(A::ResizableArray{<:Any,N}, B::Array{<:Any,N}) where {N} =
    (size(A) == size(B) && _same_elements(A.vals, B, length(A)))
Base.:(==)(A::Array{<:Any,N}, B::ResizableArray{<:Any,N}) where {N} =
    (size(A) == size(B) && _same_elements(A, B.vals, length(A)))

Base.:(==)(A::ResizableArray{<:Any,N}, B::AbstractArray{<:Any,N}) where {N} =
    (axes(A) == axes(B) && _same_elements(A.vals, B, length(A)))
Base.:(==)(A::AbstractArray{<:Any,N}, B::ResizableArray{<:Any,N}) where {N} =
    (axes(A) == axes(B) && _same_elements(A, B.vals, length(A)))

# Yields whether the `n` first elements of `A` and `B` are identical.  This
# method is unsafe as it assumes that `A` and `B` have at least `n` elements.
_same_elements(A, B, n::Integer) =
    _same_elements(IndexStyle(A), A, IndexStyle(B), B, Int(n))

function _same_elements(::IndexLinear, A, ::IndexLinear, B, n::Int)
    @inbounds for i in Base.OneTo(n)
        A[i] == B[i] || return false
    end
    return true
end

function _same_elements(::IndexLinear, A, ::IndexStyle, B, n::Int)
    i = 0
    @inbounds for j in eachindex(B)
        (i += 1) ≤ n || return true
        A[i] == B[j] || return false
    end
    return (i ≥ n)
end

function _same_elements(::IndexStyle, A, ::IndexLinear, B, n::Int)
    j = 0
    @inbounds for i in eachindex(A)
        (j += 1) ≤ n || return true
        A[i] == B[j] || return false
    end
    return (j ≥ n)
end

function _same_elements(::IndexStyle, A, ::IndexStyle, B, n::Int)
    # this case should never occur
    j = 0
    @inbounds for i in eachindex(A,B)
        (j += 1) ≤ n || return true
        A[i] == B[i] || return false
    end
    return (j ≥ n)
end

Base.resize!(A::ResizableArray, dims::Integer...) = resize!(A, dims)
function Base.resize!(A::ResizableArray, dims::Tuple{Vararg{Integer}})
    length(dims) == ndims(A) ||
        error("changing the number of dimensions is not allowed")
    return resize!(A, map(Int, dims))
end
function Base.resize!(A::ResizableArray{T,N}, dims::NTuple{N,Int}) where {T,N}
    if dims != size(A)
        checkdimensions(dims)
        newlen = prod(dims)
        newlen > length(A.vals) && resize!(A.vals, newlen)
        A.dims = dims
        A.len = newlen
    end
    return A
end

Base.sizehint!(A::ResizableArray, dims::Integer...) = sizehint!(A, dims)
function Base.sizehint!(A::ResizableArray, dims::Tuple{Vararg{Integer}})
    length(dims) == ndims(A) ||
        error("changing the number of dimensions is not allowed")
    checkdimensions(dims)
    len = prod(dims)
    len > maxlength(A) && sizehint!(parent(A), len)
    return A
end
function Base.sizehint!(A::ResizableArray, len::Integer)
    len ≥ 0 || throw(ArgumentError("number of elements must be nonnegative"))
    len > maxlength(A) && sizehint!(parent(A), len)
    return A
end

"""

```julia
shrink!(A) -> A
```

shrinks as much as possible the storage of resizable array `A` and returns `A`.
Call `copy(ResizableArray,A)` to make a copy of `A` which is a resizable array
with skrinked storage.

"""
function shrink!(A::ResizableArray)
    length(A) < length(A.vals) && resize!(A.vals, length(A))
    return A
end

"""

```julia
grow!(A, B, prepend=false) -> A
```

grows resizable array `A` with the elements of `B` and returns `A`.  If
`prepend` is `true`, the elements of `B` are inserted before those of `A`;
otherwise, the elements of `B` are appended after those of `A`.  By default,
`prepend` is `false`.

Assuming `A` has `N` dimensions, array `B` may have `N` or `N-1` dimensions.
The `N-1` leading dimensions of `A` and `B` must be identical and are the
leading dimensions of the result.  If `B` has the same number of dimensions as
`A`, the last dimension of the result is the sum of the last dimensions of `A`
and `B`; otherwise, the last dimension of the result is one plus the last
dimension of `A`.

Depending on argument `prepend`, calling the `grow!` method is equivalent to
calling `append!` or `prepend!` methods.

See also [`ResizableArray`](@ref).

"""
function grow!(A::ResizableArray{<:Any,N},
               B::AbstractArray{<:Any,M}, prepend::Bool=false) where {N,M}
    N - 1 ≤ M ≤ N || throw(DimensionMismatch("invalid number of dimensions"))
    indA = axes(A)
    indB = axes(B)
    @inbounds for d in 1:N-1
        indA[d] == indB[d] ||
            throw(DimensionMismatch("leading dimensions must be identical"))
    end
    dimN = length(indA[N]) + (M == N ? length(indB[N]) : 1)
    lenA = length(A)
    lenB = length(B)
    minlen = lenA + lenB
    buf = A.vals
    length(buf) ≥ minlen || resize!(buf, minlen)
    if prepend
        copyto!(buf, lenB + 1, buf, 1, lenA)
        copyto!(buf, 1, B, 1, lenB)
    else
        copyto!(buf, lenA + 1, B, 1, lenB)
    end
    A.len = lenA + lenB
    A.dims = ntuple(d -> (d < N ? A.dims[d] : dimN), Val(N))
    return A
end

Base.append!(dst::ResizableArray, src::AbstractArray) =
    grow!(dst, src, false)

Base.prepend!(dst::ResizableArray, src::AbstractArray) =
    grow!(dst, src, true)

@inline @propagate_inbounds Base.getindex(A::ResizableArray, i::Int) =
    (@boundscheck checkbounds(A, i);
     @inbounds getindex(A.vals, i))

@inline @propagate_inbounds Base.setindex!(A::ResizableArray, x, i::Int) =
    (@boundscheck checkbounds(A, i);
     @inbounds setindex!(A.vals, x, i))

@inline Base.checkbounds(::Type{Bool}, A::ResizableArray, i::Int) =
    (i % UInt) - 1 < length(A)

Base.copyto!(dst::ResizableArray{T}, src::Array{T}) where {T} =
    copyto!(dst, 1, src, 1, length(src))
Base.copyto!(dst::Array{T}, src::ResizableArray{T}) where {T} =
    copyto!(dst, 1, src, 1, length(src))
Base.copyto!(dst::ResizableArray{T}, src::ResizableArray{T}) where {T} =
    copyto!(dst, 1, src, 1, length(src))

function Base.copyto!(dst::ResizableArray{T}, doff::Integer,
                      src::Array{T}, soff::Integer, n::Integer) where {T}
    if n != 0
        checkcopyto(length(dst), doff, length(src), soff, n)
        unsafe_copyto!(dst.vals, doff, src, soff, n)
    end
    return dst
end

function Base.copyto!(dst::Array{T}, doff::Integer,
                      src::ResizableArray{T}, soff::Integer,
                      n::Integer) where {T}
    if n != 0
        checkcopyto(length(dst), doff, length(src), soff, n)
        unsafe_copyto!(dst, doff, src.vals, soff, n)
    end
    return dst
end

function Base.copyto!(dst::ResizableArray{T}, doff::Integer,
                      src::ResizableArray{T}, soff::Integer,
                      n::Integer) where {T}
    if n != 0
        checkcopyto(length(dst), doff, length(src), soff, n)
        unsafe_copyto!(dst.vals, doff, src.vals, soff, n)
    end
    return dst
end

@inline function checkcopyto(dlen::Integer, doff::Integer,
                             slen::Integer, soff::Integer, n::Integer)
     @noinline throw_invalid_length() =
        throw(ArgumentError("number of elements to copy must be nonnegative"))
    n ≥ 0 || throw_invalid_length()
    (doff > 0 && doff - 1 + n ≤ dlen &&
     soff > 0 && soff - 1 + n ≤ slen) || throw(BoundsError())
end

Base.unsafe_convert(::Type{Ptr{T}}, A::ResizableArray{T}) where {T} =
    Base.unsafe_convert(Ptr{T}, A.vals)

Base.pointer(A::ResizableArray) = pointer(A.vals)
Base.pointer(A::ResizableArray, i::Integer) = pointer(A.vals, i)

end # module


text:
module TestHierarchy

using Base.Test
using Logging

# configure root logger
Logging.configure(level=DEBUG)
root = Logging._root

loggerA = Logger("loggerA")
loggerB = Logger("loggerB", WARNING, [STDOUT,STDERR])

# test hierarchy
@test root.parent == root
@test loggerA.parent == root
@test loggerB.parent == loggerB

end

ext: jl


text:
#!/usr/bin/env julia

using Luxor, Colors, NamedColors

"""
compare two colors, looking just at their LUV luminance values
"""
function compare_colors(color_a, color_b)
    color_x = convert(Luv, RGB(color_a...))
    color_y = convert(Luv, RGB(color_b...))
    getfield(color_x, :l) > getfield(color_y, :l)
end

"""
draw a swatch
"""
function draw_swatch(colorname, colorvalues, pt, swatchwidth, swatchheight, column)
    gsave()
    translate(pt)
    sethue(colorvalues...)
    box(O, swatchwidth, swatchheight, :fill)
    sethue("black")
    # alternate label's y coordinates because some are so bleeding wide
    column % 2 == 0 ? text(colorname, O.x, -swatchheight/2 - 1, halign=:center) : text(colorname, O.x, -swatchheight/2 - 3, halign=:center)
    grestore()
end

"""
draw a slightly gray background behind the very light colors but stop doing it
by the time you get to the not so light ones
"""
function drawbackground(imagewidth, imageheight)
    blend_white_black = blend(Point(0, 0), Point(0, imageheight), "grey95", "white")
    setblend(blend_white_black)
    box(imagewidth/2, imageheight/2, imagewidth, imageheight, :fill)
end

function main(imagewidth, imageheight)
    # first create reverse synonym dictionary, color values as keys, color names as values
    synonyms = Dict{Tuple, Array}()
    for (k, v) in ALL_COLORS
        col_name  = k
        col_value = (red(v), green(v), blue(v))
        # get rid of this UFixed stuff first
        col_value_f = map(x -> convert(Float64, x), col_value)
        # float64 3tuple as dictionary keys, yay, cool
        if haskey(synonyms, col_value_f)
            push!(synonyms[col_value_f], col_name)
        else
            synonyms[col_value_f] = [col_name]
        end
    end

    # calculate sizes of swatches
    aspect = imagewidth/imageheight
    if aspect > 1
        n_rows = ceil(sqrt(length(synonyms)/aspect))
    else
        n_rows = ceil(sqrt(length(synonyms) * aspect))
    end
    n_cols = ceil(length(synonyms)/n_rows)

    margin = 30
    row_space = 20
    col_space = 5
    swatchwidth  = ((imagewidth  - 2margin - (col_space * n_cols )) / n_cols)
    swatchheight = ((imageheight - 2margin - (row_space * n_rows )) / n_rows)

    Drawing(imagewidth, imageheight, "/tmp/namedcolors.pdf")
    drawbackground(imagewidth, imageheight)
    fontsize(3)
    column = 1
    x, y = margin, 3margin

    for color_values in sort(collect(keys(synonyms)), lt = (x, y) -> compare_colors(x, y))
        color_synonyms = sort(synonyms[color_values])

        # draw the swatch
        draw_swatch(color_synonyms[1], color_values, Point(x, y), swatchwidth, swatchheight, column)

        # synonyms
        oldy = y # save the current y position during excursion
        for synonym in color_synonyms[2:end]
            # draw the other names for this color underneath
            fontsize(2)
            sethue("black")
            text(":$synonym", x - swatchwidth/2, y + swatchheight/2 + 2)
            fontsize(3)
            y += 2
        end
        y = oldy

        if x > (imagewidth - swatchwidth - margin)
            x = margin # next row
            column = 1
            y += swatchheight + row_space
        else
            x += swatchwidth + col_space
        end
        column += 1
    end

    # title
    fontsize(24)
    fontface("Eurostile-Bold")
    sethue(colorant"poop brown") # seriously useful color
    text("NamedColors.jl, sorted by/with LUV", imagewidth/2, 1.5margin, halign=:center)
    #footer
    fontsize(10)
    text("drawn $(Dates.format(Dates.now(), "yyyy-mm-dd HH:MM:SS")), $(length(ALL_COLORS)) named colors", imagewidth/2, imageheight-margin, halign=:center)
    finish()
    preview()
end

main(paper_sizes["A1"]...)


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

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

function _swaggerinternal_migrationExchange(_api::MigrationApi, users::String; team_id=nothing, to_old=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", Dict{String, Any}, "/migration.exchange", ["slackAuth"])
    Swagger.set_param(_ctx.query, "users", users)  # type String
    Swagger.set_param(_ctx.query, "team_id", team_id)  # type String
    Swagger.set_param(_ctx.query, "to_old", to_old)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/x-www-form-urlencoded"] : [_mediaType])
    return _ctx
end

"""

For Enterprise Grid workspaces, map local user IDs to global user IDs
Param: users::String (required)
Param: team_id::String
Param: to_old::Bool
Return: Dict{String, Any}
"""
function migrationExchange(_api::MigrationApi, users::String; team_id=nothing, to_old=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_migrationExchange(_api, users; team_id=team_id, to_old=to_old, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function migrationExchange(_api::MigrationApi, response_stream::Channel, users::String; team_id=nothing, to_old=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_migrationExchange(_api, users; team_id=team_id, to_old=to_old, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

export migrationExchange


text:
# ---
# jupyter:
#   jupytext:
#     formats: ipynb,jl:hydrogen
#     text_representation:
#       extension: .jl
#       format_name: hydrogen
#       format_version: '1.3'
#       jupytext_version: 1.11.2
#   kernelspec:
#     display_name: Julia 1.8.0-DEV
#     language: julia
#     name: julia-1.8
# ---

# %%
abstract type AbstractSep{T} end

struct Sep{T<:Union{Nothing, Tuple{<:AbstractSep, <:AbstractSep}}} <: AbstractSep{T}
    a::T
end
Sep(x::AbstractSep, y::AbstractSep) = Sep((x, y))

const Nil = Sep(nothing)
Base.show(io::IO, ::Sep{Nothing}) = print(io, "Nil")
Base.show(io::IO, x::Sep{<:Tuple}) = print(io, x.a)

# %%
Nil

# %%
a = Sep(Nil, Nil)

# %%
b = Sep(a, a)

# %%
c = Sep(a, b)

# %%
typeof(c)

# %%

max_stars_repo_name: genkuroki/public

max_issues_repo_name: genkuroki/public

max_forks_repo_name: genkuroki/public


text:
immutable LocalLevelFit{T}
    residual_std::T
    locallevel_innovation_std::T
    regression_coefs::Vector{T}
    transform_params::Vector{T}
    y::Vector{T}
    y_residuals::Vector{T}
    locallevel::Vector{T}
    locallevel_std::Vector{T}
    locallevel_innovations::Vector{T}
end #LocalLevelFit

#TODO
#function Base.show(llf::LocalLevelFit)
#end #show

function fit{T}(y::Vector{T}, X::Matrix{T}=zeros(length(y),0))

    n   = length(y) # Number of observations
    @assert n == size(X, 1)
    notmissing = !isnan(y)

    X   = X'
    m   = size(X,1) # Number of regressors

    nₓ  = 1 + m
    Q = zeros(nₓ, nₓ)
    C = [ones(1, n); X] .* notmissing'

    yclean = y .* notmissing

    function ll(params::Vector{T})
        Q[1] = exp(2params[2])
        return likelihood(yclean, C, exp(2params[1]), Q)
    end #ll

    params = optimize(ll, [0., 0.]).minimum

    #println(exp(params))
    σϵ², σμ² = exp(2params)
    y_residuals, x, Pₓ, x_residuals = smooth(yclean, C, σϵ², σμ²)

    return LocalLevelFit(sqrt(σϵ²), sqrt(σμ²), x[2:end,end], zeros(0), y, y_residuals, vec(x[1,:]), vec(Pₓ[1,1,:]), vec(x_residuals[1,:]))

end #fit

function fit{T}(y::Vector{T}, f::Function, p₀::Vector{T}, X::Matrix{T})

    n   = length(y) # Number of observations
    m   = size(f(p₀, X), 2) # Number of regressors
    @assert n == size(X, 1)

    notmissing = !isnan(y)

    nₓ  = 1 + m
    Q = zeros(nₓ, nₓ)
    yclean = y .* notmissing
    c = ones(1, n)

    function ll(params::Vector{T})
        C = [c; f(params[3:end], X)'] .* notmissing'
        Q[1] = exp(2params[2])
        return likelihood(yclean, C, exp(2params[1]), Q)
    end #ll

    params = optimize(ll, [0.; 0.; p₀]).minimum

    σϵ², σμ² = exp(2params[1:2])
    p = params[3:end]
    fX = f(p, X)'
    C = [ones(1, n); fX] .* notmissing'
    y_residuals, x, Pₓ, x_residuals = smooth(yclean, C, σϵ², σμ²)

    return LocalLevelFit(sqrt(σϵ²), sqrt(σμ²), x[2:end,end], p, y, y_residuals, vec(x[1,:]), vec(Pₓ[1,1,:]), vec(x_residuals[1,:]))

end #fit


text:
using stoosc
rc("font", family="arial")

function perform_simulation!(params)

    T = 1.0
    jet_lag = params["jet_lag"]
    trajectories = params["trajectories"]
    model_name = params["model_name"]
    problem_type = params["problem_type"]
    parameter_names = params["parameter_names"]
    parameter_values = params["parameter_values"]
    i_variable = params["i_variable"]

    model = load_model(model_name, problem_type)

    model = set_solver(model; saveat=0.01, maxiters=1e10)
    model = set_parameter_value(model, parameter_names, parameter_values)

    outfun = sol -> hcat(sol[i_variable, :])
    model = set_output(model, outfun)

    if jet_lag == "double day"
        events = create_events(
            [(:LD, 200, T/2, T/2), (:LD, 1, T, 0.5T), (:LD, 21, T/2, T/2)])
    elseif jet_lag == "double night"
        events = create_events(
            [(:LD, 200, T/2, T/2), (:LD, 1, 0.5T, T), (:LD, 21, T/2, T/2)])
    else
        throw("Unknown jet lag type")
    end

    tend = events[end] + T/2
    model = set_timespan(model, (0.0, tend))
    model = set_input(model, events)
    solution_arr = stoosc.PopulationSolution[]

    solution = simulate_population(model, trajectories, show_progress=true,
        save_trajectories=false)
    push!(solution_arr, solution)

    params["solution"] = solution

end

# Peak analysis ==============================================================
function analyze_peaks!(params)

    solution = params["solution"]
    T = 1.0
    show_plots = params["show_plots"]
    # saveplots = params["saveplots"]
    filename = params["filename"]
    period_offset = params["period_offset"]

    pr = findpeaks(solution.mean[:, 1], solution.time)
    peak_heights = peakheights(pr)
    peak_prominences = peakprominences(pr)
    peak_locations = peaklocations(pr)

    events = solution.events

    results = Dict(
        "pre_locs" => fill(NaN, 20),
        "pre_pks" => fill(NaN, 20),
        "pre_phases" => fill(NaN, 20),
        "post_locs" => fill(NaN, 20),
        "post_pks" => fill(NaN, 20),
        "post_phases" => fill(NaN, 20)
    )

    pre_counter = 0
    post_counter = 0

    for ievent = 2:size(events, 1)-1

        period_start = events[ievent, 1]
        period_end = events[ievent+1, 1]
        idx = (period_start + period_offset) .< peak_locations .<= (period_end + period_offset)
        if any(idx)

            idx_idx = argmax(peak_prominences[idx])
            peak_location = peak_locations[idx][idx_idx]
            peak_height = peak_heights[idx][idx_idx]  # peak_heights
            peak_phase = peak_location - period_start

            # if ievent > 30 && ievent <= 50
            if ievent > 180 && ievent <= 200
                pre_counter += 1
                results["pre_locs"][pre_counter] = peak_location
                results["pre_pks"][pre_counter] = peak_height
                results["pre_phases"][pre_counter] = peak_phase / T
            end

            # if ievent > 51 && ievent <= 71
            if ievent > 201 && ievent <= 221
                post_counter += 1
                results["post_locs"][post_counter] = peak_location
                results["post_pks"][post_counter] = peak_height
                results["post_phases"][post_counter] = peak_phase / T
            end

        end

    end

    if show_plots #|| saveplots
        fig, ax_arr = subplots(2, 1, figsize=(8, 2))

        ax = ax_arr[1]
        x = solution.mean[:, 1]
        t = solution.time
        idx = events[end]/2 .< t .< events[end]
        ax.plot(t, x, color="black")
        plot_events(solution.events, ax=ax)
        ax.plot(results["pre_locs"], results["pre_pks"], "o", color="blue")
        ax.plot(results["post_locs"], results["post_pks"], "o", color="red")
        ax.set_xlim(events[end]/2, events[end])
        ax.set_ylim(minimum(x[idx]), maximum(x[idx]))
        ax.set_title(filename[1:end-4])
        ax.set_xlabel("Time (au)")
        ax.set_ylabel("Conc. (au)")
        fig.tight_layout(pad=0.1)

        ax = ax_arr[2]
        ax.plot(mean(results["pre_phases"]) .- results["post_phases"])

        # if saveplots
        #     fullfilename = joinpath("hpc05", filename[1:end-4] * ".svg")
        #     savefigure(fig, fullfilename)
        # end
    end

    params["peak_analysis"] = results

end

# Save the peak analysis =====================================================
function save_peak_analysis(params)

    peak_analysis = params["peak_analysis"]
    filename = params["filename"]

    df = DataFrame(peak_analysis)
    save_data(df, filename)

end

params = Dict{String, Any}(
    "show_plots" => true,  # visual control
    "model_name" => "model02",  # model01 or model02
    "problem_type" => "sde",  # ode or sde
    "i_variable" => 1,  # model variable to use to estimate jet lag
    "jet_lag" => "double day",
    "period_offset" => -0.25,  # window shift to search for peak
    "parameter_names" => ["I", "σ"],  # parameter names
    "parameter_values" => [0.5, 0.1],  # parameter values
    "trajectories" => 1000,  # number of oscillators in population
    "filename" => "test_jet_lag.csv"  # save here the jet lag results
)

perform_simulation!(params)
analyze_peaks!(params)
save_peak_analysis(params)

max_stars_repo_name: vkumpost/stoosc

max_issues_repo_name: vkumpost/stoosc

max_forks_repo_name: vkumpost/stoosc


text:
struct Tree{T}
  root::Node{Void, T}
end

struct KeyedItems
 items::Vector
 idkey
 parentkey
end

struct StructItems{T}
 items::Vector{T}
 idfield::Symbol
 parentfield::Symbol
end

struct Table{K, V}
  data::Associative{K, V}
  getparent::Function
end


text:
#=* ДАНО: Робот находится в произвольной клетке ограниченного прямоугольного поля без внутренних перегородок и маркеров.
    +учитываются внутренние прямоугольные перегородки,которые изолированы друг от друга и от внешней перегородки

    РЕЗУЛЬТАТ: Робот — в исходном положении в центре прямого креста из маркеров, расставленных вплоть до внешней рамки.=#

function cross_but_harder(r::Robot)
for side in (Nord,West,Sud,Ost)
    count=1
    while count!=0
        count=workaround_wall(r,side)
        putmarker!(r)
    end
    while ismarker(r)==true
        workaround_wall(r,inverse(side))
    end
    side=inverse(next(side))
    end
putmarker!(r)
end

function workaround_wall(r::Robot, side::HorizonSide) #функция для обхода внутренних перегородок
num_steps=0
while isborder(r,side)==true && isborder(r,next(side))==false  #уходим от линии маркеров чтобы обойти перегородки
    move!(r,next(side))
    num_steps+=1
end
count=0
if isborder(r,side)==false
    move!(r,side)
    count+=1 #считаем шаги при движении по линии
end
if num_steps !=0
    while isborder(r,inverse(next(side)))==true #проходим перегородку на другой линии
        move!(r,side)
        count+=1
    end
    for t in 1:num_steps
    move!(r,inverse(next(side))) #возвращаемся на линию
    end
end
return count #Возвращение значения счётчика(сколько будет маркеров в линии)
end

next(side::HorizonSide)= HorizonSide(mod(Int(side)+1,4))

inverse(side::HorizonSide)=HorizonSide(mod(Int(side)+2,4))

max_stars_repo_name: ilya-design/mirea-progs

max_issues_repo_name: ilya-design/mirea-progs

max_forks_repo_name: ilya-design/mirea-progs


text:
abstract type TARegex end

struct TARegexAtom{T} <: TARegex
    symbol::T
end

struct TARegexRepetition <: TARegex
    content::TARegex
end

struct TARegexUnion <: TARegex
    terms::Set{TARegex}
end
TARegexUnion(r::TARegexUnion) = r
TARegexUnion(r::TARegex) = TARegexUnion(Set([r]))
Base.:+(r1::TARegexUnion, r2::TARegexUnion) = TARegexUnion(r1.terms ∪ r2.terms)
Base.:+(r1::TARegex, r2::TARegex) = TARegexUnion(r1)+TARegexUnion(r2)
#Base.zero(::Type{TARegexUnion}) = TARegexUnion(Set{TARegex}())

struct TARegexConcatenation <: TARegex
    terms::Vector{TARegex}
end
TARegexConcatenation(r::TARegexConcatenation)=r
TARegexConcatenation(r::TARegex) = TARegexConcatenation([r])
Base.zero(::Type{T}) where T <:TARegex = TARegexUnion(Set{TARegex}())
Base.one(::Type{T}) where T <:TARegex = TARegexConcatenation(TARegex[])
Base.zero(::T) where T <:TARegex = zero(T)
Base.one(::T) where T <:TARegex = one(T)
Base.iszero(x::TARegexUnion) = isempty(x.terms)
Base.iszero(x::TARegexConcatenation) = length(x.terms)==1 && iszero(first(x.terms))
Base.iszero(x::TARegexRepetition) = iszero(x.content)
Base.iszero(x::TARegex) = false

Base.:*(r1::TARegexConcatenation, r2::TARegexConcatenation) = TARegexConcatenation([r1.terms ; r2.terms])
Base.:*(r1::TARegexUnion, r2::TARegexUnion) = TARegexUnion(Set([t1*t2 for t1 in r1.terms for t2 in r2.terms]))
Base.:*(r1::TARegex, r2::TARegexUnion) = TARegexUnion(Set(r1 .* r2.terms))
Base.:*(r1::TARegexUnion, r2::TARegex) = TARegexUnion(Set(r1.terms .* r2))
Base.:*(r1::TARegex, r2::TARegex) = TARegexConcatenation(r1)*TARegexConcatenation(r2)

Base.hash(x::TARegexConcatenation) = hash(x.terms)
Base.hash(x::TARegexUnion) = hash(x.terms)
Base.hash(x::TARegexRepetition) = hash(x.content)
Base.hash(x::TARegexAtom) = hash(x.symbol)
Base.:(==)(x::TARegex, y::TARegex) = hash(x)==hash(y)

Base.broadcastable(x::TARegex) = Ref(x)
Base.show(io::IO, ::MIME"text/plain", x::TARegexAtom) = print(io, x.symbol)
Base.show(io::IO, ::MIME"text/plain", x::TARegexRepetition) = (s=repr("text/plain", x.content); print(io, "($(s))*"))
Base.show(io::IO, ::MIME"text/plain", x::TARegexUnion) = print(io, join(repr.(Ref("text/plain"),x.terms), "|"))
Base.show(io::IO, ::MIME"text/plain", x::TARegexConcatenation) = print(io, join(repr.(Ref("text/plain"),x.terms), "→"))

Base.promote_rule(::Type{T1},::Type{T2}) where {T1<:Union{TARegexAtom,TARegexConcatenation,TARegexRepetition,TARegexUnion},T2<:Union{TARegexAtom,TARegexConcatenation,TARegexRepetition,TARegexUnion}} = T1==T2 ? T1 : TARegex

"""
Brzozowski's method
"""
function language(ts::TTS{State,T}; forbid_messages=(_)->false, ignore_messages=(m)->m.direction==MSG_SILENT, final_states=ts.states, initial_state=ts.states[1]) where {State,T}
    X = zeros(TARegex,length(ts.states))
    M = zeros(TARegex, length(ts.states), length(ts.states))

    for state in final_states
        id = findfirst(==(state), ts.states)
        @assert !isnothing(id) "Final state $(state) not in list of states!"
        X[id] = one(TARegex)
    end

    lookup(s) = findfirst(==(s),ts.states)

    for (source,(message,target)) in ts.transitions
        M[lookup(source), lookup(target)] += if forbid_messages(message)
                zero(TARegex)
            elseif ignore_messages(message)
                one(TARegex)
            else
                TARegexAtom(message)
            end
    end

    initial_id = findfirst(==(initial_state), ts.states)
    @assert !isnothing(initial_id) "Initial state $(initial_state) not in state list."

    # make sure initial state is at position 1
    permutation = circshift(collect(1:length(ts.states)),1-initial_id)
    X = X[permutation]
    M = M[permutation,permutation]

    for n in reverse(eachindex(ts.states))
        if !iszero(M[n,n])
            X[n] = TARegexRepetition(M[n,n])*X[n]
            M[n,1:n-1] .= TARegexRepetition(M[n,n]) .* M[n,1:n-1]
        end
        X[1:n-1] .+= M[1:n-1,n] .* X[n]
        M[1:n-1,1:n-1] .+= M[1:n-1,n].*reshape(M[n,1:n-1],(1,:))
    end
    return X[1]
end


text:
"""
The convolution of a one galaxy component with one PSF component.
It also contains the derivatives of sigma with respect to the shape parameters.
It does not contain the derivatives with respect to other parameters
(pos and gal_fracdev) because they have easy expressions in terms of other known
quantities.

Args:
 - gal_fracdev_dir: "Theta direction": this is 1 or -1, depending on whether
     increasing gal_fracdev increases the weight of this GalaxyCacheComponent
     (1) or decreases it (-1).
 - gal_fracdev_i: The weight given to this type of galaxy for this celestial object.
     This is either gal_fracdev or (1 - gal_fracdev).
 - gc: The galaxy component to be convolved
 - pc: The psf component to be convolved
 - pos: The location of the celestial object in pixel coordinates as a 2x1 vector
 - gal_ab: The ratio of the galaxy minor axis to major axis (0 < gal_ab <= 1)
 - gal_scale: The scale of the galaxy major axis

Attributes:
 - gal_fracdev_dir: Same as input
 - gal_fracdev_i: Same as input
 - bmc: A BvnComponent with the convolution.
 - dSigma: A 3x3 matrix containing the derivates of
     [Sigma11, Sigma12, Sigma22] (in the rows) with respect to
     [gal_ab, gal_angle, gal_scale] (in the columns)
"""
struct GalaxyCacheComponent{T<:Number}
    gal_fracdev_dir::Float64
    gal_fracdev_i::T
    bmc::BvnComponent{T}
    sig_sf::GalaxySigmaDerivs{T}
    # [Sigma11, Sigma12, Sigma22] x [gal_ab, gal_angle, gal_scale]
end

function GalaxyCacheComponent(
        gal_fracdev_dir::Float64,
        gal_fracdev_i::T,
        gc::GalaxyComponent,
        pc::PsfComponent,
        pos::Vector{T},
        gal_ab::T,
        gal_angle::T,
        gal_scale::T,
        calculate_gradient::Bool,
        calculate_hessian::Bool) where {T<:Number}

    XiXi = get_bvn_cov(gal_ab, gal_angle, gal_scale)
    mean_s = @SVector T[pc.xiBar[1] + pos[1], pc.xiBar[2] + pos[2]]
    var_s = pc.tauBar + gc.nuBar * XiXi
    weight = pc.alphaBar * gc.etaBar  # excludes gal_fracdev

    # d siginv / dsigma is only necessary for the Hessian.
    bmc = BvnComponent(mean_s, var_s, weight, calculate_gradient && calculate_hessian)

    if calculate_gradient
        sig_sf = GalaxySigmaDerivs(gal_angle, gal_ab, gal_scale, XiXi,
                                   gc.nuBar, calculate_hessian)
    else
        sig_sf = GalaxySigmaDerivs(T)
    end

    GalaxyCacheComponent(gal_fracdev_dir, gal_fracdev_i, bmc, sig_sf)
end

struct BvnBundle{T<:Real}
    bvn_derivs::BivariateNormalDerivatives{T}
    star_mcs::Matrix{BvnComponent{T}}
    gal_mcs::Array{GalaxyCacheComponent{T},4}
    function (::Type{BvnBundle{T}}){T}(psf_K::Int, S::Int)
        return new{T}(BivariateNormalDerivatives{T}(),
                      Matrix{BvnComponent{T}}(psf_K, S),
                      Array{GalaxyCacheComponent{T}}(psf_K, 8, 2, S))
    end
end

function zero!(bvn_bundle::BvnBundle)
    BivariateNormals.zero!(bvn_bundle.bvn_derivs)
    return bvn_bundle
end

"""
Convolve the current locations and galaxy shapes with the PSF.  If
calculate_gradient is true, also calculate derivatives and hessians for
active sources.

Args:
 - S (formerly from ElboArgs)
 - patches (formerly from ElboArgs)
 - vp: (formerly from ElboArgs)
 - active_sources (formerly from ElboArgs)
 - psf_K: Number of psf components (psf from patches object)
 - n: the image id (not the band)
 - calculate_gradient: Whether to calculate derivatives for active sources.
 - calculate_hessian

Returns:
 - star_mcs: An array of BvnComponents with indices
    - PSF component
    - Source (index within active_sources)
 - gal_mcs: An array of BvnComponents with indices
    - PSF component
    - Galaxy component
    - Galaxy type
    - Source (index within active_sources)
  Hessians are only populated for s in ea.active_sources.
"""
function load_bvn_mixtures!(
                    #outputs
                    star_mcs::Matrix{BvnComponent{T}},
                    gal_mcs::Array{GalaxyCacheComponent{T},4},
                    #inputs
                    S::Int64,
                    patches::Matrix{SkyPatch},
                    source_params::Vector{Vector{T}},
                    active_sources::Vector{Int},
                    psf_K::Int64,
                    n::Int,
                    calculate_gradient::Bool=true,
                    calculate_hessian::Bool=true) where {T<:Number}
    @assert size(star_mcs, 1) == psf_K
    @assert size(star_mcs, 2) == S
    # TODO: do not keep any derviative information if the sources are not in
    # active_sources.

    for s in 1:S
        psf = patches[s, n].psf
        sp  = source_params[s]

        # TODO: it's a lucky coincidence that lidx.pos = ids.pos.
        # That's why this works when called from both log_prob.jl with `sp`
        # and elbo_objective.jl with `vp`.
        # We need a safer way to let both methods call this method.
        world_loc = sp[lidx.pos]
        m_pos = Model.linear_world_to_pix(patches[s, n].wcs_jacobian,
                                          patches[s, n].center,
                                          patches[s, n].pixel_center, world_loc)

        # Convolve the star locations with the PSF.
        for k in 1:psf_K
            pc = psf[k]
            mean_s = @SVector T[pc.xiBar[1] + m_pos[1], pc.xiBar[2] + m_pos[2]]
            star_mcs[k, s] =
              BvnComponent(mean_s, pc.tauBar, pc.alphaBar, false)
        end

        # Convolve the galaxy representations with the PSF.
        for i = 1:2 # i indexes dev vs exp galaxy types.
            gal_fracdev_dir = (i == 1) ? 1. : -1.
            gal_fracdev_i = (i == 1) ? sp[lidx.gal_fracdev] : 1. - sp[lidx.gal_fracdev]

            # Galaxies of type 1 have 8 components, and type 2 have 6 components.
            for j in 1:ifelse(i == 1, 8, 6)
                for k = 1:psf_K
                    gal_mcs[k, j, i, s] = GalaxyCacheComponent(
                        gal_fracdev_dir, gal_fracdev_i, galaxy_prototypes[i][j], psf[k],
                        m_pos,
                        sp[lidx.gal_ab], sp[lidx.gal_angle], sp[lidx.gal_scale],
                        calculate_gradient && (s in active_sources),
                        calculate_hessian)
                end
            end
        end
    end

    star_mcs, gal_mcs
end

function load_bvn_mixtures(
        S::Int64,
        patches::Matrix{SkyPatch},
        source_params::Vector{Vector{T}},
        active_sources::Vector{Int},
        psf_K::Int64,
        n::Int;
        calculate_gradient::Bool=true,
        calculate_hessian::Bool=true) where {T<:Number}
    star_mcs = Matrix{BvnComponent{T}}(psf_K, S)
    gal_mcs  = Array{GalaxyCacheComponent{T}}(psf_K, 8, 2, S)
    load_bvn_mixtures!(star_mcs, gal_mcs, S, patches, source_params,
                       active_sources, psf_K, n, calculate_gradient,
                       calculate_hessian)
end

"""
Populate fs0m and fs1m for source s in the a given pixel.

Non-standard args:
    - x: The pixel location in the image
"""
function populate_gal_fsm!(
        bvn_derivs::BivariateNormalDerivatives{T},
        fs1m::SensitiveFloat{T},
        s::Int,
        x::SVector{2,Float64},
        is_active_source::Bool,
        wcs_jacobian::Matrix{Float64},
        gal_mcs::Array{GalaxyCacheComponent{T}, 4}) where {T<:Number}
    SensitiveFloats.zero!(fs1m)
    for i = 1:2 # Galaxy types
        for j in 1:8 # Galaxy component
            # If i == 2 then there are only six galaxy components.
            if (i == 1) || (j <= 6)
                for k = 1:size(gal_mcs, 1) # PSF component
                    accum_galaxy_pos!(
                        bvn_derivs, fs1m,
                        gal_mcs[k, j, i, s], x, wcs_jacobian,
                        is_active_source)
                end
            end
        end
    end
end

"""
Populate fs0m and fs1m for source s in the a given pixel.

Non-standard args:
    - x: The pixel location in the image
"""
function populate_fsm!{T <: Number}(
                    bvn_derivs::BivariateNormalDerivatives{T},
                    fs0m::SensitiveFloat{T},
                    fs1m::SensitiveFloat{T},
                    s::Int,
                    x::SVector{2,Float64},
                    is_active_source::Bool,
                    wcs_jacobian::Matrix{Float64},
                    gal_mcs::Array{GalaxyCacheComponent{T}, 4},
                    star_mcs::Array{BvnComponent{T}, 2})
    SensitiveFloats.zero!(fs0m)
    for k = 1:size(star_mcs, 1) # PSF component
        accum_star_pos!(
            bvn_derivs, fs0m,
            star_mcs[k, s], x, wcs_jacobian, is_active_source)
    end

    populate_gal_fsm!(bvn_derivs, fs1m,
                      s, x, is_active_source,
                      wcs_jacobian, gal_mcs)
end

"""
Add the contributions of a star's bivariate normal term to the ELBO,
by updating elbo_vars.fs0m in place.

Args:
    - bvn_derivs: (formerly from elbo_vars)
    - fs0m: sensitive floats populated by this method
    - calculate_gradient: the and of is_active_source and formerly elbo_vars.calculate_gradient
    - calculate_hessian: elbo_vars: Elbo intermediate values.
    - s: The index of the current source in 1:S
    - bmc: The component to be added
    - x: An offset for the component in pixel coordinates (e.g. a pixel location)
    - wcs_jacobian: The jacobian of the function pixel = F(world) at this location.
"""
function accum_star_pos!(bvn_derivs::BivariateNormalDerivatives{T},
                         fs0m::SensitiveFloat{T},
                         bmc::BvnComponent{T},
                         x::SVector{2,Float64},
                         wcs_jacobian::Array{Float64, 2},
                         is_active_source::Bool) where {T<:Number}
    eval_bvn_pdf!(bvn_derivs, bmc, x)

    if fs0m.has_gradient && is_active_source
        get_bvn_derivs!(bvn_derivs, bmc, true, false)
    end

    fs0m.v[] += bvn_derivs.f_pre[1]

    if fs0m.has_gradient && is_active_source
        transform_bvn_ux_derivs!(bvn_derivs, wcs_jacobian, fs0m.has_hessian)
        bvn_u_d = bvn_derivs.bvn_u_d
        bvn_uu_h = bvn_derivs.bvn_uu_h

        # Accumulate the derivatives.
        for u_id in 1:2
            fs0m.d[star_ids.pos[u_id]] += bvn_derivs.f_pre[1] * bvn_u_d[u_id]
        end

        if fs0m.has_hessian
            # Hessian terms involving only the location parameters.
            # TODO: redundant term
            for u_id1 in 1:2, u_id2 in 1:2
                fs0m.h[star_ids.pos[u_id1], star_ids.pos[u_id2]] +=
                    bvn_derivs.f_pre[1] * (bvn_uu_h[u_id1, u_id2] +
                    bvn_u_d[u_id1] * bvn_u_d[u_id2])
            end
        end
    end
end

"""
Add the contributions of a galaxy component term to the ELBO by
updating fs1m in place.
"""
function accum_galaxy_pos!(bvn_derivs::BivariateNormalDerivatives{T},
                           fs1m::SensitiveFloat{T},
                           gcc::GalaxyCacheComponent{T},
                           x::SVector{2,Float64},
                           wcs_jacobian::Array{Float64, 2},
                           is_active_source::Bool) where {T<:Number}
    eval_bvn_pdf!(bvn_derivs, gcc.bmc, x)
    f = bvn_derivs.f_pre[1] * gcc.gal_fracdev_i
    fs1m.v[] += f

    if fs1m.has_gradient && is_active_source
        get_bvn_derivs!(bvn_derivs, gcc.bmc,
                        fs1m.has_gradient, fs1m.has_hessian)
        transform_bvn_derivs!(
            bvn_derivs, gcc.sig_sf, wcs_jacobian, fs1m.has_hessian)

        @aliasscope begin
            bvn_u_d = Const(bvn_derivs.bvn_u_d)
            bvn_s_d = Const(bvn_derivs.bvn_s_d)
            bvn_derivs_f_pre = Const(bvn_derivs.f_pre)

            # Accumulate the derivatives.
            @inbounds for u_id in 1:2
                fs1m.d[gal_ids.pos[u_id]] += f * bvn_u_d[u_id]
            end

            @inbounds for gal_id in 1:length(gal_shape_ids)
                fs1m.d[gal_shape_alignment[gal_id]] += f * bvn_s_d[gal_id]
            end

            # The gal_fracdev derivative. gal_fracdev just scales the entire component.
            # The direction is positive or negative depending on whether this
            # is an exp or dev component.
            @inbounds fs1m.d[gal_ids.gal_fracdev] += gcc.gal_fracdev_dir * bvn_derivs_f_pre[1]

            if fs1m.has_hessian
                # The Hessians:
                bvn_uu_h = Const(bvn_derivs.bvn_uu_h)
                bvn_ss_h = Const(bvn_derivs.bvn_ss_h)
                bvn_us_h = Const(bvn_derivs.bvn_us_h)
                gal_ids_u = Const(gal_ids.pos)

                # Hessian terms involving only the shape parameters.
                @inbounds for shape_id1 in 1:length(gal_shape_ids)
                    @inbounds for shape_id2 in 1:length(gal_shape_ids)
                        s1 = gal_shape_alignment[shape_id1]
                        s2 = gal_shape_alignment[shape_id2]
                        fs1m.h[s1, s2] +=
                            f * (bvn_ss_h[shape_id1, shape_id2] +
                                     bvn_s_d[shape_id1] * bvn_s_d[shape_id2])
                    end
                end

                # Hessian terms involving only the location parameters.
                @inbounds for u_id1 in 1:2
                    @inbounds for u_id2 in 1:2
                        u1 = gal_ids_u[u_id1]
                        u2 = gal_ids_u[u_id2]
                        fs1m.h[u1, u2] +=
                            f * (bvn_uu_h[u_id1, u_id2] + bvn_u_d[u_id1] * bvn_u_d[u_id2])
                    end
                end

                # Hessian terms involving both the shape and location parameters.
                for u_id in 1:2
                  @inbounds for shape_id in 1:length(gal_shape_ids)
                    ui = gal_ids_u[u_id]
                    si = gal_shape_alignment[shape_id]
                    fs1m.h[ui, si] +=
                        f * (bvn_us_h[u_id, shape_id] + bvn_u_d[u_id] * bvn_s_d[shape_id])
                    fs1m.h[si, ui] = fs1m.h[ui, si]
                  end
                end

                # Do the gal_fracdev hessian terms.
                devi = gal_ids.gal_fracdev
                @inbounds for u_id in 1:2
                    ui = gal_ids.pos[u_id]
                    fs1m.h[ui, devi] +=
                        bvn_derivs_f_pre[1] * gcc.gal_fracdev_dir * bvn_u_d[u_id]
                    fs1m.h[devi, ui] = fs1m.h[ui, devi]
                end
                @inbounds for shape_id in 1:length(gal_shape_ids)
                    si = gal_shape_alignment[shape_id]
                    fs1m.h[si, devi] +=
                        bvn_derivs_f_pre[1] * gcc.gal_fracdev_dir * bvn_s_d[shape_id]
                    fs1m.h[devi, si] = fs1m.h[si, devi]
                end
            end # if calculate hessian
        end
    end # if is_active_source
end


text:
struct KnapsackFeaturization <: SeaPearl.AbstractFeaturization end

numberOfFeatures =10
"""
    SeaPearl.featurize(sr::SeaPearl.DefaultStateRepresentation{KnapsackFeaturization})

The default featurise function from the SeaPearl Package is overwritten to fit the knapsack problem topology
Here, a node feature encodes the following informations :
[
    1 :   the node represents a VARIABLE
    2 :    |__ the variable type is "OBJECTIVE FUNCTION"
    3 :    |__ the variable type is "IntVarViewOpposite"
    4 :    |__ the variable type is "IntVarViewMul"
    5 :          |__ encodes the multiplicative factor a
    6 :   the node represents a CONSTRAINT
    7 :    |__ the constraint type is "SumToZero"
    8 :    |__ the constraint type is "LessOrEqualConstant"
    9 :   the node represents a VALUE
    10 :   |__ the variable value / 10
]
"""
function SeaPearl.featurize(sr::SeaPearl.DefaultStateRepresentation{KnapsackFeaturization})
    g = sr.cplayergraph
    features = zeros(Float32, numberOfFeatures, nv(g))
    for i in 1:nv(g)
        cp_vertex = SeaPearl.cpVertexFromIndex(g, i)
        if isa(cp_vertex, SeaPearl.VariableVertex)
            variable = cp_vertex.variable
            features[1,i] = 1.
            if g.cpmodel.objective == variable
                features[2,i] = 1.
            end

            if isa(variable, SeaPearl.IntVarViewOpposite)
                features[3, i] = 1.
            end
            if isa(variable, SeaPearl.IntVarViewMul)
                features[4, i] = 1.
                features[5, i] = variable.a
            end
        end
        if isa(cp_vertex, SeaPearl.ConstraintVertex)
            features[6, i] = 1.
            constraint = cp_vertex.constraint
            if isa(constraint, SeaPearl.SumToZero)
                features[7, i] = 1.
            end
            if isa(constraint, SeaPearl.LessOrEqualConstant)
                features[8, i] = 1.
            end
        end
        if isa(cp_vertex, SeaPearl.ValueVertex)
            features[9, i] = 1.
            value = cp_vertex.value
            features[10, i] = value/10 #max_weight
        end
    end
    features
end

function SeaPearl.feature_length(::Type{SeaPearl.DefaultStateRepresentation{KnapsackFeaturization, TS}}) where TS
    numberOfFeatures
end

max_stars_repo_name: corail-research/SeaPearlZoo

max_issues_repo_name: corail-research/SeaPearlZoo

max_forks_repo_name: corail-research/SeaPearlZoo


text:
module main

using conv_code
using encoder
using decoder
using channels

NN = [3.0, 3.0*10^(-0.1), 3.0*10^(-0.2), 3.0*10^(-0.3), 3.0*10^(-0.4), 3.0*10^(-0.5), 3.0*10^(-0.6), 3.0*10^(-0.7), 3.0*10^(-0.8), 3.0*10^(-0.9), 3.0*10^(-1.0)]
# Mapeamento p = Q(Sqrt(2 Eb / N0))
PP = [0.207108, 0.179801, 0.151996, 0.124387, 0.0978224, 0.0732565, 0.0516433, 0.0337817, 0.0201361, 0.0106902, 0.00491164]
code1 = ConvolutionalCode(3, [[1, 3, 4], [1, 2, 4], [1, 2, 3, 4]])
code2 = ConvolutionalCode(4, [[1, 3, 5], [1, 2, 4, 5], [1, 2, 3, 4, 5]])
code3 = ConvolutionalCode(6, [[1, 4, 5, 6, 7], [1, 3, 5, 6 , 7], [1, 2, 4, 5, 7]])

error1 = Array{Float64,1}(undef, length(NN))
error2 = Array{Float64,1}(undef, length(NN))
error3 = Array{Float64,1}(undef, length(NN))

info_bits = rand([0,1], 1000000)
encoded_bits1 = encode(code1, info_bits)
encoded_bits2 = encode(code2, info_bits)
encoded_bits3 = encode(code3, info_bits)

# for indice=1:length(PP)
# 	p = PP[indice]

# 	print("code1")
# 	decoded_bits1 = decode(p, code1, convert(Array{Array{Float64, 1}, 1}, BSC(p, encoded_bits1)))
# 	print("code2")
# 	decoded_bits2 = decode(p, code2, convert(Array{Array{Float64, 1}, 1}, BSC(p, encoded_bits2)))
# 	print("code3")
# 	decoded_bits3 = decode(p, code3, convert(Array{Array{Float64, 1}, 1}, BSC(p, encoded_bits3)))

for indice=1:length(NN)
	p = 1.0 # qualquer. Não usado pelo euclidean_cost
	N0 = NN[indice]

	print("code1")
	decoded_bits1 = decode(p, code1, AWGN(N0, convert(Array{Array{Float64, 1}, 1}, BPSK.(encoded_bits1))))
	print("code2")
	decoded_bits2 = decode(p, code2, AWGN(N0, convert(Array{Array{Float64, 1}, 1}, BPSK.(encoded_bits2))))
	print("code3")
	decoded_bits3 = decode(p, code3, AWGN(N0, convert(Array{Array{Float64, 1}, 1}, BPSK.(encoded_bits3))))

	error1[indice] = sum(abs.(decoded_bits1 - info_bits))
	error2[indice] = sum(abs.(decoded_bits2 - info_bits))
	error3[indice] = sum(abs.(decoded_bits3 - info_bits))
end

open("/Users/Eduardo/Documents/GitHub/ele32-convolutional-codes/src/error1.txt", "w") do io
	for i=1:length(error1)
		println(io, error1[i])
	end
end

open("/Users/Eduardo/Documents/GitHub/ele32-convolutional-codes/src/error2.txt", "w") do io
	for i=1:length(error2)
		println(io, error2[i])
	end
end

open("/Users/Eduardo/Documents/GitHub/ele32-convolutional-codes/src/error3.txt", "w") do io
	for i=1:length(error3)
		println(io, error3[i])
	end
end

end


text:
# NOTE: assemble weakly-singular kernels using quadgk. Should be slow, but this is
# useful to verify that integrals converge as they should.

function assemble_gk(iop;compress=Matrix)
    X,Y       = target_surface(iop), source_surface(iop)
    @timeit_debug "assemble dense part" begin
        out        = compress(iop)
    end
    @timeit_debug "compute near interaction list" begin
        dict_near = near_interaction_list(dofs(X),Y;atol=0.1)
    end
    @timeit_debug "compute singular correction" begin
        correction = singular_weights_gk(iop,dict_near)
    end
    axpy!(1,correction,out) # out <-- out + correction
end

function singular_weights_gk(iop::IntegralOperator,dict_near)
    X,Y       = target_surface(iop), source_surface(iop)
    T         = eltype(iop)
    Is    = Int[]
    Js    = Int[]
    Vs    = T[]
    # loop over all integration elements by types
    for E in keys(Y)
        iter      = ElementIterator(Y,E)
        qreg      = Y.etype2qrule[E]
        lag_basis = lagrange_basis(qnodes(qreg))
        @timeit_debug "singular weights" begin
            _singular_weights_gk!(Is,Js,Vs,iop,iter,dict_near,lag_basis,qreg)
        end
    end
    Sp = sparse(Is,Js,Vs,size(iop)...)
    return Sp
end

function _singular_weights_gk!(Is,Js,Vs,iop,iter,dict_near,lag_basis,qreg)
    yi = qnodes(qreg)
    K = kernel(iop)
    X = target_surface(iop)
    Y = source_surface(iop)
    E = eltype(iter)
    list_near = dict_near[E]
    # Over the lines below we loop over all element, find which target nodes
    # need to be regularized, and compute the regularized weights on the source
    # points for that target point.
    for (n,el) in enumerate(iter)               # loop over elements
        jglob = Y.elt2dof[E][:,n]
        for (i,jloc) in list_near[n]            # loop over near targets
            ys = yi[jloc]
            xdof   = dofs(X)[i]
            for (m,l) in enumerate(lag_basis)   # loop over lagrange basis
                val,_ = quadgk(0,ys[1],1;atol=1e-14) do ŷ
                    y    = el(ŷ)
                    jac  = jacobian(el,ŷ)
                    μ    = integration_measure(jac)
                    ydof = NystromDOF(y,-1.0,jac,-1,-1)
                    K(xdof,ydof)*μ*l(ŷ)
                end
                # push data to sparse matrix
                push!(Is,i)
                j = jglob[m]
                push!(Js,j)
                push!(Vs,val-iop[i,j])
            end
        end
    end
    return Is,Js,Vs
end

max_stars_repo_name: WaveProp/Nystrom

max_issues_repo_name: WaveProp/Nystrom

max_forks_repo_name: WaveProp/Nystrom


text:
using FaceDetection, Serialization # Serialization is so that you can save your results

num_classifiers = 10 # this is the number of Haar-like features you want to select

# provide paths to directories of training images
pos_training_path = "./data/trainset/faces/" # positive images are, for example, faces
neg_training_path = "./data/trainset/non-faces/" # negative images are, for example, non-faces.  However, the Viola-Jones algorithm is for object detection, not just for face detection

max_feature_width, max_feature_height, min_feature_height, min_feature_width = ( 4, 4, 1, 1) # or use the function to select reasonable sized feature parameters given your maximum image size (see below)
determine_feature_size(pos_training_path, neg_training_path)

# learn the features from
classifiers = learn(pos_training_path, neg_training_path, num_classifiers, min_feature_height, max_feature_height, min_feature_width, max_feature_width)

# provide paths to directories of testing images
pos_testing_path = "./data/testset/faces/"
neg_testing_path = "./data/testset/non-faces/"

# obtain results
num_faces, num_non_faces = length(filtered_ls(pos_testing_path)), length(filtered_ls(neg_testing_path));
correct_faces = sum(ensemble_vote_all(pos_testing_path, classifiers));
correct_non_faces = num_non_faces - sum(ensemble_vote_all(neg_testing_path, classifiers));
correct_faces_percent = (correct_faces / num_faces) * 100;
correct_non_faces_percent = (correct_non_faces / num_non_faces) * 100;

# print results
println("$(string(correct_faces, "/", num_faces)) ($(correct_faces_percent) %) of positive images were correctly identified.")
println("$(string(correct_non_faces, "/", num_non_faces)) ($(correct_non_faces_percent) %) of positive images were correctly identified.")

max_stars_repo_name: ashwani-rathee/Sigil

max_issues_repo_name: ashwani-rathee/Sigil

max_forks_repo_name: ashwani-rathee/Sigil


text:
export TrivialMeasure

struct TrivialMeasure <: PrimitiveMeasure end

sampletype(::TrivialMeasure) = Nothing

Pretty.quoteof(::TrivialMeasure) = :(TrivialMeasure())


text:
module ProcessMining

    import EzXML
    import DataFrames
    using AutoHashEquals
    using Pipe

    const DEFAULT_NAMESPACE = "http://www.xes-standard.org/"

    export Event
    export Trace
    export EventLog
    export read_xes
    export info
    export length

    include("types.jl")
    include("petrinets.jl")
    include("io.jl")
    include("utilities.jl")
    include("algorithms.jl")

end


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

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

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
- `identity_pool_id`: 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.

"""
bulk_publish(IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/bulkpublish"; aws_config=aws_config)
bulk_publish(IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/bulkpublish", params; aws_config=aws_config)

"""
    delete_dataset(dataset_name, identity_id, identity_pool_id)
    delete_dataset(dataset_name, identity_id, identity_pool_id, params::Dict{String,<:Any})

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
- `dataset_name`: A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9,
  '_' (underscore), '-' (dash), and '.' (dot).
- `identity_id`: 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.
- `identity_pool_id`: 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.

"""
delete_dataset(DatasetName, IdentityId, IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("DELETE", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)"; aws_config=aws_config)
delete_dataset(DatasetName, IdentityId, IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("DELETE", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)", params; aws_config=aws_config)

"""
    describe_dataset(dataset_name, identity_id, identity_pool_id)
    describe_dataset(dataset_name, identity_id, identity_pool_id, params::Dict{String,<:Any})

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
- `dataset_name`: A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9,
  '_' (underscore), '-' (dash), and '.' (dot).
- `identity_id`: 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.
- `identity_pool_id`: 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.

"""
describe_dataset(DatasetName, IdentityId, IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)"; aws_config=aws_config)
describe_dataset(DatasetName, IdentityId, IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)", params; aws_config=aws_config)

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

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
- `identity_pool_id`: 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.

"""
describe_identity_pool_usage(IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)"; aws_config=aws_config)
describe_identity_pool_usage(IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)", params; aws_config=aws_config)

"""
    describe_identity_usage(identity_id, identity_pool_id)
    describe_identity_usage(identity_id, identity_pool_id, params::Dict{String,<:Any})

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
- `identity_id`: 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.
- `identity_pool_id`: 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.

"""
describe_identity_usage(IdentityId, IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)"; aws_config=aws_config)
describe_identity_usage(IdentityId, IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)", params; aws_config=aws_config)

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

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
- `identity_pool_id`: 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.

"""
get_bulk_publish_details(IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/getBulkPublishDetails"; aws_config=aws_config)
get_bulk_publish_details(IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/getBulkPublishDetails", params; aws_config=aws_config)

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

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
- `identity_pool_id`: The Cognito Identity Pool ID for the request

"""
get_cognito_events(IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/events"; aws_config=aws_config)
get_cognito_events(IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/events", params; aws_config=aws_config)

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

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
- `identity_pool_id`: 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.

"""
get_identity_pool_configuration(IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/configuration"; aws_config=aws_config)
get_identity_pool_configuration(IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/configuration", params; aws_config=aws_config)

"""
    list_datasets(identity_id, identity_pool_id)
    list_datasets(identity_id, identity_pool_id, params::Dict{String,<:Any})

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
- `identity_id`: 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.
- `identity_pool_id`: 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.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of results to be returned.
- `"nextToken"`: A pagination token for obtaining the next page of results.
"""
list_datasets(IdentityId, IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets"; aws_config=aws_config)
list_datasets(IdentityId, IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets", params; aws_config=aws_config)

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

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.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of results to be returned.
- `"nextToken"`: A pagination token for obtaining the next page of results.
"""
list_identity_pool_usage(; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools"; aws_config=aws_config)
list_identity_pool_usage(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools", params; aws_config=aws_config)

"""
    list_records(dataset_name, identity_id, identity_pool_id)
    list_records(dataset_name, identity_id, identity_pool_id, params::Dict{String,<:Any})

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
- `dataset_name`: A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9,
  '_' (underscore), '-' (dash), and '.' (dot).
- `identity_id`: 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.
- `identity_pool_id`: 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.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"lastSyncCount"`: The last server sync count for this record.
- `"maxResults"`: The maximum number of results to be returned.
- `"nextToken"`: A pagination token for obtaining the next page of results.
- `"syncSessionToken"`: A token containing a session ID, identity ID, and expiration.
"""
list_records(DatasetName, IdentityId, IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)/records"; aws_config=aws_config)
list_records(DatasetName, IdentityId, IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("GET", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)/records", params; aws_config=aws_config)

"""
    register_device(identity_id, identity_pool_id, platform, token)
    register_device(identity_id, identity_pool_id, platform, token, params::Dict{String,<:Any})

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
- `identity_id`: The unique ID for this identity.
- `identity_pool_id`: 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.
- `platform`: The SNS platform type (e.g. GCM, SDM, APNS, APNS_SANDBOX).
- `token`: The push token.

"""
register_device(IdentityId, IdentityPoolId, Platform, Token; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/identity/$(IdentityId)/device", Dict{String, Any}("Platform"=>Platform, "Token"=>Token); aws_config=aws_config)
register_device(IdentityId, IdentityPoolId, Platform, Token, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/identity/$(IdentityId)/device", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Platform"=>Platform, "Token"=>Token), params)); aws_config=aws_config)

"""
    set_cognito_events(events, identity_pool_id)
    set_cognito_events(events, identity_pool_id, params::Dict{String,<:Any})

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
- `events`: The events to configure
- `identity_pool_id`: The Cognito Identity Pool to use when configuring Cognito Events

"""
set_cognito_events(Events, IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/events", Dict{String, Any}("Events"=>Events); aws_config=aws_config)
set_cognito_events(Events, IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/events", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Events"=>Events), params)); aws_config=aws_config)

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

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
- `identity_pool_id`: 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.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"CognitoStreams"`: Options to apply to this identity pool for Amazon Cognito streams.
- `"PushSync"`: Options to apply to this identity pool for push synchronization.
"""
set_identity_pool_configuration(IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/configuration"; aws_config=aws_config)
set_identity_pool_configuration(IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/configuration", params; aws_config=aws_config)

"""
    subscribe_to_dataset(dataset_name, device_id, identity_id, identity_pool_id)
    subscribe_to_dataset(dataset_name, device_id, identity_id, identity_pool_id, params::Dict{String,<:Any})

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
- `dataset_name`: The name of the dataset to subcribe to.
- `device_id`: The unique ID generated for this device by Cognito.
- `identity_id`: Unique ID for this identity.
- `identity_pool_id`: 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.

"""
subscribe_to_dataset(DatasetName, DeviceId, IdentityId, IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)/subscriptions/$(DeviceId)"; aws_config=aws_config)
subscribe_to_dataset(DatasetName, DeviceId, IdentityId, IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)/subscriptions/$(DeviceId)", params; aws_config=aws_config)

"""
    unsubscribe_from_dataset(dataset_name, device_id, identity_id, identity_pool_id)
    unsubscribe_from_dataset(dataset_name, device_id, identity_id, identity_pool_id, params::Dict{String,<:Any})

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
- `dataset_name`: The name of the dataset from which to unsubcribe.
- `device_id`: The unique ID generated for this device by Cognito.
- `identity_id`: Unique ID for this identity.
- `identity_pool_id`: 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.

"""
unsubscribe_from_dataset(DatasetName, DeviceId, IdentityId, IdentityPoolId; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("DELETE", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)/subscriptions/$(DeviceId)"; aws_config=aws_config)
unsubscribe_from_dataset(DatasetName, DeviceId, IdentityId, IdentityPoolId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("DELETE", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)/subscriptions/$(DeviceId)", params; aws_config=aws_config)

"""
    update_records(dataset_name, identity_id, identity_pool_id, sync_session_token)
    update_records(dataset_name, identity_id, identity_pool_id, sync_session_token, params::Dict{String,<:Any})

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
- `dataset_name`: A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9,
  '_' (underscore), '-' (dash), and '.' (dot).
- `identity_id`: 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.
- `identity_pool_id`: 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.
- `sync_session_token`: The SyncSessionToken returned by a previous call to ListRecords for
  this dataset and identity.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DeviceId"`: The unique ID generated for this device by Cognito.
- `"RecordPatches"`: A list of patch operations.
- `"x-amz-Client-Context"`: Intended to supply a device ID that will populate the
  lastModifiedBy field referenced in other methods. The ClientContext field is not yet
  implemented.
"""
update_records(DatasetName, IdentityId, IdentityPoolId, SyncSessionToken; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)", Dict{String, Any}("SyncSessionToken"=>SyncSessionToken); aws_config=aws_config)
update_records(DatasetName, IdentityId, IdentityPoolId, SyncSessionToken, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cognito_sync("POST", "/identitypools/$(IdentityPoolId)/identities/$(IdentityId)/datasets/$(DatasetName)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("SyncSessionToken"=>SyncSessionToken), params)); aws_config=aws_config)