text:
function shuffle!(r::AbstractRNG, a::AbstractVector)
	for i = length(a):-1:2
		j=round(Int,floor(rand(r)*i)+1)
		a[i], a[j] = a[j], a[i]
	end
	return a
end

function getSequential(numTP::Int64,gradientOracle)
	indices = [1:numTP;]
	r = MersenneTwister(1)
	while true
		for i in indices
			let j=i
				gg=(x)-> gradientOracle(x,j)
				produce(gg)
			end
		end
		shuffle!(r, indices)
	end
end

function getSequentialR(numTP::Int64,gradientOracle,restoreFunc)
	# println("Start of producer")
	indices = [1:numTP;]
	r = MersenneTwister(1)
	while true
		for i in indices
			let j=i
				# println("before gg assign")
				gg=(x)-> gradientOracle(x,j)
				rf=(cs)-> restoreFunc(cs,j)
				# println("before produce in producer")
				produce((gg,rf))
			end
		end
		shuffle!(r, indices)
	end
end

function getSequentialRFinite(numTP::Int64,gradientOracle,restoreFunc)
	indices = [1:numTP;]
	for i in indices
		let j=i
			gg=(x)-> gradientOracle(x,j)
			rf=(cs)-> restoreFunc(cs,j)
			# println(j)
			produce((gg,rf))
		end
	end
end

function getSequentialFinite(numTP::Int64,gradientOracle)
	indices = [1:numTP;]
	for i in indices
		let j=i
			gg=(x)-> gradientOracle(x,j)
			produce(gg)
		end
	end
end

function getRandom(numTP::Int64,gradientOracle)
    while true
		i = rand(1:numTP)
		let j=i
			gg=(x)-> gradientOracle(x,j)
			produce(gg)
		end
	end
end

function getSampleFunctionAt(j::Int64, gradientOracle)
	(x)-> gradientOracle(x,j)
end


text:
using VortexCollisions
using Test

include("test_functions.jl")

include("test_grid.jl")
include("test_fourier_transform.jl")
include("test_fourier_operators.jl")
include("test_fourier_quadrature.jl")
include("test_trapezoidal_quadrature.jl")
include("test_fokker_planck_operator.jl")
include("test_fokker_planck_operator_kernel.jl")

ext: jl


text:
module Ex5_6c
using FaultDetectionTools
using DescriptorSystems
using LinearAlgebra
using Polynomials
using Test

# Example 5.6c - Solution of an AFDP using AFDSYN
println("Example 5.6c")

# define s as an improper transfer function
s = rtf('s');
# define Gu(s), Gf(s) and Gw(s)
Gu = [(s+1)/(s+2); (s+2)/(s+3)];     # enter Gu(s)
Gw = [1/(s+2); 0];                   # enter Gw(s)
Gf = [(s+1)/(s+2) 0; 0 1];           # enter Gf(s)
p = 2; mu = 1; mw = 1; mf = 2;       # enter dimensions

# setup the synthesis model
sysf = fdimodset(dss([Gu Gf Gw],minimal = true),c =1:mu, f = mu .+ (1:mf), n = (mu+mf) .+ (1:mw));

# call of AFDSYN with the options for stability degree -3 and the synthesis
# of a scalar output filter
Q, Rfw, info = afdsyn(sysf, atol = 1.e-7, minimal = false, nullspace = false, smarg = -2, sdeg = -3,
                      rdim = 1, HDesign = [1 1]); info

println("Q = $(dss2rm(Q.sys, atol = 1.e-7))")
println("Rf = $(dss2rm(Rfw.sys[:,Rfw.faults], atol = 1.e-7))")
println("Rw = $(dss2rm(Rfw.sys[:,Rfw.noise], atol = 1.e-7))")
gap = fdif2ngap(Rfw)[1];
println("gap = $gap")
β = fdiscond(Rfw)[1];
println("scond = $β")
mmperf = fdimmperf(Rfw);
println("mmperf = $mmperf")

# check synthesis results
R = fdIFeval(Q, sysf; minimal = true, atol = 1.e-7)
@test iszero(R.sys[:,[R.controls; R.disturbances]], atol = 1.e-7) &&
      iszero(R.sys[:,[R.faults;R.noise]]-Rfw.sys[:,[Rfw.faults;Rfw.noise]]) &&
      fdisspec(Rfw, block = true) == Bool[1 1] &&
      maximum(real(gpole(Q))) >= -3 && minimum(real(gpole(Q))) <= -3 &&
      gap ≈ info.gap

# alternative least order synthesis
# call of AFDSYN with the options for stability degree -3 and the synthesis
# of a scalar output filter; the choice of HDesign preserves the achieved gap of 3
Q, Rfw, info = afdsyn(sysf, atol = 1.e-7, smarg = -3, sdeg = -3,
         HDesign = [0.1 1]); info

println("Q = $(dss2rm(Q.sys, atol = 1.e-7))")
println("Rf = $(dss2rm(Rfw.sys[:,Rfw.faults], atol = 1.e-7))")
println("Rw = $(dss2rm(Rfw.sys[:,Rfw.noise], atol = 1.e-7))")
gap = fdif2ngap(Rfw)[1]
println("gap = $gap")
β = fdiscond(Rfw)[1]
println("scond = $β")
mmperf = fdimmperf(Rfw)
println("mmperf = $mmperf")

# check synthesis results
R = fdIFeval(Q, sysf; minimal = true, atol = 1.e-7)
@test iszero(R.sys[:,[R.controls; R.disturbances]], atol = 1.e-7) &&
      iszero(R.sys[:,[R.faults;R.noise]]-Rfw.sys[:,[Rfw.faults;Rfw.noise]]) &&
      fdisspec(Rfw, block = true) == Bool[1 1] &&
      gpole(Q) ≈ [-3] &&
      gap ≈ info.gap

end # module

max_stars_repo_name: andreasvarga/FaultDetectionTools

max_issues_repo_name: andreasvarga/FaultDetectionTools

max_forks_repo_name: andreasvarga/FaultDetectionTools


text:
using FANN
using Base.Test

net = ANN([2, 2, 1], [:sigmoid, :linear])

# xor data, in a n_features x n_observation matrix
X = [ 1.0 1.0 0.0 0.0 ;
	  1.0 0.0 1.0 0.0 ]

# desired ouputs
y = [1.0 0.0 0.0 1.0]

# create dataset
dset = DataSet(X, y)

# train
train!(net, dset,
	   max_epochs=100000,
	   epochs_between_reports=0,
	   desired_error=1e-5)

@test sumabs2(predict(net, X) - y) < 100*1e-5


text:
module UndefinedMetaMacro

"!!undefined()"
undefined = ()

end


text:
#JuliaRL/src/A2C.jl

using ReinforcementLearning
using PyCall
using ReinforcementLearningEnvironments
using Random
using Flux
using TensorBoardLogger
using Dates
using Logging
using BSON
using Suppressor
include("./conf.jl")
include("./shared.jl")

"""
    runA2Csave_dir, landing_factor=1, leg_first_bonus=0)

Trains the modified LunarLander agent using A2C
from the ReinforcementLearning library.
Results will be saved at `save_dir`.

Using the default values for landing_factor and leg_first_bonus
will make the environement behave like the original LunarLander.
For more information, see the JuliaRL/CustomGym/CustomGym/lunar_lander.py file.
"""
function runA2C(save_dir::T, landing_factor=1, leg_first_bonus=0) where {T<:AbstractString}
    # clear save_dir directory
    isdir(save_dir) && rm(save_dir; force=true, recursive=true)

    lg = TBLogger(joinpath(save_dir, "tb_log"), min_level = Logging.Info)
    rng = MersenneTwister(123)

    N_ENV = 16
    UPDATE_FREQ = 10
    env = MultiThreadEnv([
        LunarLander(landing_factor, leg_first_bonus) for i in 1:N_ENV
    ])

    ns, na = length(get_state(env[1])), length(get_actions(env[1]))

    # RLBase.reset!(env, is_force = true)
    agent = Agent(
        policy = QBasedPolicy(
            learner = A2CLearner(
                approximator = ActorCritic(
                    actor = small_net_model(ns, na),
                    critic = small_net_model(ns, 1),
                    optimizer = ADAM(),
                ) |> cpu,
                γ = 0.99f0,
                actor_loss_weight = 1.0f0,
                critic_loss_weight = 0.5f0,
                entropy_loss_weight = 0.001f0,
            ),
            explorer = BatchExplorer(GumbelSoftmaxExplorer()),#= seed = nothing =#
        ),
        trajectory = CircularCompactSARTSATrajectory(;
            capacity = UPDATE_FREQ,
            state_type = Float32,
            state_size = (ns, N_ENV),
            action_type = Int,
            action_size = (N_ENV,),
            reward_type = Float32,
            reward_size = (N_ENV,),
            terminal_type = Bool,
            terminal_size = (N_ENV,),
        ),
    )
    stop_condition = StopAfterStep(Conf.duration)
    total_reward_per_episode = TotalBatchRewardPerEpisode(N_ENV)
    time_per_step = TimePerStep()
    hook = ComposedHook(
        total_reward_per_episode,
        time_per_step,
        DoEveryNStep() do t, agent, env
            with_logger(lg) do
                @info(
                    "training_AC",
                    actor_loss = agent.policy.learner.actor_loss,
                    critic_loss = agent.policy.learner.critic_loss,
                    entropy_loss = agent.policy.learner.entropy_loss,
                    loss = agent.policy.learner.loss,
                )
                for i in 1:length(env)
                    if get_terminal(env[i])
                        @info "training_AC" reward = total_reward_per_episode.rewards[i][end] log_step_increment =
                            0
                        break
                    end
                end
            end
        end,
        DoEveryNStep(Conf.save_freq) do t, agent, env
            RLCore.save(save_dir, agent)
            BSON.@save joinpath(save_dir, "stats.bson") total_reward_per_episode time_per_step
        end,
    )

    infos = @timeRet run(agent, env, stop_condition, hook)
    log_training_info(infos, agent, save_dir)
end

max_stars_repo_name: FeLusiani/JuliaRL

max_issues_repo_name: FeLusiani/JuliaRL

max_forks_repo_name: FeLusiani/JuliaRL


text:
using TuringModels
using Test

TestDir = @__DIR__
testfiles = readdir(joinpath(TestDir, "..", "scripts"))

@testset "TuringModels" begin
    exclude_testfiles = "non-identifiable.jl"

    for tf in testfiles
        if tf !in exclude_testfiles
            println("\n\ntesting $tf.\n")
            include("../scripts/$tf")
        end
    end
end


text:
using Interpolations
using QuadGK
using Jacobi
using Plots

function polynomial_decomposition(f, xs, ops; w=one, rtol=1e-8)
    x1, x2 = minimum(xs), maximum(xs)
    ys = f.(xs)
    ℑf = interpolate((xs,), ys, Gridded(Linear()))

    numerators = [quadgk(x -> ℑf(x) * op(x) * w(x), x1, x2, rtol=rtol)[1] for op in ops]
    denominators = [quadgk(x -> op(x)^2 * w(x), x1, x2, rtol=rtol)[1] for op in ops]
    cs = numerators ./ denominators

    N = length(ops)
    f′(x) = sum(cs[n] * ops[n](x) for n in 1:N)

    return cs, f′
end

@info "Decomposing into Fourier series..."

xs = range(-π, π, length=101)
f(x) = x/π + 2exp(-3(x+2)^2) -  3exp(-6(x-1)^2)

cs_even, ℑf_even = Dict(), Dict()
cs_odd,  ℑf_odd  = Dict(), Dict()
anim = @animate for N in 1:16
    ops_cos = [x -> cos(n*x) for n in 0:N]
    ops_sin = [x -> sin(n*x) for n in 1:N]
    cs_even[N], ℑf_even[N] = polynomial_decomposition(f, xs, ops_cos)
    cs_odd[N],  ℑf_odd[N]  = polynomial_decomposition(f, xs, ops_sin)
    plot(xs, f.(xs), label="", linewidth=2, xlim=(-π, π), title="Fourier series decomposition (N=$N)")
    plot!(xs, ℑf_even[N].(xs) .+ ℑf_odd[N].(xs), label="", linewidth=2)
