text:
using JuMP, Cbc

airlineModel = Model(Cbc.Optimizer)

@variable(airlineModel, t[1:6] >= 0)

route = [428 80;
         190 120;
         642 75;
         224 100;
         512 60;
         190 110]
prices = route[:,1]
demand = route[:,2]

@objective(airlineModel, Max, sum(t.*prices))

@constraint(airlineModel, t[:].<=demand)
@constraint(airlineModel, sum(t[1:4]) <= 166)
@constraint(airlineModel, sum(t[3:6]) <= 166)

res = JuMP.optimize!(airlineModel)

tickets = JuMP.value.(t)

max_stars_repo_name: valenmgama/optimization-tec

max_issues_repo_name: valenmgama/optimization-tec

max_forks_repo_name: valenmgama/optimization-tec


text:
using Base.Filesystem: rm

@testset "video rendering" begin
    has_ffmpeg = false
    try
        run(`ffmpeg -version`)
        has_ffmpeg = true
    catch e
    end
    if has_ffmpeg
        mktempdir() do tmpdir
            target = joinpath(tmpdir, "output.mp4")
            MeshCat.convert_frames_to_video(
                joinpath(@__DIR__, "data", "frames.tar"),
                target)
            @test isfile(target)
        end
    end
end

ext: jl


text:
# using Revise

using Test

using RoME

@testset "sanity check on Hex example" begin

# graphinit=false, regression since DFG v0.6.0 IIF v0.9.0 -- on tree init, issue IIF#602
fg = generateCanonicalFG_Hexagonal(graphinit=false)

getSolverParams(fg).drawtree = false
getSolverParams(fg).showtree = false
getSolverParams(fg).graphinit = false
getSolverParams(fg).treeinit = true
getSolverParams(fg).downsolve = true
getSolverParams(fg).multiproc = false
getSolverParams(fg).async = false
getSolverParams(fg).useMsgLikelihoods=true
# to disable parent factor sharing
# getSolverParams(fg).devParams[:dontUseParentFactorsInitDown] = ""

# direct solve would be
# getSolverParams(fg).async = true ## MANUAL TEMP ONLY
tree, smt, hist = solveTree!(fg) #, recordcliqs=ls(fg))
tree, smt, hist = solveTree!(fg) #, recordcliqs=ls(fg))

# tree.cliques[3]
# drawTree(tree, show=true)
# smt[3]

@error "Hex init test degraded quality during useMsgLikelihoods refactor, must restore to 55"
@test 40 < sum(-3.0 .< getPoints(getKDE(fg, :x0))[1,:] .< 3.0)
@test 40 < sum(-3.0 .< getPoints(getKDE(fg, :x0))[2,:] .< 3.0)
@test 40 < sum(-0.3 .< getPoints(getKDE(fg, :x0))[3,:] .< 0.3)

@test 40 < sum(7.0 .< getPoints(getKDE(fg, :x1))[1,:] .< 13.0)
@test 40 < sum(-3.0 .< getPoints(getKDE(fg, :x1))[2,:] .< 3.0)
@test 40 < sum(0.7 .< getPoints(getKDE(fg, :x1))[3,:] .< 1.3)

@test 40 < sum(12.0 .< getPoints(getKDE(fg, :x2))[1,:] .< 18.0)
@test 40 < sum(6.0 .< getPoints(getKDE(fg, :x2))[2,:] .< 11.0)
@test 40 < sum(1.8 .< getPoints(getKDE(fg, :x2))[3,:] .< 2.4)

@test 40 < sum(7.0 .< getPoints(getKDE(fg, :x3))[1,:] .< 13.0)
@test 40 < sum(15.0 .< getPoints(getKDE(fg, :x3))[2,:] .< 20.0)
# @test 40 < sum(-0.3 .< getPoints(getKDE(fg, :x3))[3,:] .< 0.3)

@test 40 < sum(-5.0 .< getPoints(getKDE(fg, :x4))[1,:] .< 5.0)
@test 40 < sum(13.0 .< getPoints(getKDE(fg, :x4))[2,:] .< 22.0)
@test 40 < sum(-2.8 .< getPoints(getKDE(fg, :x4))[3,:] .< -1.5)

@test 40 < sum(-8.0 .< getPoints(getKDE(fg, :x5))[1,:] .< -2.0)
@test 40 < sum(6.0 .< getPoints(getKDE(fg, :x5))[2,:] .< 11.0)
@test 40 < sum(-1.3 .< getPoints(getKDE(fg, :x5))[3,:] .< -0.7)

@test 40 < sum(-3.0 .< getPoints(getKDE(fg, :x6))[1,:] .< 3.0)
@test 40 < sum(-3.0 .< getPoints(getKDE(fg, :x6))[2,:] .< 3.0)
@test 40 < sum(-0.3 .< getPoints(getKDE(fg, :x6))[3,:] .< 0.3)

@test 40 < sum(17.0 .< getPoints(getKDE(fg, :l1))[1,:] .< 23.0)
@test 40 < sum(-5.0 .< getPoints(getKDE(fg, :l1))[2,:] .< 5.0)

0
end # testset

#
# #  Do some plotting
# using RoMEPlotting
# #
# Gadfly.set_default_plot_size(35cm,20cm)
# pl = drawPosesLandms(fg, drawhist=true)

## OR manually do clique by clique
#
# # solve by hand, one cliq at a time
# tree = wipeBuildNewTree!(fg)
# # drawTree(tree,show=true)
#
#
# # solve the first cliq
# smt, hist = solveCliq!(fg, tree, :x0, recordcliq=true)
#
# # solve second clq
# smt, hist = solveCliq!(fg, tree, :x2, cliqHistories=hist, recordcliq=true)
# # resetCliqSolve!(fg, tree, :x2)
#
# # solve forth clq
# smt, hist = solveCliq!(fg, tree, :x4, cliqHistories=hist, recordcliq=true)
# # solve forth clq
# smt, hist = solveCliq!(fg, tree, :x6, cliqHistories=hist, recordcliq=true)
# # solve forth clq
# smt, hist = solveCliq!(fg, tree, :x3, cliqHistories=hist, recordcliq=true)


text:
# Fit linear mixed-effects models to each of the three human data sets

function fit_1surp(data, basedev, col, prevcol)
    # Fit to a single set of surprisal estimates by including them in the baseline model

    # Select current and previous-word surprisal values and combine with item numbers in a temporary data frame
    surp_df = [surprisal[[col, prevcol]] surprisal[[:item]]]
    rename!(surp_df, x=>n for (x,n) = zip(names(surp_df)[1:2], [:surp, :surp_prev]))

    # Join data with current surprisal values, compute weighted average surprisal, and normalize suprisals
    data_surp = join(data, surp_df, kind=:left, on=:item, makeunique=true)
    avsurp    = mean(skipmissing(data_surp[:surp]))
    data_surp[:surp]      = zscore(data_surp[:surp])
    data_surp[:surp_prev] = zscore(data_surp[:surp_prev])

    # Fit mixed-effects model (with surprisal factor(s)) to human data.
    # Correlation terms are not included because these mess with the log-likelihoods: They come to
    # diverge from the z-scores, which are more reliable because they are hardly affected by the correlation terms
    if :logRT in names(data)
        model = fit!(LinearMixedModel(@formula(logRT ~ surp + surp_prev + logRT_prev * log_freq * log_freq_prev * nr_char * nr_char_prev * word_pos
                                               + (1|subj_nr) + (0+surp|subj_nr) + (0+surp_prev|subj_nr) + (0+logRT_prev|subj_nr) + (0+log_freq|subj_nr) + (0+log_freq_prev|subj_nr)
                                               + (0+nr_char|subj_nr) + (0+nr_char_prev|subj_nr) + (0+word_pos|subj_nr) + (1|item)), data_surp))
    elseif :logRTfirstpass in names(data)
        model = fit!(LinearMixedModel(@formula(logRTfirstpass ~ surp + surp_prev + log_freq * log_freq_prev * nr_char * nr_char_prev * word_pos * prevfix
                                               + (1|subj_nr) + (0+surp|subj_nr) + (0+surp_prev|subj_nr) + (0+log_freq|subj_nr) + (0+log_freq_prev|subj_nr)
                                               + (0+nr_char|subj_nr) + (0+nr_char_prev|subj_nr) + (0+word_pos|subj_nr) +(0+prevfix|subj_nr) + (1|item) + (0+prevfix|item)), data_surp))
    else
        model = fit!(LinearMixedModel(@formula(N400 ~ surp + baseline + log_freq * nr_char * word_pos
                                               + (1|subj_nr) + (0+surp|subj_nr) + (0+baseline|subj_nr) + (0+log_freq|subj_nr) + (0+nr_char|subj_nr) + (0+word_pos|subj_nr)
                                               + (1|item)), data_surp))
    end

    # Return deviance decrease (chi-squared), coefficient(s), z-score(s), and average surprisal
    if :N400 in names(data)
        chi2       = basedev - deviance(model)
        b_surp     = coeftable(model).cols[1][2]
        z_surp     = coeftable(model).cols[3][2]

        [chi2 b_surp z_surp avsurp]
    else
        chi2       = basedev - deviance(model)
        b_surp     = coeftable(model).cols[1][2]
        z_surp     = coeftable(model).cols[3][2]
        b_prevsurp = coeftable(model).cols[1][3]
        z_prevsurp = coeftable(model).cols[3][3]

        [chi2 b_surp z_surp b_prevsurp z_prevsurp avsurp]
    end
end

function fit_surps(data, basedev)
    # Loop over the different estimates for surprisal (i.e., over networks) and fit regression models.
    col       = surp_col
    prevcol   = prevsurp_col
    countdown = nrrep*nrtest

    for rep = 1:nrrep
        for test = 1:nrtest
            print(repr(countdown)*' ')      # Countdown to show how much left to do

            outfit_srn  = fit_1surp(data, basedev, col, prevcol)
            outfit_gru  = fit_1surp(data, basedev, col+nrtest,  prevcol+nrtest)
            outfit_lstm = fit_1surp(data, basedev, col+2nrtest, prevcol+2nrtest)

            push!(fit_results,[rep test "SRN"  outfit_srn])
            push!(fit_results,[rep test "GRU"  outfit_gru])
            push!(fit_results,[rep test "LSTM" outfit_lstm])

            col       += 1
            prevcol   += 1
            countdown -= 1
        end

        col     += 2nrtest
        prevcol += 2nrtest
    end
    print('\n')
end

#---------------------------------------------------------------------
# Self-paced reading
#---------------------------------------------------------------------
data_SPR = read_data("SPR")
data_SPR.subj_nr = CategoricalArray(data_SPR.subj_nr) # Change data types to categorical
data_SPR.item = CategoricalArray(data_SPR.item)
print("Fitting LMMs to SPR data\n")

basedev_SPR = deviance(fit!(LinearMixedModel(@formula(logRT ~ logRT_prev * log_freq * log_freq_prev * nr_char * nr_char_prev * word_pos
                                                      + (1|subj_nr) + (0+logRT_prev|subj_nr) + (0+log_freq|subj_nr) + (0+log_freq_prev|subj_nr)
                                                      + (0+nr_char|subj_nr) + (0+nr_char_prev|subj_nr) + (0+word_pos|subj_nr) + (1|item)), data_SPR)))

fit_results = DataFrame(rep=Int64[], epoch=Int64[], rnntype=String[], chi2=Float64[], b_surp=Float64[], z_surp=Float64[], b_prevsurp=Float64[], z_prevsurp=Float64[], avsurp=Float64[])
fit_surps(data_SPR, basedev_SPR)

CSV.write("lmm_SPR.csv", fit_results; delim='\t')

#---------------------------------------------------------------------
# Eye tracking
#---------------------------------------------------------------------
data_ET = read_data("ET")
data_ET.subj_nr = CategoricalArray(data_ET.subj_nr) # Change data types to categorical
data_ET.item = CategoricalArray(data_ET.item)
data_ET.prevfix = CategoricalArray(data_ET.prevfix)
print("Fitting LMMs to ET data\n")

basedev_ET = deviance(fit!(LinearMixedModel(@formula(logRTfirstpass ~ log_freq * log_freq_prev * nr_char * nr_char_prev * word_pos * prevfix
                                                     + (1|subj_nr) + (0+log_freq|subj_nr) + (0+log_freq_prev|subj_nr)
                                                     + (0+nr_char|subj_nr) + (0+nr_char_prev|subj_nr) + (0+word_pos|subj_nr) +(0+prevfix|subj_nr) + (1|item) + (0+prevfix|item)), data_ET)))

#= To get a Gamma GLMM, do the following (Somehow, I can't get GLMMs to work with more than one effect per random variable)
using GLM
fit!(GeneralizedLinearMixedModel(@formula(RTfirstpass ~ log_freq * log_freq_prev * nr_char * nr_char_prev * word_pos * prevfix + (1|subj_nr) + (1|item)), data, Gamma(), IdentityLink()), fast=true)
=#
fit_results = DataFrame(rep=Int64[], epoch=Int64[], rnntype=String[], chi2=Float64[], b_surp=Float64[], z_surp=Float64[], b_prevsurp=Float64[], z_prevsurp=Float64[], avsurp=Float64[])
fit_surps(data_ET, basedev_ET)

