text:
"""
`Archive` saves information about promising solutions during an optimization run.
"""
abstract type Archive{F,FS<:FitnessScheme} end

numdims(a::Archive) = a.numdims
fitness_type(a::Archive{F}) where F = F
fitness_scheme(a::Archive) = a.fit_scheme

"""
    archived_fitness(fit, a::Archive)

Converts given fitness `fit` to the format used by the archive `a`.
"""
archived_fitness(fit::Any, a::Archive) = convert(fitness_type(a), fit, fitness_scheme(a))

"""
Base class for individuals stored in `Archive`.
"""
abstract type ArchivedIndividual{F} <: FitIndividual{F} end

tag(indi::ArchivedIndividual) = indi.tag

"""
Individual stored in `TopListArchive`.
"""
struct TopListIndividual{F} <: ArchivedIndividual{F}
    params::Individual
    fitness::F
    tag::Int

    TopListIndividual(params::AbstractIndividual, fitness::F, tag::Int) where F =
        new{F}(params, fitness, tag)
end

Base.:(==)(x::TopListIndividual{F}, y::TopListIndividual{F}) where F =
  (x.fitness == y.fitness) && (x.params == y.params)

"""
Fitness as stored in `TopListArchive`.
"""
struct TopListFitness{F<:Number}
    fitness::F            # current fitness
    fitness_improvement_ratio::Float64
    num_fevals::Int     # number of fitness evaluations so far
    timestamp::Float64    # when archived
end

fitness(f::TopListFitness) = f.fitness

"""
Archive that maintains a top list of the best performing (best fitness)
candidates seen so far.

The two last best fitness values could be used to estimate a confidence interval for how much improvement
potential there is.
"""
mutable struct TopListArchive{F<:Number,FS<:FitnessScheme} <: Archive{F,FS}
    fit_scheme::FS        # Fitness scheme used
    start_time::Float64   # Time when archive created, we use this to approximate the starting time for the opt...
    numdims::Int          # Number of dimensions in the optimization problem. Needed for confidence interval estimation.

    num_fitnesses::Int    # Number of calls to add_candidate

    capacity::Int         # Max size of top lists
    candidates::Vector{TopListIndividual{F}}  # Top candidates and their fitness values

    # Stores a fitness history that we can later print to a csv file.
    # For each magnitude class (as defined by `magnitude_class()` function below) we
    # we save the first entry of that class. The tuple saved for each magnitude
    # class is: `(magnitude_class, time, num_fevals, fitness, width_of_confidence_interval)`
    fitness_history::Vector{TopListFitness{F}}

    function TopListArchive(fit_scheme::FS, numdims::Integer,
                            capacity::Integer = 10) where FS<:FitnessScheme
        F = fitness_type(FS)
        new{F,FS}(fit_scheme, time(), numdims, 0, capacity,
                  TopListIndividual{F}[], TopListFitness{F}[])
    end
end

fitness_scheme(a::TopListArchive) = a.fit_scheme
capacity(a::TopListArchive) = a.capacity
Base.length(a::TopListArchive) = length(a.candidates)
Base.isempty(a::TopListArchive) = isempty(a.candidates)

best_candidate(a::TopListArchive) = a.candidates[1].params
best_fitness(a::TopListArchive) = !isempty(a.candidates) ? fitness(a.candidates[1]) : nafitness(fitness_scheme(a))
last_top_fitness(a::TopListArchive) = !isempty(a.candidates) ? fitness(a.candidates[end]) : nafitness(fitness_scheme(a))

"""
    delta_fitness(a::TopListArchive)

The difference between the current best fitness and the former best fitness.
"""
function delta_fitness(a::TopListArchive)
    if length(a.fitness_history) < 2
        Inf
    else
        # FIXME aggregate fitness?
        abs(a.fitness_history[end].fitness - a.fitness_history[end-1].fitness)
    end
end

function check_stop_condition(a::TopListArchive, p::OptimizationProblem, ctrl)
    if delta_fitness(a) < ctrl.min_delta_fitness_tol
        return "Delta fitness ($(delta_fitness(a))) below tolerance ($(ctrl.min_delta_fitness_tol))"
    end

    if fitness_is_within_ftol(p, best_fitness(a), ctrl.fitness_tol)
        return "Fitness ($(best_fitness(ctrl))) within tolerance ($(ctrl.fitness_tol)) of optimum"
    end

    return "" # no conditions met
end

"""
    add_candidate!(a::TopListArchive, fitness::F, candidate[, tag=0][, num_fevals=-1])

Add a candidate with a fitness to the archive (if it is good enough).
"""
function add_candidate!(a::TopListArchive{F}, fitness::F, candidate::AbstractIndividual,
                        tag::Int=0, num_fevals::Int=-1) where F
    a.num_fitnesses += 1
    if (num_fevals == -1) num_fevals = a.num_fitnesses end

    if isempty(a.fitness_history) || is_better(fitness, best_fitness(a), fitness_scheme(a))
        # Save fitness history so we can reconstruct the most important events later.
        push!(a.fitness_history, TopListFitness{F}(fitness, fitness_improvement_ratio(a, fitness), num_fevals, time()))
    end

    if length(a) < capacity(a) ||
       !isempty(a.candidates) && is_better(fitness, last_top_fitness(a), fitness_scheme(a))
        new_cand = TopListIndividual(copy(candidate), fitness, tag)
        fs = fitness_scheme(a)
        ix = searchsortedfirst(a.candidates, new_cand,
                               # FIXME use lt=fitness_scheme(a) when v0.5 #14919 would be fixed
                               by=BlackBoxOptim.fitness, lt=(x, y) -> is_better(x, y, fs))
        if ix > length(a) || a.candidates[ix] != new_cand
            insert!(a.candidates, ix, new_cand)
        end
        (length(a) > capacity(a)) && pop!(a.candidates) # don't grow over the capacity
    end
end

"""
Get a tuple of the sign and the magnitude of the value rounded to the first digit.
Used for archiving candidates separately for each magnitude class.
"""
function magnitude_class(f)
    f = float(f)
    if f == 0.0
        (-1.0, 1e100)
    else
        (sign(f), floor(10.0*log10(abs(f)))/10.0)
    end
end

function fitness_improvement_ratio(a::Archive, newFitness)
    try
        bestfitness = best_fitness(a)
        return abs( (bestfitness - newFitness) / bestfitness )
    catch
        return 0.0
    end
end

"""
Get the distance from a fitness value to the optimum/best known fitness value.
"""
distance_to_optimum(fitness, bestfitness) = abs(fitness - bestfitness)

function fitness_history_csv_header(a::Archive)
    "Date,Time,ElapsedTime,Magnitude,NumFuncEvals,FitnessImprovementRatio,Fitness"
end

function save_fitness_history_to_csv_file(a::Archive, filename = "fitness_history.csv";
    header_prefix = "", line_prefix = "",
    include_header = true, bestfitness = nothing)

    fh = open(filename, "a+")

    if include_header
        header = [header_prefix, fitness_history_csv_header(a)]

        if bestfitness != nothing
        push!(header, "DistanceToBestFitness")
        end

        println(fh, join(header, ","))
    end

    for af in a.fitness_history
        mc = magnitude_class(af.fitness)

        line = [line_prefix, strftime("%Y-%m-%d,%T", af.timestamp),
            af.timestamp-a.start_time,
            mc[1]*mc[2], af.num_fevals, af.fitness_improvement_ratio, af.fitness]

        if bestfitness != nothing
            push!(line, distance_to_optimum(af.fitness, bestfitness))
        end

        println(fh, join(line, ","))
    end

    close(fh)
end

"""
    merge_fitness_histories(histories)

Merge the collection of multiple fitness histories and calculate the `min`, `max`, `avg` and `median`
values for fitness and FIR (fitness improvement ratio) at each point where the fitness is changing.
"""
function merge_fitness_histories(histories)
    numhist = length(histories)
    counts = ones(numhist)
    fitnesses = zeros(numhist)
    firs = zeros(numhist)
    current_feval = 1

    # Find max history length
    maxlen = mapreduce( length, max, histories )

    while maximum(counts) < maxlen
        # Find min feval for current events, this is the next current feval
        for i in 1:numhist
            t, nf, f, fir = histories[i][counts[i]]
            # FIXME ???
        end
    end
end

# Merge the fitness histories and save the average values of the fitness,
# and distance to best fitness for each change in any of the histories.
#function merge_fitness_histories_to_csv(archives::Archive[], filename = "fitness_history.csv";
#  header_prefix = "", line_prefix = "",
#  include_header = true, bestfitness = nothing)
#
#end

"""
Calculate the width of the confidence interval at a certain `p`-value.
This is based on the paper:
    Carvalho (2011), "Confidence intervals for the minimum of a
    function using extreme value statistics"

This means that the current estimate of the confidence interval for the minimum
of the optimized function lies within the interval

```
] l1 - w, l1 [
```

with probability ``(1-p)`` as the number of sampled function points goes to infinity,
where
```
w = width_of_confidence_interval(a, p)
l1 = best_fitness(a)
```
"""
function width_of_confidence_interval(a::Archive, p = 0.01)
    if length(a) < 2
        return Inf
    else
        l1 = fitness(a.candidates[1])
        l2 = fitness(a.candidates[2])
        # We use abs below so it works also for maximization.
        abs(l2 - l1) / ( (1-p)^(-2/a.numdims) - 1)
    end
end

"""
    fitness_improvement_potential(a::Archive[, p = 0.01])

Calculate the solution improvement potential.

The percentage improvement that can be expected from the current fitness value at a given `p`-value.
In theory, an optimization run should be terminated when this value is very
small, i.e. there is little improvement potential left in the run.
"""
fitness_improvement_potential(a::Archive, p = 0.01) =
    width_of_confidence_interval(a, p) / abs(best_fitness(a))


text:
"""
ksintegrateUnrolled: integrate kuramoto-sivashinsky equation (Julia)

      u_t = -u*u_x - u_xx - u_xxxx, domain x in [0,Lx], periodic BCs

 inputs
          u = initial condition (vector of u(x) values on uniform gridpoints))
         Lx = domain length
         dt = time step
         Nt = number of integration timesteps
      nsave = save every nsave-th time step

 outputs
          u = final state, vector of u(x, Nt*dt) at uniform x gridpoints

This implementation has one improvements over ksintegrateInplace.jl. It explicitly
unrolls all the vector equations into for loops. For some reason this works
better (runs faster) than the unrolled loops produced by the Julia compiler.
"""
function ksintegrateUnrolled(u, Lx, dt, Nt)
    u = (1+0im)*u                       # force u to be complex
    Nx = length(u)                      # number of gridpoints
    kx = vcat(0:Nx/2-1, 0:0, -Nx/2+1:-1)# integer wavenumbers: exp(2*pi*kx*x/L)
    alpha = 2*pi*kx/Lx                  # real wavenumbers:    exp(alpha*x)
    D = 1im*alpha                       # spectral D = d/dx operator
    L = alpha.^2 - alpha.^4             # spectral L = -D^2 - D^4 operator
    G = -0.5*D                          # spectral -1/2 D operator, to eval -u u_x = 1/2 d/dx u^2

    # convenience variables
    dt2  = dt/2
    dt32 = 3*dt/2
    A =  ones(Nx) + dt2*L
    B = (ones(Nx) - dt2*L).^(-1)

    # compute FFTW plans
    FFT! = plan_fft!(u, flags=FFTW.ESTIMATE)
    IFFT! = plan_ifft!(u, flags=FFTW.ESTIMATE)

    # compute nonlinear term Nn == N(u^n) = -u u_x and Nn1
    Nn  = G.*fft(u.^2) # Nn == -1/2 d/dx (u^2) = -u u_x, spectral
    Nn1 = copy(Nn)     # Nn1 == N(u^{n-1}). For first timestep, let Nn1 = Nn
    FFT!*u

    # timestepping loop
    for n = 0:Nt

        Nn1 .= Nn
        Nn .= u

        IFFT!*Nn # in-place FFT

        @inbounds for i = 1:length(Nn)
            @fastmath Nn[i] = Nn[i]*Nn[i]
        end

        FFT!*Nn

        @inbounds for i = 1:length(Nn)
            @fastmath Nn[i] = G[i]*Nn[i]
        end

        @inbounds for i = 1:length(u)
            @fastmath u[i] = B[i]* (A[i] * u[i] + dt32*Nn[i] - dt2*Nn1[i])
        end

    end

    IFFT!*u
    real(u)