end
mp4(anim, "fourier_decomposition.mp4", fps=5)
gif(anim, "fourier_decomposition.gif", fps=5)

@info "Decomposing into Legendre series..."

xs = range(-1, 1, length=101)
f(x) = x + 2exp(-2π*(x+2/π)^2) -  3exp(-6π*(x-1/π)^2)

cs, ℑf = Dict(), Dict()
anim = @animate for N in 0:32
    ops = [x -> legendre(x, n) for n in 0:N]
    cs[N], ℑf[N] = polynomial_decomposition(f, xs, ops)
    plot(xs, f.(xs), label="", linewidth=2, xlim=(-1, 1), title="Legendre series decomposition (N=$N)")
    plot!(xs, ℑf[N].(xs), label="", linewidth=2)
end
mp4(anim, "legendre_decomposition.mp4", fps=5)
mp4(anim, "legendre_decomposition.gif", fps=5)

@info "Decomposing into Chebyshev series..."

cs, ℑf = Dict(), Dict()
anim = @animate for N in 0:16
    w(x) = 1 / √(1 - x^2)
    ops = [x -> chebyshev(x, n) for n in 0:N]
    cs[N], ℑf[N] = polynomial_decomposition(f, xs, ops, w=w, rtol=1e-5)
    plot(xs, f.(xs), label="", linewidth=2, xlim=(-1, 1), title="Chebyshev series decomposition (N=$N)")
    plot!(xs, ℑf[N].(xs), label="", linewidth=2)
end
mp4(anim, "chebyshev_decomposition.mp4", fps=5)
mp4(anim, "chebyshev_decomposition.gif", fps=5)


text:
"""
    keyword(mode::BlendMode)
    keyword(op::CompositeOperation)

Return the keyword of `mode` or `op` as a string.

# Example
```jldoctest
julia> keyword(BlendColorDodge)
"color-dodge"

julia> keyword(CompositeSourceOver)
"source-over"
```
"""
keyword(::BlendMode{sym}) where sym = string(sym)
keyword(::CompositeOperation{sym}) where sym = string(sym)


text:
export integrate

function integrate( field :: Array{Float64,2}, mesh :: Mesh )

    nx, ny = mesh.nx, mesh.ny
    dx, dy = mesh.dx, mesh.dy

    sum(view(field,1:nx,1:ny)) * dx * dy

end


text:
#=

    This is a port of the R2 model TrueSkillArray.cs

    Output from the R2 model (skills):
    ```
    [0] Mean: 104.314
    [0] Variance: 71.6896
    [1] Mean: 99.9344
    [1] Variance: 71.7215
    [2] Mean: 92.4195
    [2] Variance: 63.2211
    ```

    Note: The only difference between R2's model TrueSkill_Simple.cs and TrueSkillArray.cs
    is that TrueSkill_Simple.cs get the data from files while TrueSkillArray.cs get the
    data from arrays in the file. The basic models are the same as well as the data
    (3 players and 3 matches).

    Here I simulate a little larger example: 10 players and 20 matches between random players.

    Players: 1:10
    Skills: [101.86991042639397, 99.81168650944693, 84.17600281171374, 99.55322670368798, 91.70866945610942, 99.41376712574124, 90.1144607234882, 96.8904551041217, 116.32792430446636, 103.5346117316912]
    Ranks based on skills (decreasing): [9, 10, 1, 2, 4, 6, 8, 5, 7, 3]
    Games:
    Game 1: [1, 10, 1]
    Game 2: [9, 3, 1]
    Game 3: [3, 2, -1]
    Game 4: [1, 7, -1]
    Game 5: [8, 3, 1]
    Game 6: [5, 6, -1]
    Game 7: [6, 9, -1]
    Game 8: [10, 3, 1]
    Game 9: [4, 2, -1]
    Game 10: [10, 5, 1]
    Game 11: [9, 2, -1]
    Game 12: [6, 2, 1]
    Game 13: [6, 1, 1]
    Game 14: [5, 1, -1]
    Game 15: [10, 6, -1]
    Game 16: [10, 3, 1]
    Game 17: [1, 9, 1]
    Game 18: [3, 2, -1]
    Game 19: [10, 3, 1]
    Game 20: [5, 10, -1]

    Summary Statistics
        parameters       mean       std   naive_se      mcse        ess      rhat   ess_per_sec
            Symbol    Float64   Float64    Float64   Float64    Float64   Float64       Float64

         skills[1]    97.1878    1.0445     0.0330    0.3302     2.1884    3.3300        0.3355
         skills[2]   105.1533    9.6393     0.3048    3.0467     2.1886    3.3293        0.3356
         skills[3]    95.1222    6.0911     0.1926    1.9118     2.2049    3.2117        0.3381
         skills[4]   102.8225    7.4180     0.2346    2.3437     2.1894    3.3231        0.3357
         skills[5]    97.1789    0.4437     0.0140    0.0224   137.7141    1.0058       21.1153
         skills[6]   100.7338    3.2006     0.1012    0.9924     2.2375    3.0112        0.3431
         skills[7]   101.0100    2.4683     0.0781    0.7741     2.2068    3.1994        0.3384
         skills[8]    96.2084    1.0064     0.0318    0.3153     2.2096    3.1808        0.3388
         skills[9]    97.4989    7.2633     0.2297    2.2818     2.2043    3.2137        0.3380
         ⋮              ⋮          ⋮         ⋮          ⋮         ⋮          ⋮           ⋮
                                                                                41 rows omitted

    Skills (based on performance)
    Player 1: 97.1878066434855
    Player 2: 105.15333131925922
    Player 3: 95.12224324765661
    Player 4: 102.82248436052862
    Player 5: 97.17893913871123
    Player 6: 100.73384589924844
    Player 7: 101.01001164175119
    Player 8: 96.20842558248593
    Player 9: 97.49887408357466
    Player 10: 88.48929120951159

    Sorted ranks (decreasing order):
    Rank 1 Player 2
    Rank 2 Player 4
    Rank 3 Player 7
    Rank 4 Player 6
    Rank 5 Player 9
    Rank 6 Player 1
    Rank 7 Player 5
    Rank 8 Player 8
    Rank 9 Player 3
    Rank 10 Player 10

    Cf true_skill.jl

=#

using Turing, StatsPlots, Distributions, StatsBase
using CSV, DataFrames
include("jl_utils.jl")

#
# Simulate skills and games
#
function trueskill_simulate(num_players=5,num_matches=10,skill_mean=100,skill_variance=10,performance_variance=15)
    # This is the real skill for the player
    skills = tzeros(num_players)
    for i in 1:num_players
        skills[i] = rand(Normal(skill_mean,skill_variance))
    end

    games = []
    # Generate <num_matches> random games.
    match = 0
    while match < num_matches
        p1 = rand(1:num_players)
        p2 = rand(1:num_players)
        if p1 != p2
            performance_p1 = rand(Normal(skills[p1],performance_variance))
            performance_p2 = rand(Normal(skills[p2],performance_variance))
            if performance_p1 > performance_p2
                game = [p1,p2,1]
            elseif performance_p1 == performance_p2
                game = [p1,p2,0]
            else
                game = [p1,p2,-1]
            end
            push!(games,game)
            match += 1
        end
    end

    return 1:num_players, skills, hcat(games...)'
end

@model function true_skill_array_r2(players,games)
    num_players = length(players)
    num_games, m = size(games)
    skills ~ filldist(Normal(100,10),num_players)

    performance = Matrix{Real}(undef, num_games,2)
    for i in 1:num_games
        performance[i,1] ~ Normal(skills[games[i,1]],15)
        performance[i,2] ~ Normal(skills[games[i,2]],15)

        if games[i,3] == 1
            true ~ Dirac(performance[i,1] > performance[i,2])
        elseif games[i,3] == 0
            true ~ Dirac(performance[i,1] == performance[i,2])
        else
            true ~ Dirac(performance[i,1] < performance[i,2])
        end
    end

end

num_players = 10
num_matches = 20
skill_mean = 100
skill_variance = 10
performance_variance = 15
players, skills,games = trueskill_simulate(num_players,num_matches,skill_mean,skill_variance, performance_variance)
println("Players: $players")
println("Skills: $skills")
println("Ranks based on skills (decreasing): $(reverse(sortperm(skills)))")
println("Games:")
for i in 1:size(games)[1]
    println("Game $i: $(games[i,:])")
end

model = true_skill_array_r2(players,games)

# chns = sample(model, Prior(), 10_000)
# chns = sample(model, MH(), 1_000)
chns = sample(model, PG(5), 1_000)
# chns = sample(model, SMC(), 1_000)
# chns = sample(model, IS(), 1_000)

# chns = sample(model, NUTS(), 1_000)
# chns = sample(model, HMC(0.1,6), 1_000)

display(chns)

println("\nSkills (based on performance)")
game_skills  = mean(group(chns,:skills))[:,2]
for i in 1:num_players
    println("Player $i: $(game_skills[i])")
end
game_ranks = game_skills |> sortperm |> reverse
println("\nSorted ranks (decreasing order):")
for i in 1:num_players
    println("Rank $i Player $(game_ranks[i])")
end

max_stars_repo_name: tias/hakank

max_issues_repo_name: tias/hakank

max_forks_repo_name: tias/hakank


text:
addprocs(3)
import POPT

@everywhere function widescaleRandomNoiseTL(x::Vector{Float64})
    n = length(x)
    expon = rand()*6 - 4
    displacement = randn(n)
    new_x = x + displacement*10^expon
end

@everywhere function f(x)
	sum(abs.(x))
end

#rosenbrock
@everywhere function g(x)
	score = 0
	for i = 1:(length(x) - 1)
		val = (100*(x[i + 1] - x[i]^2)^2 + (x[i] - 1)^2)
		score = score + val
	end
	score
end

#rastrigin function
@everywhere function r(x)
	A = 10
	return A*length(x) + sum(map(y -> y^2 - A*cos(2*pi*y), x))

end
dims = 50
start_x = 1000*randn(dims)
micro_steps = 100
macro_steps = 10000
temps = [60, 40];
println("---Priming")
val_ep, x_ep, p_val_ep = POPT.epchains(start_x, r, temps, widescaleRandomNoiseTL, 2, 2)
val_bg, x_bg, p_val_bg = POPT.blockingGreedy(start_x, r, temps, widescaleRandomNoiseTL, 2, 2)
(m_1, m_2, b_1, b_2) = POPT.runblock(start_x, r, temps, widescaleRandomNoiseTL, 2, 2)
(m_1, m_2, b_1, b_2) = POPT.runnonblock(start_x, r, temps, widescaleRandomNoiseTL, 2, 2)

#start_x = 1000*randn(dims)
#swap_scheme = [[[1, 2]]]
#@time val_pins1, x_pins1, p_val_pins1 = PTChain.partialGreedyTempering(start_x, f, temps, widescaleRandomNoiseTL, iters, reps, swap_scheme)
#println("partial swapping 1: $(val_pins1)")

#start_x = 1000*randn(dims)
#@time val_p1, x_p1, p_val_p1 = POPT.pINSChain(start_x, f, temps, widescaleRandomNoiseTL, iters, reps, swap_scheme)
#println("partial swapping 1 parallel: $(minimum(val_p1))")

#start_x = 1000*randn(dims)
#@time val_p2, x_p2, p_val_p2 = POPT.pINSChain(start_x, f, temps, widescaleRandomNoiseTL, iters, reps, swap_scheme2)
#println("partial swapping 2 parallel: $(minimum(val_p2))")

println("---Running sequential")
start_x = 1000*randn(dims)
@time val_gt, x_gt, p_val_gt, swaps_made = PTChain.greedyTempering(start_x, r, temps, widescaleRandomNoiseTL, micro_steps, macro_steps)
println("\t Sequential best was: $(val_gt)")
println("\t made $(swaps_made) swaps")

