text:
export IndeterminateException

"""
    IndeterminateException(msg = "")

Exception raised when the result of a numerical operation on a `NumberInterval`
is indeterminate.

See documentation of `Indeterminate` for information on enabling this behavior.
"""
struct IndeterminateException <: Exception
    msg
end
IndeterminateException() = IndeterminateException("")

intercept_exception(::Any) = true

"""
    missing_or_exception(msg = nothing)

Returns `Base.missing` by default.

To throw an `IndeterminateException()` instead (*only* for debugging purposes),
extend the `intercept_exception()` function from this module by defining:
```julia
    NumberIntervals.intercept_exception(::IndeterminateException) = false
```
Note that this changes behavior *globally*, across all packages processing
`NumberInterval`s and therefore should never be used in production code.
"""
function missing_or_exception(msg = nothing)
    exc = IndeterminateException(msg)
    intercept_exception(exc) && return missing
    throw(exc)
end


text:
#=
rect_im.jl
2019-07, Helena H
=#

export rect_im

using Plots
# using MIRT: jim, MIRT_image_geom, downsample2

"""
`phantom = rect_im(ig, params ;
	oversample=1, hu_scale=1, fov=maximum(ig.fovs), chat=false, how=:auto,
	replace=false, return_params=false)`

generate rectangle phantom image from parameters:
 `[x_center y_center x_width y_width angle_degrees amplitude]`

in
- `ig`				`image_geom()` object
- `params`			`[Nrect,6]` rect parameters. if empty use default

options
- `oversample::Int`	oversampling factor, for grayscale boundaries
- `hu_scale::Real`		use 1000 to scale
- `fov::Real`			default `maximum(ig.fovs)`
- `chat::Bool`			verbosity?
- `how::Symbol`			`:fast` or `:slow`; default `:auto`
- `replace::Bool`		default `false`
- `return_params::Bool`	if true, return both phantom and params

out
- `phantom`		`[nx ny]` image (Float32)
- `params`		`[Nrect 6]` rect parameters (only return if `return_params=true`)
"""
function rect_im(ig::MIRT_image_geom,
		params::AbstractArray{<:Real,2} ;
		oversample::Int = 1,
		hu_scale::Real = 1,
		fov::Real = maximum(ig.fovs),
		chat::Bool = false,
		how::Symbol = :auto,
		replace::Bool = false,
		return_params::Bool = false)

	size(params,2) != 6 && throw("bad rect parameter vector size")

	if oversample > 1
		ig = ig.over(oversample)
	end
	args = (ig.nx, ig.ny, ig.dx, ig.dy, ig.offset_x, ig.offset_y, replace)

	params[:,6] .*= hu_scale

	do_fast = params[:,5] .== 0 # default for :auto
	if how === :fast
		do_fast[:] .= true
	elseif how === :slow
		do_fast[:] .= false
	elseif how != :auto
		throw("bad how :how")
	end

	phantom = zeros(Float32, ig.nx, ig.ny)

	if any(do_fast)
		phantom += rect_im_fast(params[do_fast,:], args...)
	end

	if any(.!do_fast)
		tmp = rect_im_slow(params[.!do_fast,:], args...)
		phantom += tmp
	end

	if oversample > 1
		phantom = downsample2(phantom, oversample)
	end

	if return_params
		return (phantom, params)
	end

	return phantom
end

"""
`phantom = rect_im_fast()`
for non-rotated rectangles
	using exact integration over each pixel so over-sampling is irrelevant
"""
function rect_im_fast(params, nx, ny, dx, dy, offset_x, offset_y, replace)
	phantom = zeros(Float32, nx, ny)

	wx = (nx-1)/2 + offset_x # scalars
	wy = (ny-1)/2 + offset_y
	x1 = ((0:nx-1) .- wx) * dx # arrays
	y1 = ((0:ny-1) .- wy) * dy
	fun = (x1, x2, wx) -> # integrated rect(x/wx) function from x1 to x2
		max(min(x2, wx/2) - max(x1, -wx/2), 0)

	# ticker reset
	ne = size(params)[1]
	for ie in 1:ne
		#ticker(mfilename, ie, ne)
		rect = params[ie, :]
		cx = rect[1]
		wx = rect[3]
		cy = rect[2]
		wy = rect[4]
		theta = rect[5] * (pi/180)
		theta != 0 && throw("theta=0 required")
		value = Float32(rect[6])

		x = x1 .- cx
		y = y1 .- cy
		tx = fun.(x .- abs(dx)/2, x .+ abs(dx)/2, wx) / abs(dx)
		ty = fun.(y .- abs(dy)/2, y .+ abs(dy)/2, wy) / abs(dy)
		tmp = Float32.(tx) * Float32.(ty)' # outer product (separable)
		if replace
			phantom[tmp .> 0] .= value
		else
			phantom += value * tmp
		end
	end
	return phantom
end

"""
`phantom = rect_im_slow()`
for rotated rectangles
"""
function rect_im_slow(params_in, nx, ny, dx, dy, offset_x, offset_y, replace)

	params = copy(params_in)
	phantom = zeros(Float32, nx, ny)

	wx = (nx - 1)/2 + offset_x # scalar
	wy = (ny - 1)/2 + offset_y
	x = ((0:nx-1) .- wx) * dx
	y = ((0:ny-1) .- wy) * dy
	(xx, yy) = ndgrid(x, y)

	# ticker reset
	ne = size(params)[1]
	for ie in 1:ne
		#ticker(mfilename, ie, ne)

		rect = params[ie, :]
		cx = rect[1]
		wx = rect[3]
		cy = rect[2]
		wy = rect[4]
		theta = rect[5] * (pi/180) # Float64
		value = Float32(rect[6])

		(x,y) = rotate2d(xx .- cx, yy .- cy, theta)
		tmp = (abs.(x / wx) .< 1/2) .& (abs.(y / wy) .< 1/2) # 2d rect

		if replace
			phantom[tmp .> 0] .= value
		else
			phantom += value * tmp
		end
	end
	return phantom
end

"""
`phantom = rect_im(nx, dx, params ; args...)`

square image of size `nx` by `nx`,
specifying pixel size `dx` and rect `params`
"""
function rect_im(nx::Int, dx::Real, params ; args...)
	ig = image_geom(nx=nx, dx=1)
	return rect_im(ig, params ; args...)
end

"""
`phantom = rect_im(nx::Int, params ; args...)`

square image of size `nx` by `nx` with
pixel size `dx=1` and rect `params`
"""
function rect_im(nx::Int, params ; args...)
	return rect_im(nx, 1., params ; args...)
end

"""
`phantom = rect_im(nx::Int ; ny::Int=nx, dx::Real=1)`

image of size `nx` by `ny` (default `nx`) with specified `dx` (default 1),
defaults to `:my_rect`
"""
function rect_im(nx::Int ; ny::Int=nx, dx::Real=1,
	params::Symbol=:my_rect, args...)
	ig = image_geom(nx=nx, ny=ny, dx=dx)
	return rect_im(ig, params ; args...)
end

"""
`phantom = rect_im(nx::Int, ny::Int ; args...)`

`:my_rect` of size `nx` by `ny`
"""
function rect_im(nx::Int, ny::Int ; args...)
	return rect_im(nx, ny=ny, dx=1. ; args...)
end

"""
`phantom = rect_im(ig, code ; args...)`

`code = :my_rect | :default | :smiley`
"""
function rect_im(ig::MIRT_image_geom, params::Symbol ; args...)
	fov = ig.fovs
	if params === :my_rect
		params = my_rect(fov...)
	elseif params === :default
		params = rect_im_default_parameters(fov...)
	elseif params === :smiley
		params = smiley_parameters(fov...)
	else
		throw("bad phantom symbol $params")
	end
	return rect_im(ig, params ; args...)
end

"""
`phantom = rect_im(ig ; args...)`

`:default` (default) for given image geometry `ig`
"""
function rect_im(ig::MIRT_image_geom ; args...)
	return rect_im(ig, :default ; args...)
end

"""
`params = rect_im_default_parameters(xfov, yfov)`

default parameters
"""
function rect_im_default_parameters(xfov, yfov)
	f = 1/64
	params = [
		0	0	50	50	0	1
		10	-16	25	16	0	-0.5
		-13	15	13	13	1*45	1
		-18	0	1	1	0	1
		-12	0	1	1	0	1
		-6	0	1	1	0	1
		0	0	1	1	0	1
		6	0	1	1	0	1
		12	0	1	1	0	1
		18	0	1	1	0	1
	]

	params[:,[1,3]] .*= xfov/64 # x_center and x_width
	params[:,[2,4]] .*= yfov/64 # y_center and y_width

	return params