end

ext: jl

max_stars_repo_name: raphbacher/julia-intro

max_issues_repo_name: raphbacher/julia-intro

max_forks_repo_name: raphbacher/julia-intro


text:
@testset "Selections" begin

    @testset "Rank" begin
        Random.seed!(2);
        fitness = [5, 1, 3, 4, 2.0]
        s = ranklinear(1.0)
        @test s(fitness, 2) == [2,3]

        s = ranklinear(2.0)
        @test s([1,2], 2) == [2,2]
    end

    @testset "Uniform" begin
        s = uniformranking(2)
        @test sort(unique(s([1.0,2.0,3.0], 10))) == [2,3]
        @test sort(unique(s([5,2,3], 5))) == [1,3]
        @test_throws AssertionError s([1.,2.], 2)
    end

    @testset "Roulette" begin
        @test roulette([0.0,0.0,3.0], 2) == [3, 3]
        @test roulette([0,2,0], 2) == [2,2]
    end

    @testset "Truncation" begin
        @test truncation([0.0,2.0,3.0], 2) == [3,2]
        @test truncation([0,2,1], 1) == [2]
        @test_throws AssertionError truncation([1.,2.], 5)
    end

    @testset "Tournament" begin
        Random.seed!(2);
        @test_throws AssertionError tournament(0)
        t = tournament(2)
        @test t([0,2,0],2) == [2,2]
        @test t([0.0,0.0,1.0],2) == [3,3]
    end

    @testset "SUS" begin
        @test sort(unique(sus([1.0,0.0,2.0], 5))) == [1,3]
        @test sort(unique(sus([0,1,2], 5))) == [2,3]
    end

end


text:
"""
    SumOfSquaresError(NeuralNetwork)

Sum of squares error loss function.

    Usage:
```julia-repl
SumOfSquaresError(NeuralNetwork)
```
Arguments:
- `NeuralNetwork` : The NeuralNetwork structure.
"""
function SumOfSquaresError(NeuralNetwork)
	loss = 0.0

	for i in 1:size(NeuralNetwork.y, 1)
		loss += (NeuralNetwork.y[i] - NeuralNetwork.output[i]) ^ 2.0
    end

    return loss
end


text:
using BayesianDataFusion
using Base.Test

X = rand(1000, 50)
y = rand(50, 3)
lambda = 0.75