println("---Running blocking greedy")
start_x = 1000*randn(dims)
@time val_bg, x_bg, p_val_bg = POPT.blockingGreedy(start_x, r, temps, widescaleRandomNoiseTL, micro_steps, macro_steps)
println("\t Blocking best was: $(minimum(val_bg))")

println("---Running totally parallel")
start_x = 1000*randn(dims)
@time val_ep, x_ep, p_val_ep = POPT.epchains(start_x, r, temps, widescaleRandomNoiseTL, micro_steps, macro_steps)
println("\t Totally parallel was: $(minimum(val_ep))")

println("---Running non-blocking decentralized")
start_x = 1000*randn(dims)
@time (m_1, m_2, b_1, b_2, s_1, s_2) = POPT.runnonblock(start_x, r, temps, widescaleRandomNoiseTL, micro_steps, macro_steps)
println("\t non-blocking was: $(min(m_1, m_2))")
println("\t made $(s_1) swaps on 1 and $(s_2) swaps on 2")

println("---Running blocking decentralized")
start_x = 1000*randn(dims)
@time (m_1, m_2, b_1, b_2, s_1, s_2) = POPT.runblock(start_x, r, temps, widescaleRandomNoiseTL, micro_steps, macro_steps)
println("\t non-blocking was: $(min(m_1, m_2))")
println("\t made $(s_1) swaps on 1 and $(s_2) swaps on 2")

max_stars_repo_name: jacob-ruth/pt-optimization

max_issues_repo_name: jacob-ruth/pt-optimization

max_forks_repo_name: jacob-ruth/pt-optimization


text:
import Base.Meta: isexpr
import MacroTools: @capture, postwalk

# runs `f()` in an isolated testset, so that it doesn't influence the currently running test suite
function with_isolated_testset(f)
    ts = Test.DefaultTestSet("isolated")
    Test.push_testset(ts)
    try
        mktemp() do path, io
            redirect_stdout(io) do
                f()
            end
        end
    catch err
        rethrow(err)
    finally
        Test.pop_testset()
    end
    return ts
end

macro addfntest(macro_test)
    func_test = postwalk(macro_test) do x
        pat = :(@test_call(args__))
        if @capture(x, $pat)
            if isexpr(x, :macrocall)
                kwargs = map(x->Expr(:kw, x.args...), x.args[findall(x->isexpr(x,:(=)), x.args)])
                testex = x.args[findfirst(x->isexpr(x,:call), x.args)::Int]
                return :(test_call(Base.typesof($(testex.args...)); $(kwargs...)))
            end
        end
        return x
    end

    return quote
        $macro_test
        $func_test
    end
end

# positive case
goodf(var) = var
@addfntest let
    ts = with_isolated_testset() do
        @test_call goodf(10) # ok
    end
    @test ts.n_passed == 1
end

# negative case
# NOTE the following test is line-sensitive !
badf(var) = undefvar
let
    ts = with_isolated_testset() do
        @test_call badf(10)
    end
    @test ts.n_passed == 0
    @test length(ts.results) == 1
    r = ts.results[1]
    @test isa(r, Test.Fail)
    @test r.source === LineNumberNode((@__LINE__)-6, @__FILE__)
end

# actual error within `@test_call`
# NOTE the following test is line-sensitive !
let
    ts = with_isolated_testset() do
        @test_call undeff(10)
    end
    @test ts.n_passed == 0
    @test length(ts.results) == 1
    r = ts.results[1]
    @test isa(r, Test.Error)
    @test r.source === LineNumberNode((@__LINE__)-6, @__FILE__)
    @test occursin("UndefVarError", r.value)
end

# supports `skip` keyword
@addfntest let
    ts = with_isolated_testset() do
        @test_call skip=true badf(10)
    end
    @test ts.n_passed == 0
    @test length(ts.results) == 1
    r = ts.results[1]
    @test isa(r, Test.Broken)
    @test r.test_type === :skipped

    ts = with_isolated_testset() do
        skip = true
        @test_call skip=skip badf(10)
    end
    @test ts.n_passed == 0
    @test length(ts.results) == 1
    r = ts.results[1]
    @test isa(r, Test.Broken)
    @test r.test_type === :skipped
end

# supports `broken` keyword
@addfntest let
    ts = with_isolated_testset() do
        @test_call broken=true badf(10)
    end
    @test ts.n_passed == 0
    @test length(ts.results) == 1
    r = ts.results[1]
    @test isa(r, Test.Broken)
    @test r.test_type === :test_call

    ts = with_isolated_testset() do
        broken = true
        @test_call broken=broken badf(10)
    end
    @test ts.n_passed == 0
    @test length(ts.results) == 1
    r = ts.results[1]
    @test isa(r, Test.Broken)
    @test r.test_type === :test_call

    ts = with_isolated_testset() do
        @test_call broken=true goodf(10)
    end
    @test ts.n_passed == 0
    @test length(ts.results) == 1
    r = ts.results[1]
    @test isa(r, Test.Error)
    @test r.test_type === :test_unbroken
end

# supports JET's configurations
# synced with example used for the `@test_call` docstring
cond = false
function f(n)
    if cond           # `cond` is untyped, and will be reported by the sound analysis pass, while JET's default analysis pass will ignore it
        return sin(n)
    else
        return cos(n)
    end
end
@addfntest let
    ts = with_isolated_testset() do
        @test_call f(10) # ok
    end
    @test ts.n_passed == 1

    ts = with_isolated_testset() do
        @test_call f(10) # still be ok
    end
    @test ts.n_passed == 1

    ts = with_isolated_testset() do
        @test_call mode=:sound f(10)
    end
    @test ts.n_passed == 0
    @test length(ts.results) == 1
    r = ts.results[1]
    @test isa(r, Test.Fail)

    ts = with_isolated_testset() do
        @test_call mode=:sound broken=true f(10)
    end
    @test ts.n_passed == 0
    @test length(ts.results) == 1
    r = ts.results[1]
    @test isa(r, Test.Broken)
end


text:
# ## Ridge
# Ridge回帰の関数は少し煩雑ですが、標準化処理(データの平均値をひいて、標準偏差で割る)
# を行った後に、回帰分析を行っています。 全てが1の値を持つ列を説明変数に入れてしまうと
# 標準偏差(=0)で割るとエラーを吐くので、こういうことをしているのだと思います。
# ```julia
# using StatsBase
# function ridge(X::Matrix,y::Vector,λ=0)
#     @assert λ ≥ 0
#     n,p = size(X)
#     X̄, σ = mean_and_std(X,1) #説明変数の平均と標準偏差を記録
#     ȳ = mean(y) #目的変数については平均値を取得
#     zscore!(X,X̄,σ) #標準化処理
#     y .-= ȳ
#     β = (X'X + n*λ*I(p)) \ X'*y
#     β ./= vec(σ) #X'Xで割っているので、βをσで割っておく
#     β₀ = ȳ .- X̄*β
#     Dict("β" => β, "β₀" => β₀)
# end
# ```
# ### 例48
# 米国犯罪データをRidge回帰します。

using DelimitedFiles, Plots
using Joe:ridge
using Plots.PlotMeasures # hide
Plots.reset_defaults() # hide
default( # hide
    titlefont  = font("JuliaMono", default(:titlefontsize),  ),  # hide
    guidefont  = font("JuliaMono",  default(:guidefontsize),  ), # hide
    tickfont   = font("JuliaMono", default(:tickfontsize),   ), # hide
    legendfont = font("JuliaMono",  default(:legendfontsize), ), # hide
    left_margin = 30px, # hide
    bottom_margin = 30px # hide
) # hide
df = readdlm(joinpath("_assets","data","crime.txt"))
X = df[:,3:7]; y =df[:,1]
λ = 0:0.5:50

_,p = size(X)
β = hcat([ridge(X,y,l)["β"] for l in λ]...)
p48 = plot(size=(500,500),xlims=(0,50),ylims=(-7.5,15),
           xlabel="λ",ylabel="β")
labels=["警察への年間資金                                                 ",
        "25歳以上で高校を卒業した人の割合",
        "16-19歳で高校に通っていない人の割合",
        "18-24歳で大学生の割合",
        "25歳以上で４年制大学を卒業した人の割合"]
for j in 1:p
    global p48, λ, β, labels # hide
    plot!(p48, λ,β[j,:],label=labels[j])
end
savefig(p48,joinpath(@OUTPUT,"fig5-1.svg")) # hide
# \fig{fig5-1}

# ### 例49
# 絶対値を含む関数のプロット
using Plots
x_seq = -2:0.05:2;
p49_1 = plot(x_seq, x -> x^2-3x+abs(x),title = "y=x^2-3x+|x|")
scatter!(p49_1,[1],[-1],color=:red,legend=false)
p49_2 = plot(x_seq,x -> x^2 + x +2abs(x),title="y=x^2+x+2|x|")
scatter!(p49_2,[0],[-0],color=:red, legend=false)
p49 = plot(p49_1,p49_2,layout=(1,2),size= (500,200))
savefig(p49,joinpath(@OUTPUT,"fig5-2.svg")) # hide
# \fig{fig5-2}
# ## Lasso
# lassoのプログラムは標準化処理はridgeと共通しています。
# ### 例50
using Joe:lasso
df = readdlm(joinpath("_assets","data","crime.txt"))
X = df[:,3:7]; y =df[:,1]
λ = 0:0.5:200
_,p = size(X)
β = hcat([lasso(X,y,l)["β"] for l in λ]...)
p50 = plot(size=(500,500),xlims=(0,200),ylims=(-7.5,15),
           xlabel="λ",ylabel="β")
labels=["警察への年間資金                                                 ",
        "25歳以上で高校を卒業した人の割合",
        "16-19歳で高校に通っていない人の割合",
        "18-24歳で大学生の割合",
        "25歳以上で４年制大学を卒業した人の割合"]
for j in 1:p
    global p50, λ, β, labels # hide
    plot!(p50, λ,β[j,:],label=labels[j])
end
savefig(p50,joinpath(@OUTPUT,"fig5-3.svg")) # hide
# \fig{fig5-3}

# ### 例51
# CRANパッケージのglmnetはjuliaにも移植されています。
# ここでは[GLMNet.jl](https://github.com/JuliaStats/GLMNet.jl)を使って、クロスバリデーションによる
# λの最適化を検討します。
using GLMNet
df = readdlm(joinpath("_assets","data","crime.txt"))
X = df[:,3:7]; y =df[:,1]
cv  = glmnetcv(X,y)
# λは20くらいが最適のようです。その時の係数は以下のコードで求められます。
GLMNet.coef(cv)
# 後半の二つは係数が0になって、前半の三つの変数が選択されました。
# Python版の初版では係数の値が違うのですが、
# R版の原著ではこれらの値であまり問題はなさそうです。
# (これはPython版のScikitLearnのLassoCVでは0にされていないですね。
# ScikitLearnが悪いのか？)
# 横軸をlog λ, 縦軸を平均二乗誤差（リボンはσ）にして可視化します。
p51 = plot(xlabel="log λ", ylabel="mean squared error")
plot!(p51,log.(cv.lambda),cv.meanloss,ribbon=cv.stdloss,legend=false)
savefig(p51,joinpath(@OUTPUT,"fig5-8.svg")) # hide
# \fig{fig5-8}
# ### 問55
# 例48のcrime.txtで、今度はScikitLearnのLassoを利用してみることにします。
using ScikitLearn, DelimitedFiles
@sk_import linear_model: Lasso
@sk_import linear_model: LassoCV
df = readdlm(joinpath("_assets","data","crime.txt"))
X = df[:,3:7]; y =df[:,1];
# まずはLassoのインスタンスを作ります。
Las = Lasso(alpha=20)
# キーワード引数のalphaは上の例でいう正則化パラメータλのことです。
# Lasにデータを入力して、$\lambda=20$の時の係数を求めます。
Las.fit(X,y);
Las.coef_
# LassoCVの場合は、複数の$\lambda$の値を与えることができます。
Lcv = LassoCV(alphas=0.1:0.1:30,cv=10)
Lcv.fit(X,y)
Lcv.alpha_
# なんと$\lambda = 30$が最適のようです。
# 係数はどうでしょうか？
Lcv.coef_
# こちらも係数が0に近づいて変数選択されているようには見えません。
# これではめでたしめでたしにはならないので、設定を見直すことにします。
# Lassoオブジェクトのインスタンスを生成する際の、キーワード引数はnormalize=falseとなっています。
# scikit-learnのドキュメントによれば、normalize=trueにすると、
# 平均値をひいたあとに、二乗ノルムで割ることになっているので標準化には使えません。
# StandardScalerを使えと書いてありますが、大した処理ではないので自前で標準化したデータを投げてみます。
using DelimitedFiles, StatsBase
df = readdlm(joinpath("_assets","data","crime.txt"))
X = df[:,3:7]; y =df[:,1];
X̄,σ = mean_and_std(X,1)
XX = zscore(X,X̄,σ)
ȳ = mean(y)
yy = y .- ȳ
Lcv2 = LassoCV(alphas=0.1:0.1:30,cv=10)
Lcv2.fit(XX,yy)
@show Lcv2.alpha_;
Lcv2.coef_
# 正則化パラメータについては、それらしい値が得られました。
# 係数については、変数選択されていることは確認できましたが、値が大きいので$\sigma$で割って確かめることにします。
Lcv2.coef_ ./ σ'
# 混乱しましたが、[例50](#例50)と大体同じ係数になることを確認できました。