CSV.write("lmm_ET.csv", fit_results; delim='\t')

#---------------------------------------------------------------------
# Electroencephalography
#---------------------------------------------------------------------
data_EEG = read_data("EEG")
data_EEG.subj_nr = CategoricalArray(data_EEG[:,:subj_nr]) # Change data types to categorical
data_EEG.item = CategoricalArray(data_EEG[:,:item])
print("Fitting LMMs to EEG data\n")

basedev_EEG = deviance(fit!(LinearMixedModel(@formula(N400 ~ baseline + log_freq * nr_char * word_pos + (1|subj_nr)
                                                     + (0+baseline|subj_nr) + (0+log_freq|subj_nr) + (0+nr_char|subj_nr) +
                                                       (0+word_pos|subj_nr) + (1|item)), data_EEG)))

fit_results = DataFrame(rep=Int64[], epoch=Int64[], rnntype=String[], chi2=Float64[], b_surp=Float64[], z_surp=Float64[], avsurp=Float64[])
fit_surps(data_EEG, basedev_EEG)

CSV.write("lmm_EEG.csv", fit_results; delim='\t')

max_stars_repo_name: caurnhammer/gated-rnns

max_issues_repo_name: caurnhammer/gated-rnns

max_forks_repo_name: caurnhammer/gated-rnns


text:
function activepowervariables(m::JuMP.AbstractModel, devices::Array{T,1}, time_periods::Int64) where {T <: PowerSystems.ElectricLoad}

    on_set = [d.name for d in devices]

    t = 1:time_periods

    p_cl = @variable(m, p_cl[on_set,t] >= 0.0, start = 0.0) # Power of controllable loads

    return p_cl
end

function reactivepowervariables(m::JuMP.AbstractModel, devices::Array{T,1}, time_periods::Int64) where {T <: PowerSystems.ElectricLoad}

    on_set = [d.name for d in devices]

    t = 1:time_periods

    q_cl = @variable(m, q_cl[on_set,t] >= 0.0, start = 0.0) # Power of controllable loads

    return q_cl
end


text:
module Draftcheck

export check, rule

function get_all_filenames(filename)
    filenames = []
    _add_all_filenames!(filename, filenames, [])
    return filenames
end
function _add_all_filenames!(filename, filenames, paths)
    if filename ∈ filenames
        return
    end
    if isfile(filename)
        push!(filenames, filename)
        if dirname(filename) ∉ paths
            push!(paths, dirname(filename))
        end
        for line in readlines(filename)
            if !occursin(r"^\W*%", line)
                for a in eachmatch(r"\\input{([^}]+)}", line)
                    if a.captures[1] ∉ filenames
                        _add_all_filenames!(a.captures[1], filenames, paths)
                    end
                end
                for a in eachmatch(r"\\include{([^}]+)}", line)
                    if a.captures[1] ∉ filenames
                        _add_all_filenames!(a.captures[1], filenames, paths)
                    end
                end
            end
        end
    elseif !endswith(filename, ".tex")
        _add_all_filenames!(filename * ".tex", filenames, paths)
    else
        for path in paths
            f = joinpath(path, filename)
            if isfile(f)
                _add_all_filenames!(f, filenames, paths)
                return
            end
        end
        @warn("Missing file $filename")
    end
end

struct Rule
    name
    regex
    err
end
rules = []
function rule(name, regex, err)
    global rules
    push!(rules, Rule(name, regex, err))
end

function check(filename, rule_file; follow_links = true, allowed = Allowed())
    success = true
    if !isempty(rule_file)
        global rules = []
        include(rule_file)
    end
    if follow_links
        check(get_all_filenames(filename), "", allowed = allowed)
        return
    end

    global rules
    for (counter, line) in enumerate(readlines(filename))
        comment = occursin(r"^\W*%", line)
        if !comment
            for r in rules
                if occursin(r.regex, line) && !occursin(Regex("% OK $(r.name)"), line)
                    s = "$(r.name): $(r.err)\n$filename: $counter\n$(lstrip(line))"
                    if !contains(allowed, s)
                        println(s)
                        println()
                        success = false
                    end
                end
            end
        end
    end
    return success
end

struct Allowed
    data::Set{String}
end

function Allowed(; filename::String = "allowed.txt")
    w = Allowed(Set{String}())
    if !isfile(filename)
        return w
    end
    s = ""
    for (i, line) in enumerate(readlines(filename))
        j = mod1(i, 4)
        if j == 1
            s = line
        elseif j < 4
            s *= "\n$line"
        else
            push!(w.data, s)
        end
    end
    return w
end

contains(w::Allowed, s::String) = s ∈ w.data

function check(filenames::Vector, rule_file; follow_links = false, allowed = Allowed())
    if !isempty(rule_file)
        global rules = []
        include(rule_file)
    end
    return all(check(f, "", follow_links = follow_links, allowed = allowed) for f in filenames)
end

end # module


text:
using uwuify
using Test

@testset "uwuify" begin
    @test uwu("hello, how are you") == "hewwo, how awe you"

    # test macro
    @test uwu"hello" == "hewwo"
end


text:
using AssetRegistry
using Sockets
using WebIO

struct IJuliaConnection <: AbstractConnection
    comm::IJulia.CommManager.Comm
end

function Sockets.send(c::IJuliaConnection, data)
    IJulia.send_comm(c.comm, data)
end

Base.isopen(c::IJuliaConnection) = haskey(IJulia.CommManager.comms, c.comm.id)

WebIO.register_renderable(T::Type, ::Val{:ijulia}) = nothing

function IJulia.CommManager.register_comm(comm::IJulia.CommManager.Comm{:webio_comm}, x)
    conn = IJuliaConnection(comm)
    comm.on_msg = function (msg)
        data = msg.content["data"]
        WebIO.dispatch(conn, data)
    end
end

function main()
    if !IJulia.inited
        # If IJulia has not been initialized and connected to Jupyter itself,
        # then we have no way to display anything in the notebook and no way
        # to set up comms, so this function cannot run. That's OK, because
        # any IJulia kernels will start up with a fresh process and a fresh
        # copy of WebIO and IJulia.
        return
    end

    # https://github.com/JuliaLang/IJulia.jl/pull/755
    if isdefined(IJulia, :register_jsonmime)
        IJulia.register_jsonmime(WEBIO_NODE_MIME())
    else
        @warn "IJulia doesn't have register_mime; WebIO may not work as expected. Please upgrade to IJulia v1.13.0 or greater."
    end

    script_id = "webio-setup-$(rand(UInt64))"
    warning_div_id = "webio-warning-$(rand(UInt64))"
    setup_script = js"""
        // Immediately-invoked-function-expression to avoid global variables.
        (function() {
            var warning_div = document.getElementById($(warning_div_id));
            var hide = function () {
                var script = document.getElementById($(script_id));
                var parent = script && script.parentElement;
                var grandparent = parent && parent.parentElement;
                if (grandparent) {
                    grandparent.style.display = "none";
                }
                warning_div.style.display = "none";
            };
            if (typeof Jupyter !== "undefined") {
                console.log("WebIO detected Jupyter notebook environment.");
                // Jupyter notebook.
                var extensions = (
                    Jupyter
                    && Jupyter.notebook.config.data
                    && Jupyter.notebook.config.data.load_extensions
                );
                if (extensions && extensions[$(JUPYTER_NBEXTENSION_NAME)]) {
                    // Extension already loaded.
                    console.log("Jupyter WebIO nbextension detected; not loading ad-hoc.");
                    hide();
                    return;
                }
            } else if (window.location.pathname.includes("/lab")) {
                // Guessing JupyterLa
                console.log("Jupyter Lab detected; make sure the @webio/jupyter-lab-provider labextension is installed.");
                hide();
                return;
            }
        })();
        """
    display(HTML("""

            Unable to load WebIO. Please make sure WebIO works for your Jupyter client.
            For troubleshooting, please see
            the WebIO/IJulia documentation.

        """
    ))
end

WebIO.setup_provider(::Val{:ijulia}) = nothing # calling setup_provider(Val(:ijulia)) will display the setup javascript
WebIO.setup(:ijulia)


text:
__precompile__()

module Extern

    export @extern

    macro extern(pkg, ex)
        local installed::Bool

        installed = try
            Pkg.installed("$pkg") !== nothing
        catch
            false
        end

        if installed && isdefined(Main, pkg)
            return esc(ex)
        end

        nothing
    end

end


text:
# function convert(::Type{Float64}, x::UInt128)
#     x == 0 && return 0.0
#     n = 128-leading_zeros(x) # ndigits0z(x,2)
#     if n <= 53
#         y = ((x % UInt64) << (53-n)) & 0x000f_ffff_ffff_ffff
#     else
#         y = ((x >> (n-54)) % UInt64) & 0x001f_ffff_ffff_ffff # keep 1 extra bit
#         y = (y+1)>>1 # round, ties up (extra leading bit in case of next exponent)
#         y &= ~UInt64(trailing_zeros(x) == (n-54)) # fix last bit to round to even
#     end
#     d = ((n+1022) % UInt64) << 52
#     reinterpret(Float64, d + y)
# end

# function convert(::Type{Float64}, x::Int128)
#     x == 0 && return 0.0
#     s = ((x >>> 64) % UInt64) & 0x8000_0000_0000_0000 # sign bit
#     x = abs(x) % UInt128
#     n = 128-leading_zeros(x) # ndigits0z(x,2)
#     if n <= 53
#         y = ((x % UInt64) << (53-n)) & 0x000f_ffff_ffff_ffff
#     else
#         y = ((x >> (n-54)) % UInt64) & 0x001f_ffff_ffff_ffff # keep 1 extra bit
#         y = (y+1)>>1 # round, ties up (extra leading bit in case of next exponent)
#         y &= ~UInt64(trailing_zeros(x) == (n-54)) # fix last bit to round to even
#     end
#     d = ((n+1022) % UInt64) << 52
#     reinterpret(Float64, s | d + y)
# end

# convert an unsigned integer to a unum
@generated function Base.convert{U<:AbstractUnum, I<:Unsigned}(::Type{U}, i::I)
  c = unumConstants(U)
  n = sizeof(i) * 8
  println(c)

  quote
    i == 0 && return $(c.zero)

    usedbits = $(n) - leading_zeros(i)

    # a
    $(c.esizesize == 0 ? :(if i == 1; return ??; end) : :())

    # if usedbits <= $(c.fsize)
    #   # y = ((i % ))
    # end
  end
end


text:
include("DenseSync.jl")

p = 16
for m in 1:15
    max_connectivity(m*p, m)
end

max_stars_repo_name: yonesuke/DenseSync

max_issues_repo_name: yonesuke/DenseSync

max_forks_repo_name: yonesuke/DenseSync


text:
struct BingoCard
    numbers::Matrix{Int}
    called::Matrix{Bool}
end

function BingoCard(numbers::AbstractString)
    BingoCard(reshape(parse.(Int, split(numbers)), 5, 5), zeros(Bool, (5, 5)))
end

function loadgame(filename)
    nums, cards... = split(readchomp(filename), r"\r?\n\r?\n")
    nums = parse.(Int, split(nums, ","))
    cards = BingoCard.(cards)
    nums, cards
end

"""
Calls a number for the given `BingoCard`.
Returns true if the card is a winner after the call.
"""
function call(card::BingoCard, n::Integer)
    index = findfirst(==(n), card.numbers)
    if !isnothing(index)
        card.called[index] = true
        iswinner(card)
    else
        false
    end
end

function iswinner(card::BingoCard)
    any(all.(eachrow(card.called))) || any(all.(eachcol(card.called)))
end

function winningrow(card::BingoCard)
    for (i, col) in enumerate(eachcol(card.called))
        if all(col)
            return card.numbers[:, i]
        end
    end
    for (i, row) in enumerate(eachrow(card.called))
        if all(row)
            return card.numbers[i, :]
        end
    end
end

function part1(filename::AbstractString)
    nums, cards = loadgame(filename)
    for n in nums
        for card in cards
            if call(card, n)
                return n * sum(card.numbers .* .!card.called)
            end
        end
    end
end

function part2(filename::AbstractString)
    nums, cards = loadgame(filename)
    for n in nums
        if any(call.(cards, n))
            if length(cards) == 1
                card = only(cards)
                return n * sum(card.numbers .* .!card.called)
            else
                filter!(!iswinner, cards)
            end
        end
    end
end

max_stars_repo_name: stellartux/advent-of-code

max_issues_repo_name: stellartux/advent-of-code

max_forks_repo_name: stellartux/advent-of-code


text:
# This file is a part of LegendHDF5IO.jl, licensed under the MIT License (MIT).

using Test

Test.@testset "Package LegendHDF5IO" begin
    include("ranges/range_to_namedtuple.jl")
    include("histograms/histogram_io.jl")
end # testset


text:
# Invertible CNN layer from Putzky & Welling (2019)
# Author: Philipp Witte, pwitte3@gatech.edu
# Date: January 2020

using InvertibleNetworks, LinearAlgebra, Test

# Input
nx = 32
ny = 32
nz = 32
k = 20
n_in = 10
n_hidden = 20
batchsize = 2