end

"""
`params = my_rect(xfov, yfov)`
"""
function my_rect(xfov, yfov)
	f = 1/64
	rect = [
		35	35	20	10	45	1
		35	-35	20	10	-45	1
		-35	-35	20	10	45	1
		-35	35	20	10	-45	1
		0	0	40	40	45	1
		0	0	40	40	0	0.5
		40	0	12	1.5	0	1.5
		-40	0	12	1.5	0	1.5
	]
	return rect
end

"""
`params = smiley_parameters(xfov, yfov)`

smiley face out of rects
"""
function smiley_parameters(xfov, yfov)
	rect = [
		0	0	80	80	0	0.5
		-20	-20	10	15	0	1 #eyes
		20	-20	10	15	0	1
		0	25	50	6	0	1 #mouth
		-23	19	4	6	0	1
		23	19	4	6	0	1
	]
	return rect
end

"""
`rect_im()`

show docstring(s)
"""
function rect_im()
	@doc rect_im
end

"""
`rect_im_show()`
"""
function rect_im_show()
	#plot(1:10, 1:10)
	ig = image_geom(nx=2^8, ny=2^8, fov=100)

	x0 = rect_im(ig, [[[0.5, 0, 3, 20]*ig.dx..., 0, 1]';], oversample=3)
	p1 = jim(x0)

	x1 = rect_im(ig, :default ; oversample=3, chat=true)
	p2 = jim(x1, title="default rects")

	x2 = rect_im(ig, :my_rect ; oversample=3, chat=true)
	p3 = jim(x2, title="my rect")

	x3 =rect_im(ig, :smiley ; oversample=3, chat=true)
	p4 = jim(x3, title="smiley")

	plot(p1, p2, p3, p4)
end

function rect_im_test()
	fov = 100
	rect_im_default_parameters(fov, fov)
	rect_im_show()
	true
end

"""
`rect_im(:test)`

`rect_im(:show)`

run tests
"""
function rect_im(test::Symbol)
	if test === :show
		return rect_im_show()
	end
	test != :test && throw(ArgumentError("test $test"))
	ig = image_geom(nx=2^8, dx=3)
	@test_throws String rect_im(ig, :bad)
	rect_im(ig, :smiley, how=:fast, replace=true)
	rect_im(ig, how=:slow, replace=true)
	rect_im(32, ny=30, dx=3, params=:default, how=:slow, return_params=true)
	rect_im(32, 30)
	@test_throws String rect_im(32, :default, how=:bad)
	rect_im(:show)
	@test rect_im_test()
	rect_im()
	true
end

ext: jl


text:
using Test
using DelimitedFiles

@testset "Triangle Dislocation" begin
    P1 = [-1, -1, -5] * 1.0
    P2 = [1, -1, -5] * 1.0
    P3 = [-1, 1, -4] * 1.0
    ν = 0.25
    ss, ds, ts = 1.0, -1.0, 2.0

    xyz = [
        [-1/3, -1/3, -3.0],
        [-1/3, -1/3, -14/3],
        [-1/3, -1/3, -6.0],
        [7.0, -1.0, -5.0],
        [-7.0, -1.0, -5.],
        [-1.0, -3.0, -6.0],
        [-1.0, 3.0, -3.0],
        [3.0, -3.0, -6.0],
        [-3.0, 3.0, -3.0],
        [-1.0, -1.0, -1.0],
        [-1.0, 1.0, -1.0],
        [1.0, -1.0, -1.0],
        [-1.0, -1.0, -8.0],
        [-1.0, 1.0, -8.0],
        [1.0, -1.0, -8.0],
        ]

    @testset "displacement" begin
        u = map(x -> disp_tri3_hs(x[1], x[2], x[3], P1, P2, P3, ss, ds, ts, ν)[1], xyz)
        # validation data from Table 3, Nikkhoo & Walter, 2015
        u_truth = [
            0.0352311877319734, -0.509465745232405, -0.0450664903903138,
            -0.00230579292792908, 0.00401472894583963, 0.00483219740842196,
            0.00261498816660580, -0.00498017723062124, 0.00469791958297159,
            0.00147786823004841, 0.0037484457568832, 0.0166558386729541,
            -0.00656347406353817, -0.0105680479573571, -0.00213929091658054,
            ]
        @test u ≈ u_truth
    end

    @testset "strain ϵₓₓ" begin
        ϵ = map(x -> strain_tri3_hs(x[1], x[2], x[3], P1, P2, P3, ss, ds, ts, 2.0, 2.0)[1], xyz)
        # validation data from Table 3, Nikkhoo & Walter, 2015
        ϵ_truth = [
            0.048104700525518, -0.244188978214975, 0.0546831404832553,
            0.000829157341339727, 0.00114439668841158, -0.00386292388925956,
            -0.00243788640223540, 0.000706397690338731, 0.000211254167350266,
            0.00650800501584133, 0.000922452413344460, 0.00441202690885827,
            0.00330232019558791, 0.00876398663844928, -0.000914111766849476,
            ]
        @test ϵ ≈ ϵ_truth
    end
end

@testset "consistency between rectangular and triangular" begin
    # settings are adopted from Figure 11, Nikkhoo & Walter, 2015
    l, w = 1.5, 0.75
    dip, strike = 30.0, 10.0
    depth = 2.0
    depth_obs = 5.0

    p1 = [l/2 * sind(strike), l/2 * cosd(strike), -depth]
    p2 = [-p1[1], -p1[2], -2.0]
    p4 = [p1[1] + w * cosd(dip) * cosd(strike), p1[2] - w * cosd(dip) * sind(strike), p1[3] - w * sind(dip)]
    p3 = [p4[1] - l * sind(strike), p4[2] - l * cosd(strike), p4[3]]
    p′ = map(deepcopy, [p1, p2, p3, p4])

    xs = range(-3.0, 3.0; step=1.0)
    ys = range(-3.0, 3.0; step=1.0)

    disl = [0.0, 1.0, 0.0]
    A = [cosd(90-strike) sind(90-strike) 0; -sind(90-strike) cosd(90-strike) 0; 0 0 1]
    A⁻¹ = inv(A)
    E = Matrix{Float64}(undef, 3, 3)

    for (x, y) in Iterators.product(xs, ys)
        obs = A * [x, y, -depth_obs]
        u_okada = dc3d(obs..., 2/3, depth, dip, [-l/2, l/2], [-w, 0.0], disl)
        ux, uy, uz = A⁻¹ * u_okada[1:3]
        u_td1 = disp_tri3_hs(x, y, -depth_obs, p1, p2, p3, disl..., 0.25)
        u_td2 = disp_tri3_hs(x, y, -depth_obs, p3, p4, p1, disl..., 0.25)
        ux_td, uy_td, uz_td = map(+, u_td1, u_td2)
        @test ux_td ≈ ux && uy_td ≈ uy && uz_td ≈ uz
        E[1,1] = u_okada[4]
        E[2,2] = u_okada[8]
        E[3,3] = u_okada[12]
        E[1,2] = (u_okada[5] + u_okada[7]) / 2
        E[1,3] = (u_okada[6] + u_okada[10]) / 2
        E[2,3] = (u_okada[9] + u_okada[11]) / 2
        E[2,1] = E[1,2]
        E[3,1] = E[1,3]
        E[3,2] = E[2,3]
        E′ = A' * E * A
        ϵ_td1 = strain_tri3_hs(x, y, -depth_obs, p1, p2, p3, disl..., 1.0, 1.0)
        ϵ_td2 = strain_tri3_hs(x, y, -depth_obs, p3, p4, p1, disl..., 1.0, 1.0)
        ϵ = collect(ϵ_td1) + collect(ϵ_td2)
        @test ϵ[1] ≈ E′[1,1] && ϵ[2] ≈ E′[2,2] && ϵ[3] ≈ E′[3,3] && ϵ[4] ≈ E′[1,2] && ϵ[5] ≈ E′[1,3] && ϵ[6] ≈ E′[2,3]
    end
    @test p′ == [p1, p2, p3, p4] # test if pts coordinates have been changed
end

# @testset "Full space solution" begin
#     xs = collect(-10.0: 0.5: 10.0)
#     ys = collect(-8.0: 0.5: 8.0)
#     zs = 4.0

#     xyz = Iterators.product(zs, ys, xs) |> collect
#     Y = [q[2] for q in xyz] |> vec
#     X = [q[3] for q in xyz] |> vec
#     Z = [q[1] for q in xyz] |> vec

#     @testset "displacement" begin
#         u, v, w = disp_rect_fs(X, Y, Z, 3.0, 1.0, 0.0, 2.0, 1.0, 10.0, 75.0, 30.0, 20.0, 1.0, 0.15, 0.25, Val(:pc))
#         # validation data generated via orginal Matlab code
#         truth = readdlm(joinpath(@__DIR__, "data/test_disp_rect_fs.dat"), ' ', Float64)
#         @test truth[:,1] ≈ u && truth[:,2] ≈ v && truth[:,3] ≈ w
#     end
#     @testset "stress" begin
#         stress = stress_rect_fs(X, Y, Z, 3.0, 1.0, 0.0, 2.0, 1.0, 10.0, 75.0, 30.0, 20.0, 1.0, 0.15, 0.66e11, 0.33e11, Val(:pc))
#         # validation data generated via orginal Matlab code
#         truth = readdlm(joinpath(@__DIR__, "data/test_stress_rect_fs.dat"), ' ', Float64)
#         for i ∈ 1: 6
#             @test truth[:,i] ≈ stress[i]
#         end
#     end
# end


text:
module BEncode

export bencode, bdecode

function bencode(val::AbstractString)
    string(length(val)) * ":" * val
end

function bencode(val::Int)
    "i" * string(val) * "e"
end

function bencode(val::Array)
    "l" * join(map(bencode, val)) * "e"
end

function bencode(val::Dict)
    ks = sort(collect(keys(val)), lt = (x, y) -> isless(string(x), string(y)))
    "d" * join(map((k) -> bencode(string(k)) * bencode(val[k]), ks)) * "e"
end

function bparsestring(val::AbstractString)
    splitstr = split(val, ":", limit=2)
    thislength = parse(Int,splitstr[1])
    if length(splitstr[2]) > thislength
        thisstring = splitstr[2][1:thislength]
        return convert(String, thisstring), splitstr[2][thislength + 1:end]
    else
        return splitstr[2]
    end
end

function bparseint(val::AbstractString)
    splitstr = split(val, "e", limit=2)
    thisint = parse(Int,splitstr[1])
    if length(splitstr[2]) > 0
        return thisint, splitstr[2]
    else
        return thisint
    end
end

function bparsearray(val::AbstractString)
    array = Union{String,Int,Array,Dict}[]
    while val[1] != 'e'
        entry, val = bdecode(val)
        push!(array, entry)
    end
    if length(val) > 1
        array, val[2:end]
    else
        array
    end
end

function bparsedictentry(val::AbstractString)
    k, rest = bparsestring(val)
    v, rest = bdecode(rest)
    k, v, rest
end

function bparsedict(val::AbstractString)
    dict = Dict()
    while val[1] != 'e'
        k, v, val = bparsedictentry(val)
        dict[k] = v
    end
    if length(val) > 1
        dict, val[2:end]
    else
        dict
    end
end

function bdecode(val::AbstractString)
    if val[1] == 'i'
        bparseint(val[2:end])
    elseif val[1] == 'l'
        bparsearray(val[2:end])
    elseif val[1] == 'd'
        bparsedict(val[2:end])
    else
        bparsestring(val)
    end
end

end


text:
"""
    load_instance_by_paths(manager::ExperimentManager,
                           path_matpower::String,
                           path_OPF_ctr::String,
                           path_OPF_mat::String)

Load one instance in the database using its matpower and OPF files.
"""
function load_instance_by_paths(manager::ExperimentManager,
                                path_matpower::String,
                                path_OPF_ctr::String,
                                path_OPF_mat::String,
                                path_params::String)
    name = basename(path_matpower)[1:end - 2]
    paths = Mongoc.BSON("matpower" => abspath(path_matpower),
                        "OPF_ctr" => abspath(path_OPF_ctr),
                        "OPF_mat" => abspath(path_OPF_mat),
                        "params" => path_params)
    graph = construct_network_graph(abspath(path_matpower))
    features = get_features_instance(graph, paths["matpower"])
    return db.push_instance!(manager.instances, name, paths, features)
end

"""
    load_instance_by_name(manager::ExperimentManager,
                          name::String,
                          path_matpower::String,
                          path_OPF::String)

Load one instance by its name and matpower/OPF files.
"""
function load_instance_by_name(manager::ExperimentManager,
                               name::String,
                               path_matpower::String,
                               path_OPF::String,
                               path_params::String)
    abspath_matpower = abspath(path_matpower)
    abspath_OPF = abspath(path_OPF)
    path_matpower_instance = joinpath(abspath_matpower, "$(name).m")
    path_OPF_ctr = joinpath(abspath_OPF, "$(name)_sdp_ctr.txt")
    path_OPF_mat = joinpath(abspath_OPF, "$(name)_sdp_mat.txt")
    path_params = joinpath(abspath(path_params), "$(name).csv")
    paths = Mongoc.BSON("matpower" => path_matpower_instance,
                        "OPF_ctr" => path_OPF_ctr,
                        "OPF_mat" => path_OPF_mat,
                        "params" => path_params)
    graph = construct_network_graph(path_matpower_instance)
    features = get_features_instance(graph, paths["matpower"])
    return db.push_instance!(manager.instances, name, paths, features)
end

"""
    load_instance_by_name(manager::ExperimentManager,
                          name::String,
                          path_data::String="./data")

Load one instance by its name a single directory for matpower/OPF files.
"""
function load_instance_by_name(manager::ExperimentManager,
                               name::String,
                               path_data::String="./data")
    abspath_data = abspath(path_data)
    path_matpower = joinpath(abspath_data, "matpower/$(name).m")
    path_OPF_ctr = joinpath(abspath_data, "OPF/$(name)_sdp_ctr.txt")
    path_OPF_mat = joinpath(abspath_data, "OPF/$(name)_sdp_mat.txt")
    path_params = joinpath(abspath_data, "params_merge", "$(name).csv")
    graph = construct_network_graph(path_matpower)
    paths = Mongoc.BSON("matpower" => path_matpower,
                        "OPF_ctr" => path_OPF_ctr,
                        "OPF_mat" => path_OPF_mat,
                        "params" => path_params)
    features = get_features_instance(graph, paths["matpower"])
    return db.push_instance!(manager.instances, name, paths, features)
end

"""
    load_instance_by_size(manager::ExperimentManager,
                          min_size=0,
                          max_size=10000,
                          path_data::String="./data")

Load all the instance in the directory `path_data` with a graph size in [min_size, max_size]
"""
function load_instance_by_size(manager::ExperimentManager,
                               min_size=0,
                               max_size=10000,
                               path_data::String="./data")
    paths_matpower = readdir(joinpath(path_data, "matpower"))
    for name in paths_matpower
        graph = construct_network_graph(joinpath(path_data, "matpower", name))
        if nv(graph) >= min_size && nv(graph) <= max_size
            name = basename(name)[1:end - 2]
            load_instance_by_name(manager, name, path_data)
        end
    end
end

max_stars_repo_name: charlyalizadeh/OPFdecgen

max_issues_repo_name: charlyalizadeh/OPFdecgen

max_forks_repo_name: charlyalizadeh/OPFdecgen


text:
"""
Simple random `IndividualsSelector`.

The probabilties of all candidates are equal.
"""
struct SimpleSelector <: IndividualsSelector
end

select(::SimpleSelector, population, n::Integer) =
    sample(1:popsize(population), n, ordered=false, replace=false)


text:
# by Lazaro Alonso
using GeoMakie, Proj4, CairoMakie
using GeoMakie.GeoInterface
using GeoMakie.GeoJSON
using Downloads
CairoMakie.activate!()
let
    states = Downloads.download("https://raw.githubusercontent.com/PublicaMundi/MappingAPI/master/data/geojson/us-states.json")
    states_geo = GeoJSON.read(read(states, String))
    n = length(GeoInterface.features(states_geo))

    trans = Proj4.Transformation("+proj=longlat +datum=WGS84", "+proj=wintri",
        always_xy=true)
    # see https://proj.org/operations/projections/index.html for more options
    ptrans = Makie.PointTrans{2}(trans)

    fig = Figure(resolution = (1250,700), fontsize = 22)
    ax = Axis(fig[1,1], aspect = DataAspect(),
        title = "Projection: Winkel Tripel, US States")
    # all input data coordinates are projected using this function
    ax.scene.transformation.transform_func[] = ptrans
    # add some limits, still it needs to be manual
    lons = -180:180
    lats = -90:90
    points = [Point2f0(lon, lat) for lon in lons, lat in lats]
    rectLimits = FRect2D(Makie.apply_transform(ptrans, points))
    limits!(ax, rectLimits)
    # now the plot
    lines!(ax, GeoMakie.coastlines(), color = :black)
    poly!(ax, states_geo, color= 1:n, colormap = :plasma, strokecolor = :black,
        strokewidth = 1, overdraw = true, transformation=(:xy,10))

    hidedecorations!(ax, ticks = false, label = false, grid=false)
    hidespines!(ax)
    fig
    save(joinpath(@__DIR__, "output", "geoCoastlinesStatesUS.png"), fig) # HIDE
end
using Pkg # HIDE
Pkg.status(["GeoMakie", "Proj4", "CairoMakie", "GeoInterface", "GeoJSON", "Downloads"]) # HIDE

max_stars_repo_name: MisterBiggs/BeautifulMakie

max_issues_repo_name: MisterBiggs/BeautifulMakie

max_forks_repo_name: MisterBiggs/BeautifulMakie


text:
#  Copyright 2017, Iain Dunning, Joey Huchette, Miles Lubin, and contributors
#  This Source Code Form is subject to the terms of the Mozilla Public
#  License, v. 2.0. If a copy of the MPL was not distributed with this
#  file, You can obtain one at https://mozilla.org/MPL/2.0/.
#############################################################################
# JuMP
# An algebraic modeling language for Julia
# See https://github.com/jump-dev/JuMP.jl
#############################################################################

"""
    Containers

Module defining the containers `DenseAxisArray` and `SparseAxisArray` that
behaves as a regular `AbstractArray` but with custom indexes that are not
necessarily integers.
"""
module Containers

# Arbitrary typed indices. Linear indexing not supported.
struct IndexAnyCartesian <: Base.IndexStyle end
Base.IndexStyle(::IndexAnyCartesian, ::IndexAnyCartesian) = IndexAnyCartesian()

export DenseAxisArray, SparseAxisArray

include("DenseAxisArray.jl")
include("SparseAxisArray.jl")

function Base.eachindex(
    g::Base.Generator{<:Union{DenseAxisArray,SparseAxisArray}},
)
    return eachindex(g.iter)
end

# The generic implementation uses `LinearIndices` which is not supported by
# `DenseAxisArray` and `SparseAxisArray`.
function Base.collect_to_with_first!(
    dest::Union{DenseAxisArray,SparseAxisArray},
    first_value,
    iterator,
    state,
)
    indices = eachindex(iterator)
    dest[first(indices)] = first_value
    for index in Iterators.drop(indices, 1)
        element, state = iterate(iterator, state)
        dest[index] = element
    end
    return dest
end

include("generate_container.jl")
include("vectorized_product_iterator.jl")
include("nested_iterator.jl")
include("no_duplicate_dict.jl")
include("container.jl")
include("macro.jl")

end

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
module ServerStateExample

using Matte

const title = "Matte Example :: Server-side state"

function ui()
    sidebar_layout(
        side_panel(
            h1("Push this button"),
            br(),
            button("my_button", "Push me")
        ),
        main_panel(
            p("You have pushed the button: ", text_output("my_count"), " times")
        )
    )
end

function register_session_vars()
    Dict(
        :count => 0
    )
end

module Server

function my_count(my_button, session)
    if my_button
        session.count += 1
    end
    session.count
end

end

end


text:
using SparseArrays

function invariant_constraint!(
    M_orb::AbstractMatrix{<:AbstractFloat},
    M::Matrix{<:Integer},
    invariant_vec::SparseVector,
)
    M_orb .= zero(eltype(M_orb))
    for i in eachindex(M)
        if M[i] ∈ SparseArrays.nonzeroinds(invariant_vec)
            M_orb[i] += invariant_vec[M[i]]
        end
    end
    return M_orb
end


text:
using FFTW
using LinearAlgebra
using DSP
using Plots

function pcfm(m,k,nWaveforms=1)
  """
  pcfm(m,k)
  Compute the PCFM waveform for a randomly initialized phase code

    # Arguments
    - `m::Integer`: Phase code length
    - `k::Integer`: Oversampling factor
  """
  # Number of unique phase code values (i.e., no oversampling)
  n = trunc(Int,m/k)
  # Construct the array of phase code changes
  minAlpha = -pi/k
  maxAlpha = pi/k
  alpha = minAlpha .+(maxAlpha-minAlpha).*rand(Float64,(n, nWaveforms))
  # Phase shaping filter
  g = ones(k,1)./k
  g = vec(vcat(g,zeros(m-k,1)))
  B = zeros(m,n)
  for ii in 1:n
    B[:,ii] = cumsum(shiftsignal(g,ii*k))
  end
  s = exp.(im.*B*alpha)
  return (s,alpha,B)
end


text:
# Copyright (c) 2020-2021, Bank of Canada
# All rights reserved.

# """
#     TimeSeriesEcon

# This package is part of the StateSpaceEcon ecosystem.
# TimeSeriesEcon.jl provides functionality to work with
# low-Frequency discrete macroeconomic time-series data.

# ### Frequencies (abstract type):
#  - Unit
#  - Monthly
#  - Quarterly
#  - Yearly

# ### Types:

#  - `MIT{Frequency}` (aka "Moment In Time")
#      - a primitive type denoting monthly, quarterly, and yearly dates
#  - `TSeries{Frequency}`
#      - an `AbstractVector` that can be indexed using `MIT`

# ### Functions:

#  - `MIT` Constructors/Functions
#     - `mm(year::Int, period::Int)`: returns a monthly `MIT` type instance
#     - `qq(year::Int, period::Int)`: returns a quarterly `MIT` type instance
#     - `yy(year::Int)`: returns a yearly `MIT` type instance
#     - `ii(x::Int)`: returns a unit `MIT` type instance
#     - `year(x::MIT)`: returns a `Int64` year value associated with `x`
#     - `period(x::MIT)`: returns a `Int64` period value associated with `x`
#     - `frequencyof(x::MIT)`: returns `<: Frequency` assosicated wtih `x`

#  - Functions operating on `TSeries`
#     - `mitrange(x::TSeries)`: returns a `UnitRange{MIT{Frequency}}` for the given `x`
#     - `firstdate(x::TSeries)`: returns `MIT{Frequency}` first date associated with `x`
#     - `lastdate(x::TSeries)`: returns `MIT{Frequency}` last date associated with `x`
#     - `ppy(x::TSeries)`: returns the number of periods per year for `x::TSeries`. (`ppy` also accepts `x::MIT` and `x::Frequency`)
#     - `shift(x::TSeries, i::Int64)`: shifts the dates of `x` by `firstdate(x) - i`
#     - `shift!`: in-place version of `shift`
#     - `pct(x::TSeries, shift_value::Int64; islog::Bool = false)`: calculates percent rate of change of `x::TSeries`
#     - `apct(x::TSeries, islog::Bool = false)`: calculates annualized percent rate of change of `x::TSeries`
#     - `nanrm!(x::TSeries, type::Symbol=:both)`: removes `NaN` from `x::TSeries`
# """
module TimeSeriesEcon

include("momentintime.jl")
export MIT, Duration
export mm, qq, yy, pp
export Monthly, Quarterly, Yearly, Frequency, YPFrequency, Unit
export year, period, mit2yp
export frequencyof
export U, Y, Q1, Q2, Q3, Q4
export M1, M2, M3, M4, M5, M6
export M7, M8, M9, M10, M11, M12

include("tseries.jl")
export TSeries
export firstdate, lastdate, rangeof
export typenan, istypenan

include("tsbroadcast.jl")
include("tsmath.jl")
export shift, shift!, lag, lag!, lead, lead!

include("fconvert.jl")
export overlay, fconvert

include("mvtseries.jl")
export MVTSeries
export rawdata, colnames, columns

# export ppy
# export pct, apct
# export nanrm!

include("recursive.jl")
export @rec

include("plotrecipes.jl")

"""
    rangeof(s; drop::Integer)

Return the stored range of `s` adjusted by dropping `drop` periods. If `drop` is
positive, we drop from the beginning and if `drop` is negative we drop from the
end. This adds convenience when using [`@rec`](@ref)

Example
```
julia> q = TSeries(20Q1:21Q4); rangeof(q; drop=1)
20Q2:21Q4

julia> rangeof(q; drop=-4)
20Q1:20Q4

julia> q[begin:begin+1] .= 1; @rec rangeof(q; drop=2) q[t] = q[t-1] + q[t-2]; q
8-element TSeries{Quarterly} with range 20Q1:21Q4:
    20Q1 : 1.0
    20Q2 : 1.0
    20Q3 : 2.0
    20Q4 : 3.0
    21Q1 : 5.0
    21Q2 : 8.0
    21Q3 : 13.0
    21Q4 : 21.0
```
"""
@inline rangeof(x::Union{TSeries, MVTSeries}; drop::Integer) =
    (rng = rangeof(x);
        drop > 0 ? (first(rng) + drop:last(rng)) : (first(rng):last(rng)+drop))

include("workspaces.jl")

end


text:
mutable struct MainPathState{T<:Integer} <: TraversalState
    edges::Vector{SimpleEdge{T}}
    #weights::Vector{U}
end

function newvisitfn!(s::MainPathState, u, v)
    push!(s.edges, SimpleEdge(u, v))
    #push!(s.weights, weights(g, u, v))
    return true
end

function revisitfn!(s::MainPathState, u, v)
    push!(s.edges, SimpleEdge(u, v))
    #push!(s.weights, weights(g, u, v))
    return true
end

###########################
# Forward Local Main Path

struct ForwardLocal <: MainPathAlgorithm end

struct ForwardLocalResult{T<:Integer, U<:Real} <: MainPathResult
    edges::Vector{SimpleEdge{T}}
    weights::Vector{U}
    totalweight::U
end

function mainpath(
    g::AbstractGraph{T},
    s,
    weights::AbstractMatrix{U},
    ::ForwardLocal) where T <: Integer where U <: Real

    edges = Vector{SimpleEdge{T}}()
    state = MainPathState(edges)
    traverse_graph!(g, s, BreadthFirst(neighborfn=emax_outneighbors), state) # TODO emax_outneighbors gets weights from the graph object not from the input matrix
    w = [weights[src(e), dst(e)] for e in state.edges]

    return ForwardLocalResult(state.edges, w, sum(w))
end

mainpath(g::AbstractGraph{T}, s, ::ForwardLocal) where T <: Integer = mainpath(g, s, weights(g), ForwardLocal())

function mainpath(
    g::AbstractGraph{T},
    weights::AbstractMatrix{U},
    ::ForwardLocal) where T <: Integer where U <: Real

    sources = get_sources(g)
    sweights = [max_outweight(g, v, weights) for v in sources]
    s = sources[sweights .== maximum(sweights)]

    mainpath(g, s, weights, ForwardLocal())
end

mainpath(g::AbstractGraph{T}, ::ForwardLocal) where T <: Integer = mainpath(g, weights(g), ForwardLocal())

###########################
# Backward Local Main Path

struct BackwardLocal <: MainPathAlgorithm end

struct BackwardLocalResult{T<:Integer, U<:Real} <: MainPathResult
    edges::Vector{SimpleEdge{T}}
    weights::Vector{U}
    totalweight::U
end

function mainpath(
    g::AbstractGraph{T},
    s,
    weights::AbstractMatrix{U},
    ::BackwardLocal) where T <: Integer where U <: Real

    edges = Vector{SimpleEdge{T}}()
    state = MainPathState(edges)
    traverse_graph!(g, s, BreadthFirst(neighborfn=emax_inneighbors), state)
    state.edges = reverse.(state.edges)
    w = [weights[src(e), dst(e)] for e in state.edges]

    return BackwardLocalResult(state.edges, w, sum(w))
end

mainpath(g::AbstractGraph{T}, s, ::BackwardLocal) where T <: Integer = mainpath(g, s, weights(g), BackwardLocal())

function mainpath(
    g::AbstractGraph{T},
    weights::AbstractMatrix{U},
    ::BackwardLocal) where T <: Integer where U <: Real

    sinks = get_sinks(g)
    sweights = [max_inweight(g, v, weights) for v in sinks]
    s = sinks[sweights .== maximum(sweights)]

    mainpath(g, s, weights, BackwardLocal())
end

mainpath(g::AbstractGraph{T}, ::BackwardLocal) where T <: Integer = mainpath(g, weights(g), BackwardLocal())


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

"""
    abort_document_version_upload(document_id, version_id)
    abort_document_version_upload(document_id, version_id, params::Dict{String,<:Any})

Aborts the upload of the specified document version that was previously initiated by
InitiateDocumentVersionUpload. The client should make this call only when it no longer
intends to upload the document version, or fails to do so.

# Arguments
- `document_id`: The ID of the document.
- `version_id`: The ID of the version.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
function abort_document_version_upload(
    DocumentId, VersionId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "DELETE",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function abort_document_version_upload(
    DocumentId,
    VersionId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "DELETE",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Activates the specified user. Only active users can access Amazon WorkDocs.

# Arguments
- `user_id`: The ID of the user.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
function activate_user(UserId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "POST",
        "/api/v1/users/$(UserId)/activation";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function activate_user(
    UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "POST",
        "/api/v1/users/$(UserId)/activation",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    add_resource_permissions(principals, resource_id)
    add_resource_permissions(principals, resource_id, params::Dict{String,<:Any})

Creates a set of permissions for the specified folder or document. The resource permissions
are overwritten if the principals already have different permissions.

# Arguments
- `principals`: The users, groups, or organization being granted permission.
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"NotificationOptions"`: The notification options.
"""
function add_resource_permissions(
    Principals, ResourceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "POST",
        "/api/v1/resources/$(ResourceId)/permissions",
        Dict{String,Any}("Principals" => Principals);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function add_resource_permissions(
    Principals,
    ResourceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "POST",
        "/api/v1/resources/$(ResourceId)/permissions",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("Principals" => Principals), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_comment(document_id, text, version_id)
    create_comment(document_id, text, version_id, params::Dict{String,<:Any})

Adds a new comment to the specified document version.

# Arguments
- `document_id`: The ID of the document.
- `text`: The text of the comment.
- `version_id`: The ID of the document version.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"NotifyCollaborators"`: Set this parameter to TRUE to send an email out to the document
  collaborators after the comment is created.
- `"ParentId"`: The ID of the parent comment.
- `"ThreadId"`: The ID of the root comment in the thread.
- `"Visibility"`: The visibility of the comment. Options are either PRIVATE, where the
  comment is visible only to the comment author and document owner and co-owners, or PUBLIC,
  where the comment is visible to document owners, co-owners, and contributors.
"""
function create_comment(
    DocumentId, Text, VersionId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "POST",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comment",
        Dict{String,Any}("Text" => Text);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_comment(
    DocumentId,
    Text,
    VersionId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "POST",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comment",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("Text" => Text), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_custom_metadata(custom_metadata, resource_id)
    create_custom_metadata(custom_metadata, resource_id, params::Dict{String,<:Any})

Adds one or more custom properties to the specified resource (a folder, document, or
version).

# Arguments
- `custom_metadata`: Custom metadata in the form of name-value pairs.
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"versionid"`: The ID of the version, if the custom metadata is being added to a document
  version.
"""
function create_custom_metadata(
    CustomMetadata, ResourceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "PUT",
        "/api/v1/resources/$(ResourceId)/customMetadata",
        Dict{String,Any}("CustomMetadata" => CustomMetadata);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_custom_metadata(
    CustomMetadata,
    ResourceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "PUT",
        "/api/v1/resources/$(ResourceId)/customMetadata",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("CustomMetadata" => CustomMetadata), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Creates a folder with the specified name and parent folder.

# Arguments
- `parent_folder_id`: The ID of the parent folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"Name"`: The name of the new folder.
"""
function create_folder(ParentFolderId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "POST",
        "/api/v1/folders",
        Dict{String,Any}("ParentFolderId" => ParentFolderId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_folder(
    ParentFolderId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "POST",
        "/api/v1/folders",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ParentFolderId" => ParentFolderId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_labels(labels, resource_id)
    create_labels(labels, resource_id, params::Dict{String,<:Any})

Adds the specified list of labels to the given resource (a document or folder)

# Arguments
- `labels`: List of labels to add to the resource.
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
function create_labels(
    Labels, ResourceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "PUT",
        "/api/v1/resources/$(ResourceId)/labels",
        Dict{String,Any}("Labels" => Labels);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_labels(
    Labels,
    ResourceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "PUT",
        "/api/v1/resources/$(ResourceId)/labels",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("Labels" => Labels), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_notification_subscription(endpoint, organization_id, protocol, subscription_type)
    create_notification_subscription(endpoint, organization_id, protocol, subscription_type, params::Dict{String,<:Any})

Configure Amazon WorkDocs to use Amazon SNS notifications. The endpoint receives a
confirmation message, and must confirm the subscription. For more information, see
Subscribe to Notifications in the Amazon WorkDocs Developer Guide.

# Arguments
- `endpoint`: The endpoint to receive the notifications. If the protocol is HTTPS, the
  endpoint is a URL that begins with https.
- `organization_id`: The ID of the organization.
- `protocol`: The protocol to use. The supported value is https, which delivers
  JSON-encoded messages using HTTPS POST.
- `subscription_type`: The notification type.

"""
function create_notification_subscription(
    Endpoint,
    OrganizationId,
    Protocol,
    SubscriptionType;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "POST",
        "/api/v1/organizations/$(OrganizationId)/subscriptions",
        Dict{String,Any}(
            "Endpoint" => Endpoint,
            "Protocol" => Protocol,
            "SubscriptionType" => SubscriptionType,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_notification_subscription(
    Endpoint,
    OrganizationId,
    Protocol,
    SubscriptionType,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "POST",
        "/api/v1/organizations/$(OrganizationId)/subscriptions",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "Endpoint" => Endpoint,
                    "Protocol" => Protocol,
                    "SubscriptionType" => SubscriptionType,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_user(given_name, password, surname, username)
    create_user(given_name, password, surname, username, params::Dict{String,<:Any})

Creates a user in a Simple AD or Microsoft AD directory. The status of a newly created user
is \"ACTIVE\". New users can access Amazon WorkDocs.

# Arguments
- `given_name`: The given name of the user.
- `password`: The password of the user.
- `surname`: The surname of the user.
- `username`: The login name of the user.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"EmailAddress"`: The email address of the user.
- `"OrganizationId"`: The ID of the organization.
- `"StorageRule"`: The amount of storage for the user.
- `"TimeZoneId"`: The time zone ID of the user.
"""
function create_user(
    GivenName,
    Password,
    Surname,
    Username;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "POST",
        "/api/v1/users",
        Dict{String,Any}(
            "GivenName" => GivenName,
            "Password" => Password,
            "Surname" => Surname,
            "Username" => Username,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_user(
    GivenName,
    Password,
    Surname,
    Username,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "POST",
        "/api/v1/users",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "GivenName" => GivenName,
                    "Password" => Password,
                    "Surname" => Surname,
                    "Username" => Username,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deactivates the specified user, which revokes the user's access to Amazon WorkDocs.

# Arguments
- `user_id`: The ID of the user.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
function deactivate_user(UserId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "DELETE",
        "/api/v1/users/$(UserId)/activation";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function deactivate_user(
    UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "DELETE",
        "/api/v1/users/$(UserId)/activation",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_comment(comment_id, document_id, version_id)
    delete_comment(comment_id, document_id, version_id, params::Dict{String,<:Any})

Deletes the specified comment from the document version.

# Arguments
- `comment_id`: The ID of the comment.
- `document_id`: The ID of the document.
- `version_id`: The ID of the document version.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
function delete_comment(
    CommentId, DocumentId, VersionId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "DELETE",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comment/$(CommentId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_comment(
    CommentId,
    DocumentId,
    VersionId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "DELETE",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comment/$(CommentId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deletes custom metadata from the specified resource.

# Arguments
- `resource_id`: The ID of the resource, either a document or folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"deleteAll"`: Flag to indicate removal of all custom metadata properties from the
  specified resource.
- `"keys"`: List of properties to remove.
- `"versionId"`: The ID of the version, if the custom metadata is being deleted from a
  document version.
"""
function delete_custom_metadata(
    ResourceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "DELETE",
        "/api/v1/resources/$(ResourceId)/customMetadata";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_custom_metadata(
    ResourceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "DELETE",
        "/api/v1/resources/$(ResourceId)/customMetadata",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Permanently deletes the specified document and its associated metadata.

# Arguments
- `document_id`: The ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
function delete_document(DocumentId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "DELETE",
        "/api/v1/documents/$(DocumentId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_document(
    DocumentId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "DELETE",
        "/api/v1/documents/$(DocumentId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Permanently deletes the specified folder and its contents.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
function delete_folder(FolderId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "DELETE",
        "/api/v1/folders/$(FolderId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_folder(
    FolderId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "DELETE",
        "/api/v1/folders/$(FolderId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deletes the contents of the specified folder.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
function delete_folder_contents(FolderId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "DELETE",
        "/api/v1/folders/$(FolderId)/contents";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_folder_contents(
    FolderId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "DELETE",
        "/api/v1/folders/$(FolderId)/contents",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deletes the specified list of labels from a resource.

# Arguments
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"deleteAll"`: Flag to request removal of all labels from the specified resource.
- `"labels"`: List of labels to delete from the resource.
"""
function delete_labels(ResourceId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "DELETE",
        "/api/v1/resources/$(ResourceId)/labels";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_labels(
    ResourceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "DELETE",
        "/api/v1/resources/$(ResourceId)/labels",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_notification_subscription(organization_id, subscription_id)
    delete_notification_subscription(organization_id, subscription_id, params::Dict{String,<:Any})

Deletes the specified subscription from the specified organization.

# Arguments
- `organization_id`: The ID of the organization.
- `subscription_id`: The ID of the subscription.

"""
function delete_notification_subscription(
    OrganizationId, SubscriptionId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "DELETE",
        "/api/v1/organizations/$(OrganizationId)/subscriptions/$(SubscriptionId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_notification_subscription(
    OrganizationId,
    SubscriptionId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "DELETE",
        "/api/v1/organizations/$(OrganizationId)/subscriptions/$(SubscriptionId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deletes the specified user from a Simple AD or Microsoft AD directory.

# Arguments
- `user_id`: The ID of the user.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Do not set this field when
  using administrative API actions, as in accessing the API using AWS credentials.
"""
function delete_user(UserId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "DELETE",
        "/api/v1/users/$(UserId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_user(
    UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "DELETE",
        "/api/v1/users/$(UserId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Describes the user activities in a specified time period.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"activityTypes"`: Specifies which activity types to include in the response. If this
  field is left empty, all activity types are returned.
- `"endTime"`: The timestamp that determines the end time of the activities. The response
  includes the activities performed before the specified timestamp.
- `"includeIndirectActivities"`: Includes indirect activities. An indirect activity results
  from a direct activity performed on a parent resource. For example, sharing a parent folder
  (the direct activity) shares all of the subfolders and documents within the parent folder
  (the indirect activity).
- `"limit"`: The maximum number of items to return.
- `"marker"`: The marker for the next set of results.
- `"organizationId"`: The ID of the organization. This is a mandatory parameter when using
  administrative API (SigV4) requests.
- `"resourceId"`: The document or folder ID for which to describe activity types.
- `"startTime"`: The timestamp that determines the starting time of the activities. The
  response includes the activities performed after the specified timestamp.
- `"userId"`: The ID of the user who performed the action. The response includes activities
  pertaining to this user. This is an optional parameter and is only applicable for
  administrative API (SigV4) requests.
"""
function describe_activities(; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "GET", "/api/v1/activities"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function describe_activities(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "GET",
        "/api/v1/activities",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_comments(document_id, version_id)
    describe_comments(document_id, version_id, params::Dict{String,<:Any})

List all the comments for the specified document version.

# Arguments
- `document_id`: The ID of the document.
- `version_id`: The ID of the document version.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"limit"`: The maximum number of items to return.
- `"marker"`: The marker for the next set of results. This marker was received from a
  previous call.
"""
function describe_comments(
    DocumentId, VersionId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "GET",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comments";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_comments(
    DocumentId,
    VersionId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)/comments",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Retrieves the document versions for the specified document. By default, only active
versions are returned.

# Arguments
- `document_id`: The ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"fields"`: Specify \"SOURCE\" to include initialized versions and a URL for the source
  document.
- `"include"`: A comma-separated list of values. Specify \"INITIALIZED\" to include
  incomplete versions.
- `"limit"`: The maximum number of versions to return with this call.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
"""
function describe_document_versions(
    DocumentId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "GET",
        "/api/v1/documents/$(DocumentId)/versions";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_document_versions(
    DocumentId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/documents/$(DocumentId)/versions",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Describes the contents of the specified folder, including its documents and subfolders. By
default, Amazon WorkDocs returns the first 100 active document and folder metadata items.
If there are more results, the response includes a marker that you can use to request the
next set of results. You can also request initialized documents.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"include"`: The contents to include. Specify \"INITIALIZED\" to include initialized
  documents.
- `"limit"`: The maximum number of items to return with this call.
- `"marker"`: The marker for the next set of results. This marker was received from a
  previous call.
- `"order"`: The order for the contents of the folder.
- `"sort"`: The sorting criteria.
- `"type"`: The type of items.
"""
function describe_folder_contents(
    FolderId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "GET",
        "/api/v1/folders/$(FolderId)/contents";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_folder_contents(
    FolderId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/folders/$(FolderId)/contents",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Describes the groups specified by the query. Groups are defined by the underlying Active
Directory.

# Arguments
- `search_query`: A query to describe groups by group name.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"limit"`: The maximum number of items to return with this call.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"organizationId"`: The ID of the organization.
"""
function describe_groups(searchQuery; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "GET",
        "/api/v1/groups",
        Dict{String,Any}("searchQuery" => searchQuery);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_groups(
    searchQuery,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/groups",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("searchQuery" => searchQuery), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Lists the specified notification subscriptions.

# Arguments
- `organization_id`: The ID of the organization.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"limit"`: The maximum number of items to return with this call.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
"""
function describe_notification_subscriptions(
    OrganizationId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "GET",
        "/api/v1/organizations/$(OrganizationId)/subscriptions";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_notification_subscriptions(
    OrganizationId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/organizations/$(OrganizationId)/subscriptions",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Describes the permissions of a specified resource.

# Arguments
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"limit"`: The maximum number of items to return with this call.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call)
- `"principalId"`: The ID of the principal to filter permissions by.
"""
function describe_resource_permissions(
    ResourceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "GET",
        "/api/v1/resources/$(ResourceId)/permissions";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_resource_permissions(
    ResourceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/resources/$(ResourceId)/permissions",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Describes the current user's special folders; the RootFolder and the RecycleBin. RootFolder
is the root of user's files and folders and RecycleBin is the root of recycled items. This
is not a valid action for SigV4 (administrative API) clients. This action requires an
authentication token. To get an authentication token, register an application with Amazon
WorkDocs. For more information, see Authentication and Access Control for User Applications
in the Amazon WorkDocs Developer Guide.

# Arguments
- `authentication`: Amazon WorkDocs authentication token.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"limit"`: The maximum number of items to return.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
"""
function describe_root_folders(
    Authentication; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "GET",
        "/api/v1/me/root",
        Dict{String,Any}("headers" => Dict{String,Any}("Authentication" => Authentication));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_root_folders(
    Authentication,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/me/root",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "headers" => Dict{String,Any}("Authentication" => Authentication)
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Describes the specified users. You can describe all users or filter the results (for
example, by status or organization). By default, Amazon WorkDocs returns the first 24
active or pending users. If there are more results, the response includes a marker that you
can use to request the next set of results.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"fields"`: A comma-separated list of values. Specify \"STORAGE_METADATA\" to include the
  user storage quota and utilization information.
- `"include"`: The state of the users. Specify \"ALL\" to include inactive users.
- `"limit"`: The maximum number of items to return.
- `"marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"order"`: The order for the results.
- `"organizationId"`: The ID of the organization.
- `"query"`: A query to filter users by user name.
- `"sort"`: The sorting criteria.
- `"userIds"`: The IDs of the users.
"""
function describe_users(; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "GET", "/api/v1/users"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function describe_users(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "GET",
        "/api/v1/users",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Retrieves details of the current user for whom the authentication token was generated. This
is not a valid action for SigV4 (administrative API) clients. This action requires an
authentication token. To get an authentication token, register an application with Amazon
WorkDocs. For more information, see Authentication and Access Control for User Applications
in the Amazon WorkDocs Developer Guide.

# Arguments
- `authentication`: Amazon WorkDocs authentication token.

"""
function get_current_user(Authentication; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "GET",
        "/api/v1/me",
        Dict{String,Any}("headers" => Dict{String,Any}("Authentication" => Authentication));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_current_user(
    Authentication,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/me",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "headers" => Dict{String,Any}("Authentication" => Authentication)
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Retrieves details of a document.

# Arguments
- `document_id`: The ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"includeCustomMetadata"`: Set this to TRUE to include custom metadata in the response.
"""
function get_document(DocumentId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "GET",
        "/api/v1/documents/$(DocumentId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_document(
    DocumentId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/documents/$(DocumentId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Retrieves the path information (the hierarchy from the root folder) for the requested
document. By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the
requested document and only includes the IDs of the parent folders in the path. You can
limit the maximum number of levels. You can also request the names of the parent folders.

# Arguments
- `document_id`: The ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"fields"`: A comma-separated list of values. Specify NAME to include the names of the
  parent folders.
- `"limit"`: The maximum number of levels in the hierarchy to return.
- `"marker"`: This value is not supported.
"""
function get_document_path(DocumentId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "GET",
        "/api/v1/documents/$(DocumentId)/path";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_document_path(
    DocumentId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/documents/$(DocumentId)/path",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_document_version(document_id, version_id)
    get_document_version(document_id, version_id, params::Dict{String,<:Any})

Retrieves version metadata for the specified document.

# Arguments
- `document_id`: The ID of the document.
- `version_id`: The version ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"fields"`: A comma-separated list of values. Specify \"SOURCE\" to include a URL for the
  source document.
- `"includeCustomMetadata"`: Set this to TRUE to include custom metadata in the response.
"""
function get_document_version(
    DocumentId, VersionId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "GET",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_document_version(
    DocumentId,
    VersionId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Retrieves the metadata of the specified folder.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"includeCustomMetadata"`: Set to TRUE to include custom metadata in the response.
"""
function get_folder(FolderId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "GET",
        "/api/v1/folders/$(FolderId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_folder(
    FolderId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/folders/$(FolderId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Retrieves the path information (the hierarchy from the root folder) for the specified
folder. By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the
requested folder and only includes the IDs of the parent folders in the path. You can limit
the maximum number of levels. You can also request the parent folder names.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"fields"`: A comma-separated list of values. Specify \"NAME\" to include the names of
  the parent folders.
- `"limit"`: The maximum number of levels in the hierarchy to return.
- `"marker"`: This value is not supported.
"""
function get_folder_path(FolderId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "GET",
        "/api/v1/folders/$(FolderId)/path";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_folder_path(
    FolderId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "GET",
        "/api/v1/folders/$(FolderId)/path",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Retrieves a collection of resources, including folders and documents. The only
CollectionType supported is SHARED_WITH_ME.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: The Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"collectionType"`: The collection type.
- `"limit"`: The maximum number of resources to return.
- `"marker"`: The marker for the next set of results. This marker was received from a
  previous call.
- `"userId"`: The user ID for the resource collection. This is a required field for
  accessing the API operation using IAM credentials.
"""
function get_resources(; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "GET", "/api/v1/resources"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function get_resources(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "GET",
        "/api/v1/resources",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Creates a new document object and version object. The client specifies the parent folder ID
and name of the document to upload. The ID is optionally specified when creating a new
version of an existing document. This is the first step to upload a document. Next, upload
the document to the URL returned from the call, and then call UpdateDocumentVersion. To
cancel the document upload, call AbortDocumentVersionUpload.

# Arguments
- `parent_folder_id`: The ID of the parent folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"ContentCreatedTimestamp"`: The timestamp when the content of the document was
  originally created.
- `"ContentModifiedTimestamp"`: The timestamp when the content of the document was modified.
- `"ContentType"`: The content type of the document.
- `"DocumentSizeInBytes"`: The size of the document, in bytes.
- `"Id"`: The ID of the document.
- `"Name"`: The name of the document.
"""
function initiate_document_version_upload(
    ParentFolderId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "POST",
        "/api/v1/documents",
        Dict{String,Any}("ParentFolderId" => ParentFolderId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function initiate_document_version_upload(
    ParentFolderId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "POST",
        "/api/v1/documents",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ParentFolderId" => ParentFolderId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Removes all the permissions from the specified resource.

# Arguments
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
"""
function remove_all_resource_permissions(
    ResourceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "DELETE",
        "/api/v1/resources/$(ResourceId)/permissions";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function remove_all_resource_permissions(
    ResourceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "DELETE",
        "/api/v1/resources/$(ResourceId)/permissions",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    remove_resource_permission(principal_id, resource_id)
    remove_resource_permission(principal_id, resource_id, params::Dict{String,<:Any})

Removes the permission for the specified principal from the specified resource.

# Arguments
- `principal_id`: The principal ID of the resource.
- `resource_id`: The ID of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"type"`: The principal type of the resource.
"""
function remove_resource_permission(
    PrincipalId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "DELETE",
        "/api/v1/resources/$(ResourceId)/permissions/$(PrincipalId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function remove_resource_permission(
    PrincipalId,
    ResourceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "DELETE",
        "/api/v1/resources/$(ResourceId)/permissions/$(PrincipalId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Updates the specified attributes of a document. The user must have access to both the
document and its parent folder, if applicable.

# Arguments
- `document_id`: The ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"Name"`: The name of the document.
- `"ParentFolderId"`: The ID of the parent folder.
- `"ResourceState"`: The resource state of the document. Only ACTIVE and RECYCLED are
  supported.
"""
function update_document(DocumentId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "PATCH",
        "/api/v1/documents/$(DocumentId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_document(
    DocumentId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "PATCH",
        "/api/v1/documents/$(DocumentId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_document_version(document_id, version_id)
    update_document_version(document_id, version_id, params::Dict{String,<:Any})

Changes the status of the document version to ACTIVE.  Amazon WorkDocs also sets its
document container to ACTIVE. This is the last step in a document upload, after the client
uploads the document to an S3-presigned URL returned by InitiateDocumentVersionUpload.

# Arguments
- `document_id`: The ID of the document.
- `version_id`: The version ID of the document.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"VersionStatus"`: The status of the version.
"""
function update_document_version(
    DocumentId, VersionId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "PATCH",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_document_version(
    DocumentId,
    VersionId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "PATCH",
        "/api/v1/documents/$(DocumentId)/versions/$(VersionId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Updates the specified attributes of the specified folder. The user must have access to both
the folder and its parent folder, if applicable.

# Arguments
- `folder_id`: The ID of the folder.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"Name"`: The name of the folder.
- `"ParentFolderId"`: The ID of the parent folder.
- `"ResourceState"`: The resource state of the folder. Only ACTIVE and RECYCLED are
  accepted values from the API.
"""
function update_folder(FolderId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "PATCH",
        "/api/v1/folders/$(FolderId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_folder(
    FolderId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return workdocs(
        "PATCH",
        "/api/v1/folders/$(FolderId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Updates the specified attributes of the specified user, and grants or revokes
administrative privileges to the Amazon WorkDocs site.

# Arguments
- `user_id`: The ID of the user.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Authentication"`: Amazon WorkDocs authentication token. Not required when using AWS
  administrator credentials to access the API.
- `"GivenName"`: The given name of the user.
- `"GrantPoweruserPrivileges"`: Boolean value to determine whether the user is granted
  Poweruser privileges.
- `"Locale"`: The locale of the user.
- `"StorageRule"`: The amount of storage for the user.
- `"Surname"`: The surname of the user.
- `"TimeZoneId"`: The time zone ID of the user.
- `"Type"`: The type of the user.
"""
function update_user(UserId; aws_config::AbstractAWSConfig=global_aws_config())
    return workdocs(
        "PATCH",
        "/api/v1/users/$(UserId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_user(
    UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return workdocs(
        "PATCH",
        "/api/v1/users/$(UserId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end


text:
export Stack

mutable struct Stack{T}
    data::Vector{T}
    Stack{T}(d::T) where T = new(T[d])
end

function Base.show(io::IO, s::Stack)
    print(io, "Stack([")
    for (i, x) in enumerate(s.data)
        print(io, "$(x)")
        if i != length(s.data)
            print(io, ", ")
        end
    end
    print(io, "])")
end

Base.pop!(s::Stack) = deleteat!(s.data, 1)

Base.push!(s::Stack, d) = pushfirst!(s.data, d)


text:
#! /usr/bin/julia

# Rosetta Code, Count in octal

for i in one(Int64):typemax(Int64)
    print(oct(i), " ")
    sleep(0.1)
end

max_stars_repo_name: MichaeLeroy/rosetta-code

max_issues_repo_name: MichaeLeroy/rosetta-code

max_forks_repo_name: MichaeLeroy/rosetta-code


text:
function repl_startdebugger_request(conn, params::String, crashreporting_pipename)
    hideprompt() do
        debug_pipename = params
        try
            @debug "Trying to connect to debug adapter."
            socket = Sockets.connect(debug_pipename)
            try
                DebugAdapter.startdebug(socket, function (err, bt)
                    printstyled(stderr, "Error while running the debugger", color=:red, bold=true)
                    printstyled(stderr, " (consider adding a breakpoint for uncaught exceptions):\n", color=:red)
                    Base.display_error(stderr, err, bt)
                end)
            finally
                close(socket)
            end
        catch err
            global_err_handler(err, catch_backtrace(), crashreporting_pipename, "Debugger")
        end
    end
end

function remove_lln!(ex::Expr)
    for i in length(ex.args):-1:1
        if ex.args[i] isa LineNumberNode
            deleteat!(ex.args, i)
        elseif ex.args[i] isa Expr
            remove_lln!(ex.args[i])
        end
    end
end

macro enter(command)
    remove_lln!(command)
    :(JSONRPC.send_notification(conn_endpoint[], "debugger/enter", (code = $(string(command)), filename = $(string(__source__.file)))))
end

macro run(command)
    remove_lln!(command)
    :(JSONRPC.send_notification(conn_endpoint[], "debugger/run", (code = $(string(command)), filename = $(string(__source__.file)))))
end


text:
immutable HomotheticSystem2{T} <: Model
    a::T
    ω::T
    δ₁::T
    δ₂::T
end

Base.show(io::IO, ::Type{HomotheticSystem2}) = print(io, "Homothetic System-2")

function Base.show(io::IO, m::HomotheticSystem2)
    @printf(
        io,
        "Homothetic System-2 (a = %.3f, ω = %.3f, δ₁ = %.3f, δ₂ = %.3f)",
        m.a,
        m.ω,
        m.δ₁,
        m.δ₂,
    )
end

function initial_parameters(::Type{HomotheticSystem2})
    return Float64[log(1.0), logit(0.5), logit(0.25), logit(0.75)]
end

canonical_parameters(m::HomotheticSystem2) = (m.a, m.ω, m.δ₁, m.δ₂)

function HomotheticSystem2(parameters::Vector)
    a = exp(parameters[1])
    ω = invlogit(parameters[2])
    δ₁ = invlogit(parameters[3])
    δ₂ = invlogit(parameters[4])
    return HomotheticSystem2(a, ω, δ₁, δ₂)
end

@inline function predict(
    m::HomotheticSystem2,
    x2::Real,
    t2::Real,
    x1::Real,
    t1::Real,
)
    a, ω, δ₁, δ₂ = m.a, m.ω, m.δ₁, m.δ₂
    u1 = log(x1 * (ω * δ₁^t1 + (1 - ω) * δ₂^t1))
    u2 = log(x2 * (ω * δ₁^t2 + (1 - ω) * δ₂^t2))
    z = a * (u2 - u1)
    p = invlogit(z)
    return p
end

@inline function gradient_component(
    m::HomotheticSystem2,
    x2::Real,
    t2::Real,
    x1::Real,
    t1::Real,
)
    a, ω, δ₁, δ₂ = m.a, m.ω, m.δ₁, m.δ₂
    d_t2 = ω * δ₁^t2 + (1 - ω) * δ₂^t2
    d_t1 = ω * δ₁^t1 + (1 - ω) * δ₂^t1
    u2 = log(x2 * d_t2)
    u1 = log(x1 * d_t1)
    gr = (
        (u2 - u1) * a,
        a * ((δ₁^t2 - δ₂^t2) / d_t2 - (δ₁^t1 - δ₂^t1) / d_t1) * ω * (1 - ω),
        a * ((ω * t2 * δ₁^(t2 - 1)) / d_t2 - (ω * t1 * δ₁^(t1 - 1)) / d_t1) * δ₁ * (1 - δ₁),
        a * (((1 - ω) * t2 * δ₂^(t2 - 1)) / d_t2 - ((1 - ω) * t1 * δ₂^(t1 - 1)) / d_t1) * δ₂ * (1 - δ₂),
    )
    return gr
end


text:
using Crystallography: Lattice
using LinearAlgebra: I

export distortby, strainstate

# See https://link.springer.com/content/pdf/10.1007%2F978-3-7091-0382-1_7.pdf and https://doi.org/10.2138/am-1997-1-207
distortby(lattice::Lattice, strain::TensorStrain) =
    Lattice((I + strain.data) * lattice.data)
distortby(lattice::Lattice, strain::EngineeringStrain) =
    distortby(lattice, TensorStrain(strain))

strainstate(old::Lattice, new::Lattice) = TensorStrain(new.data / old.data - I)