text:
using Manopt

M = SymmetricPositiveDefinite(2)

for i= 1:1000
    a = randomMPoint(M)
    b = randomMPoint(M)
    c = randomMPoint(M)
    d = randomMPoint(M)
    m = b

    ξb = log(M,b,c) + parallelTransport(M,c,b,log(M,c,a)) - log(M,b,d)
        + parallelTransport(M,m,b,log(M,m,d)) - parallelTransport(M,m,b,log(M,m,a))
    ηb = log(M,b,c)

    v = dot(M,b,ξb,ηb)

    print("Test: ",v,"\n")
end


text:
"""
A Julia library for reading and writing MIDI files.
"""
module MIDI

include("constants.jl")
include("note.jl")
include("trackevent.jl")
include("miditrack.jl")
include("midifile.jl")
include("variablelength.jl")
include("convert.jl")
include("findevents.jl")

export testmidi, testnotes

"""
    testmidi()
Return the path to a test MIDI file.
"""
testmidi() = joinpath(dirname(@__DIR__), "test", "doxy.mid")

"""
    testnotes()
Return a test set of human-played MIDI notes on the piano.
"""
testnotes() = getnotes(readMIDIFile(testmidi()), 4)

end


text:
using DashBootstrapComponents, DashHtmlComponents

progress = html_div([
    dbc_progress(value=50, style=Dict("height" => "1px"), className="mb-3"),
    dbc_progress(value=50, style=Dict("height" => "30px")),
]);

max_stars_repo_name: harisbal/dash-bootstrap-components

max_issues_repo_name: harisbal/dash-bootstrap-components

max_forks_repo_name: harisbal/dash-bootstrap-components


text:
using HarwellRutherfordBoeing
using Krylov
using LinearOperators
# using ProfileView

# M = HarwellBoeingMatrix("data/illc1033.rra");
M = HarwellBoeingMatrix("data/illc1850.rra");
A = M.matrix;
(m, n) = size(A);
@printf("System size: %d rows and %d columns\n", m, n);

# Define a linear operator with preallocation.
Ap = zeros(m);
Atq = zeros(n);
op = LinearOperator(m, n, false, false,
                    p -> A_mul_B!(1.0,  A, p, 0.0, Ap),
                    q -> At_mul_B!(1.0, A, q, 0.0, Atq),
                    q -> At_mul_B!(1.0, A, q, 0.0, Atq));
λ = 1.0e-3;
λ > 0.0 && (N = 1./λ * opEye(n))