# Input image
X = glorot_uniform(nx, ny, nz, k, batchsize)
X0 = glorot_uniform(nx, ny, nz, k, batchsize)

# 1x1 convolution and residual blocks
C = Conv1x1(k)
RB = ResidualBlock(nx, ny, nz, n_in, n_hidden, batchsize)

# Invertible i-RIM coupling layer
L = CouplingLayerIRIM(C, RB)

# Forward + backward
Y = L.forward(X)
Y0 = L.forward(X0)
ΔY = Y0 - Y
ΔX, X0_ = L.backward(ΔY, Y0)

@test isapprox(norm(X0_ - X0)/norm(X0), 0f0, atol=1f-2)


text:
module QueryStrategies

using Reexport
using Distances

import MLKernels
import MLLabelUtils
import PyCall
import LinearAlgebra:
    det
import Statistics:
    mean,
    cov
import SVDD
import NearestNeighbors

const gaussian_kde = PyCall.PyNULL()

function __init__()
    copy!(gaussian_kde, PyCall.pyimport_conda("scipy.stats", "scipy").gaussian_kde)
end

include("qs_base.jl")
include("qs_utils.jl")

include("SequentialQueryStrategies/SequentialQueryStrategies.jl")
@reexport using .SequentialQueryStrategies

include("BatchQueryStrategies/BatchQueryStrategies.jl")
@reexport using .BatchQueryStrategies

include("QuerySynthesisStrategies/QuerySynthesisStrategies.jl")
@reexport using .QuerySynthesisStrategies

include("HybridQuerySynthesisPQs.jl")

include("SubspaceQueryStrategies/SubspaceQueryStrategies.jl")
@reexport using .SubspaceQueryStrategies

export
    QueryStrategy,
    HybridQuerySynthesisPQs,
    KDEException, MissingLabelTypeException,

    get_query_objects,
    initialize_qs,
    qs_score,
    multi_kde,
    filter_array
end


text:
# defines variables found in INDEXB.INC for use in Julia

const JBTOT  =  102
const JBFUSE =  35

const VARS = OffsetArrays.OffsetArray(Array{String,1}(undef, JBTOT+1), 0:JBTOT)
VARS[ 0]  = "      s    "; const JSA    =  0;
VARS[ 1]  = "      x    "; const JXA    =  1;
VARS[ 2]  = "      y    "; const JYA    =  2;
VARS[ 3]  = "      z    "; const JZA    =  3;
VARS[ 4]  = "    twist  "; const JTW    =  4;
VARS[ 5]  = "     EIcc  "; const JECC   =  5;
VARS[ 6]  = "     EInn  "; const JENN   =  6;
VARS[ 7]  = "     EIcn  "; const JECN   =  7;
VARS[ 8]  = "     EIcs  "; const JECS   =  8;
VARS[ 9]  = "     EIsn  "; const JESN   =  9;
VARS[10]  = "      GJ   "; const JGJ    = 10;
VARS[11]  = "      EA   "; const JEA    = 11;
VARS[12]  = "      GKc  "; const JGKC   = 12;
VARS[13]  = "      GKn  "; const JGKN   = 13;
VARS[14]  = "     mgcc  "; const JMCC1  = 14;
VARS[15]  = "     mgnn  "; const JMNN1  = 15;
VARS[16]  = "      mg   "; const JMG1   = 16;
VARS[17]  = "     Ccg   "; const JCCG1  = 17;
VARS[18]  = "     Ncg   "; const JNCG1  = 18;
VARS[19]  = "    Dmgcc  "; const JMCC2  = 19;
VARS[20]  = "    Dmgnn  "; const JMNN2  = 20;
VARS[21]  = "     Dmg   "; const JMG2   = 21;
VARS[22]  = "    DCcg   "; const JCCG2  = 22;
VARS[23]  = "    DNcg   "; const JNCG2  = 23;
VARS[24]  = "     Cea   "; const JCEA   = 24;
VARS[25]  = "     Nea   "; const JNEA   = 25;
VARS[26]  = "     Cta   "; const JCTA   = 26;
VARS[27]  = "     Nta   "; const JNTA   = 27;
VARS[28]  = "    tdeps  "; const JTDE   = 28;
VARS[29]  = "    tdgam  "; const JTDG   = 29;
VARS[30]  = "   Cshell  "; const JCSH   = 30;
VARS[31]  = "   Nshell  "; const JNSH   = 31;
VARS[32]  = "  Atshell  "; const JASH   = 32;
VARS[33]  = "   radius  "; const JRAD   = 33;
VARS[34]  = "     Cdf   "; const JCDF   = 34;
VARS[35]  = "     Cdp   "; const JCDP   = 35;
VARS[36]  = "    chord  "; const JCH    = 36;
VARS[37]  = "     Xax   "; const JXAX   = 37;
VARS[38]  = "    alpha  "; const JAL    = 38;
VARS[39]  = "      Cm   "; const JCM    = 39;
VARS[40]  = "    CLmax  "; const JCMX   = 40;
VARS[41]  = "    CLmin  "; const JCMN   = 41;
VARS[42]  = "    dCLda  "; const JDCL   = 42;
VARS[43]  = "   dCLdF1  "; const JCLF1  = 43;
VARS[44]  = "   dCLdF2  "; const JCLF2  = 44;
VARS[45]  = "   dCLdF3  "; const JCLF3  = 45;
VARS[46]  = "   dCLdF4  "; const JCLF4  = 46;
VARS[47]  = "   dCLdF5  "; const JCLF5  = 47;
VARS[48]  = "   dCLdF6  "; const JCLF6  = 48;
VARS[49]  = "   dCLdF7  "; const JCLF7  = 49;
VARS[50]  = "   dCLdF8  "; const JCLF8  = 50;
VARS[51]  = "   dCLdF9  "; const JCLF9  = 51;
VARS[52]  = "   dCLdF10 "; const JCLF10 = 52;
VARS[53]  = "   dCLdF11 "; const JCLF11 = 53;
VARS[54]  = "   dCLdF12 "; const JCLF12 = 54;
VARS[55]  = "   dCLdF13 "; const JCLF13 = 55;
VARS[56]  = "   dCLdF14 "; const JCLF14 = 56;
VARS[57]  = "   dCLdF15 "; const JCLF15 = 57;
VARS[58]  = "   dCLdF16 "; const JCLF16 = 58;
VARS[59]  = "   dCLdF17 "; const JCLF17 = 59;
VARS[60]  = "   dCLdF18 "; const JCLF18 = 60;
VARS[61]  = "   dCLdF19 "; const JCLF19 = 61;
VARS[62]  = "   dCLdF20 "; const JCLF20 = 62;
VARS[63]  = "   dCMdF1  "; const JCMF1  = 63;
VARS[64]  = "   dCMdF2  "; const JCMF2  = 64;
VARS[65]  = "   dCMdF3  "; const JCMF3  = 65;
VARS[66]  = "   dCMdF4  "; const JCMF4  = 66;
VARS[67]  = "   dCMdF5  "; const JCMF5  = 67;
VARS[68]  = "   dCMdF6  "; const JCMF6  = 68;
VARS[69]  = "   dCMdF7  "; const JCMF7  = 69;
VARS[70]  = "   dCMdF8  "; const JCMF8  = 70;
VARS[71]  = "   dCMdF9  "; const JCMF9  = 71;
VARS[72]  = "   dCMdF10 "; const JCMF10 = 72;
VARS[73]  = "   dCMdF11 "; const JCMF11 = 73;
VARS[74]  = "   dCMdF12 "; const JCMF12 = 74;
VARS[75]  = "   dCMdF13 "; const JCMF13 = 75;
VARS[76]  = "   dCMdF14 "; const JCMF14 = 76;
VARS[77]  = "   dCMdF15 "; const JCMF15 = 77;
VARS[78]  = "   dCMdF16 "; const JCMF16 = 78;
VARS[79]  = "   dCMdF17 "; const JCMF17 = 79;
VARS[80]  = "   dCMdF18 "; const JCMF18 = 80;
VARS[81]  = "   dCMdF19 "; const JCMF19 = 81;
VARS[82]  = "   dCMdF20 "; const JCMF20 = 82;
VARS[83]  = "   dCDdF1  "; const JCDF1  = 83;
VARS[84]  = "   dCDdF2  "; const JCDF2  = 84;
VARS[85]  = "   dCDdF3  "; const JCDF3  = 85;
VARS[86]  = "   dCDdF4  "; const JCDF4  = 86;
VARS[87]  = "   dCDdF5  "; const JCDF5  = 87;
VARS[88]  = "   dCDdF6  "; const JCDF6  = 88;
VARS[89]  = "   dCDdF7  "; const JCDF7  = 89;
VARS[90]  = "   dCDdF8  "; const JCDF8  = 90;
VARS[91]  = "   dCDdF9  "; const JCDF9  = 91;
VARS[92]  = "   dCDdF10 "; const JCDF10 = 92;
VARS[93]  = "   dCDdF11 "; const JCDF11 = 93;
VARS[94]  = "   dCDdF12 "; const JCDF12 = 94;
VARS[95]  = "   dCDdF13 "; const JCDF13 = 95;
VARS[96]  = "   dCDdF14 "; const JCDF14 = 96;
VARS[97]  = "   dCDdF15 "; const JCDF15 = 97;
VARS[98]  = "   dCDdF16 "; const JCDF16 = 98;
VARS[99]  = "   dCDdF17 "; const JCDF17 = 99;
VARS[100] = "   dCDdF18 "; const JCDF18 = 100;
VARS[101] = "   dCDdF19 "; const JCDF19 = 101;
VARS[102] = "   dCDdF20 "; const JCDF20 = 102;


text:
# Dev code for simple convergence test, copied out from dev.jl

push!(LOAD_PATH, string(pwd(),"/src"))

using Revise
using PyPlot
import IterativeSolvers
import LinearMaps

using ModifiedStokesSolver
import AnalyticDomains
using PUX

# Params
alpha = 10.0
numpanels_list = vcat(25,30:10:120)
ticks = [30, 60, 120]

panelorder = 16
curve = AnalyticDomains.starfish()

# Setup a problem
srand(1)
Nsrc = 5
Rsrc = 1.4

theta = 2*pi*rand(Nsrc)
src = Rsrc*[cos.(theta) sin.(theta)]'
str = 1-2*rand(2, Nsrc)
ubc(targ) = fmm_stokeslet_targ(src, targ, str, alpha)
ubc_grad(targ) = fmm_stokeslet_targ(src, targ, str, alpha, ifgrad=true)

# Ntrg = 50
# theta = 2*pi*rand(Ntrg)
# zt_interior = 0.65*(rand(Ntrg).*[cos.(theta) sin.(theta)])'

Ngrid = 30
dcurve = discretize(curve, 500, panelorder)
x = linspace(-1.4, 1.4, Ngrid)
X, Y = ModifiedStokesSolver.ndgrid(x, x)
zt = [vec(X) vec(Y)]'
interior = ModifiedStokesSolver.interior_points(dcurve, zt)
zt_interior = zt[:, interior]

function solve(numpanels, method=:dense)
    # Discretize
    @show numpanels
    dcurve = discretize(curve, numpanels, panelorder)
    panel_length = sum(dcurve.dS[1:panelorder])
    @show panel_length*alpha

    N = dcurve.numpoints
    # Right hand side
    rhs = ubc(dcurve.points)
    # Left hand side
    println("* Assembly")
    if method==:dense
        LHS = system_matrix(dcurve, alpha)
    elseif method==:fmm
        flhs = system_matvec(dcurve, alpha)
        LHS = LinearMaps.LinearMap(flhs, 2*N)
    else
        error(method)
    end
    println("* Solve")
    if method==:dense
        sol = LHS\vec(rhs)
    else
        # GMRES solve
        maxiter = 150
        tol = 1e-15
        sol, gmlog = IterativeSolvers.gmres(LHS, rhs; tol=tol, restart=maxiter, maxiter=maxiter, verbose=false, log=true)
        println( (gmlog.isconverged ? "  Converged" : "Did NOT converge"),
                 " in $(gmlog.iters) iterations, residual=",
                 gmlog.data[:resnorm][end])
    end
    density = reshape(sol, 2, N)

    # Estimate density resolution
    L = ModifiedStokesSolver.legendre_matrix(panelorder)
    density_resolution = 0.0;
    for i=1:numpanels
        xcoeff = L*density[1, (1:panelorder) + panelorder*(i-1)]
        ycoeff = L*density[2, (1:panelorder) + panelorder*(i-1)]
        xres = max(abs(xcoeff[end]), abs(xcoeff[end-1]))
        yres = max(abs(ycoeff[end]), abs(ycoeff[end-1]))
        res = max(xres, yres)
        density_resolution = max(density_resolution, res)
    end
    @show density_resolution

    ## VOLUME ERROR EVAL
    dlp, dlpgrad1, dlpgrad2 = doublelayer_fast(dcurve, density, zt_interior, alpha, ifgrad=true)
    ref, refgrad1, refgrad2 = ubc_grad(zt_interior)
    @show relerr = maximum(abs.(ref.-dlp)) / maximum(abs.(ref))
    unorm = maximum(abs.(ref))
    gradnorm = max( maximum(abs.(refgrad1)), maximum(abs.(refgrad2)) )
    @show rmserr = sqrt( sum(vec((dlp.-ref).^2))/length(ref) ) / unorm

    @show graderr = max( maximum(abs.(refgrad1.-dlpgrad1)),
                         maximum(abs.(refgrad2.-dlpgrad2)) ) / gradnorm

    # plot
    err = abs.(dlp-ref)
    E = zero(X)
    E[interior] = max.(err[1,:],err[2,:]) / unorm
    figure(3)
    clf()
    pcolor(X, Y, log10.(E))
    clim(-15, -2)
    axis("equal")
    colorbar()

    return relerr, rmserr, graderr, density_resolution