b2  = solve_full(X'*X, y, lambda)
be2 = (X'*X + eye(size(X,2)) * lambda) \ y

@test_approx_eq b2 be2

######## test general AtA_mul_B! #######
A = rand(500, 20)
x = rand(20)
y = ones(20)

AtA_mul_B!(y, A, x, 0.5)
ye = (A'*A + eye(20)*0.5)*x
@test_approx_eq y ye


text:
module ImageScraper

export scrape_images

include("image_scraper.jl")

end # module

max_stars_repo_name: Bmillidgework/Image-Scraper

max_issues_repo_name: Bmillidgework/Image-Scraper

max_forks_repo_name: Bmillidgework/Image-Scraper


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

"""
    CreateCertificateAuthority()

Creates a root or subordinate private certificate authority (CA). You must specify the CA configuration, the certificate revocation list (CRL) configuration, the CA type, and an optional idempotency token to avoid accidental creation of multiple CAs. The CA configuration specifies the name of the algorithm and key size to be used to create the CA private key, the type of signing algorithm that the CA uses, and X.500 subject information. The CRL configuration specifies the CRL expiration period in days (the validity period of the CRL), the Amazon S3 bucket that will contain the CRL, and a CNAME alias for the S3 bucket that is included in certificates issued by the CA. If successful, this action returns the Amazon Resource Name (ARN) of the CA. ACM Private CAA assets that are stored in Amazon S3 can be protected with encryption. For more information, see Encrypting Your CRLs.  Both PCA and the IAM principal must have permission to write to the S3 bucket that you specify. If the IAM principal making the call does not have permission to write to the bucket, then an exception is thrown. For more information, see Configure Access to ACM Private CA.

# Required Parameters
- `CertificateAuthorityConfiguration`: Name and bit size of the private key algorithm, the name of the signing algorithm, and X.500 certificate subject information.
- `CertificateAuthorityType`: The type of the certificate authority.

# Optional Parameters
- `IdempotencyToken`: Alphanumeric string that can be used to distinguish between calls to CreateCertificateAuthority. For a given token, ACM Private CA creates exactly one CA. If you issue a subsequent call using the same token, ACM Private CA returns the ARN of the existing CA and takes no further action. If you change the idempotency token across multiple calls, ACM Private CA creates a unique CA for each unique token.
- `RevocationConfiguration`: Contains a Boolean value that you can use to enable a certification revocation list (CRL) for the CA, the name of the S3 bucket to which ACM Private CA will write the CRL, and an optional CNAME alias that you can use to hide the name of your bucket in the CRL Distribution Points extension of your CA certificate. For more information, see the CrlConfiguration structure.
- `Tags`: Key-value pairs that will be attached to the new private CA. You can associate up to 50 tags with a private CA. For information using tags with IAM to manage permissions, see Controlling Access Using IAM Tags.
"""
create_certificate_authority(CertificateAuthorityConfiguration, CertificateAuthorityType; aws_config::AWSConfig=global_aws_config()) = acm_pca("CreateCertificateAuthority", Dict{String, Any}("CertificateAuthorityConfiguration"=>CertificateAuthorityConfiguration, "CertificateAuthorityType"=>CertificateAuthorityType); aws_config=aws_config)
create_certificate_authority(CertificateAuthorityConfiguration, CertificateAuthorityType, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("CreateCertificateAuthority", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityConfiguration"=>CertificateAuthorityConfiguration, "CertificateAuthorityType"=>CertificateAuthorityType), args)); aws_config=aws_config)

"""
    CreateCertificateAuthorityAuditReport()

Creates an audit report that lists every time that your CA private key is used. The report is saved in the Amazon S3 bucket that you specify on input. The IssueCertificate and RevokeCertificate actions use the private key.   Both PCA and the IAM principal must have permission to write to the S3 bucket that you specify. If the IAM principal making the call does not have permission to write to the bucket, then an exception is thrown. For more information, see Configure Access to ACM Private CA.  ACM Private CAA assets that are stored in Amazon S3 can be protected with encryption. For more information, see Encrypting Your Audit Reports.

# Required Parameters
- `AuditReportResponseFormat`: The format in which to create the report. This can be either JSON or CSV.
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) of the CA to be audited. This is of the form:  arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 .
- `S3BucketName`: The name of the S3 bucket that will contain the audit report.

"""
create_certificate_authority_audit_report(AuditReportResponseFormat, CertificateAuthorityArn, S3BucketName; aws_config::AWSConfig=global_aws_config()) = acm_pca("CreateCertificateAuthorityAuditReport", Dict{String, Any}("AuditReportResponseFormat"=>AuditReportResponseFormat, "CertificateAuthorityArn"=>CertificateAuthorityArn, "S3BucketName"=>S3BucketName); aws_config=aws_config)
create_certificate_authority_audit_report(AuditReportResponseFormat, CertificateAuthorityArn, S3BucketName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("CreateCertificateAuthorityAuditReport", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AuditReportResponseFormat"=>AuditReportResponseFormat, "CertificateAuthorityArn"=>CertificateAuthorityArn, "S3BucketName"=>S3BucketName), args)); aws_config=aws_config)

"""
    CreatePermission()

Grants one or more permissions on a private CA to the AWS Certificate Manager (ACM) service principal (acm.amazonaws.com). These permissions allow ACM to issue and renew ACM certificates that reside in the same AWS account as the CA. You can list current permissions with the ListPermissions action and revoke them with the DeletePermission action.  About Permissions    If the private CA and the certificates it issues reside in the same account, you can use CreatePermission to grant permissions for ACM to carry out automatic certificate renewals.   For automatic certificate renewal to succeed, the ACM service principal needs permissions to create, retrieve, and list certificates.   If the private CA and the ACM certificates reside in different accounts, then permissions cannot be used to enable automatic renewals. Instead, the ACM certificate owner must set up a resource-based policy to enable cross-account issuance and renewals. For more information, see Using a Resource Based Policy with ACM Private CA.

# Required Parameters
- `Actions`: The actions that the specified AWS service principal can use. These include IssueCertificate, GetCertificate, and ListPermissions.
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) of the CA that grants the permissions. You can find the ARN by calling the ListCertificateAuthorities action. This must have the following form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 .
- `Principal`: The AWS service or identity that receives the permission. At this time, the only valid principal is acm.amazonaws.com.

# Optional Parameters
- `SourceAccount`: The ID of the calling account.
"""
create_permission(Actions, CertificateAuthorityArn, Principal; aws_config::AWSConfig=global_aws_config()) = acm_pca("CreatePermission", Dict{String, Any}("Actions"=>Actions, "CertificateAuthorityArn"=>CertificateAuthorityArn, "Principal"=>Principal); aws_config=aws_config)
create_permission(Actions, CertificateAuthorityArn, Principal, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("CreatePermission", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Actions"=>Actions, "CertificateAuthorityArn"=>CertificateAuthorityArn, "Principal"=>Principal), args)); aws_config=aws_config)

"""
    DeleteCertificateAuthority()

Deletes a private certificate authority (CA). You must provide the Amazon Resource Name (ARN) of the private CA that you want to delete. You can find the ARN by calling the ListCertificateAuthorities action.   Deleting a CA will invalidate other CAs and certificates below it in your CA hierarchy.  Before you can delete a CA that you have created and activated, you must disable it. To do this, call the UpdateCertificateAuthority action and set the CertificateAuthorityStatus parameter to DISABLED.  Additionally, you can delete a CA if you are waiting for it to be created (that is, the status of the CA is CREATING). You can also delete it if the CA has been created but you haven't yet imported the signed certificate into ACM Private CA (that is, the status of the CA is PENDING_CERTIFICATE).  When you successfully call DeleteCertificateAuthority, the CA's status changes to DELETED. However, the CA won't be permanently deleted until the restoration period has passed. By default, if you do not set the PermanentDeletionTimeInDays parameter, the CA remains restorable for 30 days. You can set the parameter from 7 to 30 days. The DescribeCertificateAuthority action returns the time remaining in the restoration window of a private CA in the DELETED state. To restore an eligible CA, call the RestoreCertificateAuthority action.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. This must have the following form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 .

# Optional Parameters
- `PermanentDeletionTimeInDays`: The number of days to make a CA restorable after it has been deleted. This can be anywhere from 7 to 30 days, with 30 being the default.
"""
delete_certificate_authority(CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("DeleteCertificateAuthority", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
delete_certificate_authority(CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("DeleteCertificateAuthority", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)

"""
    DeletePermission()

Revokes permissions on a private CA granted to the AWS Certificate Manager (ACM) service principal (acm.amazonaws.com).  These permissions allow ACM to issue and renew ACM certificates that reside in the same AWS account as the CA. If you revoke these permissions, ACM will no longer renew the affected certificates automatically. Permissions can be granted with the CreatePermission action and listed with the ListPermissions action.   About Permissions    If the private CA and the certificates it issues reside in the same account, you can use CreatePermission to grant permissions for ACM to carry out automatic certificate renewals.   For automatic certificate renewal to succeed, the ACM service principal needs permissions to create, retrieve, and list certificates.   If the private CA and the ACM certificates reside in different accounts, then permissions cannot be used to enable automatic renewals. Instead, the ACM certificate owner must set up a resource-based policy to enable cross-account issuance and renewals. For more information, see Using a Resource Based Policy with ACM Private CA.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Number (ARN) of the private CA that issued the permissions. You can find the CA's ARN by calling the ListCertificateAuthorities action. This must have the following form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 .
- `Principal`: The AWS service or identity that will have its CA permissions revoked. At this time, the only valid service principal is acm.amazonaws.com

# Optional Parameters
- `SourceAccount`: The AWS account that calls this action.
"""
delete_permission(CertificateAuthorityArn, Principal; aws_config::AWSConfig=global_aws_config()) = acm_pca("DeletePermission", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn, "Principal"=>Principal); aws_config=aws_config)
delete_permission(CertificateAuthorityArn, Principal, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("DeletePermission", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn, "Principal"=>Principal), args)); aws_config=aws_config)

"""
    DeletePolicy()

Deletes the resource-based policy attached to a private CA. Deletion will remove any access that the policy has granted. If there is no policy attached to the private CA, this action will return successful. If you delete a policy that was applied through AWS Resource Access Manager (RAM), the CA will be removed from all shares in which it was included.  The AWS Certificate Manager Service Linked Role that the policy supports is not affected when you delete the policy.  The current policy can be shown with GetPolicy and updated with PutPolicy.  About Policies    A policy grants access on a private CA to an AWS customer account, to AWS Organizations, or to an AWS Organizations unit. Policies are under the control of a CA administrator. For more information, see Using a Resource Based Policy with ACM Private CA.   A policy permits a user of AWS Certificate Manager (ACM) to issue ACM certificates signed by a CA in another account.   For ACM to manage automatic renewal of these certificates, the ACM user must configure a Service Linked Role (SLR). The SLR allows the ACM service to assume the identity of the user, subject to confirmation against the ACM Private CA policy. For more information, see Using a Service Linked Role with ACM.   Updates made in AWS Resource Manager (RAM) are reflected in policies. For more information, see Using AWS Resource Access Manager (RAM) with ACM Private CA.

# Required Parameters
- `ResourceArn`: The Amazon Resource Number (ARN) of the private CA that will have its policy deleted. You can find the CA's ARN by calling the ListCertificateAuthorities action. The ARN value must have the form arn:aws:acm-pca:region:account:certificate-authority/01234567-89ab-cdef-0123-0123456789ab.

"""
delete_policy(ResourceArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("DeletePolicy", Dict{String, Any}("ResourceArn"=>ResourceArn); aws_config=aws_config)
delete_policy(ResourceArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("DeletePolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn), args)); aws_config=aws_config)

"""
    DescribeCertificateAuthority()

Lists information about your private certificate authority (CA) or one that has been shared with you. You specify the private CA on input by its ARN (Amazon Resource Name). The output contains the status of your CA. This can be any of the following:     CREATING - ACM Private CA is creating your private certificate authority.    PENDING_CERTIFICATE - The certificate is pending. You must use your ACM Private CA-hosted or on-premises root or subordinate CA to sign your private CA CSR and then import it into PCA.     ACTIVE - Your private CA is active.    DISABLED - Your private CA has been disabled.    EXPIRED - Your private CA certificate has expired.    FAILED - Your private CA has failed. Your CA can fail because of problems such a network outage or backend AWS failure or other errors. A failed CA can never return to the pending state. You must create a new CA.     DELETED - Your private CA is within the restoration period, after which it is permanently deleted. The length of time remaining in the CA's restoration period is also included in this action's output.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. This must be of the form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 .

"""
describe_certificate_authority(CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("DescribeCertificateAuthority", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
describe_certificate_authority(CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("DescribeCertificateAuthority", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)

"""
    DescribeCertificateAuthorityAuditReport()

Lists information about a specific audit report created by calling the CreateCertificateAuthorityAuditReport action. Audit information is created every time the certificate authority (CA) private key is used. The private key is used when you call the IssueCertificate action or the RevokeCertificate action.

# Required Parameters
- `AuditReportId`: The report ID returned by calling the CreateCertificateAuthorityAuditReport action.
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) of the private CA. This must be of the form:  arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 .

"""
describe_certificate_authority_audit_report(AuditReportId, CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("DescribeCertificateAuthorityAuditReport", Dict{String, Any}("AuditReportId"=>AuditReportId, "CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
describe_certificate_authority_audit_report(AuditReportId, CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("DescribeCertificateAuthorityAuditReport", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AuditReportId"=>AuditReportId, "CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)

"""
    GetCertificate()

Retrieves a certificate from your private CA or one that has been shared with you. The ARN of the certificate is returned when you call the IssueCertificate action. You must specify both the ARN of your private CA and the ARN of the issued certificate when calling the GetCertificate action. You can retrieve the certificate if it is in the ISSUED state. You can call the CreateCertificateAuthorityAuditReport action to create a report that contains information about all of the certificates issued and revoked by your private CA.

# Required Parameters
- `CertificateArn`: The ARN of the issued certificate. The ARN contains the certificate serial number and must be in the following form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012/certificate/286535153982981100925020015808220737245
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. This must be of the form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 .

"""
get_certificate(CertificateArn, CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("GetCertificate", Dict{String, Any}("CertificateArn"=>CertificateArn, "CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
get_certificate(CertificateArn, CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("GetCertificate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateArn"=>CertificateArn, "CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)

"""
    GetCertificateAuthorityCertificate()

Retrieves the certificate and certificate chain for your private certificate authority (CA) or one that has been shared with you. Both the certificate and the chain are base64 PEM-encoded. The chain does not include the CA certificate. Each certificate in the chain signs the one before it.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) of your private CA. This is of the form:  arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 .

"""
get_certificate_authority_certificate(CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("GetCertificateAuthorityCertificate", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
get_certificate_authority_certificate(CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("GetCertificateAuthorityCertificate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)

"""
    GetCertificateAuthorityCsr()

Retrieves the certificate signing request (CSR) for your private certificate authority (CA). The CSR is created when you call the CreateCertificateAuthority action. Sign the CSR with your ACM Private CA-hosted or on-premises root or subordinate CA. Then import the signed certificate back into ACM Private CA by calling the ImportCertificateAuthorityCertificate action. The CSR is returned as a base64 PEM-encoded string.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) that was returned when you called the CreateCertificateAuthority action. This must be of the form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012

"""
get_certificate_authority_csr(CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("GetCertificateAuthorityCsr", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
get_certificate_authority_csr(CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("GetCertificateAuthorityCsr", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)

"""
    GetPolicy()

Retrieves the resource-based policy attached to a private CA. If either the private CA resource or the policy cannot be found, this action returns a ResourceNotFoundException.  The policy can be attached or updated with PutPolicy and removed with DeletePolicy.  About Policies    A policy grants access on a private CA to an AWS customer account, to AWS Organizations, or to an AWS Organizations unit. Policies are under the control of a CA administrator. For more information, see Using a Resource Based Policy with ACM Private CA.   A policy permits a user of AWS Certificate Manager (ACM) to issue ACM certificates signed by a CA in another account.   For ACM to manage automatic renewal of these certificates, the ACM user must configure a Service Linked Role (SLR). The SLR allows the ACM service to assume the identity of the user, subject to confirmation against the ACM Private CA policy. For more information, see Using a Service Linked Role with ACM.   Updates made in AWS Resource Manager (RAM) are reflected in policies. For more information, see Using AWS Resource Access Manager (RAM) with ACM Private CA.

# Required Parameters
- `ResourceArn`: The Amazon Resource Number (ARN) of the private CA that will have its policy retrieved. You can find the CA's ARN by calling the ListCertificateAuthorities action.

"""
get_policy(ResourceArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("GetPolicy", Dict{String, Any}("ResourceArn"=>ResourceArn); aws_config=aws_config)
get_policy(ResourceArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("GetPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn), args)); aws_config=aws_config)

"""
    ImportCertificateAuthorityCertificate()

Imports a signed private CA certificate into ACM Private CA. This action is used when you are using a chain of trust whose root is located outside ACM Private CA. Before you can call this action, the following preparations must in place:   In ACM Private CA, call the CreateCertificateAuthority action to create the private CA that that you plan to back with the imported certificate.   Call the GetCertificateAuthorityCsr action to generate a certificate signing request (CSR).   Sign the CSR using a root or intermediate CA hosted by either an on-premises PKI hierarchy or by a commercial CA.   Create a certificate chain and copy the signed certificate and the certificate chain to your working directory.   The following requirements apply when you import a CA certificate.   You cannot import a non-self-signed certificate for use as a root CA.   You cannot import a self-signed certificate for use as a subordinate CA.   Your certificate chain must not include the private CA certificate that you are importing.   Your ACM Private CA-hosted or on-premises CA certificate must be the last certificate in your chain. The subordinate certificate, if any, that your root CA signed must be next to last. The subordinate certificate signed by the preceding subordinate CA must come next, and so on until your chain is built.    The chain must be PEM-encoded.   The maximum allowed size of a certificate is 32 KB.   The maximum allowed size of a certificate chain is 2 MB.    Enforcement of Critical Constraints  ACM Private CA allows the following extensions to be marked critical in the imported CA certificate or chain.   Basic constraints (must be marked critical)   Subject alternative names   Key usage   Extended key usage   Authority key identifier   Subject key identifier   Issuer alternative name   Subject directory attributes   Subject information access   Certificate policies   Policy mappings   Inhibit anyPolicy   ACM Private CA rejects the following extensions when they are marked critical in an imported CA certificate or chain.   Name constraints   Policy constraints   CRL distribution points   Authority information access   Freshest CRL   Any other extension

# Required Parameters
- `Certificate`: The PEM-encoded certificate for a private CA. This may be a self-signed certificate in the case of a root CA, or it may be signed by another CA that you control.
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. This must be of the form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012

# Optional Parameters
- `CertificateChain`: A PEM-encoded file that contains all of your certificates, other than the certificate you're importing, chaining up to your root CA. Your ACM Private CA-hosted or on-premises root certificate is the last in the chain, and each certificate in the chain signs the one preceding.  This parameter must be supplied when you import a subordinate CA. When you import a root CA, there is no chain.
"""
import_certificate_authority_certificate(Certificate, CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("ImportCertificateAuthorityCertificate", Dict{String, Any}("Certificate"=>Certificate, "CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
import_certificate_authority_certificate(Certificate, CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("ImportCertificateAuthorityCertificate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Certificate"=>Certificate, "CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)

"""
    IssueCertificate()

Uses your private certificate authority (CA), or one that has been shared with you, to issue a client certificate. This action returns the Amazon Resource Name (ARN) of the certificate. You can retrieve the certificate by calling the GetCertificate action and specifying the ARN.   You cannot use the ACM ListCertificateAuthorities action to retrieve the ARNs of the certificates that you issue by using ACM Private CA.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. This must be of the form:  arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012
- `Csr`: The certificate signing request (CSR) for the certificate you want to issue. You can use the following OpenSSL command to create the CSR and a 2048 bit RSA private key.   openssl req -new -newkey rsa:2048 -days 365 -keyout private/test_cert_priv_key.pem -out csr/test_cert_.csr  If you have a configuration file, you can use the following OpenSSL command. The usr_cert block in the configuration file contains your X509 version 3 extensions.   openssl req -new -config openssl_rsa.cnf -extensions usr_cert -newkey rsa:2048 -days -365 -keyout private/test_cert_priv_key.pem -out csr/test_cert_.csr  Note: A CSR must provide either a subject name or a subject alternative name or the request will be rejected.
- `SigningAlgorithm`: The name of the algorithm that will be used to sign the certificate to be issued.  This parameter should not be confused with the SigningAlgorithm parameter used to sign a CSR.
- `Validity`: Information describing the validity period of the certificate. When issuing a certificate, ACM Private CA sets the \"Not Before\" date in the validity field to date and time minus 60 minutes. This is intended to compensate for time inconsistencies across systems of 60 minutes or less.  The validity period configured on a certificate must not exceed the limit set by its parents in the CA hierarchy.

# Optional Parameters
- `IdempotencyToken`: Custom string that can be used to distinguish between calls to the IssueCertificate action. Idempotency tokens time out after one hour. Therefore, if you call IssueCertificate multiple times with the same idempotency token within 5 minutes, ACM Private CA recognizes that you are requesting only one certificate and will issue only one. If you change the idempotency token for each call, PCA recognizes that you are requesting multiple certificates.
- `TemplateArn`: Specifies a custom configuration template to use when issuing a certificate. If this parameter is not provided, ACM Private CA defaults to the EndEntityCertificate/V1 template. For CA certificates, you should choose the shortest path length that meets your needs. The path length is indicated by the PathLenN portion of the ARN, where N is the CA depth. Note: The CA depth configured on a subordinate CA certificate must not exceed the limit set by its parents in the CA hierarchy. The following service-owned TemplateArn values are supported by ACM Private CA:    arn:aws:acm-pca:::template/CodeSigningCertificate/V1   arn:aws:acm-pca:::template/CodeSigningCertificate_CSRPassthrough/V1   arn:aws:acm-pca:::template/EndEntityCertificate/V1   arn:aws:acm-pca:::template/EndEntityCertificate_CSRPassthrough/V1   arn:aws:acm-pca:::template/EndEntityClientAuthCertificate/V1   arn:aws:acm-pca:::template/EndEntityClientAuthCertificate_CSRPassthrough/V1   arn:aws:acm-pca:::template/EndEntityServerAuthCertificate/V1   arn:aws:acm-pca:::template/EndEntityServerAuthCertificate_CSRPassthrough/V1   arn:aws:acm-pca:::template/OCSPSigningCertificate/V1   arn:aws:acm-pca:::template/OCSPSigningCertificate_CSRPassthrough/V1   arn:aws:acm-pca:::template/RootCACertificate/V1   arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen0/V1   arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen1/V1   arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen2/V1   arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen3/V1   For more information, see Using Templates.
"""
issue_certificate(CertificateAuthorityArn, Csr, SigningAlgorithm, Validity; aws_config::AWSConfig=global_aws_config()) = acm_pca("IssueCertificate", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn, "Csr"=>Csr, "SigningAlgorithm"=>SigningAlgorithm, "Validity"=>Validity); aws_config=aws_config)
issue_certificate(CertificateAuthorityArn, Csr, SigningAlgorithm, Validity, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("IssueCertificate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn, "Csr"=>Csr, "SigningAlgorithm"=>SigningAlgorithm, "Validity"=>Validity), args)); aws_config=aws_config)

"""
    ListCertificateAuthorities()

Lists the private certificate authorities that you created by using the CreateCertificateAuthority action.

# Optional Parameters
- `MaxResults`: Use this parameter when paginating results to specify the maximum number of items to return in the response on each page. If additional items exist beyond the number you specify, the NextToken element is sent in the response. Use this NextToken value in a subsequent request to retrieve additional items.
- `NextToken`: Use this parameter when paginating results in a subsequent request after you receive a response with truncated results. Set it to the value of the NextToken parameter from the response you just received.
- `ResourceOwner`: Use this parameter to filter the returned set of certificate authorities based on their owner. The default is SELF.
"""
list_certificate_authorities(; aws_config::AWSConfig=global_aws_config()) = acm_pca("ListCertificateAuthorities"; aws_config=aws_config)
list_certificate_authorities(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("ListCertificateAuthorities", args; aws_config=aws_config)

"""
    ListPermissions()

List all permissions on a private CA, if any, granted to the AWS Certificate Manager (ACM) service principal (acm.amazonaws.com).  These permissions allow ACM to issue and renew ACM certificates that reside in the same AWS account as the CA.  Permissions can be granted with the CreatePermission action and revoked with the DeletePermission action.  About Permissions    If the private CA and the certificates it issues reside in the same account, you can use CreatePermission to grant permissions for ACM to carry out automatic certificate renewals.   For automatic certificate renewal to succeed, the ACM service principal needs permissions to create, retrieve, and list certificates.   If the private CA and the ACM certificates reside in different accounts, then permissions cannot be used to enable automatic renewals. Instead, the ACM certificate owner must set up a resource-based policy to enable cross-account issuance and renewals. For more information, see Using a Resource Based Policy with ACM Private CA.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Number (ARN) of the private CA to inspect. You can find the ARN by calling the ListCertificateAuthorities action. This must be of the form: arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 You can get a private CA's ARN by running the ListCertificateAuthorities action.

# Optional Parameters
- `MaxResults`: When paginating results, use this parameter to specify the maximum number of items to return in the response. If additional items exist beyond the number you specify, the NextToken element is sent in the response. Use this NextToken value in a subsequent request to retrieve additional items.
- `NextToken`: When paginating results, use this parameter in a subsequent request after you receive a response with truncated results. Set it to the value of NextToken from the response you just received.
"""
list_permissions(CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("ListPermissions", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
list_permissions(CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("ListPermissions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)

"""
    ListTags()

Lists the tags, if any, that are associated with your private CA or one that has been shared with you. Tags are labels that you can use to identify and organize your CAs. Each tag consists of a key and an optional value. Call the TagCertificateAuthority action to add one or more tags to your CA. Call the UntagCertificateAuthority action to remove tags.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) that was returned when you called the CreateCertificateAuthority action. This must be of the form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012

# Optional Parameters
- `MaxResults`: Use this parameter when paginating results to specify the maximum number of items to return in the response. If additional items exist beyond the number you specify, the NextToken element is sent in the response. Use this NextToken value in a subsequent request to retrieve additional items.
- `NextToken`: Use this parameter when paginating results in a subsequent request after you receive a response with truncated results. Set it to the value of NextToken from the response you just received.
"""
list_tags(CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("ListTags", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
list_tags(CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("ListTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)

"""
    PutPolicy()

Attaches a resource-based policy to a private CA.  A policy can also be applied by sharing a private CA through AWS Resource Access Manager (RAM). The policy can be displayed with GetPolicy and removed with DeletePolicy.  About Policies    A policy grants access on a private CA to an AWS customer account, to AWS Organizations, or to an AWS Organizations unit. Policies are under the control of a CA administrator. For more information, see Using a Resource Based Policy with ACM Private CA.   A policy permits a user of AWS Certificate Manager (ACM) to issue ACM certificates signed by a CA in another account.   For ACM to manage automatic renewal of these certificates, the ACM user must configure a Service Linked Role (SLR). The SLR allows the ACM service to assume the identity of the user, subject to confirmation against the ACM Private CA policy. For more information, see Using a Service Linked Role with ACM.   Updates made in AWS Resource Manager (RAM) are reflected in policies. For more information, see Using AWS Resource Access Manager (RAM) with ACM Private CA.

# Required Parameters
- `Policy`: The path and filename of a JSON-formatted IAM policy to attach to the specified private CA resource. If this policy does not contain all required statements or if it includes any statement that is not allowed, the PutPolicy action returns an InvalidPolicyException. For information about IAM policy and statement structure, see Overview of JSON Policies.
- `ResourceArn`: The Amazon Resource Number (ARN) of the private CA to associate with the policy. The ARN of the CA can be found by calling the ListCertificateAuthorities action.

"""
put_policy(Policy, ResourceArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("PutPolicy", Dict{String, Any}("Policy"=>Policy, "ResourceArn"=>ResourceArn); aws_config=aws_config)
put_policy(Policy, ResourceArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("PutPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Policy"=>Policy, "ResourceArn"=>ResourceArn), args)); aws_config=aws_config)

"""
    RestoreCertificateAuthority()

Restores a certificate authority (CA) that is in the DELETED state. You can restore a CA during the period that you defined in the PermanentDeletionTimeInDays parameter of the DeleteCertificateAuthority action. Currently, you can specify 7 to 30 days. If you did not specify a PermanentDeletionTimeInDays value, by default you can restore the CA at any time in a 30 day period. You can check the time remaining in the restoration period of a private CA in the DELETED state by calling the DescribeCertificateAuthority or ListCertificateAuthorities actions. The status of a restored CA is set to its pre-deletion status when the RestoreCertificateAuthority action returns. To change its status to ACTIVE, call the UpdateCertificateAuthority action. If the private CA was in the PENDING_CERTIFICATE state at deletion, you must use the ImportCertificateAuthorityCertificate action to import a certificate authority into the private CA before it can be activated. You cannot restore a CA after the restoration period has ended.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) that was returned when you called the CreateCertificateAuthority action. This must be of the form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012

"""
restore_certificate_authority(CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("RestoreCertificateAuthority", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
restore_certificate_authority(CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("RestoreCertificateAuthority", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)

"""
    RevokeCertificate()

Revokes a certificate that was issued inside ACM Private CA. If you enable a certificate revocation list (CRL) when you create or update your private CA, information about the revoked certificates will be included in the CRL. ACM Private CA writes the CRL to an S3 bucket that you specify. A CRL is typically updated approximately 30 minutes after a certificate is revoked. If for any reason the CRL update fails, ACM Private CA attempts makes further attempts every 15 minutes. With Amazon CloudWatch, you can create alarms for the metrics CRLGenerated and MisconfiguredCRLBucket. For more information, see Supported CloudWatch Metrics.  Both PCA and the IAM principal must have permission to write to the S3 bucket that you specify. If the IAM principal making the call does not have permission to write to the bucket, then an exception is thrown. For more information, see Configure Access to ACM Private CA.  ACM Private CA also writes revocation information to the audit report. For more information, see CreateCertificateAuthorityAuditReport.  You cannot revoke a root CA self-signed certificate.

# Required Parameters
- `CertificateAuthorityArn`: Amazon Resource Name (ARN) of the private CA that issued the certificate to be revoked. This must be of the form:  arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012
- `CertificateSerial`: Serial number of the certificate to be revoked. This must be in hexadecimal format. You can retrieve the serial number by calling GetCertificate with the Amazon Resource Name (ARN) of the certificate you want and the ARN of your private CA. The GetCertificate action retrieves the certificate in the PEM format. You can use the following OpenSSL command to list the certificate in text format and copy the hexadecimal serial number.   openssl x509 -in file_path -text -noout  You can also copy the serial number from the console or use the DescribeCertificate action in the AWS Certificate Manager API Reference.
- `RevocationReason`: Specifies why you revoked the certificate.

"""
revoke_certificate(CertificateAuthorityArn, CertificateSerial, RevocationReason; aws_config::AWSConfig=global_aws_config()) = acm_pca("RevokeCertificate", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn, "CertificateSerial"=>CertificateSerial, "RevocationReason"=>RevocationReason); aws_config=aws_config)
revoke_certificate(CertificateAuthorityArn, CertificateSerial, RevocationReason, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("RevokeCertificate", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn, "CertificateSerial"=>CertificateSerial, "RevocationReason"=>RevocationReason), args)); aws_config=aws_config)

"""
    TagCertificateAuthority()

Adds one or more tags to your private CA. Tags are labels that you can use to identify and organize your AWS resources. Each tag consists of a key and an optional value. You specify the private CA on input by its Amazon Resource Name (ARN). You specify the tag by using a key-value pair. You can apply a tag to just one private CA if you want to identify a specific characteristic of that CA, or you can apply the same tag to multiple private CAs if you want to filter for a common relationship among those CAs. To remove one or more tags, use the UntagCertificateAuthority action. Call the ListTags action to see what tags are associated with your CA.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. This must be of the form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012
- `Tags`: List of tags to be associated with the CA.

"""
tag_certificate_authority(CertificateAuthorityArn, Tags; aws_config::AWSConfig=global_aws_config()) = acm_pca("TagCertificateAuthority", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn, "Tags"=>Tags); aws_config=aws_config)
tag_certificate_authority(CertificateAuthorityArn, Tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("TagCertificateAuthority", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn, "Tags"=>Tags), args)); aws_config=aws_config)

"""
    UntagCertificateAuthority()

Remove one or more tags from your private CA. A tag consists of a key-value pair. If you do not specify the value portion of the tag when calling this action, the tag will be removed regardless of value. If you specify a value, the tag is removed only if it is associated with the specified value. To add tags to a private CA, use the TagCertificateAuthority. Call the ListTags action to see what tags are associated with your CA.

# Required Parameters
- `CertificateAuthorityArn`: The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. This must be of the form:   arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012
- `Tags`: List of tags to be removed from the CA.

"""
untag_certificate_authority(CertificateAuthorityArn, Tags; aws_config::AWSConfig=global_aws_config()) = acm_pca("UntagCertificateAuthority", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn, "Tags"=>Tags); aws_config=aws_config)
untag_certificate_authority(CertificateAuthorityArn, Tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("UntagCertificateAuthority", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn, "Tags"=>Tags), args)); aws_config=aws_config)

"""
    UpdateCertificateAuthority()

Updates the status or configuration of a private certificate authority (CA). Your private CA must be in the ACTIVE or DISABLED state before you can update it. You can disable a private CA that is in the ACTIVE state or make a CA that is in the DISABLED state active again.  Both PCA and the IAM principal must have permission to write to the S3 bucket that you specify. If the IAM principal making the call does not have permission to write to the bucket, then an exception is thrown. For more information, see Configure Access to ACM Private CA.

# Required Parameters
- `CertificateAuthorityArn`: Amazon Resource Name (ARN) of the private CA that issued the certificate to be revoked. This must be of the form:  arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012

# Optional Parameters
- `RevocationConfiguration`: Revocation information for your private CA.
- `Status`: Status of your private CA.
"""
update_certificate_authority(CertificateAuthorityArn; aws_config::AWSConfig=global_aws_config()) = acm_pca("UpdateCertificateAuthority", Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn); aws_config=aws_config)
update_certificate_authority(CertificateAuthorityArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = acm_pca("UpdateCertificateAuthority", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CertificateAuthorityArn"=>CertificateAuthorityArn), args)); aws_config=aws_config)


text:
abstract type AbstractProblem{T} end

Base.@kwdef struct GeneralBTPDE{T,S} <: AbstractProblem{T}
    model::Model{T}
    matrices::NamedTuple
    abstol::T = 1e-6
    reltol::T = 1e-4
    odesolver::S = QNDF(autodiff = false)
end

Base.@kwdef struct IntervalConstanBTPDE{T} <: AbstractProblem{T}
    model::Model{T}
    matrices::NamedTuple
    θ::T
    timestep::T
end

Base.@kwdef struct HADC{T,S} <: AbstractProblem{T}
    model::Model{T}
    matrices::NamedTuple
    abstol::T = 1e-6
    reltol::T = 1e-4
    odesolver::S = QNDF(autodiff = false)
end

Base.@kwdef struct Karger{T,S} <: AbstractProblem{T}
    model::Model{T}
    difftensors::Vector{SMatrix{3,3,T,9}}
    odesolver::S
    timestep::T
end

Base.@kwdef struct Laplace{T} <: AbstractProblem{T}
    model::Model{T}
    matrices::NamedTuple
    neig_max::Int
end

Base.@kwdef struct MatrixFormalism{T} <: AbstractProblem{T}
    model::Model{T}
    matrices::NamedTuple
    lap_eig::NamedTuple
    ninterval::Int
end

Base.@kwdef struct AnalyticalLaplace{T} <: AbstractProblem{T}
    ρ::Vector{Complex{T}}
    r::Vector{T}
    D::Vector{T}
    W::Vector{T}
    T₂::Vector{T}
    γ::T
    dim::Int
    eiglim::T
    eigstep::T
end

Base.@kwdef struct AnalyticalMatrixFormalism{T} <: AbstractProblem{T}
    analytical_laplace::AnalyticalLaplace{T}
    lap_mat::NamedTuple
    volumes::Vector{T}
end


text:
# ---
# title: 962. Maximum Width Ramp
# id: problem962
# author: Indigo
# date: 2021-01-25
# difficulty: Medium
# categories: Array
# link: <https://leetcode.com/problems/maximum-width-ramp/description/>
# hidden: true
# ---
#
# Given an array `A` of integers, a _ramp_  is a tuple `(i, j)` for which `i <
# j` and `A[i] <= A[j]`.  The width of such a ramp is `j - i`.
#
# Find the maximum width of a ramp in `A`.  If one doesn't exist, return 0.
#
#
#
# **Example 1:**
#
#
#
#     Input: [6,0,8,2,1,5]
#     Output: 4
#     Explanation:
#     The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5.
#
#
# **Example 2:**
#
#
#
#     Input: [9,8,1,0,1,9,4,0,4,1]
#     Output: 7
#     Explanation:
#     The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.
#
#
#
#
# **Note:**
#
#   1. `2 <= A.length <= 50000`
#   2. `0 <= A[i] <= 50000`
#
#
#
#
## @lc code=start
using LeetCode

function max_width_ramp(A::Vector{Int})
    res = 0
    stk = [1]
    for i in 2:length(A)
        (A[i] < A[stk[end]]) && (push!(stk, i))
    end
    for i in length(A):-1:2
        idx = i
        while !isempty(stk) && A[stk[end]] <= A[i]
            idx = pop!(stk)
        end
        res = max(i - idx, res)
    end
    return res
end
## @lc code=end


text:
url="http://datosabiertos.salud.gob.mx/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip";
turl="https://www.coneval.org.mx/Medicion/Documents/Pobreza_municipal/Concentrado_indicadores_de_pobreza.zip";
murl="http://www.conapo.gob.mx/work/models/CONAPO/intensidad_migratoria/base_completa/IIM2010_BASEMUN.xls";

if Sys.iswindows()
    path=chop(@__DIR__, tail=3)*"Docs\\";
    pathCov=chop(@__DIR__, tail=3)*"Docs\\Cov_data\\";
    pathINEGI=chop(@__DIR__, tail=3)*"Docs\\Datos INEGI\\Datos ";
    pathCSV="C:\\archivos_CSV_COVID_data_tool\\"
elseif Sys.islinux()
    path=chop(@__DIR__, tail=3)*"Docs/";
    pathCov=chop(@__DIR__, tail=3)*"Docs/Cov_data/";
    pathINEGI=chop(@__DIR__, tail=3)*"Docs/Datos INEGI/Datos ";
    pathCSV="/home/archivos_CSV_COVID_data_tool/"
end


text:
# Adaptive scaling Metropolis
struct AdaptiveScalingMetropolis{StepT <: StepSize, FT <: AbstractFloat} <: AdaptState
    sc::Base.RefValue{FT} # The log-scaling which is adapted
    α_opt::FT             # The desired acceptance rate
    step::StepT           # The step size sequence
end

"""
    r = AdaptiveScalingMetropolis(x0, α_opt, sc, step)
    r = AdaptiveScalingMetropolis(α_opt, sc, step)

Constructor for AdaptiveScalingMetropolis state.

# Arguments
- `x0`: The initial state vector (not used).
- `α_opt`: Desired mean accept rate; default `0.234`.
- `sc`: Initial scaling; default `1.0`.
- `step`: Step size object; default `PolynomialStepSize(0.66)`.

If `s` is `RWMState`, then proposal samples may be drawn calling
 `draw!(s, r)` and adaptation is performed with `adapt!(r, s, α)`.
"""
function AdaptiveScalingMetropolis(α_opt::FT=0.234, sc::FT=FT(1.0),
      step=PolynomialStepSize(FT(0.66))) where {FT <: AbstractFloat}
    AdaptiveScalingMetropolis(Ref(log(sc)), α_opt, step)
end
function AdaptiveScalingMetropolis(x0::VT,
      α_opt::FT=length(x0)==1 ? FT(0.44) : FT(0.234),
      sc::FT=FT(1.0), step=PolynomialStepSize(FT(0.66))) where {FT <: AbstractFloat, VT <: AbstractVector{FT}}
    AdaptiveScalingMetropolis(α_opt, sc, step)
end

@inline function adapt!(s::AdaptiveScalingMetropolis, sr::RWMState,
      α::AbstractFloat, k::Real) :: Nothing
    dα = α - s.α_opt
    γ = get(s.step, k)
    s.sc[] += γ*dα
    nothing
end
@inline function draw!(sr::RWMState, sa::AdaptiveScalingMetropolis) :: Nothing
    draw!(sr, exp(sa.sc[]))
    nothing
end

# Adaptive scaling within AM
struct AdaptiveScalingWithinAdaptiveMetropolis{d,AMT <: AdaptiveMetropolis,
      ASMT <: AdaptiveScalingMetropolis} <: AdaptState
    AM::AMT
    ASM::ASMT
end

"""
    r = AdaptiveScalingWithinAdaptiveMetropolis(x0, α_opt, sc, stepAM, stepASM)

Constructor for AdaptiveScalingWithinAdaptiveMetropolis state.

# Arguments
- `x0`: The initial state vector.
- `α_opt`: Desired mean accept rate; default `0.234`.
- `sc`: Initial scaling; default `2.38/sqrt(d)` where `d` is the dimension.
- `stepAM`: Step size object for covariance adaptation;
             default `PolynomialStepSize(0.66)`.
- `stepASM`: Step size object for scaling adaptation;
             default `PolynomialStepSize(0.66)`.

If `s` is `RWMState`, then proposal samples may be drawn calling
 `draw!(s, r)` and adaptation is performed with `adapt!(r, s, α)` or
 `adapt_rb!(r, s, α)`.
"""
function AdaptiveScalingWithinAdaptiveMetropolis(x0::T,
      α_opt=length(x0)==1 ? FT(0.44) : FT(0.234),
      sc=FT(2.38/sqrt(length(x0))),
      stepAM::StepSize=PolynomialStepSize(FT(0.66)),
      stepASM::StepSize=PolynomialStepSize(FT(0.66))) where {FT <: AbstractFloat,
      T<:AbstractVector{FT}}
    d = length(x0)
    ASM = AdaptiveScalingMetropolis(α_opt, sc, stepASM)
    AM = AdaptiveMetropolis(x0, one(FT), stepAM)
    AdaptiveScalingWithinAdaptiveMetropolis{d,typeof(AM),typeof(ASM)}(AM, ASM)
end

@inline function adapt!(s::AdaptiveScalingWithinAdaptiveMetropolis,
      sr::RWMState, α::AbstractFloat, k::Real) :: Nothing
    adapt!(s.AM, sr, α, k)
    adapt!(s.ASM, sr, α, k)
    nothing
end
@inline function draw!(sr::RWMState,
      s::AdaptiveScalingWithinAdaptiveMetropolis) :: Nothing
    draw!(sr, s.AM.L, exp(s.ASM.sc[]))
end

@inline function adapt_rb!(s::AdaptiveScalingWithinAdaptiveMetropolis,
      sr::RWMState, α::AbstractFloat, k::Real) :: Nothing
    adapt_rb!(s.AM, sr, α, k)
    adapt!(s.ASM, sr, α, k)
    nothing
end


text:
# Quick testing function:
using Revise
using RadiativeTransfer.Scattering
using Distributions
using FastGaussQuadrature
using Plots
using KernelAbstractions
using CUDA
using ProgressMeter

# Define median radius, sigma and wavelength (all in micron!)
μ  = 0.3
σ  = 6.82
wl = 0.55

FT = Float64

# Generate aerosol:
aero1 = Scattering.UnivariateAerosol(LogNormal(log(μ), log(σ)), 30.0, 10000,1.3,-1e-6)

# Obtain Gauss Legendre Quadrature Points:
x,w = gausslegendre( aero1.nquad_radius )
maxSizeParam = 2π * aero1.r_max/wl
n_max = Scattering.get_n_max(maxSizeParam)
x_sizeParam  = x*maxSizeParam/2 .+ maxSizeParam/2

#x_sizeParam=
# 1) Gauss Legendre quadrature over μ (requires 2Nmax-1 to be accurate!)
n_mu = 2n_max-1;

μ, w_μ = gausslegendre( n_mu )

leg_π = zeros(n_max,n_mu)
leg_τ = zeros(n_max,n_mu)

# Pre-compute π and τ:
Scattering.compute_mie_π_τ!(μ, n_max, leg_π, leg_τ)

function testSiewert(x_sizeParam,leg_π,leg_τ, aero1, λ,μ,w_μ )
    size1 = size(leg_π)[2]
    # Wavenumber:
    k = 2π/λ
    # Radius
    r = x_sizeParam/2π*wl

    S₁  = zeros(Complex{FT},length(x_sizeParam),size1)
    S₂  = zeros(Complex{FT},length(x_sizeParam),size1)
    f₁₁ = zeros(length(x_sizeParam),size1)
    f₃₃ = zeros(length(x_sizeParam),size1)
    f₁₂ = zeros(length(x_sizeParam),size1)
    f₃₄ = zeros(length(x_sizeParam),size1)
    C_ext = zeros(length(x_sizeParam))
    C_sca = zeros(length(x_sizeParam))
    # Weights for the size distribution:
    wₓ = pdf.(aero1.size_distribution,r)
    # Try Gauss-Legendre later (add to wx)

    # normalize:
    wₓ /= sum(wₓ)
    #wₓ /= maximum(x_sizeParam/2π*wl)

    @showprogress 1 "Computing PhaseFunctions Siewert NAI-2 style ..." for i = 1:length(x_sizeParam)
        #println(i, " ", x_sizeParam[i])
        # Maximum expansion (see eq. A17 from de Rooij and Stap, 1984)
        n_max = Scattering.get_n_max(x_sizeParam[i])
        an = (zeros(Complex{FT},n_max))
        bn = (zeros(Complex{FT},n_max))
        # Weighting for sums of 2n+1
        n_ = collect(1:n_max);
        n_ = 2n_ .+ 1

        # Pre-allocate Dn:
        y = x_sizeParam[i] * (aero1.nᵣ-aero1.nᵢ);
        nmx = round(Int, max(n_max, abs(y))+25 )
        Dn = zeros(Complex{FT},nmx)

        #Scattering.compute_mie_ab!(x_sizeParam[i],aero1.nᵣ-aero1.nᵢ*im,view(an,1:n_max),view(bn,1:n_max),Dn)
        #S1[i,:],S2[i,:] = Scattering.compute_mie_S1S2(view(an,1:n_max), view(bn,1:n_max), leg_π, leg_τ)
        Scattering.compute_mie_ab!(x_sizeParam[i],aero1.nᵣ-aero1.nᵢ*im,an,bn,Dn)
        S₁[i,:],S₂[i,:] = Scattering.compute_mie_S1S2(an, bn, leg_π, leg_τ)

        # Compute Extinction and scattering cross sections:
        C_sca[i] = 2pi/k^2 * (n_' * (abs2.(an) + abs2.(bn)))
        C_ext[i] = 2pi/k^2 * (n_' * real(an + bn))

        # Compute scattering matrix components per size parameter:
        f₁₁[i,:] = 0.5/x_sizeParam[i]^2  * real(abs2.(S₁[i,:]) + abs2.(S₂[i,:]));
        f₃₃[i,:] = 0.5/x_sizeParam[i]^2  * real(S₁[i,:] .* conj(S₂[i,:]) + S₂[i,:] .* conj(S₁[i,:]));
        f₁₂[i,:] = -0.5/x_sizeParam[i]^2  * real(abs2.(S₁[i,:]) - abs2.(S₂[i,:]));
        f₃₄[i,:] = -0.5/x_sizeParam[i]^2 * imag(S₁[i,:] .* conj(S₂[i,:]) - S₂[i,:] .* conj(S₁[i,:]));

    end
    bulk_C_sca =  sum(wₓ .* C_sca)
    bulk_C_ext =  sum(wₓ .* C_ext)
    bulk_f₁₁   =  sum(4π*r.^2 .*  wₓ .* f₁₁,dims=1)
    bulk_f₃₃   =  sum(4π*r.^2 .*  wₓ .* f₃₃,dims=1)
    bulk_f₁₂   =  sum(4π*r.^2 .*  wₓ .* f₁₂,dims=1)
    bulk_f₃₄   =  sum(4π*r.^2 .*  wₓ .* f₃₄,dims=1)

    # Normalize Phase function with bulk scattering cross section.
    bulk_f₁₁ /= bulk_C_sca
    bulk_f₃₃ /= bulk_C_sca
    bulk_f₁₂ /= bulk_C_sca
    bulk_f₃₄ /= bulk_C_sca

    lMax = length(μ);
    P, P², R², T² = Scattering.compute_legendre_poly(μ,lMax)
    # Compute Greek coefficients:
    α = zeros(lMax)
    β = zeros(lMax)
    δ = zeros(lMax)
    γ = zeros(lMax)
    ϵ = zeros(lMax)
    ζ = zeros(lMax)
    #@show size(avg_f11), size(P), size(w_μ), size(f11), size(wₓ)
    for l=0:length(β)-1
        # Factorial can be smarter through recursion I guess!
        fac = (2l+1)/2 * sqrt(factorial(big(l-2))/factorial(big(l+2)))
        δ[l+1] = (2l+1)/2 * sum(w_μ' * (bulk_f₃₃[1,:] .* P[l+1,:]))
        β[l+1] = (2l+1)/2 * sum(w_μ' * (bulk_f₁₁[1,:] .* P[l+1,:]))
        γ[l+1] = fac * sum(w_μ' * (bulk_f₁₂[1,:] .* P²[l+1,:]))
        ϵ[l+1] = fac * sum(w_μ' * (bulk_f₃₄[1,:] .* P²[l+1,:]))
        ζ[l+1] = fac * sum(w_μ' * (bulk_f₃₃[1,:] .* R²[l+1,:] + bulk_f₁₁[1,:] .* T²[l+1,:]) )
        α[l+1] = fac * sum(w_μ' * (bulk_f₁₁[1,:] .* R²[l+1,:] + bulk_f₃₃[1,:] .* T²[l+1,:]) )
    end
    return bulk_f₁₁, bulk_f₁₂, f₁₁, f₃₃, f₁₂,f₃₄,  C_ext, C_sca,bulk_C_sca, bulk_C_ext, α, β, γ, δ, ϵ, ζ
end

@time bulk_f₁₁, bulk_f₁₂, f₁₁, f₃₃, f₁₂,f₃₄,  C_ext, C_sca,avg_C_sca, avg_C_ext, α, β, γ, δ, ϵ, ζ= testSiewert(x_sizeParam, leg_π,leg_τ, aero1,wl,μ,w_μ)

l = @layout [a ; b; c; d; e; f]
p1 = plot(α,label="α")
p2 = plot(β,label="β")
p3 = plot(γ,label="γ")
p4 = plot(δ,label="δ")
p5 = plot(ϵ,label="ϵ")
p6 = plot(ζ,label="ζ")

plot(p1, p2, p3,p4,p5,p6, layout = l)
plot!(size=(400,600))

# Test single particle:
function testSingle(index)
    lMax = 750;
    P⁰, P², R², T² = Scattering.compute_legendre_poly(μ,lMax)
    ϵ_s = zeros(lMax);
    #index = 100
    for l=0:lMax-1
        fac = (2l+1)/2 * sqrt(factorial(big(l-2))/factorial(big(l+2)))
        ϵ_s[l+1] = fac * sum(w_μ' * (f₃₄[index,:] .* P²[l+1,:]))
    end
    return ϵ_s
end

plot(testSingle(1000))


text:
function piecewise(x)
	IfElse.ifelse(x[1] < 0.5, 0.0,
		IfElse.ifelse(x[1] < 2.0, m_ss * x[1] - 0.5 * m_ss,
			-0.250 * m_ss * (x[1] - 2.0) + 1.5 * m_ss))
end

function d_piecewise(x)
	IfElse.ifelse(x[1] < 0.5, 0.0,
		IfElse.ifelse(x[1] < 2.0, m_ss,
			-0.250 * m_ss))
end

function mirror_and_repeat(x; l::T = 5.0) where {T}
	# l = length of the pattern  ---^_/^-
	# we repeat it this way ---^_/^--^\_^------^_/^--^\_^---
	# section ≡ even -> normal pattern
	# section ≡ odd -> mirrored pattern
	section = floor(x / l)
	x_rel = x % l
	mir = (section % 2) == 1
	if !mir
		x_mir = x_rel
	elseif mir # mirroring
		x_mir = l - x_rel
	end
	mult = mir == 1 ? -1 : 1
	return x_mir, mult
end

# smooth kinks w/ cubic polynomial
poly(a, z) = a[4] + a[3] * z + a[2] * z^2.0 + a[1] * z^3.0
d_poly(a, z) = a[3] + 2.0 * a[2] * z + 3.0 * a[1] * z^2.0

function generate_piecewise_terrain(mss; repeat::Bool = false)
	# piece 1
	m1 = 0.0
	x1 = 0.4
	y1 = m1 * x1

	m2 = m_ss
	x2 = 0.6
	y2 = m2 * 0.1

	A1 = [x1^3.0 x1^2.0 x1 1.0;
	      x2^3.0 x2^2.0 x2 1.0;
		  3.0 * x1^2.0 2.0 * x1 1.0 0.0;
		  3.0 * x2^2.0 2.0 * x2 1.0 0.0]
	b1 = [y1; y2; m1; m2]

	a1 = A1 \ b1

	@assert isapprox(poly(a1, x1) - y1, 0.0, atol = 1.0e-8)
	@assert isapprox(poly(a1, x2) - y2, 0.0, atol = 1.0e-8)

	# piece 2
	m1 = m_ss
	x1 = 1.4
	y1 = m_ss * x1

	m2 = -0.250 * m_ss
	x2 = 1.6
	y2 = m_ss * 1.5 + m2 * 0.1

	A2 = [x1^3.0 x1^2.0 x1 1.0;
	      x2^3.0 x2^2.0 x2 1.0;
		  3.0 * x1^2.0 2.0 * x1 1.0 0.0;
		  3.0 * x2^2.0 2.0 * x2 1.0 0.0]
	b2 = [y1; y2; m1; m2]

	a2 = A2 \ b2

	@assert isapprox(poly(a2, x1) - y1, 0.0, atol = 1.0e-8)
	@assert isapprox(poly(a2, x2) - y2, 0.0, atol = 1.0e-8)

	if !repeat
		function piecewise_smoothed(x)
			IfElse.ifelse(x[1] < 0.4, 0.0,
				IfElse.ifelse(x[1] < 0.6, poly(a1, x[1]),
					IfElse.ifelse(x[1] < 1.9, m_ss * x[1] - 0.5 * m_ss,
						IfElse.ifelse(x[1] < 2.1, poly(a2, x[1] - 0.5),
						-0.250 * m_ss * (x[1] - 2.0) + 1.5 * m_ss))))
		end

		function d_piecewise_smoothed(x)
			IfElse.ifelse(x[1] < 0.4, 0.0,
				IfElse.ifelse(x[1] < 0.6, d_poly(a1, x[1]),
					IfElse.ifelse(x[1] < 1.9, m_ss,
						IfElse.ifelse(x[1] < 2.1, d_poly(a2, x[1] - 0.5),
						-0.250 * m_ss))))
		end
		return piecewise_smoothed, d_piecewise_smoothed
	elseif repeat
		@show "repp"
		function piecewise_repeat_smoothed(x)
			x_mir, mult = mirror_and_repeat(x[1]; l = 5.0)
			IfElse.ifelse(x_mir < 0.4, mult * 0.0,
				IfElse.ifelse(x_mir < 0.6, mult * poly(a1, x_mir),
					IfElse.ifelse(x_mir < 1.9, mult * (m_ss * x_mir - 0.5 * m_ss),
						IfElse.ifelse(x_mir < 2.1, mult * poly(a2, x_mir - 0.5),
						mult * (-0.250 * m_ss * (x_mir - 2.0) + 1.5 * m_ss)))))
		end

		function d_piecewise_repeat_smoothed(x)
			x_mir, mult = mirror_and_repeat(x[1]; l = 5.0)
			IfElse.ifelse(x_mir < 0.4, 0.0,
				IfElse.ifelse(x_mir < 0.6, d_poly(a1, x_mir),
					IfElse.ifelse(x_mir < 1.9, m_ss,
						IfElse.ifelse(x_mir < 2.1, d_poly(a2, x_mir - 0.5),
						-0.250 * m_ss))))
		end
		return piecewise_repeat_smoothed, d_piecewise_repeat_smoothed
	end
end

# x = range(-1.0, stop = 4.0, length = 1000)
# plot(x, piecewise.(x))#, aspect_ratio = :equal)
# plot!(x, piecewise_smoothed.(x))#, aspect_ratio = :equal)
#
# plot(x, d_piecewise.(x), aspect_ratio = :equal)
# plot!(x, d_piecewise_smoothed.(x), aspect_ratio = :equal)

m_ss = tan(deg2rad(10.0)) # 10 degree slope
p1, dp1 = generate_piecewise_terrain(m_ss, repeat = false)
piecewise1_2D_lc = Environment{R2, LinearizedCone}(p1, dp1)
plot(-1:0.01:15, piecewise1_2D_lc.surf.(-1:0.01:15))
plot!(-1:0.01:15, piecewise1_2D_lc.surf_grad.(-1:0.01:15))

m_ss = tan(deg2rad(-15.0)) # 10 degree slope
p2, dp2 = generate_piecewise_terrain(m_ss)
piecewise2_2D_lc = Environment{R2, LinearizedCone}(p2, dp2)
# plot(-1:0.01:15, piecewise2_2D_lc.surf.(-1:0.01:15))
# plot!(-1:0.01:15, piecewise2_2D_lc.surf_grad.(-1:0.01:15))

# vis = Visualizer()
# open(vis)
# plot_surface!(vis, piecewise1_2D_lc, n = 100)
# plot_surface!(vis, piecewise2_2D_lc, n = 100)


text:
@testset "Internals" begin
    @test ThreadingUtilities.store!(pointer(UInt[]), (), 1) == 1
    @test ThreadingUtilities.store!(pointer(UInt[]), nothing, 1) == 1
    x = zeros(UInt, 100);
    GC.@preserve x begin
        t1 = (1.0, C_NULL, Val(7), (3, UInt(17)), VectorizationBase.stridedpointer(x))
        @test ThreadingUtilities.store!(pointer(x), t1, 0) === mapreduce(sizeof, +, t1)
        @test ThreadingUtilities.store!(pointer(x), Val(0), 0) == 0
        @test ThreadingUtilities.load(pointer(x), typeof(t1), 0) === (mapreduce(sizeof, +, t1), t1)
        @test ThreadingUtilities.load(pointer(x), Val{0}, 0) === (0, Val(0))
        @test ThreadingUtilities.store!(pointer(x), 0xb502916f%UInt, 72) == 72 + sizeof(Int)
        @test ThreadingUtilities.load(pointer(x), UInt, 72) == (72 + sizeof(Int),0xb502916f%UInt)
        nt1 = (;a = 1.0)
        @test ThreadingUtilities.store!(pointer(x), nt1, 0) === sizeof(nt1)
        @test ThreadingUtilities.load(pointer(x), typeof(nt1), 0) === (sizeof(nt1), nt1)
    end
end


text:
"""
Use jld save to a dictionary of variables, then unpack the dictionary after
load

NOT YET WORKING
"""

# using JSON
using JLD
using Parameters

"""
Plot the performance statistics of greedy_multi_path for 1 random end-user pair
over a range of graph sizes and for different numbers of max_path (1,2,3) (ie. the
maximum number of paths that can be purified by a given end-user pair.)
"""

# COOL BLACK MAGIC CODE
# Get the string of a variable identifier
# macro Name(arg)
#     string(arg)
# end

# function string_as_varname(s::AbstractString,v::Any)
#          s=Symbol(s)
#          @eval (($s) = ($v))
# end

# """
# Get a list of the symbolic variable names within scope.
# """
# function varnames()::Array{Symbol, 1}
#     # First 4 variables are modules, don't want to include them
#     vars = names(Main)[5:end]::Array{Symbol, 1}
#     # Filter ans
#     filter!(e->e!=:ans, vars)
#     return vars
# end

make_data = false
if make_data == true

    # Some example data
    a = 1
    b = 2.2
    c = [3 3; 3 3]

    # Pack dictionary with data using Parameters macro
    d = Dict{Symbol, Any}()
    @pack! d = a, b, c
    # Save data
    save("foo.jld", "data", d)
else
    # TODO Load data
    d = load("foo.jld")["data"]
    @unpack a, b, c = d
end

# function magic_save(filename::String, data...)
#     d = Dict{Symbol, Any}()
#     # @pack! d = data
#     # save("$filename.jld", "$filename", d)
# end

macro Magic_save(filename::String, data...)
    d = Dict{Symbol, Any}()
    @pack! d = data
    save("$filename.jld", "$filename", d)
end

macro Magic_load(filename::String, names...)
    d = load("$filename.jld")["$filename"]
    @unpack names = d
end

# function magic_load(filename::String, varnames...)
#     d = load("$filename.jld")["$filename"]
#     @unpack varnames = d
# end

e = 1
f = 2
g = 3

max_stars_repo_name: FalafelGood/QuNet

max_issues_repo_name: FalafelGood/QuNet

max_forks_repo_name: FalafelGood/QuNet


text:
cd(@__DIR__); include("setups/grid23x22.jl")
gr(dpi = 200)

##
frame = sgwt_frame(W; nf = 6)
filters = sgwt_filter_banks(W, 𝛌; nf = 6)
plot(𝛌, filters', lw = 3, size = (800, 450), grid = false, frame = :box,
    legendfontsize = 14, xlab = latexstring("\\lambda"), xguidefontsize = 14,
    lab = [latexstring("h(\\lambda)") latexstring("g(s_{1}\\lambda)") latexstring("g(s_{2}\\lambda)") latexstring("g(s_{3}\\lambda)") latexstring("g(s_{4}\\lambda)") latexstring("g(s_{5}\\lambda)")])
# plot!(𝛌, sum(filters, dims = 1)[:]/6, c = :black, lw = 3, lab = "partition of unity")
plt = current()
savefig(plt, "../figs/Grid$(Nx)x$(Ny)_SGWT_filter_banks.png")


text:
@testset "Metadata" begin
    sample_text1 = "This is a string"
    sample_text2 = "This is also a string"

    sd1 = StringDocument(sample_text1)
    sd2 = StringDocument(sample_text2)
    crps = Corpus([sd1, sd2])

    # Single document metadata getters
    @test isequal(title(sd1), "Untitled Document")
    @test isequal(language(sd1), Languages.English())
    @test isequal(author(sd1), "Unknown Author")
    @test isequal(timestamp(sd1), "Unknown Time")

    # Single document metadata setters
    title!(sd1, "Document")
    language!(sd1, Languages.German())
    author!(sd1, "Author")
    timestamp!(sd1, "Time")
    @test isequal(title(sd1), "Document")
    @test isequal(language(sd1), Languages.German())
    @test isequal(author(sd1), "Author")
    @test isequal(timestamp(sd1), "Time")

    # Metadata getters for an entire corpus
    @test isequal(TextAnalysis.titles(crps), ["Document", "Untitled Document"])
    @test isequal(languages(crps), [Languages.German(), Languages.English()])
    @test isequal(authors(crps), ["Author", "Unknown Author"])
    @test isequal(timestamps(crps), ["Time", "Unknown Time"])

    # Metadata setters for an entire corpus
    titles!(crps, "Document")
    languages!(crps, Languages.Spanish())
    authors!(crps, "Author")
    timestamps!(crps, "Time")
    @test isequal(TextAnalysis.titles(crps), ["Document", "Document"])
    @test isequal(languages(crps), [Languages.Spanish(), Languages.Spanish()])
    @test isequal(authors(crps), ["Author", "Author"])
    @test isequal(timestamps(crps), ["Time", "Time"])
    titles!(crps, ["Untitled Document", "Untitled Document"])
    languages!(crps, [Languages.English(), Languages.English()])
    authors!(crps, ["Unknown Author", "Unknown Author"])
    timestamps!(crps, ["Unknown Time", "Unknown Time"])
    @test isequal(TextAnalysis.titles(crps), ["Untitled Document", "Untitled Document"])
    @test isequal(languages(crps), [Languages.English(), Languages.English()])
    @test isequal(authors(crps), ["Unknown Author", "Unknown Author"])
    @test isequal(timestamps(crps), ["Unknown Time", "Unknown Time"])
end


text:
using Test
using CLIMA
using CLIMA.RootSolvers

CLIMA.init()

if CLIMA.array_type() != Array
  CLIMA.gpu_allowscalar(false)

  @testset "RootSolvers CUDA - compact solution " begin
    for FT in [Float32, Float64]
      X0 = cu(rand(FT, 5,5))
      X1 = cu(rand(FT, 5,5)) .+ 1000
      f(x) = x^2 - 100^2

      sol = RootSolvers.find_zero.(f, X0, X1, SecantMethod(), CompactSolution())
      converged = map(x->x.converged, sol)
      X_roots = map(x->x.root, sol)
      @test all(converged)
      @test eltype(X_roots) == eltype(X0)
      @test all(X_roots .≈ 100)
    end
  end

  @testset "RootSolvers CUDA - verbose solution " begin
    for FT in [Float32, Float64]
      X0 = cu(rand(FT, 5,5))
      X1 = cu(rand(FT, 5,5)) .+ 1000
      f(x) = x^2 - 100^2

      sol = RootSolvers.find_zero.(f, X0, X1, SecantMethod(), VerboseSolution())
      converged = map(x->x.converged, sol)
      X_roots = map(x->x.root, sol)
      err = map(x->x.err, sol)
      iter_performed = map(x->x.iter_performed, sol)
      @test all(converged)
      @test eltype(X_roots) == eltype(X0)
      @test all(X_roots .≈ 100)
      @test all(err .< 1e-2)
      @test all(iter_performed .< 20)
    end
  end
end

max_stars_repo_name: favba/CLIMA

max_issues_repo_name: favba/CLIMA

max_forks_repo_name: favba/CLIMA


text:
function evalmaximum(f, intervals::Vector{Tuple{arb, arb}};
                     evaltype = :ball,
                     n = 4,
                     absmax = false)
    evals = Vector{Tuple{arb, arb}}(undef, length(intervals))
    if evaltype == :ball
        maybeabs = ifelse(absmax, abs, identity)
        Threads.@threads for i in 1:length(intervals)
            evals[i] = getinterval(maybeabs(f(setinterval(intervals[i]...))))
        end
    elseif evaltype == :taylor
        Threads.@threads for i in 1:length(intervals)
            evals[i] = getinterval(maximumtaylor(f, intervals[i], n, absmax = absmax))
        end
    end

    evals
end

function enclosemaximum(f,
                        a::arb,
                        b::arb;
                        # A priori computed lower bound of maximum
                        lower_bound::arb = neginf(a),
                        absmax = false,
                        evaltype = :ball,
                        n = 4,
                        # FIXME: This should be epsilon in the precision of the input parameters
                        atol = sqrt(eps()),
                        rtol = sqrt(eps()),
                        maxevals = 10^3,
                        store_trace = false,
                        show_trace = false,
                        callback = nothing,
                        extended_trace = false)
    @assert isfinite(a) && isfinite(b) && a < b

    intervals = [(a, b)]
    maxenclosure = setinterval(neginf(a), posinf(a))
    E = radius(maxenclosure)
    numevals = 0
    iteration = 0
    imprecise_input_last_iteration = false
    imprecise_input = false

    trace = MaximumTrace()
    if show_trace
        print(trace)
    end

    while (!(E < atol)
           && !(E/abs(maxenclosure) <= rtol)
           && numevals <= maxevals
           && !imprecise_input)
        iteration += 1

        # Lower and upper bound maximum on each interval
        evals = evalmaximum(f, intervals, evaltype = evaltype, n = n, absmax = absmax)
        numevals += length(intervals)

        # Find global lower and upper bound for maximum
        maxlower = neginf(a)
        maxupper = neginf(a)
        for (lower, upper) in evals
            if isfinite(lower) && !(lower < maxlower)
                maxlower = max(maxlower, lower)
            end

            if !(upper < maxupper)
                maxupper = max(maxupper, upper)
            end
        end

        if maxupper < lower_bound
            @error "given lower bound is larger than maximum"
            return parent(a)(NaN)
        end

        maxenclosure = setinterval(maxlower, maxupper)

        maxlower = max(maxlower, lower_bound)

        # Split intervals where the maximum could be located
        nextintervals = Vector{eltype(intervals)}()
        for i in 1:length(intervals)
            if !(evals[i][2] < maxlower)
                midpoint = 0.5*(intervals[i][1] + intervals[i][2])
                push!(nextintervals, (intervals[i][1], midpoint))
                push!(nextintervals, (midpoint, intervals[i][2]))
            end
        end

        # Update trace
        if !extended_trace
            dt = Dict()
        else
            dt = Dict("intervals" => intervals, "evaluations" => evals)
        end
        update!(trace,
                MaximumState(iteration, length(intervals), maxenclosure, dt),
                store_trace,
                show_trace,
                callback)

        intervals = nextintervals

        # If using Taylor series and no substantial improvement is
        # made from previous iteration this usually hints at working
        # with to low precision
        if evaltype == :taylor && isfinite(maxenclosure) && radius(maxenclosure) > 0.8*E
            if imprecise_input_last_iteration
                imprecise_input = true
            end
            imprecise_input_last_iteration = true
        else
            imprecise_input_last_iteration = false
        end

        E = radius(maxenclosure)
    end

    if imprecise_input && !(E < atol || E/abs(maxenclosure) <= rtol || !(numevals <= maxevals))
        @warn "Maximum likely needs to be computed with higher precision than $(precision(parent(a)))"
    end

    if store_trace
        return maxenclosure, trace
    end

    maxenclosure
end


text:
# Code for Day 9 of Advent of Code: https://adventofcode.com/2018/day/9
# Julia Solution
#
# Copyright (C) 2018 Lawrence Woodman <lwoodman@vlifesystems.com>
# Licensed under an MIT licence.  Please see LICENCE.md for details.

using Printf

mutable struct Game
  numPlayers
  lastMarble
  current
  marbles
  Game(numPlayers, lastMarble) = new(numPlayers, lastMarble, -1, Dict())
  Game() = new(0, 0, -1, Dict())
end

mutable struct Marble
  prev
  next
end

function start(g::Game)
  g.marbles = Dict(0 => Marble(0,0))
  g.current = 0
end

function next(g::Game, value)
  g.marbles[value].next
end

function prev(g::Game, value)
  g.marbles[value].prev
end

function prev7(g::Game)
  v = g.current
  for i in 1:7
    v = prev(g, v)
  end
  v
end

function remove(g::Game, value)
  prev = g.marbles[value].prev
  next = g.marbles[value].next
  g.marbles[prev].next = next
  g.marbles[next].prev = prev
  g.current = next
  delete!(g.marbles, value)
end

function insert(g::Game, beforeValue, value)
  before = g.marbles[beforeValue]
  beforePrev = before.prev
  g.marbles[value] = Marble(before.prev, beforeValue)
  g.marbles[beforeValue].prev = value
  g.marbles[beforePrev].next = value
  g.current = value
end

function add(g::Game, value)
  if value % 23 == 0
    throw(ArgumentError("can't add multiple of 23"))
  end
  next1 = next(g, g.current)
  next2 = next(g, next1)
  insert(g, next2, value)
end

function getInput(filename)
  game = Game()
  open(filename) do file
    for ln in eachline(file)
      gameWords = split(ln)
      game = Game(parse(Int32, gameWords[1]), parse(Int32, gameWords[7]))
      break
    end
  end
  game
end

function play(g::Game)
  playerNum = 1
  start(g)
  scores = Dict()
  for m in 1:g.lastMarble
    if m % 23 == 0
      removeValue = prev7(g)
      remove(g, removeValue)
      playerScore = get(scores, playerNum, 0)
      scores[playerNum] = playerScore+m+removeValue
    else
      add(g, m)
    end
    playerNum = playerNum + 1
    if playerNum >= g.numPlayers
      playerNum = 0
    end
  end
  highestScore = 0
  for (p, s) in scores
    if s > highestScore
      highestScore = s
    end
  end
  highestScore
end

function part1(game)
  play(game)
end

function part2(game)
  game.lastMarble = game.lastMarble*100
  play(game)
end

game = getInput("day9.input")
@printf "part1: %d\n" part1(game)
@printf "part2: %d\n" part2(game)

max_stars_repo_name: lawrencewoodman/adventofcode

max_issues_repo_name: lawrencewoodman/adventofcode

max_forks_repo_name: lawrencewoodman/adventofcode


text:
using HDF5

"""Load debugging info from SGLTR"""
function sgdebug(fname::AbstractString, convert64=true)
    fid = h5open(fname, "r")
    try
        k1h = a_read(fid["IMS"], "kernel1_h")
        k1v = a_read(fid["IMS"], "kernel1_v")
        k2h = a_read(fid["IMS"], "kernel2_h")
        k2v = a_read(fid["IMS"], "kernel2_v")
        k2v = a_read(fid["IMS"], "kernel2_v")
        t_low = a_read(fid["IMS"], "threshold_low")
        t_high = a_read(fid["IMS"], "threshold_high")
        S = read(fid, "IMS/raw")'
        L = read(fid, "IMS/laplace")'
        B = read(fid, "IMS/rm_base")'

        vars = @qvs k1h k1v k2h k2v S L B t_low t_high
        if convert64
            vars = [(k, map(Float64, v)) for (k,v) in vars]
        end
        Dict(vars)
    catch
        rethrow()
    finally
        close(fid)
    end
end

"""Generate SGLTR debug file"""
function sgltr_debug(fname::AbstractString)
    dname = fname * ".debug"
    peaks = readall(pipeline(`sgltr $fname -d $dname`, stderr=DevNull))
    readdlm(IOBuffer(peaks), '\t'; header=true)
end

"""Clip to interesting part of the measurement"""
interesting(S) = S[1:400, 760:1250]


text:
using NewtonsMethod
using Test

using Polynomials
@testset "NewtonsMethod.jl" begin
    @testset "root_of_a_known_function" begin
        f(x) = (x-1)^3
        f_prime(x) = 3*(x-1)^2
        root = 1
        @test root ≈ fixedpointmap(f, f_prime, 2).value #test with first method (f, f', x_0)
        @test root ≈ fixedpointmap(f, 2).value #test with second method (f, x_0)

        f(x) = (x-4)/x
        f_prime(x) = 4/(x^2)
        root = 4
        @test root ≈ fixedpointmap(f, f_prime, 2).value #test with first method (f, f', x_0)
        @test root ≈ fixedpointmap(f, 2).value #test with second method (f, x_0)

    end
    @testset "comparing with Polynomials.roots" begin
        #check the one of the roots of 2 - 5*x + 2*x^2 and comparing it with roots()
        p = Poly([2, -5, 2], :x)
        p′ = polyder(p)
        root = roots(p)
        @test any(root .≈ fixedpointmap(p, p′, 2).value) #test with first method (f, f', x_0)
        @test any(root .≈ fixedpointmap(p, 2).value) #test with second method (f, x_0)

        p = Poly([2, -5, 2, 10], :x)
        p′ = polyder(p)
        root = roots(p)
        @test any(root .≈ fixedpointmap(p, p′, 2).value) #test with first method (f, f', x_0)
        @test any(root .≈ fixedpointmap(p, 2).value) #test with second method (f, x_0)
    end

    @testset "testing BigFloat" begin
        #check the one of the roots of 2 - 5*x + 2*x^2 and comparing it with roots()
        f(x) = (x-1)^3
        f_prime(x) = 3*(x-1)^2
        root = 1.0
        @test root ≈ fixedpointmap(f, f_prime, BigFloat(2)).value #test with first method (f, f', x_0)
        @test root ≈ fixedpointmap(f, BigFloat(2)).value #test with second method (f, x_0)
    end

    @testset "testing non-convergence" begin
        #check the one of the roots of 2 - 5*x + 2*x^2 and comparing it with roots()
        f(x) = x^2 + 1
        f_prime(x) = 2*x
        @test nothing == fixedpointmap(f, f_prime, 2) #test with first method (f, f', x_0)
        @test nothing == fixedpointmap(f, 2) #test with second method (f, x_0)
    end

    @testset "maxiter is working" begin
        #check the one of the roots of 2 - 5*x + 2*x^2 and comparing it with roots()
        f(x) = (x-1)^3
        f_prime(x) = 3*(x-1)^2
        root = 1
        #if with maxiter = 2, we doesn't get the root, then the test will be passed: it means maxiter is working.
        @test_broken root ≈ fixedpointmap(f, f_prime, 2, maxiter = 2).value #test with first method (f, f', x_0)
        @test_broken root ≈ fixedpointmap(f, 2, maxiter = 2).value #test with second method (f, x_0)
    end
    @testset "tolerance is working" begin
        #check the one of the roots of 2 - 5*x + 2*x^2 and comparing it with roots()
        f(x) = (x-1)^3
        f_prime(x) = 3*(x-1)^2
        root = 1
        #if with tolerance = 1E-3, we doesn't get the root, then the test will be passed: it means maxiter is working.
        @test_broken root ≈ fixedpointmap(f, f_prime, 2, tolerance = 1E-3).value #test with first method (f, f', x_0)
        @test_broken root ≈ fixedpointmap(f, 2, tolerance = 1E-3).value #test with second method (f, x_0)
    end

end


text:
using Documenter, ArchGDAL

DocMeta.setdocmeta!(
    ArchGDAL,
    :DocTestSetup,
    :(using ArchGDAL, GDAL);
    recursive = true,
)

# make sure you have run the tests before such that the test files are present
makedocs(
    modules = [ArchGDAL],
    format = Documenter.HTML(;
        prettyurls = get(ENV, "CI", "false") == "true",
        canonical = "https://yeesian.com/ArchGDAL.jl",
        assets = String[],
    ),
    sitename = "ArchGDAL.jl",
    workdir = joinpath(@__DIR__, "..", "test"),
    strict = true,
    pages = [
        "index.md",
        "ArchGDAL Quickstart Guide" => "quickstart.md",
        "GDAL Datasets" => "datasets.md",
        "Feature Data" => "features.md",
        "Raster Data" => "rasters.md",
        "Working with Images" => "images.md",
        "Tables Interface" => "tables.md",
        "Geometric Operations" => "geometries.md",
        "Spatial Projections" => "projections.md",
        # TODO: Uncomment the following line once we support Spatialite
        # See https://github.com/JuliaGeo/GDAL.jl/issues/65#issuecomment-493890448.
        # "Working with Spatialite" => "spatialite.md",
        "Interactive versus Scoped Objects" => "memory.md",
        "Design Considerations" => "considerations.md",
        "API Reference" => "reference.md",
    ],
)

deploydocs(repo = "github.com/yeesian/ArchGDAL.jl.git", push_preview = true)