for nrhs = 1 : size(M.rhs, 2)
  b = M.rhs[:,nrhs];
  (x, stats) = lsqr(op, b, λ=λ, sqd=λ > 0, atol=0.0, btol=0.0, N=N);
  # @profile (x, stats) = lsqr(op, b, λ=λ, sqd=λ > 0, atol=0.0, btol=0.0, N=N);
  @time (x, stats) = lsqr(op, b, λ=λ, sqd=λ > 0, atol=0.0, btol=0.0, N=N);
  show(stats);
  resid = norm(A' * (A * x - b) + λ * x) / norm(b);
  @printf("LSQR: Relative residual: %8.1e\n", resid);
  @printf("LSQR: ‖x‖: %8.1e\n", norm(x));
end

# ProfileView.view()


text:
module CalciumNetwork

using SpikingNeuralNets, SpikingNeuralNets.LIFs,
        SpikingNeuralNets.Inputs, SpikingNeuralNets.GraphUtils,
        SpikingNeuralNets.SNNPlot
using LightGraphs, SimpleWeightedGraphs, Plots

#--------------------------------Graph Definition-------------------------------
# number of neurons in excitatory and inhibitory populations
const Nex = 25
const Nin = 25

# Build a meta-graph with excitatory and inhibitory populations and probabilistic connections
metaGraph = SimpleWeightedDiGraph(2)
probabilityGraph = SimpleWeightedDiGraph(2)
add_edge!(metaGraph, 1, 1, 1.0);   add_edge!(probabilityGraph, 1, 1, 0.9)
add_edge!(metaGraph, 1, 2, 1.0);   add_edge!(probabilityGraph, 1, 2, 0.75)
add_edge!(metaGraph, 2, 1, -1.0);  add_edge!(probabilityGraph, 2, 1, 0.8)
add_edge!(metaGraph, 2, 2, -1.0);  add_edge!(probabilityGraph, 2, 2, 0.66)

# Boolean arrays to serve as accessors for different populations
const excitatory = [trues(Nex); falses(Nin + Nex + Nin)]
const inhibitory = [falses(Nex); trues(Nin); falses(Nex + Nin)]
const inputsex = [falses(Nex+Nin); trues(Nex); falses(Nin)]
const inputsin = [falses(Nex+Nin+Nex); trues(Nin)]

# LIF Parameters
const dt = 0.02e-3      # Timestep
const Vrest = -70e-3     # Resting potential (-70 mV)
const Vθ = -50e-3        # Firing threshold (-50 mV)
const Vreset = -55e-3   # Reset potential (-55 mv)
const Vi = -70e-3       # inhibitory reversal potential (-70 mV)
const Mg = 1e-3         # Mg concentration (1 mM)
const λext = 2.4e3      # Rate of spontaneous external inputs (2.4 kHz)

Cm(n::Integer)::Real = excitatory[n] ? 0.5e-9 : 0.2e-9  # membrane capacitance (nF)
Rm(n::Integer)::Real = 1.0 / Cm(n)          # membrane resistance
gL(n::Integer)::Real = excitatory[n] ? 25e-9 : 20e-9    # membrane leak conductance (nS)
τref(n::Integer)::Real = excitatory[n] ? 2e-3 : 1e-3        # refractory period (mS)
τ(n::Integer)::Real = Cm(n) / gL(n)

# synaptic conductances (nS)
gext(n::Integer)::Real = excitatory[n] ? 0.25e-9 : 0.2e-9
gNMDA(n::Integer)::Real = excitatory[n] ? 0.15e-9 : 0.13e-9
gGABA(n::Integer)::Real = excitatory[n] ? 1.0e-9 : 1.25e-9

# synaptic decay times
const τext = 2e-3/dt
const α = 500.0*dt
const τNMDAd = 100e-3/dt # decay
const τNMDAr = 2e-3/dt # rise
const τGABA = 5e-3/dt

# synaptic current and gating functions
function Iext(lif::LIF, n::Integer, s::AbstractVector{<:Real})::Real
    return -gext(n) * voltage(lif, n) * s[1]
end
function dsext(lif::LIF{VT}, n::Integer, s::AbstractVector{VT})::Vector{VT} where {VT <: Real}
    input = spikes(lif, inputs(lif, n))
    return @. -(s/τext) + input
end

function INMDA(lif::LIF{VT}, n::Integer, vars::Matrix{VT}; inputs=false)::Real where {VT <: Real}
    v = voltage(lif, n)
    input = sum(weights(lif.graph)[excitors(lif, n; inputs=inputs), n] .* view(vars, :, 1))
    return -gNMDA(n) * v * input / (1 + Mg * exp(-0.062v) / 3.57)
end
function dvarsNMDA(lif::LIF{VT}, n::Integer, vars::Matrix{VT}; inputs=false)::Matrix{VT} where {VT <: Real}
    dvars = similar(vars)
    s, x = eachcol(vars)
    input = spikes(lif, excitors(lif, n; inputs=inputs))
    dvars[:, 1] = @. -(s/τNMDAd) + α*x*(1 - s)
    dvars[:, 2] = @. -(x/τNMDAr) + input
    return dvars
end

function IGABA(lif::LIF{VT}, n::Integer, s::AbstractVector{VT}; inputs=false)::Real where {VT <: Real}
    return -gGABA(n) * (voltage(lif, n) - Vi) * sum(s)
end
function dsGABA(lif::LIF{VT}, n::Integer, s::AbstractVector{VT}; inputs=false)::Vector{VT} where {VT <: Real}
    input = spikes(lif, inhibitors(lif, n; inputs=inputs))
    return @. -(s/τGABA) + input
end

function run(; iterations=100, window=100)
    # randomly generate a graph
    graph = ComplexGraph(metaGraph, [Nex, Nin], probabilityGraph; selfloops=false)
    # add external input neurons for all neurons, whose spikes will be pre-defined by a ConstantPoissonInput
    add_inputs!(graph, vertices(graph), fill(1.0, nv(graph)))

    # input iterator: randomly draw from a Poisson distribution every timestep
    I = ConstantPoissonInput(λext*dt, Nex+Nin, iterations)

    # construct an LIF with the above parameters
    lif = LIF{Float64, Int}(graph; dt=dt, Vrest=fill(Vrest, nv(graph)),
                            Vθ=fill(Vθ, nv(graph)),
                            Vreset=fill(Vreset, nv(graph)),
                            τ=τ.(vertices(graph)),
                            R=Rm.(vertices(graph)),
                            τref=τref.(vertices(graph)))
    add_channel!(lif, "ext", Iext, dsext, [zeros(1) for n in neurons(lif)])
    add_channel!(lif, "NMDA", INMDA, dvarsNMDA, [zeros(length(excitors(lif, n)), 2) for n in neurons(lif)])
    add_channel!(lif, "GABA", IGABA, dsGABA, [zeros(length(inhibitors(lif, n))) for n in neurons(lif)])

    # run the simulation and make some plots
    step!(lif, I; threaded=true)
    S = spiketrain(lif, iterations)[1:(Nex+Nin),:]

    Rex, t = smooth(S[1:Nex, :]; window=window, timestep=dt)
    Rin, t = smooth(S[(Nex+1):end, :]; window=window, timestep=dt)

    display(plot(rasterplot(S; timestep=dt),
                 plot(t, [Rex Rin], ylab="Firing Rate (Hz)", label=["Excitatory", "Inhibitory"]),
                 xlim=[0.0, iterations*dt], layout=(2,1), xlab="Time (s)"))
end

end


text:
@testset "Cylinder Constraint" begin

    # Test CylinderConstraint
    T = Float64
    n = 4
    P = 5
    x = 2
    y = 3
    z = 4
    X0 = SVector{n,T}([13.0, 1.0, 1.0, 2.0])
    p1 = SVector{P,T}([ 1.0,  1.0,  1.0,  0.0,  1.0])
    p2 = SVector{P,T}([ 0.0,  0.0,  0.0,  1.0,  0.0])
    p3 = SVector{P,T}([ 1.0,  1.0,  3.0,  1.0,  2.0])
    v = SVector{P,Symbol}([:z, :z, :z, :x, :y])
    l = SVector{P,T}([ 5.0,  2.0,  0.5,  2.0,  10.0])
    r = SVector{P,T}([ 3.0,  2.0,  7.0,  3.0,  1.0])

    con = CylinderConstraint(n,p1,p2,p3,v,l,r,x,y,z)
    TrajectoryOptimization.evaluate(con,X0)

    @test norm(TrajectoryOptimization.evaluate(con,X0) - [8.0, 3.0, 0.0, 8.0, 1.0], 1) < 1e-10
    # @test (@ballocated $(TrajectoryOptimization.evaluate)($con,$X0)) == 0

    function easy_jacobian(con,X)
        function local_evaluate(X)
            return TrajectoryOptimization.evaluate(con,X)
        end
        return ForwardDiff.jacobian(local_evaluate, X)
    end
    ∇c_easy = easy_jacobian(con, X0)
    ∇c = zeros(MMatrix{P,n,T,P*n})
    jacobian!(∇c,con,X0)
    @test norm(∇c - ∇c_easy, 1) < 1e-10
    # @test (@ballocated $jacobian!($∇c,$con,$X0)) == 0

end


text:
@doc doc"""
Minimise une fonction en utilisant l'algorithme des régions de confiance avec
    - le pas de Cauchy
ou
    - le pas issu de l'algorithme du gradient conjugue tronqué

# Syntaxe
```julia
xk, nb_iters, f(xk), flag = Regions_De_Confiance(algo,f,gradf,hessf,x0,option)
```

# Entrées :

   * **algo**        : (String) string indicant la méthode à utiliser pour calculer le pas
        - **"gct"**   : pour l'algorithme du gradient conjugué tronqué
        - **"cauchy"**: pour le pas de Cauchy
   * **f**           : (Function) la fonction à minimiser
   * **gradf**       : (Function) le gradient de la fonction f
   * **hessf**       : (Function) la hessiene de la fonction à minimiser
   * **x0**          : (Array{Float,1}) point de départ
   * **options**     : (Array{Float,1})
     * **deltaMax**      : utile pour les m-à-j de la région de confiance
                      ``R_{k}=\left\{x_{k}+s ;\|s\| \leq \Delta_{k}\right\}``
     * **gamma1,gamma2** : ``0 < \gamma_{1} < 1 < \gamma_{2}`` pour les m-à-j de ``R_{k}``
     * **eta1,eta2**     : ``0 < \eta_{1} < \eta_{2} < 1`` pour les m-à-j de ``R_{k}``
     * **delta0**        : le rayon de départ de la région de confiance
     * **max_iter**      : le nombre maximale d'iterations
     * **Tol_abs**       : la tolérence absolue
     * **Tol_rel**       : la tolérence relative

# Sorties:

   * **xmin**    : (Array{Float,1}) une approximation de la solution du problème : ``min_{x \in \mathbb{R}^{n}} f(x)``
   * **fxmin**   : (Float) ``f(x_{min})``
   * **flag**    : (Integer) un entier indiquant le critère sur lequel le programme à arrêter
      - **0**    : Convergence
      - **1**    : stagnation du ``x``
      - **2**    : stagnation du ``f``
      - **3**    : nombre maximal d'itération dépassé
   * **nb_iters** : (Integer)le nombre d'iteration qu'à fait le programme

# Exemple d'appel
```julia
algo="gct"
f(x)=100*(x[2]-x[1]^2)^2+(1-x[1])^2
gradf(x)=[-400*x[1]*(x[2]-x[1]^2)-2*(1-x[1]) ; 200*(x[2]-x[1]^2)]
hessf(x)=[-400*(x[2]-3*x[1]^2)+2  -400*x[1];-400*x[1]  200]
x0 = [1; 0]
options = []
xmin, fxmin, flag,nb_iters = Regions_De_Confiance(algo,f,gradf,hessf,x0,options)
```
"""
function Regions_De_Confiance(algo,f::Function,gradf::Function,hessf::Function,x0,options)

    if options == []
        deltaMax = 10
        gamma1 = 0.5
        gamma2 = 2.00
        eta1 = 0.25
        eta2 = 0.75
        delta0 = 2
        max_iter = 50
        Tol_abs = sqrt(eps())
        Tol_rel = 1e-15
    else
        deltaMax = options[1]
        gamma1 = options[2]
        gamma2 = options[3]
        eta1 = options[4]
        eta2 = options[5]
        delta0 = options[6]
        max_iter = options[7]
        Tol_abs = options[8]
        Tol_rel = options[9]
    end

    n = length(x0)
    xmin = zeros(n)
    fxmin = f(xmin)
    flag = 0
    nb_iters = 0

    xk = x0
    deltak = delta0
    convergence = max(Tol_rel*norm(gradf(x0)),Tol_abs)

    while norm(gradf(xk))> convergence  # condition de convergence non satisfaite
        if algo == "cauchy"
            sk,e = Pas_De_Cauchy(gradf(xk),hessf(xk),deltak)
        elseif algo == "gct"
            sk = Gradient_Conjugue_Tronque(gradf(xk),hessf(xk),[deltak,max_iter,1e-6])
        end

        #Expression de la fonction f(xk+sk) et f(xk)
        f_sk = f(xk+sk)
        f_xk = f(xk)

        #Expression de la quadratique
        m_sk = f_xk + transpose(gradf(xk))*sk + (1/2)*transpose(sk)*hessf(xk)*sk
        m_xk = f_xk

        #Calcul de rhok
        rho_k = (f_xk - f_sk)/(m_xk - m_sk)

        #Mise a jour de l'itéré
        xmin = xk
        if rho_k >= eta1
            xk = xk + sk
        end

        d = xk - xmin
        nb_iters = nb_iters + 1

        #Mise a jour de la région de confiance
        if rho_k >= eta2
            deltak = min(gamma2*deltak, deltaMax)
        elseif eta1 <= rho_k <= eta2
            deltak += 0
        else
            deltak *= gamma1
        end

        if nb_iters >= max_iter # nombre maximal atteint
            flag = 3
            break
        end

        if norm(d) > 0
            if norm(d)<= max(Tol_rel*norm(xmin),Tol_abs) #stagnation de xk
                flag = 1
                break

            elseif abs(f(xk)- f(xmin)) <= max(Tol_rel*abs(f(xmin)), Tol_abs) #stagnation de f
                flag = 2
                break
            end
        end
end

xmin = xk;
fxmin = f(xmin)

    return xmin, fxmin, flag, nb_iters
end

max_stars_repo_name: faicaltoubali/ENSEEIHT

max_issues_repo_name: faicaltoubali/ENSEEIHT

max_forks_repo_name: faicaltoubali/ENSEEIHT


text:
function needs_USE_GPL_LIBS(s::String)
    contains(s, "CHOLMOD") && return true
    return false
end

const HEADER = """
# This file is a part of Julia. License is MIT: https://julialang.org/license

# Steps to regenerate this file:
# 1. Remove all `precompile` calls
# 2. Rebuild system image
# 3. Enable TRACE_COMPILE in options.h and rebuild
# 4. Run `./julia 2> precompiles.txt` and do various things.
# 5. Run `./julia contrib/fixup_precompile.jl precompiles.txt to overwrite `precompile.jl`
#    or ./julia contrib/fixup_precompile.jl --merge precompiles.txt to merge into existing
#    `precompile.jl`
"""

function fixup_precompile(new_precompile_file; merge=false)
    old_precompile_file = joinpath(Sys.BINDIR, "..", "..", "base", "precompile.jl")
    precompile_statements = Set{String}()

    for file in [new_precompile_file; merge ? old_precompile_file : []]
        for line in eachline(file)
            line = strip(line)
            # filter out closures, which might have different generated names in different environments
            contains(line, r"#[0-9]") && continue
            # Other stuff than precompile statements might have been written to STDERR
            startswith(line, "precompile(Tuple{") || continue
            # Ok, add the line
            push!(precompile_statements, line)
        end
    end

    open(old_precompile_file, "w") do f
        println(f, HEADER)
        println(f, """
        let
        PrecompileStagingArea = Module()
        for (_pkgid, _mod) in Base.loaded_modules
            if !(_pkgid.name in ("Main", "Core", "Base"))
                @eval PrecompileStagingArea \$(Symbol(_mod)) = \$_mod
            end
        end
        @eval PrecompileStagingArea begin""")
        for statement in sort(collect(precompile_statements))
            isgpl = needs_USE_GPL_LIBS(statement)
            isgpl && print(f, "if Base.USE_GPL_LIBS\n    ")
            println(f, statement)
            isgpl && println(f, "end")
        end
        println(f, "end\nend")
    end
    if merge
        "Merged $new_precompile_file into $old_precompile_file"
    else
        "Overwrite $old_precompile_file with $new_precompile_file"
    end
end

if length(ARGS) == 1
    fixup_precompile(joinpath(pwd(), ARGS[1]))
elseif length(ARGS) == 2
    @assert ARGS[1] == "--merge"
    fixup_precompile(joinpath(pwd(), ARGS[2]); merge = true)
else
    error("invalid arguments")
end

max_stars_repo_name: blegat/julia

max_issues_repo_name: blegat/julia

max_forks_repo_name: blegat/julia


text:
# testing nearal ODE
# https://discourse.julialang.org/t/diffeqflux-with-time-as-additional-input-to-neural-ode/26456/3
# https://discourse.julialang.org/t/defining-and-input-signal-for-a-differential-equation/23703/10
# https://github.com/JuliaDiffEq/DiffEqFlux.jl#universal-differential-equations-for-neural-optimal-control
# https://docs.juliadiffeq.org/stable/tutorials/ode_example/#Defining-Parameterized-Functions-1

using Pkg
Pkg.activate(@__DIR__)
pkg"instantiate"
0
pkg"precompile"

# using Revise

# using Flux
# using DiffEqFlux, OrdinaryDiffEq, Optim

using DiffEqFlux, Flux, Optim, OrdinaryDiffEq
using DifferentialEquations

# Requires Julia 1.3 and up
import Base.Threads.@spawn

## Fix issue Zygote.jl #440 #516
using Zygote

Zygote.@adjoint function vcat(xs::Union{Number, AbstractVector}...)
    vcat(xs...), dy -> begin
        d = 0
        map(xs) do x
            x isa Number && return dy[d+=1]
            l = length(x)
            dx = dy[d+1:d+l]
            d += l
            return dx
        end
    end
end

## Load MAT VicPrk data

using TransformUtils
using Plots
using MAT
using Interpolations

vpdata = matread(ENV["HOME"]*"/data/dataset_victoria_park/original_MATLAB_dataset/aa3_dr.mat")

# utility functions

include(joinpath(@__DIR__, "..", "wheeled", "parametricWheelOdo.jl"))

vpdata["time"] .*= 1e-3
vpdata["time"] = round.(vpdata["time"][:], digits=5)

vpsensors = hcat(vpdata["time"],
                 vpdata["speed"],
                 vpdata["steering"])
#

steer =  LinearInterpolation( (vpdata["time"],) , vpdata["steering"][:])
speed =  LinearInterpolation( (vpdata["time"],) , vpdata["speed"][:])

odo = allOdoEasy(vpsensors)
# vcat(ode_data, zeros(Float32, size()))

START=1
STOP=1500
plot(odo[START:STOP,1], odo[START:STOP,2])
# plot(odo[:,1], odo[:,2])

ode_data = odo[START:STOP,:]' .|> Float32

# x_i, y_i, theta_i, vx_i
u0 = Float32[0.; 0.; 0.; 0.]
# u0 = zeros(Float32, 4) #Float32(1.1)

datasize = size(ode_data,2)
tspan = (Float32(vpdata["time"][1]), Float32(vpdata["time"][datasize]))
ts = range(tspan[1],tspan[2],length=datasize)

## Specialized Neural model with time dependent inputs==========================

# model = Chain(x -> x.^3,
#               Dense(4,50,tanh),
#               Dense(50,3,tanh))
model = FastChain(FastDense(6,10,relu), FastDense(10,10,relu), FastDense(10,4,relu))
# model parameters
p = initial_params(model)

# regular ODE states -- i.e. non-time-dependent input states
# θ is all non-time-dependent input parameters
θ = Float32[u0;p]

t0 = vpdata["time"][1] |> Float32

function dudt_(u,p,t)
  # sp = 0 < t ? speed(t) : 0.0
  # st = 0 < t ? steer(t) : 0.0
  # tidx = findmin(abs.(vpdata["time"][:]*1e-3 .- t))[2]
  tidx = round(Int, (t-t0)*40+1) # interpolation approach has issues with train
  tidx = 1 < tidx ? tidx : 1
  sp = vpdata["speed"][tidx, 1] + 1e-6*randn()
  st = vpdata["steering"][tidx, 1]

  # @show t, sp, st # cant differentiate
  input = [u; sp; st]
  model(input, p)
end

# count = 0
# incrementCount(x...) = global count += 1
# periodic = PeriodicCallback(incrementCount, 0.25)

input0 = [0f0;0f0]
prob = ODEProblem(dudt_, u0, tspan, p)
concrete_solve(prob, Tsit5(), u0, p, abstol=1e-8, reltol=1e-6, saveat=ts)
Array(  concrete_solve(prob,Tsit5(), θ[1:4], θ[5:end], saveat=ts) )# , callback=periodic  )

function predict_adjoint(θ)
  Array(  concrete_solve(prob, Tsit5(), θ[1:4], θ[5:end], saveat=ts)  )
end

predict_adjoint(θ)

function loss_adjoint(θ)
  pred = predict_adjoint(θ)
  loss = 0.0
  for idx in 1:size(ode_data,2)
    loss = (ode_data[1,idx]-pred[1,idx])^2 + (ode_data[2,idx]-pred[2,idx])^2 + (cos(ode_data[3,idx])-cos(pred[3,idx]))^2 + (sin(ode_data[3,idx])-sin(pred[3,idx]))^2 # + (pred[4,idx])^2
  end
  loss
end

# Callback
cb = function (θ,l)
  println(l)
  #display(plot(solve(remake(prob,p=Flux.data(p3),u0=Flux.data(u0)),Tsit5(),saveat=0.1),ylim=(0,6)))
  return false
end

# loss1 = loss_adjoint(θ)

function doTraining(model, u0; maxiters=50)
  p = initial_params(model)
  θlocal = Float32[u0;p]
  l = loss_adjoint(θlocal)
  cb(θlocal,l)

  res = DiffEqFlux.sciml_train(loss_adjoint, θlocal, ADAM(0.1/(100*rand())), cb = cb, maxiters=maxiters)
  # res = DiffEqFlux.sciml_train(loss_adjoint, θ, BFGS(initial_stepnorm=0.01), cb = cb)

  return res
end

res = doTraining(model, u0, maxiters=10)

res.minimum

function trainGeneration(model, u0; maxiters::Int=50, MC::Int=30)

  TASKS = Vector{Any}(undef,MC)
  for i in 1:MC
    TASKS[i] = Threads.@spawn doTraining(model, u0, maxiters=maxiters)
  end

  RES = Vector{Any}(undef,MC)
  for i in 1:MC
    RES[i] = fetch(TASKS[i])
    @show i, RES[i].minimum
  end

  PP = Vector{Vector{Float32}}(undef, MC)
  CO = zeros(MC)

  for i in 1:MC
    CO[i] = RES[i].minimum
    PP[i] = deepcopy(RES[i].minimizer)
  end

  # TASKS = Vector{Any}(undef,MC)
  # RES = Vector{Any}(undef,MC)
  # GC.gc()
  ord = sortperm(CO)
  return PP[ord], CO[ord]
end

PPs, COs = trainGeneration(model, u0; maxiters=50)

GC.gc()

## PLOT result =================================================================

# p vectors

sort(CO)
PPm = hcat(PPs...)

heatmap(PPm)

XX = predict_adjoint(PPs[1])

DRx = [odo[START:STOP,1]';XX[1,:]']'
DRy = [odo[START:STOP,2]';XX[2,:]']'

fn = plot(DRx, DRy, fmt=:svg)

savefig(ENV["HOME"]*"/Documents/networks/test.svg")

plot(XX[1:2,:]')

plot(odo[START:STOP,1], odo[START:STOP,2])
plot(XX[1,:], XX[2,:])

plot(vpsensors[:,2])
plot(vpsensors[:,3])

gui()

##==============================================================================
## Store result

using DelimitedFiles
using Dates

res.minimizer

for i in 3:32
  res = RES[i-2]
  writedlm(ENV["HOME"]*"/Documents/networks/neural_$i.txt", res.minimizer)
  fid = open(ENV["HOME"]*"/Documents/networks/config_$i.txt", "w")
  println(fid, "minimum=$(res.minimum)")
  println(fid, "model = FastChain(FastDense(6,10,relu), FastDense(10,10,relu), FastDense(10,4,relu))")
  close(fid)
end

#


text:
using Distributed, Pkg
@everywhere using Distributed, Pkg
Pkg.activate(".")
@everywhere Pkg.activate(".")
using LTMSim, DataFrames, SimpleHypergraphs, Statistics, Plots, PyPlot, Random, Serialization, LaTeXStrings
@everywhere using LTMSim, DataFrames, SimpleHypergraphs, Statistics, Random, Serialization

metav = range(0.1, stop = 0.9, step = 0.1)
runs = 1
N = 50
M = 50
r = 1
# hr = randomH(N, M)
# hk = randomHkuniform(N, M, r)
# hd = randomHduniform(N, M, r)
# hp = randomHpreferential(N, 0.5)
# hg = hg_load("data/got.hgf")

# graphs = [("Random", hr),
# 		  ("RandomK", hk),
# 		  ("RandomD", hd),
# 		  ("RandomP", hp)
# 		  ,("GoT", hg)]
graphs = [("NBA", dual(hg_load("data/nba.hgf"))),
		  ("DBLP-2017", hg_load("data/dblp.hgf"))]

gres = Dict{String,Any}()

for metae in [0.2,0.5,0.8]
	for g in graphs
		data = Dict{String,Vector{Vector{Int}}}()

		data["BinarySearch(H)"] = Vector{Vector{Int}}()
		data["Greedy(H)"] = Vector{Vector{Int}}()
		data["Greedy([H]₂)"] = Vector{Vector{Int}}()
		data["SubTSS(H)"] = Vector{Vector{Int}}()

		for n = metav
			println("mv=$n me=$metae n=$(nhv(g[2])) e=$(nhe(g[2]))")
		    results = @distributed (append!) for run = 1:runs
		        metaV = proportionalMetaV(g[2], n)
		        metaE = proportionalMetaE(g[2], metae)

				r1 = greedy_tss_2section(g[2], metaV, metaE)
				println("greedy_tss_2section")

				r2 = bisect(g[2], metaV, metaE)
				println("bisect ")

				r3 = greedy_tss(g[2], metaV, metaE)
				println("greedy_tss ")

				r4 = sub_tss_opt2(g[2], metaV, metaE)
				println("sub_tss_opt2 ")
				println("end mv=$n me=$metae n=$(nhv(g[2])) e=$(nhe(g[2]))")

				[(r1, r2, r3, r4[1])]

		    end
		    push!(data["Greedy([H]₂)"], [r[1] for r in results])
		    push!(data["BinarySearch(H)"], [r[2] for r in results])
		    push!(data["Greedy(H)"], [r[3] for r in results])
			push!(data["SubTSS(H)"], [r[4][1] for r in results])

		    println("end ", n)

		end
		push!(gres, "graph-$(g[1])-meta-e-$metae" => data)
		# here the result are for one metae e a particular graph
	end
end
### data
serialize("res/paper/exp3/scenario3.data", gres)

results = deserialize("res/paper/exp3/scenario3.data")

for metae = [0.2,0.5,0.8]
	for g in graphs

		data = results["graph-$(g[1])-meta-e-$metae"]

		labels_dict = Dict{String,String}(
		    "BinarySearch(H)" => "StaticGreedy",
		    "Greedy(H)" => "DynamicGreedy",
		    "Greedy([H]₂)" => L"DynamicGreedy_{[H]_2}",
			"SubTSS(H)" => "SubTSS"
		)

		### plotting
		ticks = metav
		clf()
		plt.figure(figsize = (7, 5))
		val = -0.4
		c = 1
		colorz = ["#2C7BB6", "#D7191C", "#FF8900", "#33CC33"]
		labels = Array{String,1}()
		for algo in ["BinarySearch(H)", "Greedy([H]₂)", "Greedy(H)", "SubTSS(H)"]# keys(data)
		    val, c

		    y = Array{Float64,1}()

		    for v = 1:length(collect((metav)))
		        push!(y, mean(data[algo][v]))
		    end

		    push!(
		        labels,
		        labels_dict[algo]
		    )

		    b = plt.plot(collect(metav), y, "bo", color = colorz[c])

		    c += 1

			println(y)
		end
		plt.title("graph-$(g[1])-meta-e-$metae")
		plt.legend(labels, fontsize = "x-large", loc = "lower right")

		# plt.xlim(-2, length(ticks)*2)
		#plt.ylim(0, 30)

		plt.xticks(ticks, fontsize = "x-large") # range(0, length(ticks) * 2, step=2),
		plt.yticks(fontsize = "x-large")

		ylabel("Influence set size", fontstyle = "italic", fontsize = "xx-large", labelpad = 10) # fontweight="semibold",
		# xlabel("Thresholds", fontsize="x-large", fontweight="semibold", labelpad=10)

		plt.tight_layout()

		gcf()

		PyPlot.savefig("res/paper/exp3/graph-$(g[1])-meta-e-$metae.png")
		println("res/paper/exp3/graph-$(g[1])-meta-e-$metae.png")

		#plt.clf()
	end
end


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

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

Checks the availability of one or more image layers in a repository. When an image is pushed to a repository, each image layer is checked to verify if it has been uploaded before. If it has been uploaded, then the image layer is skipped.  This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.

# Required Parameters
- `layerDigests`: The digests of the image layers to check.
- `repositoryName`: The name of the repository that is associated with the image layers to check.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the image layers to check. If you do not specify a registry, the default registry is assumed.
"""

batch_check_layer_availability(layerDigests, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("BatchCheckLayerAvailability", Dict{String, Any}("layerDigests"=>layerDigests, "repositoryName"=>repositoryName); aws_config=aws_config)
batch_check_layer_availability(layerDigests, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("BatchCheckLayerAvailability", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("layerDigests"=>layerDigests, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    BatchDeleteImage()

Deletes a list of specified images within a repository. Images are specified with either an imageTag or imageDigest. You can remove a tag from an image by specifying the image's tag in your request. When you remove the last tag from an image, the image is deleted from your repository. You can completely delete an image (and all of its tags) by specifying the image's digest in your request.

# Required Parameters
- `imageIds`: A list of image ID references that correspond to images to delete. The format of the imageIds reference is imageTag=tag or imageDigest=digest.
- `repositoryName`: The repository that contains the image to delete.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the image to delete. If you do not specify a registry, the default registry is assumed.
"""

batch_delete_image(imageIds, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("BatchDeleteImage", Dict{String, Any}("imageIds"=>imageIds, "repositoryName"=>repositoryName); aws_config=aws_config)
batch_delete_image(imageIds, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("BatchDeleteImage", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("imageIds"=>imageIds, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    BatchGetImage()

Gets detailed information for an image. Images are specified with either an imageTag or imageDigest. When an image is pulled, the BatchGetImage API is called once to retrieve the image manifest.

# Required Parameters
- `imageIds`: A list of image ID references that correspond to images to describe. The format of the imageIds reference is imageTag=tag or imageDigest=digest.
- `repositoryName`: The repository that contains the images to describe.

# Optional Parameters
- `acceptedMediaTypes`: The accepted media types for the request. Valid values: application/vnd.docker.distribution.manifest.v1+json | application/vnd.docker.distribution.manifest.v2+json | application/vnd.oci.image.manifest.v1+json
- `registryId`: The AWS account ID associated with the registry that contains the images to describe. If you do not specify a registry, the default registry is assumed.
"""

batch_get_image(imageIds, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("BatchGetImage", Dict{String, Any}("imageIds"=>imageIds, "repositoryName"=>repositoryName); aws_config=aws_config)
batch_get_image(imageIds, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("BatchGetImage", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("imageIds"=>imageIds, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    CompleteLayerUpload()

Informs Amazon ECR that the image layer upload has completed for a specified registry, repository name, and upload ID. You can optionally provide a sha256 digest of the image layer for data validation purposes. When an image is pushed, the CompleteLayerUpload API is called once per each new image layer to verify that the upload has completed.  This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.

# Required Parameters
- `layerDigests`: The sha256 digest of the image layer.
- `repositoryName`: The name of the repository to associate with the image layer.
- `uploadId`: The upload ID from a previous InitiateLayerUpload operation to associate with the image layer.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry to which to upload layers. If you do not specify a registry, the default registry is assumed.
"""

complete_layer_upload(layerDigests, repositoryName, uploadId; aws_config::AWSConfig=global_aws_config()) = ecr("CompleteLayerUpload", Dict{String, Any}("layerDigests"=>layerDigests, "repositoryName"=>repositoryName, "uploadId"=>uploadId); aws_config=aws_config)
complete_layer_upload(layerDigests, repositoryName, uploadId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("CompleteLayerUpload", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("layerDigests"=>layerDigests, "repositoryName"=>repositoryName, "uploadId"=>uploadId), args)); aws_config=aws_config)

"""
    CreateRepository()

Creates a repository. For more information, see Amazon ECR Repositories in the Amazon Elastic Container Registry User Guide.

# Required Parameters
- `repositoryName`: The name to use for the repository. The repository name may be specified on its own (such as nginx-web-app) or it can be prepended with a namespace to group the repository into a category (such as project-a/nginx-web-app).

# Optional Parameters
- `encryptionConfiguration`: The encryption configuration for the repository. This determines how the contents of your repository are encrypted at rest.
- `imageScanningConfiguration`: The image scanning configuration for the repository. This determines whether images are scanned for known vulnerabilities after being pushed to the repository.
- `imageTagMutability`: The tag mutability setting for the repository. If this parameter is omitted, the default setting of MUTABLE will be used which will allow image tags to be overwritten. If IMMUTABLE is specified, all image tags within the repository will be immutable which will prevent them from being overwritten.
- `tags`: The metadata that you apply to the repository to help you categorize and organize them. Each tag consists of a key and an optional value, both of which you define. Tag keys can have a maximum character length of 128 characters, and tag values can have a maximum length of 256 characters.
"""

create_repository(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("CreateRepository", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
create_repository(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("CreateRepository", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    DeleteLifecyclePolicy()

Deletes the lifecycle policy associated with the specified repository.

# Required Parameters
- `repositoryName`: The name of the repository.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
"""

delete_lifecycle_policy(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("DeleteLifecyclePolicy", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
delete_lifecycle_policy(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("DeleteLifecyclePolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    DeleteRepository()

Deletes a repository. If the repository contains images, you must either delete all images in the repository or use the force option to delete the repository.

# Required Parameters
- `repositoryName`: The name of the repository to delete.

# Optional Parameters
- `force`:  If a repository contains images, forces the deletion.
- `registryId`: The AWS account ID associated with the registry that contains the repository to delete. If you do not specify a registry, the default registry is assumed.
"""

delete_repository(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("DeleteRepository", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
delete_repository(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("DeleteRepository", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    DeleteRepositoryPolicy()

Deletes the repository policy associated with the specified repository.

# Required Parameters
- `repositoryName`: The name of the repository that is associated with the repository policy to delete.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the repository policy to delete. If you do not specify a registry, the default registry is assumed.
"""

delete_repository_policy(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("DeleteRepositoryPolicy", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
delete_repository_policy(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("DeleteRepositoryPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    DescribeImageScanFindings()

Returns the scan findings for the specified image.

# Required Parameters
- `imageId`:
- `repositoryName`: The repository for the image for which to describe the scan findings.

# Optional Parameters
- `maxResults`: The maximum number of image scan results returned by DescribeImageScanFindings in paginated output. When this parameter is used, DescribeImageScanFindings only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeImageScanFindings request with the returned nextToken value. This value can be between 1 and 1000. If this parameter is not used, then DescribeImageScanFindings returns up to 100 results and a nextToken value, if applicable.
- `nextToken`: The nextToken value returned from a previous paginated DescribeImageScanFindings request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return.
- `registryId`: The AWS account ID associated with the registry that contains the repository in which to describe the image scan findings for. If you do not specify a registry, the default registry is assumed.
"""

describe_image_scan_findings(imageId, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("DescribeImageScanFindings", Dict{String, Any}("imageId"=>imageId, "repositoryName"=>repositoryName); aws_config=aws_config)
describe_image_scan_findings(imageId, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("DescribeImageScanFindings", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("imageId"=>imageId, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    DescribeImages()

Returns metadata about the images in a repository.  Beginning with Docker version 1.9, the Docker client compresses image layers before pushing them to a V2 Docker registry. The output of the docker images command shows the uncompressed image size, so it may return a larger image size than the image sizes returned by DescribeImages.

# Required Parameters
- `repositoryName`: The repository that contains the images to describe.

# Optional Parameters
- `filter`: The filter key and value with which to filter your DescribeImages results.
- `imageIds`: The list of image IDs for the requested repository.
- `maxResults`: The maximum number of repository results returned by DescribeImages in paginated output. When this parameter is used, DescribeImages only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeImages request with the returned nextToken value. This value can be between 1 and 1000. If this parameter is not used, then DescribeImages returns up to 100 results and a nextToken value, if applicable. This option cannot be used when you specify images with imageIds.
- `nextToken`: The nextToken value returned from a previous paginated DescribeImages request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return. This option cannot be used when you specify images with imageIds.
- `registryId`: The AWS account ID associated with the registry that contains the repository in which to describe images. If you do not specify a registry, the default registry is assumed.
"""

describe_images(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("DescribeImages", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
describe_images(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("DescribeImages", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    DescribeRepositories()

Describes image repositories in a registry.

# Optional Parameters
- `maxResults`: The maximum number of repository results returned by DescribeRepositories in paginated output. When this parameter is used, DescribeRepositories only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeRepositories request with the returned nextToken value. This value can be between 1 and 1000. If this parameter is not used, then DescribeRepositories returns up to 100 results and a nextToken value, if applicable. This option cannot be used when you specify repositories with repositoryNames.
- `nextToken`: The nextToken value returned from a previous paginated DescribeRepositories request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return. This option cannot be used when you specify repositories with repositoryNames.  This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes.
- `registryId`: The AWS account ID associated with the registry that contains the repositories to be described. If you do not specify a registry, the default registry is assumed.
- `repositoryNames`: A list of repositories to describe. If this parameter is omitted, then all repositories in a registry are described.
"""

describe_repositories(; aws_config::AWSConfig=global_aws_config()) = ecr("DescribeRepositories"; aws_config=aws_config)
describe_repositories(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("DescribeRepositories", args; aws_config=aws_config)

"""
    GetAuthorizationToken()

Retrieves an authorization token. An authorization token represents your IAM authentication credentials and can be used to access any Amazon ECR registry that your IAM principal has access to. The authorization token is valid for 12 hours. The authorizationToken returned is a base64 encoded string that can be decoded and used in a docker login command to authenticate to a registry. The AWS CLI offers an get-login-password command that simplifies the login process. For more information, see Registry Authentication in the Amazon Elastic Container Registry User Guide.

# Optional Parameters
- `registryIds`: A list of AWS account IDs that are associated with the registries for which to get AuthorizationData objects. If you do not specify a registry, the default registry is assumed.
"""

get_authorization_token(; aws_config::AWSConfig=global_aws_config()) = ecr("GetAuthorizationToken"; aws_config=aws_config)
get_authorization_token(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("GetAuthorizationToken", args; aws_config=aws_config)

"""
    GetDownloadUrlForLayer()

Retrieves the pre-signed Amazon S3 download URL corresponding to an image layer. You can only get URLs for image layers that are referenced in an image. When an image is pulled, the GetDownloadUrlForLayer API is called once per image layer that is not already cached.  This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.

# Required Parameters
- `layerDigest`: The digest of the image layer to download.
- `repositoryName`: The name of the repository that is associated with the image layer to download.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the image layer to download. If you do not specify a registry, the default registry is assumed.
"""

get_download_url_for_layer(layerDigest, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("GetDownloadUrlForLayer", Dict{String, Any}("layerDigest"=>layerDigest, "repositoryName"=>repositoryName); aws_config=aws_config)
get_download_url_for_layer(layerDigest, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("GetDownloadUrlForLayer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("layerDigest"=>layerDigest, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    GetLifecyclePolicy()

Retrieves the lifecycle policy for the specified repository.

# Required Parameters
- `repositoryName`: The name of the repository.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
"""

get_lifecycle_policy(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("GetLifecyclePolicy", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
get_lifecycle_policy(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("GetLifecyclePolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    GetLifecyclePolicyPreview()

Retrieves the results of the lifecycle policy preview request for the specified repository.

# Required Parameters
- `repositoryName`: The name of the repository.

# Optional Parameters
- `filter`: An optional parameter that filters results based on image tag status and all tags, if tagged.
- `imageIds`: The list of imageIDs to be included.
- `maxResults`: The maximum number of repository results returned by GetLifecyclePolicyPreviewRequest in
 paginated output. When this parameter is used, GetLifecyclePolicyPreviewRequest only returns
 maxResults results in a single page along with a nextToken
 response element. The remaining results of the initial request can be seen by sending
 another GetLifecyclePolicyPreviewRequest request with the returned nextToken
 value. This value can be between 1 and 1000. If this
 parameter is not used, then GetLifecyclePolicyPreviewRequest returns up to
 100 results and a nextToken value, if
 applicable. This option cannot be used when you specify images with imageIds.
- `nextToken`: The nextToken value returned from a previous paginated
 GetLifecyclePolicyPreviewRequest request where maxResults was used and the
 results exceeded the value of that parameter. Pagination continues from the end of the
 previous results that returned the nextToken value. This value is
 null when there are no more results to return. This option cannot be used when you specify images with imageIds.
- `registryId`: The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
"""

get_lifecycle_policy_preview(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("GetLifecyclePolicyPreview", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
get_lifecycle_policy_preview(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("GetLifecyclePolicyPreview", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    GetRepositoryPolicy()

Retrieves the repository policy for the specified repository.

# Required Parameters
- `repositoryName`: The name of the repository with the policy to retrieve.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
"""

get_repository_policy(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("GetRepositoryPolicy", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
get_repository_policy(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("GetRepositoryPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    InitiateLayerUpload()

Notifies Amazon ECR that you intend to upload an image layer. When an image is pushed, the InitiateLayerUpload API is called once per image layer that has not already been uploaded. Whether or not an image layer has been uploaded is determined by the BatchCheckLayerAvailability API action.  This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.

# Required Parameters
- `repositoryName`: The name of the repository to which you intend to upload layers.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry to which you intend to upload layers. If you do not specify a registry, the default registry is assumed.
"""

initiate_layer_upload(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("InitiateLayerUpload", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
initiate_layer_upload(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("InitiateLayerUpload", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    ListImages()

Lists all the image IDs for the specified repository. You can filter images based on whether or not they are tagged by using the tagStatus filter and specifying either TAGGED, UNTAGGED or ANY. For example, you can filter your results to return only UNTAGGED images and then pipe that result to a BatchDeleteImage operation to delete them. Or, you can filter your results to return only TAGGED images to list all of the tags in your repository.

# Required Parameters
- `repositoryName`: The repository with image IDs to be listed.

# Optional Parameters
- `filter`: The filter key and value with which to filter your ListImages results.
- `maxResults`: The maximum number of image results returned by ListImages in paginated output. When this parameter is used, ListImages only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another ListImages request with the returned nextToken value. This value can be between 1 and 1000. If this parameter is not used, then ListImages returns up to 100 results and a nextToken value, if applicable.
- `nextToken`: The nextToken value returned from a previous paginated ListImages request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return.  This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes.
- `registryId`: The AWS account ID associated with the registry that contains the repository in which to list images. If you do not specify a registry, the default registry is assumed.
"""

list_images(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("ListImages", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
list_images(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("ListImages", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    ListTagsForResource()

List the tags for an Amazon ECR resource.

# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the only supported resource is an Amazon ECR repository.

"""

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

"""
    PutImage()

Creates or updates the image manifest and tags associated with an image. When an image is pushed and all new image layers have been uploaded, the PutImage API is called once to create or update the image manifest and the tags associated with the image.  This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.

# Required Parameters
- `imageManifest`: The image manifest corresponding to the image to be uploaded.
- `repositoryName`: The name of the repository in which to put the image.

# Optional Parameters
- `imageDigest`: The image digest of the image manifest corresponding to the image.
- `imageManifestMediaType`: The media type of the image manifest. If you push an image manifest that does not contain the mediaType field, you must specify the imageManifestMediaType in the request.
- `imageTag`: The tag to associate with the image. This parameter is required for images that use the Docker Image Manifest V2 Schema 2 or Open Container Initiative (OCI) formats.
- `registryId`: The AWS account ID associated with the registry that contains the repository in which to put the image. If you do not specify a registry, the default registry is assumed.
"""

put_image(imageManifest, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("PutImage", Dict{String, Any}("imageManifest"=>imageManifest, "repositoryName"=>repositoryName); aws_config=aws_config)
put_image(imageManifest, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("PutImage", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("imageManifest"=>imageManifest, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    PutImageScanningConfiguration()

Updates the image scanning configuration for the specified repository.

# Required Parameters
- `imageScanningConfiguration`: The image scanning configuration for the repository. This setting determines whether images are scanned for known vulnerabilities after being pushed to the repository.
- `repositoryName`: The name of the repository in which to update the image scanning configuration setting.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the repository in which to update the image scanning configuration setting. If you do not specify a registry, the default registry is assumed.
"""

put_image_scanning_configuration(imageScanningConfiguration, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("PutImageScanningConfiguration", Dict{String, Any}("imageScanningConfiguration"=>imageScanningConfiguration, "repositoryName"=>repositoryName); aws_config=aws_config)
put_image_scanning_configuration(imageScanningConfiguration, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("PutImageScanningConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("imageScanningConfiguration"=>imageScanningConfiguration, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    PutImageTagMutability()

Updates the image tag mutability settings for the specified repository. For more information, see Image Tag Mutability in the Amazon Elastic Container Registry User Guide.

# Required Parameters
- `imageTagMutability`: The tag mutability setting for the repository. If MUTABLE is specified, image tags can be overwritten. If IMMUTABLE is specified, all image tags within the repository will be immutable which will prevent them from being overwritten.
- `repositoryName`: The name of the repository in which to update the image tag mutability settings.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the repository in which to update the image tag mutability settings. If you do not specify a registry, the default registry is assumed.
"""

put_image_tag_mutability(imageTagMutability, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("PutImageTagMutability", Dict{String, Any}("imageTagMutability"=>imageTagMutability, "repositoryName"=>repositoryName); aws_config=aws_config)
put_image_tag_mutability(imageTagMutability, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("PutImageTagMutability", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("imageTagMutability"=>imageTagMutability, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    PutLifecyclePolicy()

Creates or updates the lifecycle policy for the specified repository. For more information, see Lifecycle Policy Template.

# Required Parameters
- `lifecyclePolicyText`: The JSON repository policy text to apply to the repository.
- `repositoryName`: The name of the repository to receive the policy.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the repository. If you do
 not specify a registry, the default registry is assumed.
"""

put_lifecycle_policy(lifecyclePolicyText, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("PutLifecyclePolicy", Dict{String, Any}("lifecyclePolicyText"=>lifecyclePolicyText, "repositoryName"=>repositoryName); aws_config=aws_config)
put_lifecycle_policy(lifecyclePolicyText, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("PutLifecyclePolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("lifecyclePolicyText"=>lifecyclePolicyText, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    SetRepositoryPolicy()

Applies a repository policy to the specified repository to control access permissions. For more information, see Amazon ECR Repository Policies in the Amazon Elastic Container Registry User Guide.

# Required Parameters
- `policyText`: The JSON repository policy text to apply to the repository. For more information, see Amazon ECR Repository Policies in the Amazon Elastic Container Registry User Guide.
- `repositoryName`: The name of the repository to receive the policy.

# Optional Parameters
- `force`: If the policy you are attempting to set on a repository policy would prevent you from setting another policy in the future, you must force the SetRepositoryPolicy operation. This is intended to prevent accidental repository lock outs.
- `registryId`: The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
"""

set_repository_policy(policyText, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("SetRepositoryPolicy", Dict{String, Any}("policyText"=>policyText, "repositoryName"=>repositoryName); aws_config=aws_config)
set_repository_policy(policyText, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("SetRepositoryPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("policyText"=>policyText, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    StartImageScan()

Starts an image vulnerability scan. An image scan can only be started once per day on an individual image. This limit includes if an image was scanned on initial push. For more information, see Image Scanning in the Amazon Elastic Container Registry User Guide.

# Required Parameters
- `imageId`:
- `repositoryName`: The name of the repository that contains the images to scan.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry that contains the repository in which to start an image scan request. If you do not specify a registry, the default registry is assumed.
"""

start_image_scan(imageId, repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("StartImageScan", Dict{String, Any}("imageId"=>imageId, "repositoryName"=>repositoryName); aws_config=aws_config)
start_image_scan(imageId, repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("StartImageScan", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("imageId"=>imageId, "repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    StartLifecyclePolicyPreview()

Starts a preview of a lifecycle policy for the specified repository. This allows you to see the results before associating the lifecycle policy with the repository.

# Required Parameters
- `repositoryName`: The name of the repository to be evaluated.

# Optional Parameters
- `lifecyclePolicyText`: The policy to be evaluated against. If you do not specify a policy, the current policy for the repository is used.
- `registryId`: The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
"""

start_lifecycle_policy_preview(repositoryName; aws_config::AWSConfig=global_aws_config()) = ecr("StartLifecyclePolicyPreview", Dict{String, Any}("repositoryName"=>repositoryName); aws_config=aws_config)
start_lifecycle_policy_preview(repositoryName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("StartLifecyclePolicyPreview", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("repositoryName"=>repositoryName), args)); aws_config=aws_config)

"""
    TagResource()

Adds specified tags to a resource with the specified ARN. Existing tags on a resource are not changed if they are not specified in the request parameters.

# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) of the the resource to which to add tags. Currently, the only supported resource is an Amazon ECR repository.
- `tags`: The tags to add to the resource. A tag is an array of key-value pairs. Tag keys can have a maximum character length of 128 characters, and tag values can have a maximum length of 256 characters.

"""

tag_resource(resourceArn, tags; aws_config::AWSConfig=global_aws_config()) = ecr("TagResource", Dict{String, Any}("resourceArn"=>resourceArn, "tags"=>tags); aws_config=aws_config)
tag_resource(resourceArn, tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("TagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceArn"=>resourceArn, "tags"=>tags), args)); aws_config=aws_config)

"""
    UntagResource()

Deletes specified tags from a resource.

# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) of the resource from which to remove tags. Currently, the only supported resource is an Amazon ECR repository.
- `tagKeys`: The keys of the tags to be removed.

"""

untag_resource(resourceArn, tagKeys; aws_config::AWSConfig=global_aws_config()) = ecr("UntagResource", Dict{String, Any}("resourceArn"=>resourceArn, "tagKeys"=>tagKeys); aws_config=aws_config)
untag_resource(resourceArn, tagKeys, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("UntagResource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceArn"=>resourceArn, "tagKeys"=>tagKeys), args)); aws_config=aws_config)

"""
    UploadLayerPart()

Uploads an image layer part to Amazon ECR. When an image is pushed, each new image layer is uploaded in parts. The maximum size of each image layer part can be 20971520 bytes (or about 20MB). The UploadLayerPart API is called once per each new image layer part.  This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.

# Required Parameters
- `layerPartBlob`: The base64-encoded layer part payload.
- `partFirstByte`: The position of the first byte of the layer part witin the overall image layer.
- `partLastByte`: The position of the last byte of the layer part within the overall image layer.
- `repositoryName`: The name of the repository to which you are uploading layer parts.
- `uploadId`: The upload ID from a previous InitiateLayerUpload operation to associate with the layer part upload.

# Optional Parameters
- `registryId`: The AWS account ID associated with the registry to which you are uploading layer parts. If you do not specify a registry, the default registry is assumed.
"""

upload_layer_part(layerPartBlob, partFirstByte, partLastByte, repositoryName, uploadId; aws_config::AWSConfig=global_aws_config()) = ecr("UploadLayerPart", Dict{String, Any}("layerPartBlob"=>layerPartBlob, "partFirstByte"=>partFirstByte, "partLastByte"=>partLastByte, "repositoryName"=>repositoryName, "uploadId"=>uploadId); aws_config=aws_config)
upload_layer_part(layerPartBlob, partFirstByte, partLastByte, repositoryName, uploadId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = ecr("UploadLayerPart", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("layerPartBlob"=>layerPartBlob, "partFirstByte"=>partFirstByte, "partLastByte"=>partLastByte, "repositoryName"=>repositoryName, "uploadId"=>uploadId), args)); aws_config=aws_config)


text:
module Transits

using ChainRulesCore
using Reexport
using StaticArrays

export AbstractLimbDark,
       PolynomialLimbDark,
       QuadLimbDark,
       IntegratedLimbDark,
       SecondaryLimbDark,
       compute,
       Orbits,
       # distributions
       Kipping13

include("orbits/Orbits.jl")
@reexport using .Orbits
using .Orbits: AbstractOrbit

"""
    AbstractLimbDark

A limb dark law need only need to implement `compute(::Law, b, r)` to extend the limb darkening interface.

# See also
[`compute`](@ref)
"""
abstract type AbstractLimbDark end

Base.broadcastable(law::AbstractLimbDark) = Ref(law)

"""
    (::AbstractLimbDark)(b, r)

An alias for calling [`compute`](@ref)

# Examples
```jldoctest
julia> ld = PolynomialLimbDark([0.4, 0.26]);

julia> ld(0, 0.01)
0.9998785437247428
```
"""
(ld::AbstractLimbDark)(args...; kwargs...) = compute(ld, args...; kwargs...)

"""
    compute(::AbstractLimbDark, b, r; kwargs...)

Compute the relative flux for the given impact parameter `b` and radius ratio `r`. The impact parameter is unitless. The radius ratio is given in terms of the host; e.g., if the companion is half the size of the host, r=0.5.
"""
function compute end

"""
    compute(::AbstractLimbDark, orbit::AbstractOrbit, t, r)

Compute the relative flux by calculating the impact parameter at time `t` from the given orbit. The time needs to be compatible with the period of the orbit, nominally in days.

# Examples
```jldoctest orb
julia> ld = PolynomialLimbDark([0.4, 0.26]);

julia> orbit = SimpleOrbit(period=3, duration=1);

julia> ld(orbit, 0, 0.1) # primary egress
0.9878664434953113

julia> ld(orbit, 0.1, 0.1) # 0.1 d
0.9879670695533511
```
this works effortlessly with libraries like [Unitful.jl](https://github.com/painterqubits/Unitful.jl)

```jldoctest orb
julia> using Unitful

julia> orbit = SimpleOrbit(period=3u"d", duration=3u"hr");

julia> ld(orbit, 0u"d", 0.1)
0.9878664434953113
```
"""
function compute(ld::AbstractLimbDark, orbit::AbstractOrbit, t, r)
    coords = Orbits.relative_position(orbit, t)
    # make sure los is in front of star
    if coords[3] > 0
        μ = sqrt(coords[1]^2 + coords[2]^2)
        return compute(ld, μ, r)
    else
        return one(eltype(coords))
    end
end

include("polynomial/elliptic.jl")
include("polynomial/series.jl")
include("polynomial/poly.jl")
include("polynomial/poly-grads.jl")
include("polynomial/quad.jl")
include("polynomial/quad-grads.jl")
include("integrated.jl")
include("secondary.jl")
include("distributions.jl")

end