end

ntests = length(numpanels_list)
max_errors = zeros(ntests)
rms_errors = zeros(ntests)
grad_errors = zeros(ntests)
density_resolution = zeros(ntests)
for i=1:ntests
    max_errors[i], rms_errors[i], grad_errors[i], density_resolution[i] = solve(numpanels_list[i])
end

close("all")

## Convergence plot
xquant = numpanels_list
figure(1, figsize=(4,3))
clf()
loglog(xquant, max_errors, ".-", label=L"||\tilde u - u||_\infty")
loglog(xquant, grad_errors, "*--", label=L"||\nabla\tilde u - \nabla u||_\infty")
#loglog(xquant, rms_errors, ".-", label="RMS err")
#loglog(xquant, density_resolution, ".--", label="Density")
# loglog(xquant, density_resolution[end]*(xquant/xquant[end]).^-(panelorder-2), "--k", label="$(panelorder-2)th order")
# loglog(xquant, density_resolution[end]*(xquant/xquant[end]).^-(panelorder-1), "--k", label="$(panelorder-1)th order")
# loglog(xquant, density_resolution[end]*(xquant/xquant[end]).^-panelorder, "--k", label="$(panelorder)th order")
mid = div(length(xquant),2)
loglog(xquant, (max_errors[mid]+grad_errors[mid])/2*(xquant/xquant[mid]).^-panelorder, "--k", label="$(panelorder)th order")
grid()
legend()
axis("auto")
ylim(1e-15, 1)
xticks(ticks, ticks)
minorticks_off()
xlabel("Number of panels")
ylabel("Relative error")
#title(L"\alpha="*string(alpha))
tight_layout(0)

## Domain plot
figure(2, figsize=(4,3))
clf()
t = linspace(0,2*pi,1000)
tau = curve.tau.(t)
plot(real(tau), imag(tau), label=L"\partial\Omega")
plot(src[1,:], src[2,:], "*", label="sources")
plot(zt_interior[1,:], zt_interior[2,:], ".", label="targets")
legend(loc="lower left")
axis("off")
axis("tight")
axis("equal")
tight_layout(0)

function write_fig(num, name)
    figure(num)
    savefig(name)
    println("Saved $name")
end

function save_conv_figs()
    write_fig(1, "../docs/paper/figs/convergence_homogeneous.pdf")
    write_fig(2, "../docs/paper/figs/convergence_homogeneous_geometry.pdf")
end

println("Done.\n")
println("Number of interior points: ", size(zt_interior,2),"\n")
println("Call save_conv_figs() to write plots to disk");


text:
@testset "Test dictionary time period conversion" begin
    faketimes1 = Dict("one" => Dates.Week(40), "two" => Dates.Day(6))
    faketimes2 = Dict("one" => Dates.Minute(40), "two" => Dates.Minute(6))
    faketimes3 = Dict("one" => Dates.Millisecond(3), "two" => Dates.Second(4), "three" => Dates.Minute(40), "four" => Dates.Hour(3))
    convert1 = IS.time_period_conversion(faketimes1)
    convert2 = IS.time_period_conversion(faketimes2)
    convert3 = IS.time_period_conversion(faketimes3)
    for dict in [convert1, convert2, convert3]
        for (k, v) in dict
            @test typeof(v) == Dates.Millisecond
        end
    end
end

@testset "Test time period conversion" begin
    fake1 = IS.time_period_conversion(Dates.Day(2))
    fake2 = IS.time_period_conversion(Dates.Hour(2))
    fake3 = IS.time_period_conversion(Dates.Minute(2))
    fake4 = IS.time_period_conversion(Dates.Second(2))
    fake5 = IS.time_period_conversion(Dates.Millisecond(2))
    fake_times = [fake1, fake2, fake3, fake4, fake5]
    for time_period in fake_times
        @test typeof(time_period) == Dates.Millisecond
    end
end


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

using AWS.Compat
using AWS.UUIDs
"""
    CreateServer()

Instantiates an autoscaling virtual server based on the selected file transfer protocol in AWS. When you make updates to your file transfer protocol-enabled server or when you work with users, use the service-generated ServerId property that is assigned to the newly created server.

# Optional Parameters
- `Certificate`: The Amazon Resource Name (ARN) of the AWS Certificate Manager (ACM) certificate. Required when Protocols is set to FTPS. To request a new public certificate, see Request a public certificate in the  AWS Certificate Manager User Guide. To import an existing certificate into ACM, see Importing certificates into ACM in the  AWS Certificate Manager User Guide. To request a private certificate to use FTPS through private IP addresses, see Request a private certificate in the  AWS Certificate Manager User Guide. Certificates with the following cryptographic algorithms and key sizes are supported:   2048-bit RSA (RSA_2048)   4096-bit RSA (RSA_4096)   Elliptic Prime Curve 256 bit (EC_prime256v1)   Elliptic Prime Curve 384 bit (EC_secp384r1)   Elliptic Prime Curve 521 bit (EC_secp521r1)    The certificate must be a valid SSL/TLS X.509 version 3 certificate with FQDN or IP address specified and information about the issuer.
- `EndpointDetails`: The virtual private cloud (VPC) endpoint settings that are configured for your file transfer protocol-enabled server. When you host your endpoint within your VPC, you can make it accessible only to resources within your VPC, or you can attach Elastic IPs and make it accessible to clients over the internet. Your VPC's default security groups are automatically assigned to your endpoint.
- `EndpointType`: The type of VPC endpoint that you want your file transfer protocol-enabled server to connect to. You can choose to connect to the public internet or a VPC endpoint. With a VPC endpoint, you can restrict access to your server and resources only within your VPC.  It is recommended that you use VPC as the EndpointType. With this endpoint type, you have the option to directly associate up to three Elastic IPv4 addresses (BYO IP included) with your server's endpoint and use VPC security groups to restrict traffic by the client's public IP address. This is not possible with EndpointType set to VPC_ENDPOINT.
- `HostKey`: The RSA private key as generated by the ssh-keygen -N \"\" -m PEM -f my-new-server-key command.  If you aren't planning to migrate existing users from an existing SFTP-enabled server to a new server, don't update the host key. Accidentally changing a server's host key can be disruptive.  For more information, see Change the host key for your SFTP-enabled server in the AWS Transfer Family User Guide.
- `IdentityProviderDetails`: Required when IdentityProviderType is set to API_GATEWAY. Accepts an array containing all of the information required to call a customer-supplied authentication API, including the API Gateway URL. Not required when IdentityProviderType is set to SERVICE_MANAGED.
- `IdentityProviderType`: Specifies the mode of authentication for a file transfer protocol-enabled server. The default value is SERVICE_MANAGED, which allows you to store and access user credentials within the AWS Transfer Family service. Use the API_GATEWAY value to integrate with an identity provider of your choosing. The API_GATEWAY setting requires you to provide an API Gateway endpoint URL to call for authentication using the IdentityProviderDetails parameter.
- `LoggingRole`: Allows the service to write your users' activity to your Amazon CloudWatch logs for monitoring and auditing purposes.
- `Protocols`: Specifies the file transfer protocol or protocols over which your file transfer protocol client can connect to your server's endpoint. The available protocols are:    SFTP (Secure Shell (SSH) File Transfer Protocol): File transfer over SSH    FTPS (File Transfer Protocol Secure): File transfer with TLS encryption    FTP (File Transfer Protocol): Unencrypted file transfer    If you select FTPS, you must choose a certificate stored in AWS Certificate Manager (ACM) which will be used to identify your file transfer protocol-enabled server when clients connect to it over FTPS. If Protocol includes either FTP or FTPS, then the EndpointType must be VPC and the IdentityProviderType must be API_GATEWAY. If Protocol includes FTP, then AddressAllocationIds cannot be associated. If Protocol is set only to SFTP, the EndpointType can be set to PUBLIC and the IdentityProviderType can be set to SERVICE_MANAGED.
- `SecurityPolicyName`: Specifies the name of the security policy that is attached to the server.
- `Tags`: Key-value pairs that can be used to group and search for file transfer protocol-enabled servers.
"""

create_server(; aws_config::AWSConfig=global_aws_config()) = transfer("CreateServer"; aws_config=aws_config)
create_server(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("CreateServer", args; aws_config=aws_config)

"""
    CreateUser()

Creates a user and associates them with an existing file transfer protocol-enabled server. You can only create and associate users with servers that have the IdentityProviderType set to SERVICE_MANAGED. Using parameters for CreateUser, you can specify the user name, set the home directory, store the user's public key, and assign the user's AWS Identity and Access Management (IAM) role. You can also optionally add a scope-down policy, and assign metadata with tags that can be used to group and search for users.

# Required Parameters
- `Role`: The IAM role that controls your users' access to your Amazon S3 bucket. The policies attached to this role will determine the level of access you want to provide your users when transferring files into and out of your Amazon S3 bucket or buckets. The IAM role should also contain a trust relationship that allows the file transfer protocol-enabled server to access your resources when servicing your users' transfer requests.
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server instance. This is the specific server that you added your user to.
- `UserName`: A unique string that identifies a user and is associated with a file transfer protocol-enabled server as specified by the ServerId. This user name must be a minimum of 3 and a maximum of 100 characters long. The following are valid characters: a-z, A-Z, 0-9, underscore '_', hyphen '-', period '.', and at sign '@'. The user name can't start with a hyphen, period, and at sign.

# Optional Parameters
- `HomeDirectory`: The landing directory (folder) for a user when they log in to the file transfer protocol-enabled server using the client. An example is  your-Amazon-S3-bucket-name>/home/username .
- `HomeDirectoryMappings`: Logical directory mappings that specify what Amazon S3 paths and keys should be visible to your user and how you want to make them visible. You will need to specify the \"Entry\" and \"Target\" pair, where Entry shows how the path is made visible and Target is the actual Amazon S3 path. If you only specify a target, it will be displayed as is. You will need to also make sure that your IAM role provides access to paths in Target. The following is an example.  '[ \"/bucket2/documentation\", { \"Entry\": \"your-personal-report.pdf\", \"Target\": \"/bucket3/customized-reports/{transfer:UserName}.pdf\" } ]'  In most cases, you can use this value instead of the scope-down policy to lock your user down to the designated home directory (\"chroot\"). To do this, you can set Entry to '/' and set Target to the HomeDirectory parameter value.  If the target of a logical directory entry does not exist in Amazon S3, the entry will be ignored. As a workaround, you can use the Amazon S3 API to create 0 byte objects as place holders for your directory. If using the CLI, use the s3api call instead of s3 so you can use the put-object operation. For example, you use the following: aws s3api put-object --bucket bucketname --key path/to/folder/. Make sure that the end of the key name ends in a '/' for it to be considered a folder.
- `HomeDirectoryType`: The type of landing directory (folder) you want your users' home directory to be when they log into the file transfer protocol-enabled server. If you set it to PATH, the user will see the absolute Amazon S3 bucket paths as is in their file transfer protocol clients. If you set it LOGICAL, you will need to provide mappings in the HomeDirectoryMappings for how you want to make Amazon S3 paths visible to your users.
- `Policy`: A scope-down policy for your user so you can use the same IAM role across multiple users. This policy scopes down user access to portions of their Amazon S3 bucket. Variables that you can use inside this policy include {Transfer:UserName}, {Transfer:HomeDirectory}, and {Transfer:HomeBucket}.  For scope-down policies, AWS Transfer Family stores the policy as a JSON blob, instead of the Amazon Resource Name (ARN) of the policy. You save the policy as a JSON blob and pass it in the Policy argument. For an example of a scope-down policy, see Creating a scope-down policy. For more information, see AssumeRole in the AWS Security Token Service API Reference.
- `SshPublicKeyBody`: The public portion of the Secure Shell (SSH) key used to authenticate the user to the file transfer protocol-enabled server.
- `Tags`: Key-value pairs that can be used to group and search for users. Tags are metadata attached to users for any purpose.
"""

create_user(Role, ServerId, UserName; aws_config::AWSConfig=global_aws_config()) = transfer("CreateUser", Dict{String, Any}("Role"=>Role, "ServerId"=>ServerId, "UserName"=>UserName); aws_config=aws_config)
create_user(Role, ServerId, UserName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("CreateUser", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Role"=>Role, "ServerId"=>ServerId, "UserName"=>UserName), args)); aws_config=aws_config)

"""
    DeleteServer()

Deletes the file transfer protocol-enabled server that you specify. No response returns from this operation.

# Required Parameters
- `ServerId`: A unique system-assigned identifier for a file transfer protocol-enabled server instance.

"""

delete_server(ServerId; aws_config::AWSConfig=global_aws_config()) = transfer("DeleteServer", Dict{String, Any}("ServerId"=>ServerId); aws_config=aws_config)
delete_server(ServerId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("DeleteServer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId), args)); aws_config=aws_config)

"""
    DeleteSshPublicKey()

Deletes a user's Secure Shell (SSH) public key. No response is returned from this operation.

# Required Parameters
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server instance that has the user assigned to it.
- `SshPublicKeyId`: A unique identifier used to reference your user's specific SSH key.
- `UserName`: A unique string that identifies a user whose public key is being deleted.

"""

delete_ssh_public_key(ServerId, SshPublicKeyId, UserName; aws_config::AWSConfig=global_aws_config()) = transfer("DeleteSshPublicKey", Dict{String, Any}("ServerId"=>ServerId, "SshPublicKeyId"=>SshPublicKeyId, "UserName"=>UserName); aws_config=aws_config)
delete_ssh_public_key(ServerId, SshPublicKeyId, UserName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("DeleteSshPublicKey", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId, "SshPublicKeyId"=>SshPublicKeyId, "UserName"=>UserName), args)); aws_config=aws_config)

"""
    DeleteUser()

Deletes the user belonging to a file transfer protocol-enabled server you specify. No response returns from this operation.  When you delete a user from a server, the user's information is lost.

# Required Parameters
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server instance that has the user assigned to it.
- `UserName`: A unique string that identifies a user that is being deleted from a file transfer protocol-enabled server.

"""

delete_user(ServerId, UserName; aws_config::AWSConfig=global_aws_config()) = transfer("DeleteUser", Dict{String, Any}("ServerId"=>ServerId, "UserName"=>UserName); aws_config=aws_config)
delete_user(ServerId, UserName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("DeleteUser", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId, "UserName"=>UserName), args)); aws_config=aws_config)

"""
    DescribeSecurityPolicy()

Describes the security policy that is attached to your file transfer protocol-enabled server. The response contains a description of the security policy's properties. For more information about security policies, see Working with security policies.

# Required Parameters
- `SecurityPolicyName`: Specifies the name of the security policy that is attached to the server.

"""

describe_security_policy(SecurityPolicyName; aws_config::AWSConfig=global_aws_config()) = transfer("DescribeSecurityPolicy", Dict{String, Any}("SecurityPolicyName"=>SecurityPolicyName); aws_config=aws_config)
describe_security_policy(SecurityPolicyName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("DescribeSecurityPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("SecurityPolicyName"=>SecurityPolicyName), args)); aws_config=aws_config)

"""
    DescribeServer()

Describes a file transfer protocol-enabled server that you specify by passing the ServerId parameter. The response contains a description of a server's properties. When you set EndpointType to VPC, the response will contain the EndpointDetails.

# Required Parameters
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server.

"""

describe_server(ServerId; aws_config::AWSConfig=global_aws_config()) = transfer("DescribeServer", Dict{String, Any}("ServerId"=>ServerId); aws_config=aws_config)
describe_server(ServerId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("DescribeServer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId), args)); aws_config=aws_config)

"""
    DescribeUser()

Describes the user assigned to the specific file transfer protocol-enabled server, as identified by its ServerId property. The response from this call returns the properties of the user associated with the ServerId value that was specified.

# Required Parameters
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server that has this user assigned.
- `UserName`: The name of the user assigned to one or more file transfer protocol-enabled servers. User names are part of the sign-in credentials to use the AWS Transfer Family service and perform file transfer tasks.

"""

describe_user(ServerId, UserName; aws_config::AWSConfig=global_aws_config()) = transfer("DescribeUser", Dict{String, Any}("ServerId"=>ServerId, "UserName"=>UserName); aws_config=aws_config)
describe_user(ServerId, UserName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("DescribeUser", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId, "UserName"=>UserName), args)); aws_config=aws_config)

"""
    ImportSshPublicKey()

Adds a Secure Shell (SSH) public key to a user account identified by a UserName value assigned to the specific file transfer protocol-enabled server, identified by ServerId. The response returns the UserName value, the ServerId value, and the name of the SshPublicKeyId.

# Required Parameters
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server.
- `SshPublicKeyBody`: The public key portion of an SSH key pair.
- `UserName`: The name of the user account that is assigned to one or more file transfer protocol-enabled servers.

"""

import_ssh_public_key(ServerId, SshPublicKeyBody, UserName; aws_config::AWSConfig=global_aws_config()) = transfer("ImportSshPublicKey", Dict{String, Any}("ServerId"=>ServerId, "SshPublicKeyBody"=>SshPublicKeyBody, "UserName"=>UserName); aws_config=aws_config)
import_ssh_public_key(ServerId, SshPublicKeyBody, UserName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("ImportSshPublicKey", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId, "SshPublicKeyBody"=>SshPublicKeyBody, "UserName"=>UserName), args)); aws_config=aws_config)

"""
    ListSecurityPolicies()

Lists the security policies that are attached to your file transfer protocol-enabled servers.

# Optional Parameters
- `MaxResults`: Specifies the number of security policies to return as a response to the ListSecurityPolicies query.
- `NextToken`: When additional results are obtained from the ListSecurityPolicies command, a NextToken parameter is returned in the output. You can then pass the NextToken parameter in a subsequent command to continue listing additional security policies.
"""

list_security_policies(; aws_config::AWSConfig=global_aws_config()) = transfer("ListSecurityPolicies"; aws_config=aws_config)
list_security_policies(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("ListSecurityPolicies", args; aws_config=aws_config)

"""
    ListServers()

Lists the file transfer protocol-enabled servers that are associated with your AWS account.

# Optional Parameters
- `MaxResults`: Specifies the number of file transfer protocol-enabled servers to return as a response to the ListServers query.
- `NextToken`: When additional results are obtained from the ListServers command, a NextToken parameter is returned in the output. You can then pass the NextToken parameter in a subsequent command to continue listing additional file transfer protocol-enabled servers.
"""

list_servers(; aws_config::AWSConfig=global_aws_config()) = transfer("ListServers"; aws_config=aws_config)
list_servers(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("ListServers", args; aws_config=aws_config)

"""
    ListTagsForResource()

Lists all of the tags associated with the Amazon Resource Number (ARN) you specify. The resource can be a user, server, or role.

# Required Parameters
- `Arn`: Requests the tags associated with a particular Amazon Resource Name (ARN). An ARN is an identifier for a specific AWS resource, such as a server, user, or role.

# Optional Parameters
- `MaxResults`: Specifies the number of tags to return as a response to the ListTagsForResource request.
- `NextToken`: When you request additional results from the ListTagsForResource operation, a NextToken parameter is returned in the input. You can then pass in a subsequent command to the NextToken parameter to continue listing additional tags.
"""

list_tags_for_resource(Arn; aws_config::AWSConfig=global_aws_config()) = transfer("ListTagsForResource", Dict{String, Any}("Arn"=>Arn); aws_config=aws_config)
list_tags_for_resource(Arn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("ListTagsForResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Arn"=>Arn), args)); aws_config=aws_config)

"""
    ListUsers()

Lists the users for a file transfer protocol-enabled server that you specify by passing the ServerId parameter.

# Required Parameters
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server that has users assigned to it.

# Optional Parameters
- `MaxResults`: Specifies the number of users to return as a response to the ListUsers request.
- `NextToken`: When you can get additional results from the ListUsers call, a NextToken parameter is returned in the output. You can then pass in a subsequent command to the NextToken parameter to continue listing additional users.
"""

list_users(ServerId; aws_config::AWSConfig=global_aws_config()) = transfer("ListUsers", Dict{String, Any}("ServerId"=>ServerId); aws_config=aws_config)
list_users(ServerId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("ListUsers", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId), args)); aws_config=aws_config)

"""
    StartServer()

Changes the state of a file transfer protocol-enabled server from OFFLINE to ONLINE. It has no impact on a server that is already ONLINE. An ONLINE server can accept and process file transfer jobs. The state of STARTING indicates that the server is in an intermediate state, either not fully able to respond, or not fully online. The values of START_FAILED can indicate an error condition. No response is returned from this call.

# Required Parameters
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server that you start.

"""

start_server(ServerId; aws_config::AWSConfig=global_aws_config()) = transfer("StartServer", Dict{String, Any}("ServerId"=>ServerId); aws_config=aws_config)
start_server(ServerId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("StartServer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId), args)); aws_config=aws_config)

"""
    StopServer()

Changes the state of a file transfer protocol-enabled server from ONLINE to OFFLINE. An OFFLINE server cannot accept and process file transfer jobs. Information tied to your server, such as server and user properties, are not affected by stopping your server. Stopping the server will not reduce or impact your file transfer protocol endpoint billing. The state of STOPPING indicates that the server is in an intermediate state, either not fully able to respond, or not fully offline. The values of STOP_FAILED can indicate an error condition. No response is returned from this call.

# Required Parameters
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server that you stopped.

"""

stop_server(ServerId; aws_config::AWSConfig=global_aws_config()) = transfer("StopServer", Dict{String, Any}("ServerId"=>ServerId); aws_config=aws_config)
stop_server(ServerId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("StopServer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId), args)); aws_config=aws_config)

"""
    TagResource()

Attaches a key-value pair to a resource, as identified by its Amazon Resource Name (ARN). Resources are users, servers, roles, and other entities. There is no response returned from this call.

# Required Parameters
- `Arn`: An Amazon Resource Name (ARN) for a specific AWS resource, such as a server, user, or role.
- `Tags`: Key-value pairs assigned to ARNs that you can use to group and search for resources by type. You can attach this metadata to user accounts for any purpose.

"""

tag_resource(Arn, Tags; aws_config::AWSConfig=global_aws_config()) = transfer("TagResource", Dict{String, Any}("Arn"=>Arn, "Tags"=>Tags); aws_config=aws_config)
tag_resource(Arn, Tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("TagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Arn"=>Arn, "Tags"=>Tags), args)); aws_config=aws_config)

"""
    TestIdentityProvider()

If the IdentityProviderType of a file transfer protocol-enabled server is API_Gateway, tests whether your API Gateway is set up successfully. We highly recommend that you call this operation to test your authentication method as soon as you create your server. By doing so, you can troubleshoot issues with the API Gateway integration to ensure that your users can successfully use the service.

# Required Parameters
- `ServerId`: A system-assigned identifier for a specific file transfer protocol-enabled server. That server's user authentication method is tested with a user name and password.
- `UserName`: The name of the user account to be tested.

# Optional Parameters
- `ServerProtocol`: The type of file transfer protocol to be tested. The available protocols are:   Secure Shell (SSH) File Transfer Protocol (SFTP)   File Transfer Protocol Secure (FTPS)   File Transfer Protocol (FTP)
- `SourceIp`: The source IP address of the user account to be tested.
- `UserPassword`: The password of the user account to be tested.
"""

test_identity_provider(ServerId, UserName; aws_config::AWSConfig=global_aws_config()) = transfer("TestIdentityProvider", Dict{String, Any}("ServerId"=>ServerId, "UserName"=>UserName); aws_config=aws_config)
test_identity_provider(ServerId, UserName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("TestIdentityProvider", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId, "UserName"=>UserName), args)); aws_config=aws_config)

"""
    UntagResource()

Detaches a key-value pair from a resource, as identified by its Amazon Resource Name (ARN). Resources are users, servers, roles, and other entities. No response is returned from this call.

# Required Parameters
- `Arn`: The value of the resource that will have the tag removed. An Amazon Resource Name (ARN) is an identifier for a specific AWS resource, such as a server, user, or role.
- `TagKeys`: TagKeys are key-value pairs assigned to ARNs that can be used to group and search for resources by type. This metadata can be attached to resources for any purpose.

"""

untag_resource(Arn, TagKeys; aws_config::AWSConfig=global_aws_config()) = transfer("UntagResource", Dict{String, Any}("Arn"=>Arn, "TagKeys"=>TagKeys); aws_config=aws_config)
untag_resource(Arn, TagKeys, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("UntagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Arn"=>Arn, "TagKeys"=>TagKeys), args)); aws_config=aws_config)

"""
    UpdateServer()

Updates the file transfer protocol-enabled server's properties after that server has been created. The UpdateServer call returns the ServerId of the server you updated.

# Required Parameters
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server instance that the user account is assigned to.

# Optional Parameters
- `Certificate`: The Amazon Resource Name (ARN) of the AWS Certificate Manager (ACM) certificate. Required when Protocols is set to FTPS. To request a new public certificate, see Request a public certificate in the  AWS Certificate Manager User Guide. To import an existing certificate into ACM, see Importing certificates into ACM in the  AWS Certificate Manager User Guide. To request a private certificate to use FTPS through private IP addresses, see Request a private certificate in the  AWS Certificate Manager User Guide. Certificates with the following cryptographic algorithms and key sizes are supported:   2048-bit RSA (RSA_2048)   4096-bit RSA (RSA_4096)   Elliptic Prime Curve 256 bit (EC_prime256v1)   Elliptic Prime Curve 384 bit (EC_secp384r1)   Elliptic Prime Curve 521 bit (EC_secp521r1)    The certificate must be a valid SSL/TLS X.509 version 3 certificate with FQDN or IP address specified and information about the issuer.
- `EndpointDetails`: The virtual private cloud (VPC) endpoint settings that are configured for your file transfer protocol-enabled server. With a VPC endpoint, you can restrict access to your server to resources only within your VPC. To control incoming internet traffic, you will need to associate one or more Elastic IP addresses with your server's endpoint.
- `EndpointType`: The type of endpoint that you want your file transfer protocol-enabled server to connect to. You can choose to connect to the public internet or a VPC endpoint. With a VPC endpoint, you can restrict access to your server and resources only within your VPC.  It is recommended that you use VPC as the EndpointType. With this endpoint type, you have the option to directly associate up to three Elastic IPv4 addresses (BYO IP included) with your server's endpoint and use VPC security groups to restrict traffic by the client's public IP address. This is not possible with EndpointType set to VPC_ENDPOINT.
- `HostKey`: The RSA private key as generated by ssh-keygen -N \"\" -m PEM -f my-new-server-key.  If you aren't planning to migrate existing users from an existing file transfer protocol-enabled server to a new server, don't update the host key. Accidentally changing a server's host key can be disruptive.  For more information, see Change the host key for your SFTP-enabled server in the AWS Transfer Family User Guide.
- `IdentityProviderDetails`: An array containing all of the information required to call a customer's authentication API method.
- `LoggingRole`: Changes the AWS Identity and Access Management (IAM) role that allows Amazon S3 events to be logged in Amazon CloudWatch, turning logging on or off.
- `Protocols`: Specifies the file transfer protocol or protocols over which your file transfer protocol client can connect to your server's endpoint. The available protocols are:   Secure Shell (SSH) File Transfer Protocol (SFTP): File transfer over SSH   File Transfer Protocol Secure (FTPS): File transfer with TLS encryption   File Transfer Protocol (FTP): Unencrypted file transfer    If you select FTPS, you must choose a certificate stored in AWS Certificate Manager (ACM) which will be used to identify your server when clients connect to it over FTPS. If Protocol includes either FTP or FTPS, then the EndpointType must be VPC and the IdentityProviderType must be API_GATEWAY. If Protocol includes FTP, then AddressAllocationIds cannot be associated. If Protocol is set only to SFTP, the EndpointType can be set to PUBLIC and the IdentityProviderType can be set to SERVICE_MANAGED.
- `SecurityPolicyName`: Specifies the name of the security policy that is attached to the server.
"""

update_server(ServerId; aws_config::AWSConfig=global_aws_config()) = transfer("UpdateServer", Dict{String, Any}("ServerId"=>ServerId); aws_config=aws_config)
update_server(ServerId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("UpdateServer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId), args)); aws_config=aws_config)

"""
    UpdateUser()

Assigns new properties to a user. Parameters you pass modify any or all of the following: the home directory, role, and policy for the UserName and ServerId you specify. The response returns the ServerId and the UserName for the updated user.

# Required Parameters
- `ServerId`: A system-assigned unique identifier for a file transfer protocol-enabled server instance that the user account is assigned to.
- `UserName`: A unique string that identifies a user and is associated with a file transfer protocol-enabled server as specified by the ServerId. This user name must be a minimum of 3 and a maximum of 100 characters long. The following are valid characters: a-z, A-Z, 0-9, underscore '_', hyphen '-', period '.', and at sign '@'. The user name can't start with a hyphen, period, and at sign.

# Optional Parameters
- `HomeDirectory`: Specifies the landing directory (folder) for a user when they log in to the file transfer protocol-enabled server using their file transfer protocol client. An example is your-Amazon-S3-bucket-name>/home/username.
- `HomeDirectoryMappings`: Logical directory mappings that specify what Amazon S3 paths and keys should be visible to your user and how you want to make them visible. You will need to specify the \"Entry\" and \"Target\" pair, where Entry shows how the path is made visible and Target is the actual Amazon S3 path. If you only specify a target, it will be displayed as is. You will need to also make sure that your IAM role provides access to paths in Target. The following is an example.  '[ \"/bucket2/documentation\", { \"Entry\": \"your-personal-report.pdf\", \"Target\": \"/bucket3/customized-reports/{transfer:UserName}.pdf\" } ]'  In most cases, you can use this value instead of the scope-down policy to lock your user down to the designated home directory (\"chroot\"). To do this, you can set Entry to '/' and set Target to the HomeDirectory parameter value.  If the target of a logical directory entry does not exist in Amazon S3, the entry will be ignored. As a workaround, you can use the Amazon S3 API to create 0 byte objects as place holders for your directory. If using the CLI, use the s3api call instead of s3 so you can use the put-object operation. For example, you use the following: aws s3api put-object --bucket bucketname --key path/to/folder/. Make sure that the end of the key name ends in a / for it to be considered a folder.
- `HomeDirectoryType`: The type of landing directory (folder) you want your users' home directory to be when they log into the file transfer protocol-enabled server. If you set it to PATH, the user will see the absolute Amazon S3 bucket paths as is in their file transfer protocol clients. If you set it LOGICAL, you will need to provide mappings in the HomeDirectoryMappings for how you want to make Amazon S3 paths visible to your users.
- `Policy`: Allows you to supply a scope-down policy for your user so you can use the same IAM role across multiple users. The policy scopes down user access to portions of your Amazon S3 bucket. Variables you can use inside this policy include {Transfer:UserName}, {Transfer:HomeDirectory}, and {Transfer:HomeBucket}.  For scope-down policies, AWS Transfer Family stores the policy as a JSON blob, instead of the Amazon Resource Name (ARN) of the policy. You save the policy as a JSON blob and pass it in the Policy argument. For an example of a scope-down policy, see Creating a scope-down policy. For more information, see AssumeRole in the AWS Security Token Service API Reference.
- `Role`: The IAM role that controls your users' access to your Amazon S3 bucket. The policies attached to this role will determine the level of access you want to provide your users when transferring files into and out of your Amazon S3 bucket or buckets. The IAM role should also contain a trust relationship that allows the file transfer protocol-enabled server to access your resources when servicing your users' transfer requests.
"""

update_user(ServerId, UserName; aws_config::AWSConfig=global_aws_config()) = transfer("UpdateUser", Dict{String, Any}("ServerId"=>ServerId, "UserName"=>UserName); aws_config=aws_config)
update_user(ServerId, UserName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = transfer("UpdateUser", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ServerId"=>ServerId, "UserName"=>UserName), args)); aws_config=aws_config)


text:
rand_reward{T<:FloatingPoint}(::Type{T}, dims...) = 1 .- 2*rand(T, dims...)

rand_reward{T<:Integer}(::Type{T}, dims...) = rand(T, dims...)

sum_columns_to_one(a::Array) = a ./ sum(a, 1)

# replace all elements of `a` with 0 where `mask` is `false`
function zero_mask!{T}(a::AbstractArray{T,3}, mask::AbstractArray{Bool,2})
    all(sum(mask, 1) .> 0) ||
        error("All columns of mask must have at least one 'true' value.")
    size(mask) == size(a)[1:2] ||
        error("Mask size must be `states`×`states`.")
    for k = 1:size(a)[3]
        setindex!(sub(a, :, :, k), zero(T), find(!mask))
    end
end

function zero_mask!{T}(a::AbstractArray{T,3}, mask::AbstractArray{Bool,3})
    all(sum(mask, 1) .> 0) ||
        error("All columns of mask must have at least one 'true' value.")
    size(mask) == size(a) ||
        error("Mask size must be `states`×`states`×`actions`.")
    setindex!(a, zero(T), find(!mask))
end

function random{P<:FloatingPoint,R<:Real,N}(
    ::Type{P},
    ::Type{R},
    states,
    actions,
    mask::Nullable{Array{Bool,N}},
)
    transition = rand(P, states, states, actions)
    isnull(mask) ? nothing : zero_mask!(transition, get(mask))
    transition = sum_columns_to_one(transition)
    reward = rand_reward(R, states, actions)
    (transition, reward)
end

random{P,R}(::Type{P}, ::Type{R}, states, actions, mask::Array{Bool}) =
    random(P, R, states, actions, Nullable(mask))

random{P,R}(::Type{P}, ::Type{R}, states, actions) =
    random(P, R, states, actions, Nullable{Array{Bool,1}}())

random{N}(states, actions, mask::Nullable{Array{Bool,N}}) =
    random(Float64, Float64, states, actions, mask)

random(states, actions, mask::Array{Bool}) =
 random(states, actions, Nullable(mask))

random(states, actions) = random(states, actions, Nullable{Array{Bool,1}}())


text:
#!/usr/bin/env julia

#load path to qjulia home directory
push!(LOAD_PATH, joinpath(@__DIR__, "..", "core"))
push!(LOAD_PATH, joinpath(@__DIR__, "..", "libs/quda-routines"))
push!(LOAD_PATH, joinpath(@__DIR__, "..", "libs/scidac-routines"))
push!(LOAD_PATH, joinpath(@__DIR__, "..", "main/fields"))

import QJuliaBlas
import QJuliaReduce
import QJuliaUtils
import QJuliaEnums
import QJuliaInterface
import QJuliaGaugeUtils
import QJuliaComms
import QJuliaSolvers
import QUDARoutines
import SCIDACRoutines

using Random
using LinearAlgebra
using MPI

#create function/type alias
double  = Float64
float   = Float64

load_config_from_file = "/home/astrel/Configs/wl_5p5_x2p38_um0p4125_cfg_1000.lime"

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

[QJuliaUtils.gridsize_from_cmdline[i] = 1 for i = 1:length(QJuliaUtils.gridsize_from_cmdline)]
QJuliaUtils.get_rank_order("col")

#initialize MPI
MPI.Init()

QUDARoutines.initCommsGridQuda_qj(length(QJuliaUtils.gridsize_from_cmdline), QJuliaUtils.gridsize_from_cmdline, QJuliaUtils.lex_rank_from_coords_t_c, C_NULL)

QUDARoutines.initQuda_qj(0)

Random.seed!(2019)

solve_unit_source = true

const lx = 16
const ly = 16
const lz = 16
const lt = 64
const ls = 1

const dim = 4
const vol = lx*ly*lz*lt*ls

#field latt point sizes
const ssize = 12
const gsize = 9

const splen = vol*ssize
const gflen = vol*gsize

const sp_real_len = 2*vol*ssize
const sp_real_parity_len = Int(sp_real_len / 2)

sp_in = Vector{Complex{Float64}}(undef, splen)
sp_ou = Vector{Complex{Float64}}(undef, splen)
gauge = Matrix{Complex{Float64}}(undef, gflen, 4)

if solve_unit_source == false
  QJuliaUtils.gen_random_spinor!(sp_in)
else
  QJuliaUtils.gen_unit_spinor!(sp_ou)
end

gauge_param = QJuliaInterface.QJuliaGaugeParam_qj()
gauge_param.X = (lx, ly, lz, lt)
gauge_param.cpu_prec   = QJuliaEnums.QJULIA_DOUBLE_PRECISION
gauge_param.t_boundary = QJuliaEnums.QJULIA_PERIODIC_T
gauge_param.gtype      = QJuliaEnums.QJULIA_WILSON_LINKS
gauge_param.anisotropy = 2.38

gauge_param.cuda_prec                     = QJuliaEnums.QJULIA_DOUBLE_PRECISION
gauge_param.reconstruct                   = QJuliaEnums.QJULIA_RECONSTRUCT_12
gauge_param.cuda_prec_sloppy              = QJuliaEnums.QJULIA_SINGLE_PRECISION
gauge_param.reconstruct_sloppy            = QJuliaEnums.QJULIA_RECONSTRUCT_12
gauge_param.cuda_prec_precondition        = QJuliaEnums.QJULIA_DOUBLE_PRECISION
gauge_param.reconstruct_precondition      = QJuliaEnums.QJULIA_RECONSTRUCT_12
gauge_param.reconstruct_refinement_sloppy = QJuliaEnums.QJULIA_RECONSTRUCT_12
gauge_param.cuda_prec_refinement_sloppy   = QJuliaEnums.QJULIA_HALF_PRECISION

#println("======= Gauge parameters =======")
#QJuliaInterface.printQudaGaugeParam_qj(gauge_param)

#load configuration from file or generate random one:
gauge_load_type = 1
if load_config_from_file != ""
  Xdims = Vector{Cint}(undef, 4)
  for i in 1:length(Xdims); Xdims[i] = gauge_param.X[i] ; end
  qio_prec = Cint(8) #gauge_param.cuda_prec

  SCIDACRoutines.QMPInitComms_qj(0, C_NULL, QJuliaUtils.gridsize_from_cmdline)
  SCIDACRoutines.read_gauge_field_qj(load_config_from_file, gauge, qio_prec, Xdims, 0, C_NULL)
  gauge_load_type = 2
end
QJuliaGaugeUtils.construct_gauge_field!(gauge, gauge_load_type, gauge_param)

gauge_param.gtype       = QJuliaEnums.QJULIA_SU3_LINKS 		#currently cannot set QJULIA_WILSON_LINKS (=QJULIA_SU3_LINKS)  for QUDA

x_face_size = gauge_param.X[2]*gauge_param.X[3]*Int(gauge_param.X[4]/2);
y_face_size = gauge_param.X[1]*gauge_param.X[3]*Int(gauge_param.X[4]/2);
z_face_size = gauge_param.X[1]*gauge_param.X[2]*Int(gauge_param.X[4]/2);
t_face_size = gauge_param.X[1]*gauge_param.X[2]*Int(gauge_param.X[3]/2);

gauge_param.ga_pad = max(x_face_size, y_face_size, z_face_size, t_face_size);

QUDARoutines.loadGaugeQuda_qj(gauge, gauge_param)

#Check plaquette
plaq = Array{Cdouble, 1}(undef, 3)
QUDARoutines.plaqQuda_qj(plaq)
println("Computed plaquette is ", plaq[1], ", (spatial = ",  plaq[2], ", temporal = ", plaq[3], ")")

mass = -0.4125
#mass = -0.95

inv_param = QJuliaInterface.QJuliaInvertParam_qj()
inv_param.residual_type = QJuliaEnums.QJULIA_L2_RELATIVE_RESIDUAL
#println("======= Invert parameters =======")
#QJuliaInterface.printQudaInvertParam_qj(inv_param)

inv_param.mass = mass
inv_param.kappa = 1.0 / (2.0 * (1.0 + 3.0/gauge_param.anisotropy + mass))
inv_param.maxiter = 200
inv_param.tol  = 1e-9

inv_param.cuda_prec = QJuliaEnums.QJULIA_DOUBLE_PRECISION
inv_param.cuda_prec_sloppy = QJuliaEnums.QJULIA_SINGLE_PRECISION
inv_param.cuda_prec_precondition = QJuliaEnums.QJULIA_HALF_PRECISION
inv_param.solution_type = QJuliaEnums.QJULIA_MATPC_SOLUTION
#inv_param.inv_type = QJuliaEnums.QJULIA_PIPEPCG_INVERTER
inv_param.inv_type = QJuliaEnums.QJULIA_FCG_INVERTER

println("Kappa = ",  inv_param.kappa)

mdagm(out, inp)    = QUDARoutines.MatDagMatQuda_qj(out, inp, inv_param)
mat(out, inp)    = QUDARoutines.MatQuda_qj(out, inp, inv_param)
Doe(out, inp)      = QUDARoutines.dslashQuda_qj(out, inp, inv_param, QJuliaEnums.QJULIA_EVEN_PARITY)
Deo(out, inp)      = QUDARoutines.dslashQuda_qj(out, inp, inv_param, QJuliaEnums.QJULIA_ODD_PARITY )

# Setup preconditioner
precond_param = QJuliaInterface.QJuliaInvertParam_qj()

precond_param.residual_type            = QJuliaEnums.QJULIA_L2_RELATIVE_RESIDUAL
#precond_param.inv_type                 = QJuliaEnums.QJULIA_PIPECG_INVERTER
#precond_param.inv_type                 = QJuliaEnums.QJULIA_INVALID_INVERTER
precond_param.inv_type                 = QJuliaEnums.QJULIA_LANMR_INVERTER #wroks for naive and fails for pipelined
precond_param.dslash_type_precondition = QJuliaEnums.QJULIA_WILSON_DSLASH
precond_param.kappa                    = 1.0 / (2.0 * (1 + 3/gauge_param.anisotropy + mass))
precond_param.cuda_prec                = QJuliaEnums.QJULIA_DOUBLE_PRECISION
precond_param.cuda_prec_sloppy         = QJuliaEnums.QJULIA_SINGLE_PRECISION
precond_param.cuda_prec_precondition   = QJuliaEnums.QJULIA_DOUBLE_PRECISION
precond_param.solution_type            = QJuliaEnums.QJULIA_MATPC_SOLUTION
precond_param.maxiter                  = precond_param.inv_type == QJuliaEnums.QJULIA_PCG_INVERTER ? 30 : 10
precond_param.Nsteps    	       = 1

mdagmPre(out, inp)  = QUDARoutines.MatDagMatQuda_qj(out, inp, precond_param)

pre_solv_param = QJuliaSolvers.QJuliaSolverParam_qj()

pre_solv_param.inv_type  = precond_param.inv_type
pre_solv_param.tol       = 1e-2
#
pre_solv_param.maxiter   = precond_param.maxiter
pre_solv_param.Nsteps    = 1
pre_solv_param.global_reduction = false

K(out, inp) = QJuliaSolvers.solve(out, inp, mdagmPre, mdagmPre, pre_solv_param)

x_even = view(reinterpret(double, sp_ou), 1:sp_real_parity_len)
x_odd  = view(reinterpret(double, sp_ou), sp_real_parity_len+1:sp_real_len)

b_even = view(reinterpret(double, sp_in), 1:sp_real_parity_len)
b_odd  = view(reinterpret(double, sp_in), sp_real_parity_len+1:sp_real_len)

tmpl_src_norm = norm(sp_ou)

if solve_unit_source == true
  mat(sp_in, sp_ou)
  sp_ou .=@. 0.0
end

init_src_norm = norm(sp_in)
println("Initial source norm:: ", init_src_norm, " , template src norm is: ", tmpl_src_norm)

#Auxiliary field
tmp = Vector{double}(undef, sp_real_len)

t_even = view(tmp, 1:sp_real_parity_len)
t_odd  = view(tmp, sp_real_parity_len+1:sp_real_len)

#random intial guess
#QJuliaUtils.gen_random_spinor!(sp_ou, splen)

#prepare source/solution:
if inv_param.matpc_type == QJuliaEnums.QJULIA_MATPC_EVEN_EVEN
  # src = b_e + k D_eo b_o
  Deo(t_even, b_odd)
  x_odd .=@. b_even + inv_param.kappa*t_even
end

#
init_prec_src_norm = norm(x_odd)
#
println("Initial precondtioned source norm:: ", init_prec_src_norm, " , requested tolerance: ", inv_param.tol)

solv_param = QJuliaSolvers.QJuliaSolverParam_qj()
# Set up parameters
solv_param.inv_type               = inv_param.inv_type
solv_param.inv_type_precondition  = precond_param.inv_type
solv_param.tol                    = inv_param.tol
#
solv_param.maxiter                = inv_param.maxiter
solv_param.delta                  = 1e-2
solv_param.nKrylov                = 4 #8 is very good for unit source
solv_param.Nsteps                 = 2

if precond_param.inv_type != QJuliaEnums.QJULIA_INVALID_INVERTER
  QJuliaSolvers.solve(x_even, x_odd, mdagm, mdagm, solv_param, K)
else
  QJuliaSolvers.solve(x_even, x_odd, mdagm, mdagm, solv_param)
end

#compute true residual:
r = t_odd
mdagm(r, x_even)
r  .=@. x_odd - r
r2 = dot(r, r)
println("True residual norm: ", sqrt(r2))

#reconstruct source/solution:
if inv_param.matpc_type == QJuliaEnums.QJULIA_MATPC_EVEN_EVEN
  # x_o = b_o + k D_oe x_e
  Doe(t_odd, x_even)
  x_odd .=@. b_odd + inv_param.kappa*t_odd
end

if solve_unit_source == true
  QJuliaUtils.gen_unit_spinor!(sp_in)
  sp_ou .=@. sp_in - sp_ou
  error_norm = norm(sp_ou)
  println("Solution error: ", error_norm)
end

QUDARoutines.endQuda_qj()
MPI.Finalize()

max_stars_repo_name: alexstrel/QJulia

max_issues_repo_name: alexstrel/QJulia

max_forks_repo_name: alexstrel/QJulia


text:
# define orbit by its length and minimum value
mutable struct Orbit{T<:AbstractFloat}
    β::Real
    length::Int
    min::T
    b::Float64
end

# two orbits are equivalent when their βs, length and min agree
function Base.:(==)(o1::Orbit{T},o2::Orbit{T}) where T
    (o1.β == o2.β) && (o1.length == o2.length) && (o1.min == o2.min)
end

# two equivalent orbits added adds their basins
function Base.:(+)(o1::Orbit{T},o2::Orbit{T}) where T
    @assert o1 == o2 "$o1 != $o2."
    o1.b += o2.b
    return o1
end

# addition without uniqueness check
function unsafe_add(o1::Orbit{T},o2::Orbit{T}) where T
    o1.b += o2.b
    return o1
end

# return index of first element in x equal to y
function findin(x::Array{T,1},y::T) where T
    @inbounds for i in 1:length(x)
        x[i] == y && return i
    end
end

# orbit array reduction methods for distributed calculation
# check for uniqueness and extend orbit array if so
reduce_orbits(x::Orbit{T},y::Orbit{T}) where T = x == y ? [unsafe_add(x,y)] : [x,y]

function reduce_orbits(x::Orbit{T},y::Array{Orbit{T},1}) where T
    if x in y
        y[findin(y,x)] += x
        return y
    else
        return push!(y,x)
    end
end

function reduce_orbits(x::Array{Orbit{T},1},y::Orbit{T}) where T
    if y in x
        x[findin(x,y)] += y
        return x
    else
        return push!(x,y)
    end
end

function reduce_orbits(x::Array{Orbit{T},1},y::Array{Orbit{T},1}) where T
    for o in x
        y = reduce_orbits(o,y)
    end
    return y
end

# convert a single orbit to a Vector{Orbit{T}}
reduce_orbits(x::Array{Orbit{T},1}) where T = x
reduce_orbits(x::Orbit{T}) where T = [x]

function normalise_basins!(orbits::Array{Orbit{T},1}) where T
    s = 0.0
    for o in orbits
        s += o.b
    end
    for o in orbits
        o.b /= s
    end
end

# define < for sorting
function Base.isless(o1::Orbit{T},o2::Orbit{T}) where T
    o1.length < o2.length
end

function Base.show(io::IO, o::Orbit{T}) where T

    l = @sprintf("%6d",o.length)
    m = @sprintf("%16s",repr(o.min))
    b = @sprintf("%22s",repr(o.b))

    print(io,"Orbit{$T,β=$(repr(o.β))}(length=$l, min=$m, basin=$b)")
end

max_stars_repo_name: milankl/BernoulliMap

max_issues_repo_name: milankl/BernoulliMap

max_forks_repo_name: milankl/BernoulliMap


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

mutable struct PrivateLinkServiceConnectionProperties <: SwaggerModel
    provisioningState::Any # spec type: Union{ Nothing, ProvisioningState } # spec name: provisioningState
    privateLinkServiceId::Any # spec type: Union{ Nothing, String } # spec name: privateLinkServiceId
    groupIds::Any # spec type: Union{ Nothing, Vector{String} } # spec name: groupIds
    requestMessage::Any # spec type: Union{ Nothing, String } # spec name: requestMessage
    privateLinkServiceConnectionState::Any # spec type: Union{ Nothing, PrivateLinkServiceConnectionState } # spec name: privateLinkServiceConnectionState

    function PrivateLinkServiceConnectionProperties(;provisioningState=nothing, privateLinkServiceId=nothing, groupIds=nothing, requestMessage=nothing, privateLinkServiceConnectionState=nothing)
        o = new()
        validate_property(PrivateLinkServiceConnectionProperties, Symbol("provisioningState"), provisioningState)
        setfield!(o, Symbol("provisioningState"), provisioningState)
        validate_property(PrivateLinkServiceConnectionProperties, Symbol("privateLinkServiceId"), privateLinkServiceId)
        setfield!(o, Symbol("privateLinkServiceId"), privateLinkServiceId)
        validate_property(PrivateLinkServiceConnectionProperties, Symbol("groupIds"), groupIds)
        setfield!(o, Symbol("groupIds"), groupIds)
        validate_property(PrivateLinkServiceConnectionProperties, Symbol("requestMessage"), requestMessage)
        setfield!(o, Symbol("requestMessage"), requestMessage)
        validate_property(PrivateLinkServiceConnectionProperties, Symbol("privateLinkServiceConnectionState"), privateLinkServiceConnectionState)
        setfield!(o, Symbol("privateLinkServiceConnectionState"), privateLinkServiceConnectionState)
        o
    end
end # type PrivateLinkServiceConnectionProperties

const _property_map_PrivateLinkServiceConnectionProperties = Dict{Symbol,Symbol}(Symbol("provisioningState")=>Symbol("provisioningState"), Symbol("privateLinkServiceId")=>Symbol("privateLinkServiceId"), Symbol("groupIds")=>Symbol("groupIds"), Symbol("requestMessage")=>Symbol("requestMessage"), Symbol("privateLinkServiceConnectionState")=>Symbol("privateLinkServiceConnectionState"))
const _property_types_PrivateLinkServiceConnectionProperties = Dict{Symbol,String}(Symbol("provisioningState")=>"ProvisioningState", Symbol("privateLinkServiceId")=>"String", Symbol("groupIds")=>"Vector{String}", Symbol("requestMessage")=>"String", Symbol("privateLinkServiceConnectionState")=>"PrivateLinkServiceConnectionState")
Base.propertynames(::Type{ PrivateLinkServiceConnectionProperties }) = collect(keys(_property_map_PrivateLinkServiceConnectionProperties))
Swagger.property_type(::Type{ PrivateLinkServiceConnectionProperties }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_PrivateLinkServiceConnectionProperties[name]))}
Swagger.field_name(::Type{ PrivateLinkServiceConnectionProperties }, property_name::Symbol) =  _property_map_PrivateLinkServiceConnectionProperties[property_name]

function check_required(o::PrivateLinkServiceConnectionProperties)
    true
end

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


text:
module Replication

using Agents
using Distributed
using JLD2
@everywhere using ProgressMeter

"""
	generate_filename(prefix="")

Generate filename from list of parameters.
"""
function generate_filename(prefix=""; kwargs...)
    kwargs_str = [
        begin
            k = replace(string(k), r"[-_ ]" => "+")
            v = last(splitdir(string(v)))
            "{$(k)_$(v)}"
        end for (k, v) in kwargs
    ]
    if !isempty(prefix)
        kwargs_str = [prefix; kwargs_str...]
    end
    return join(kwargs_str, "_")
end

function replication(
    init_model::Function,
    agent_step!,
    model_step!,
    steps,
    n::Integer;
    post_process=(adf, mdf) -> (adf, mdf),
    seed_offset=0,
    adata,
    mdata,
    kwargs...,
)
    kwargs = Dict(kwargs)
    delete!(kwargs, :seed)
    models = ([seed => init_model(; seed=seed + seed_offset, kwargs...) for seed in 1:n])
    data = @showprogress pmap(models) do (seed, model)
        adf, mdf = run!(model, agent_step!, model_step!, steps; adata=adata, mdata=mdata)
        df = post_process(adf, mdf)
        seed => df
    end
    return Dict(data)
end

end

max_stars_repo_name: ndgnuh/RiceBPH

max_issues_repo_name: ndgnuh/RiceBPH

max_forks_repo_name: ndgnuh/RiceBPH


text:
# Julia wrapper for header: /opt/ffmpeg/include/libavutil/hash.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

export
    av_hash_alloc,
    av_hash_names,
    av_hash_get_name,
    av_hash_get_size,
    av_hash_init,
    av_hash_update,
    av_hash_final,
    av_hash_final_bin,
    av_hash_final_hex,
    av_hash_final_b64,
    av_hash_freep

function av_hash_alloc(ctx,name)
    ccall((:av_hash_alloc,libavutil),Cint,(Ptr{Ptr{AVHashContext}},Ptr{Uint8}),ctx,name)
end

function av_hash_names(i::Integer)
    ccall((:av_hash_names,libavutil),Ptr{Uint8},(Cint,),i)
end

function av_hash_get_name(ctx)
    ccall((:av_hash_get_name,libavutil),Ptr{Uint8},(Ptr{AVHashContext},),ctx)
end

function av_hash_get_size(ctx)
    ccall((:av_hash_get_size,libavutil),Cint,(Ptr{AVHashContext},),ctx)
end

function av_hash_init(ctx)
    ccall((:av_hash_init,libavutil),Void,(Ptr{AVHashContext},),ctx)
end

function av_hash_update(ctx,src,len::Integer)
    ccall((:av_hash_update,libavutil),Void,(Ptr{AVHashContext},Ptr{Uint8},Cint),ctx,src,len)
end

function av_hash_final(ctx,dst)
    ccall((:av_hash_final,libavutil),Void,(Ptr{AVHashContext},Ptr{Uint8}),ctx,dst)
end

function av_hash_final_bin(ctx,dst,size::Integer)
    ccall((:av_hash_final_bin,libavutil),Void,(Ptr{AVHashContext},Ptr{Uint8},Cint),ctx,dst,size)
end

function av_hash_final_hex(ctx,dst,size::Integer)
    ccall((:av_hash_final_hex,libavutil),Void,(Ptr{AVHashContext},Ptr{Uint8},Cint),ctx,dst,size)
end

function av_hash_final_b64(ctx,dst,size::Integer)
    ccall((:av_hash_final_b64,libavutil),Void,(Ptr{AVHashContext},Ptr{Uint8},Cint),ctx,dst,size)
end

function av_hash_freep(ctx)
    ccall((:av_hash_freep,libavutil),Void,(Ptr{Ptr{AVHashContext}},),ctx)
end


text:
"""
    list(x)

Create list monad, which is really just a 1-dimensional array.
"""
list(x::AbstractVector) = x
list(x::T) where T = T[x]

# fmap of a list monad just maps over every element
fmap(f::Function, x::AbstractVector) = map(f, x)

"""
    flatten(x)

Flatten a list x.

# Example
```jldoctest
julia> flatten([1, [2,3], [4, [5], 6]])
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6
```
"""
flatten

# dispatch by length of array - Val(0) for empty array, Val(1) otherwise
flatten(x::AbstractVector{T}) where T = flatten(lenval(x), x)

# returns singleton type
lenval(x::AbstractVector{T}) where T = length(x) == 0 ? Val(0) : Val(1)

# empty array - nothing to flatten
flatten(::Val{0}, x::AbstractVector{T}) where T = x

# non-empty array - flatten every element and combine them together
flatten(::Val{1}, x::AbstractVector{T}) where T = reduce(vcat, map(flatten, x))

# non-array - nothing to flatten
flatten(x) = x


text:
import AQFED.Black: blackScholesFormula
import AQFED.TermStructure: CapitalizedDividend, futureValue
export priceEuropean

function priceEuropean(
    p::DeelstraBasketPricer,
    isCall::Bool,
    strike::Number,
    rawForward::Number, #The raw forward to τ (without cash dividends)
    variance::Number,
    τ::Number,
    discountDf::Number, #discount factor to payment date
    dividends::Vector{CapitalizedDividend},
)
    if length(dividends) == 0
        return blackScholesFormula(isCall, strike, spot, variance, spot / rawForward, discountDf)
    elseif length(dividends) == 1 && dividends[1].dividend.exDate < sqrt(eps(Float64))
        forward = rawForward - futureValue(dividends[1])
        return blackScholesFormula(isCall, strike, forward, variance, one(Float64), discountDf)
    end

    sumDiv = sum(futureValue(cd) for cd in dividends)
    n = length(dividends) + 1
    weight = ones(Number, n)
    spots = ones(Number, n)
    tvar = zeros(Number, n)
    dfAsset = discountDf
    forwards = zeros(Number, n)
    for i = 1:n-1
        spots[i] = dividends[i].dividend.amount
        forwards[i] = futureValue(dividends[i]) #dividends[i].dividend.amount/dividends[i].capitalizationFactor #-r
        tvar[i] = variance / τ * dividends[i].dividend.exDate
    end
    spots[n] = strike
    forwards[n] = strike
    tvar[n] = variance
    correlation = zeros(Number, (n, n))
    for (i, vi) in enumerate(tvar)
        for j = 1:(i-1)
            vj = tvar[j]
            if vi != 0 && vj != 0
                correlation[i, j] = min(vi, vj) / sqrt(vi * vj)
                # else is zero
            end
        end
        correlation[i, i] = one(Float64)
    end
    for i = 1:n
        for j = i+1:n
            correlation[i, j] = correlation[j, i]
        end
    end
    priceFixed = priceEuropean(p, !isCall, rawForward, dfAsset, spots, forwards, tvar, weight, correlation)

    if isCall
        return priceFixed
    else
        forward = priceEuropean(p, true, 0.0, rawForward, variance, τ, discountDf, dividends)
        return priceFixed - (forward - strike) * discountDf
    end
end


text:
function ITRFVersionLoader()
    return ITRFVersionLoader(())
end

function ITRFVersionLoader(arg0::JString)
    return ITRFVersionLoader((JString,), arg0)
end

function ITRFVersionLoader(arg0::JString, arg1::DataProvidersManager)
    return ITRFVersionLoader((JString, DataProvidersManager), arg0, arg1)
end

function get_configuration(obj::ITRFVersionLoader, arg0::JString, arg1::jint)
    return jcall(obj, "getConfiguration", ITRFVersionLoader_ITRFVersionConfiguration, (JString, jint), arg0, arg1)
end


text:
import WaterLily
using WaterLily: AutoBody, Simulation
using GeometricMultigrid: Poisson,FieldVector
using LinearAlgebra: norm2

function poisson_setup!(a)
    a.u⁰ .= a.u; a.u .= 0
    WaterLily.conv_diff!(a.f,a.u⁰,ν=a.ν)
    WaterLily.BDIM!(a); WaterLily.BC!(a.u,a.U)
    WaterLily.@inside a.σ[I] = (WaterLily.div(I,a.u)+a.σᵥ[I])/a.Δt[end]
    a.u .= a.u⁰ # roll-back!
end

function sim_collect_poisson!(sim;Δt=0.1,remeasure)
    a = sim.flow # less typing
    WaterLily.sim_step!(sim,WaterLily.sim_time(sim)+Δt;remeasure)  # ∫ over dt & get new a.p
    WaterLily.measure!(a,sim.body;t=sim.L/sim.U*WaterLily.sim_time(sim)) # get new a.μ₀
    poisson_setup!(a)                            # get new a.σ
    return Poisson(copy(a.μ₀)),FieldVector(copy(a.p)),FieldVector(copy(a.σ))
end

function circle(p=6;Re=250,n=16,m=8,T=Float64)
    radius = 2^(p-2)
    center, ν = radius*m/2, radius/Re
    body = AutoBody((x,t)->norm2(x .- center) - radius)
    return Simulation((n*radius+2,m*radius+2), [1.,0.], radius; ν, body, T)
end

function TGV(p=6;Re=1e5,T=Float64)
    L = 2^p; U = 1; ν = U*L/Re
    function uλ(i,vx)
        x,y,z = @. (vx-1.5)*π/L                # scaled coordinates
        i==1 && return -U*sin(x)*cos(y)*cos(z) # u_x
        i==2 && return  U*cos(x)*sin(y)*cos(z) # u_y
        return 0.                              # u_z
    end
    return Simulation((L+2,L+2,L+2),zeros(3),L;U,uλ,ν,T)
end

function donut(p=6;Re=1e3,T=Float64)
    n = 2^p
    center,R,r = [n/2,n/2,n/2], n/4, n/16
    ν = R/Re
    body = AutoBody() do xyz,t
        x,y,z = xyz - center
        norm2([x,norm2([y,z])-R])-r
    end
    Simulation((2n+2,n+2,n+2),[1.,0.,0.],R;ν,body,T)
end

using StaticArrays: SVector, @SMatrix
function wing(p=6;Re=250,U=1,amp=π/4,ϵ=0.5,thk=2ϵ+√2,T=Float64)
    L = 2^(p-1)
    sdf(x,t) = norm2(x .- SVector(0.,clamp(x[2],-L/2,L/2)))-thk/2
    function map(x,t)
        α = amp*cos(t*U/L); R = @SMatrix [cos(α) sin(α); -sin(α) cos(α)]
        R * (x.-SVector(3L+L*sin(t*U/L)+0.01,4L))
    end
    body = AutoBody(sdf,map)
    Simulation((6L+2,6L+2),zeros(2),L;U,ν=U*L/Re,body,ϵ,T)
end

using Interpolations
function shark(p=6;k=5.3,A=0.1,St=0.3,Re=1e4,U=1,
              width = [0.02,0.07,0.06,0.048,0.03,0.019,0.01],
              envelope = [0.2,0.21,0.23,0.4,0.88,1.0],T=Float64)
    L = 2^p
    fit = y-> scale(interpolate(y, BSpline(Quadratic(Line(OnGrid())))), range(0,1,length=length(y)))
	thk,amp = fit(width),fit(envelope)
    s(x) = clamp(x[1]/L,0,1)
    sdf(x,t) = norm2(x.-L*SVector(s(x),0.))-L*thk(s(x))
    ω = 2π*St*U/(2A*L)
    function map(x,t)
        xc = x.-L # shift origin
        return xc-SVector(0.,A*L*amp(s(xc))*sin(k*s(xc)-ω*t))
    end
    return Simulation((4L+2,2L+2),[U,0.],L;ν=U*L/Re,body=AutoBody(sdf,map),T)
end

using DataStructures
function create_waterlily(;len=100,Δt=0.1,cases=[circle,TGV,donut,wing,shark],p=6,kw...)
    data = OrderedDict()
    for case ∈ cases
        @show case
        remeasure = case ∈ (wing,shark)
        sim = case(p;kw...)
        case==circle && WaterLily.sim_step!(sim,20)
        case == circle && WaterLily.sim_step!(sim,15)
        data[case] = [sim_collect_poisson!(sim;Δt,remeasure) for i ∈ 1:len]
    end
    return data
end


text:
module RocketSkipCompleteOperatorTest

using Test
using Rocket

include("../test_helpers.jl")

@testset "operator: skip_complete()" begin

    println("Testing: operator skip_complete()")

    run_proxyshowcheck("SkipComplete", skip_complete())

    run_testset([
        (
            source = from(1:5) |> skip_complete(),
            values = @ts([ 1:5 ])
        ),
        (
            source = completed() |> skip_complete(),
            values = @ts()
        ),
        (
            source = faulted(1) |> skip_complete(),
            values = @ts(e(1))
        ),
        (
            source = never() |> skip_complete(),
            values = @ts()
        )
    ])

end

end