text:
struct LKPyramid
    layers::Vector{Matrix{Gray{Float64}}}

    Iy::Union{Nothing, Vector{Matrix{Gray{Float64}}}}
    Ix::Union{Nothing, Vector{Matrix{Gray{Float64}}}}

    Iyy::Union{Nothing, Vector{Matrix{Gray{Float64}}}}
    Ixx::Union{Nothing, Vector{Matrix{Gray{Float64}}}}
    Iyx::Union{Nothing, Vector{Matrix{Gray{Float64}}}}
end

function LKPyramid(image, levels; downsample = 2, σ = 1.0, compute_gradients::Bool = true)
    pyramid = gaussian_pyramid(image, levels, downsample, σ)
    !compute_gradients &&
        return LKPyramid(pyramid, nothing, nothing, nothing, nothing, nothing)

    total_levels = levels + 1
    Iy = Vector{Matrix{Gray{Float64}}}(undef, total_levels)
    Ix = Vector{Matrix{Gray{Float64}}}(undef, total_levels)

    Iyy = Vector{Matrix{Gray{Float64}}}(undef, total_levels)
    Ixx = Vector{Matrix{Gray{Float64}}}(undef, total_levels)
    Iyx = Vector{Matrix{Gray{Float64}}}(undef, total_levels)

    filling = Fill(zero(eltype(pyramid[1])))
    for (i, layer) in enumerate(pyramid)
        Iy[i], Ix[i] = imgradients(layer, KernelFactors.scharr, filling)
        Iyy[i], Ixx[i], Iyx[i] = compute_partial_derivatives(Iy[i], Ix[i])
    end
    LKPyramid(pyramid, Iy, Ix, Iyy, Ixx, Iyx)
end

function optflow(
    first_img::AbstractMatrix{T}, second_img::AbstractMatrix{T},
    points::Vector{SVector{2, Float64}}, algorithm::LucasKanade,
) where T <: Gray
    displacement = fill(SVector{2, Float64}(0.0, 0.0), length(points))
    first_pyramid = LKPyramid(first_img, algorithm.pyramid_levels)
    second_pyramid = LKPyramid(
        second_img, algorithm.pyramid_levels; compute_gradients=false,
    )
    optflow!(first_pyramid, second_pyramid, points, displacement, algorithm)
end

function optflow!(
    first_img::AbstractMatrix{T}, second_img::AbstractMatrix{T},
    points::Vector{SVector{2, Float64}}, displacement::Vector{SVector{2, Float64}},
    algorithm::LucasKanade,
) where T <: Gray
    first_pyramid = LKPyramid(first_img, algorithm.pyramid_levels)
    second_pyramid = LKPyramid(
        second_img, algorithm.pyramid_levels; compute_gradients=false,
    )
    optflow!(first_pyramid, second_pyramid, points, displacement, algorithm)
end

function optflow!(
    first_pyramid::LKPyramid, second_pyramid::LKPyramid,
    points::Vector{SVector{2, Float64}}, displacement::Vector{SVector{2, Float64}},
    algorithm::LucasKanade,
)
    has_enough_layers =
        length(first_pyramid.layers) > algorithm.pyramid_levels &&
        length(second_pyramid.layers) > algorithm.pyramid_levels
    has_enough_layers || throw("Not enough layers in pyramids.")

    n_points = length(points)
    status = trues(n_points)

    window = algorithm.window_size
    window2x = 2 * window

    for level in (algorithm.pyramid_levels + 1):-1:1
        level_resolution = axes(first_pyramid.layers[level])
        # Interpolate layer to get sub-pixel precision.
        # We never go out-of-bound, so there is no need to extrapolate.
        interploated_layer = interpolate(second_pyramid.layers[level], BSpline(Linear()))

        for n in 1:n_points
            @inbounds !status[n] && continue

            point = get_pyramid_coordinate(@inbounds(points[n]), level)
            offsets = get_offsets(point, point, window, level_resolution)
            grid = get_grid(point, offsets)

            G_inv, min_eigenvalue = compute_spatial_gradient(first_pyramid, grid, level)
            if min_eigenvalue < algorithm.eigenvalue_threshold
                @inbounds status[n] = false
                continue
            end

            pyramid_contribution = SVector{2}(0.0, 0.0)
            for _ in 1:algorithm.iterations
                putative_flow = @inbounds displacement[n] + pyramid_contribution
                putative_correspondence = point + putative_flow
                if !lies_in(level_resolution, putative_correspondence)
                    @inbounds status[n] = false
                    break
                end

                new_offsets = get_offsets(
                    point, putative_correspondence, window, level_resolution,
                )
                # Recalculate gradient only if the offset changes.
                if new_offsets != offsets
                    offsets = new_offsets
                    grid = get_grid(point, offsets)
                    G_inv, min_eigenvalue = compute_spatial_gradient(
                        first_pyramid, grid, level,
                    )
                    if min_eigenvalue < algorithm.eigenvalue_threshold
                        @inbounds status[n] = false
                        break
                    end
                else
                    offsets = new_offsets
                    grid = get_grid(point, offsets)
                end

                estimated_flow = compute_flow_vector(
                    putative_correspondence,
                    first_pyramid, interploated_layer, level,
                    grid, offsets, G_inv,
                )
                # Epsilon termination criteria.
                abs(estimated_flow[1]) < algorithm.ϵ &&
                    abs(estimated_flow[2]) < algorithm.ϵ && break

                pyramid_contribution += estimated_flow
                # Check if tracked point is out of image bounds.
                if !lies_in(level_resolution, point + pyramid_contribution)
                    @inbounds status[n] = false
                    break
                end
            end
            @inbounds begin
            # Check if flow is too big.
            if status[n] && is_lost(displacement[n], window2x)
                status[n] = false
            end
            if status[n]
                displacement[n] += pyramid_contribution
                level != 1 && (displacement[n] *= 2.0)
            end
            end
        end
    end

    displacement, status
end

function compute_partial_derivatives(Iy, Ix; σ = 4)
    kernel = KernelFactors.gaussian(σ)
    kernel_factors = kernelfactors((kernel, kernel))

    squared = typeof(Iy)(undef, size(Iy))
    filtered = typeof(Iy)(undef, size(Iy))

    squared .= Iy .* Iy
    imfilter!(filtered, squared, kernel_factors)
    Iyy_integral_table = integral_image(filtered)

    squared .= Ix .* Ix
    imfilter!(filtered, squared, kernel_factors)
    Ixx_integral_table = integral_image(filtered)

    squared .= Iy .* Ix
    imfilter!(filtered, squared, kernel_factors)
    Iyx_integral_table = integral_image(filtered)

    Iyy_integral_table, Ixx_integral_table, Iyx_integral_table
end

function _compute_spatial_gradient(
    grid, Iyy_integral, Iyx_integral, Ixx_integral,
)
    sum_Iyy = boxdiff(Iyy_integral, grid[1], grid[2])
    sum_Ixx = boxdiff(Ixx_integral, grid[1], grid[2])
    sum_Iyx = boxdiff(Iyx_integral, grid[1], grid[2])
    SMatrix{2, 2, Float64}(sum_Iyy, sum_Iyx, sum_Iyx, sum_Ixx)
end

function compute_spatial_gradient(pyramid::LKPyramid, grid, level)
    G = _compute_spatial_gradient(
        grid, pyramid.Iyy[level], pyramid.Iyx[level], pyramid.Ixx[level],
    )
    U, S, V = svd2x2(G)
    G_inv = pinv2x2(U, S, V)
    min_eigenvalue = min(S[1, 1], S[2, 2]) / prod(length.(grid))

    G_inv, min_eigenvalue
end

function prepare_linear_system(corresponding_point, A, Iy, Ix, offsets, B)
    P, Q = size(A)
    by, bx = 0.0, 0.0

    @inbounds for q in 1:Q, p in 1:P
        r = corresponding_point[1] + offsets[1][p]
        c = corresponding_point[2] + offsets[2][q]

        δI = A[p, q] - B(r, c)
        by += δI * Iy[p, q]
        bx += δI * Ix[p, q]
    end

    SVector{2, Float64}(by, bx)
end

function compute_flow_vector(
    corresponding_point,
    first_pyramid::LKPyramid, etp, level,
    grid, offsets, G_inv,
)
    b = prepare_linear_system(
        corresponding_point,
        view(first_pyramid.layers[level], grid[1], grid[2]),
        view(first_pyramid.Iy[level], grid[1], grid[2]),
        view(first_pyramid.Ix[level], grid[1], grid[2]),
        offsets, etp,
    )
    G_inv * b
end

@inline is_lost(displacement, window) =
    @inbounds(displacement[1] > window || displacement[2] > window)

@inline lies_in(area, point) = @inbounds(
    first(area[1]) ≤ point[1] ≤ last(area[1]) &&
    first(area[2]) ≤ point[2] ≤ last(area[2])
)

"""
# Arguments
- `level`: Level of the pyramid in `[1, levels]` range.
"""
@inline get_pyramid_coordinate(point, level) = floor.(Int, point ./ 2 ^ (level - 1))

function get_offsets(point, new_point, window, image_axes)
    rows, cols = image_axes

    @inbounds begin
    up = floor(Int, min(window, min(point[1], new_point[1]) - first(rows)))
    down = floor(Int, min(window, last(rows) - max(point[1], new_point[1])))
    left = floor(Int, min(window, min(point[2], new_point[2]) - first(cols)))
    right = floor(Int, min(window, last(cols) - max(point[2], new_point[2])))
    end

    (-up:down, -left:right)
end

function get_grid(point, offsets)
    map(point, offsets) do p, o
        p+first(o):p+last(o)
    end
end


text:
module CoexistenceHoles

import LinearAlgebra: diagind, rank, pinv, eigvals, diagm, norm, diag
import StatsBase: sample
import Distributions # have to import this separately because of a weird thing with JuliaCall in R
import Distributions: Uniform, Normal, Bernoulli, LogNormal
import ProgressMeter: @showprogress
import Convex: Variable, minimize, solve!
import SCS: Optimizer
import IterTools: reverse
import Ripserer: Rips, ripserer
import Combinatorics: combinations
import Random: seed!, shuffle

include("create_hypergraph.jl")
include("hypergraph_analysis.jl")

export  random_communitymatrix,
        randomize_communitymatrix,
        random_growthvector,
        is_GLVlocallystable,
        is_GLVpermanent,
        randomize_growthvector,
        assembly_hypergraph_GLV,
        disassembly_hypergraph,
        betti_hypergraph_ripscomplex,
        read_hypergraph,
        hypergraph_subdivide,
        minimal_simplicial_complex,
        save_hypergraph_dat
end

ext: jl

max_issues_repo_name: mtangulo/coexistenceholes

max_forks_repo_name: mtangulo/coexistenceholes


text:
y = Vector{Int}(df[:y])
X = Matrix(Matrix{Float64}(df[:,[:x1,:x2]])')

# initial vectors
k,n = size(X)
py = proportions(y)
γ0 = norminvcdf.(cumsum(py))[1:end-1]
β0 = zeros(k)
θ0 = [β0..., γ0...]

# tmp arrays
tmpη = Array{eltype(X)}(undef,n)
tmpgrad = Vector{Float64}(undef,length(θ0))

# --------- check that LL functions are the same ---------

for model in (:logit,:probit,)

    @show model

    @testset "testing cdf/pdf derivatives for $model" begin
        for z in -10.:10.
            fd = Calculus.gradient((x) -> OrderedResponse.cdf(x, Val{model}), z)
            ad = OrderedResponse.pdf(z, Val{model})

            fh = Calculus.hessian( (x) -> OrderedResponse.cdf(x, Val{model}), z)
            ah = OrderedResponse.dpdf(z, Val{model})

            @test isapprox(fd, ad, atol=1e-9, rtol=1e-8)
            @test isapprox(fh, ah, atol=3.79e-7, rtol=1e-5)
            # @test fd ≈ ad
            # @test fh ≈ ah
            @test abs(fd - ad) < 1e-5
            @test abs(fh - ah) < 1e-5
        end
    end

    # ------------- closures ---------------

    # function LL!(grad::Vector{T}, hess::Matrix{T}, tmpgrad::Vector, η::Vector, y::Vector{<:Integer}, X::Matrix, β::Vector, γ::Vector, model::Type{Val{D}}, sgn::Real=-one(T)) where {D,T}

    f(θ::Vector)                = OrderedResponse.orLL!(zeros(0), zeros(0,0), zeros(0), tmpη, y, X, θ[1:2], θ[3:4], Val{model}, -1.0)
    g!(grad::Vector, θ::Vector) = OrderedResponse.orLL!(grad    , zeros(0,0), tmpgrad , tmpη, y, X, θ[1:2], θ[3:4], Val{model}, -1.0)
    h!(hess::Matrix, θ::Vector) = OrderedResponse.orLL!(zeros(4),       hess, tmpgrad , tmpη, y, X, θ[1:2], θ[3:4], Val{model}, -1.0)

    function g(θ::Vector)
        grad = similar(θ)
        g!(grad, θ)
        return grad
    end

    function h(θ::Vector)
        grad = similar(θ)
        hess = Matrix{eltype(grad)}(undef,length(grad), length(grad))
        h!(hess, θ)
        return hess
    end

    # --------- derivative -free search ---------

    optf = Optim.optimize(f, θ0)
    @show optf
    @test_broken optf.minimizer ≈ θpolr(model)
    @test norm(optf.minimizer .- θpolr(model), Inf) < 3e-5

    # --------- opt with derivatives ---------

    @test Calculus.derivative(f, θ0) ≈ g(θ0)
    @test_broken Calculus.derivative(f, optf.minimizer) ≈ g(optf.minimizer)
    @test norm(Calculus.derivative(f, optf.minimizer) .- g(optf.minimizer), Inf) < 1e-5

    optg = Optim.optimize(f, g!, θ0)
    @show optg
    # @test_broken optf.minimizer ≈ optg.minimizer
    # @test_broken optg.minimizer ≈ θpolr(model)
    @test norm(optf.minimizer .- optg.minimizer, Inf) < 1e-4
    @test norm(optg.minimizer .- θpolr(model), Inf) < 1e-7
    @show optg.minimizer .- θpolr(model)

    # -------- newton-rhapson ------------

    maxhessdiff = maximum(abs.(Calculus.hessian(f, θ0) .- h(θ0)))
    println("\nMaximum FD for Hessian in $model model is $maxhessdiff\n")
    @test maxhessdiff < 0.2

    opth = Optim.optimize(f, g!, h!, θ0)
    vcov = h(opth.minimizer)\Matrix(I,4,4)

    @test norm(opth.minimizer .- θpolr(model), Inf) < 1e-7
    @test norm((vcov .- vcovpolr(model))[:], Inf) < 2.7e-4
    # @test_broken opth.minimizer ≈ θpolr(model)
    @test_broken vcov ≈ vcovpolr(model)

    @show opth.minimizer .- θpolr(model)
    @show sqrt.(diag(vcov)) .- sqrt.(diag(vcovstata(model)))

end


text:
struct PathTable{D,T}
    table::Array{Union{T,Nothing},D}
end

# Case where no dimensional expansion is needed.
function PathTable(table::Array{Vector{T},D}, fullsize::NTuple{D}) where {T,D}
    return PathTable{D,T}([isempty(t) ? nothing : first(t) for t in table])
end

function PathTable(table::Array{Vector{T},D}, fullsize::NTuple{N}) where {T,D,N}
    newtable = map(CartesianIndices(fullsize)) do idx
        a = first(Tuple(idx))
        b = Base.tail(Tuple(idx))

        vector = table[b...]
        return checkbounds(Bool, vector, a) ? vector[a] : nothing
    end
    return PathTable{N,T}(newtable)
end

Base.getindex(p::PathTable, i...) = getindex(p.table, i...)

# Iterator protocol
Base.iterate(p::PathTable) = iterate(p.table)
Base.iterate(p::PathTable, state) = iterate(p.table, state)
Base.length(p::PathTable) = length(p.table)
Base.size(pathtable::PathTable) = size(pathtable.table)
Base.size(pathtable::PathTable, i) = size(pathtable.table, i)
Base.IteratorSize(p::PathTable) = Base.IteratorSize(p.table)

function findaddress(pathtable::PathTable{D}, address::Address{D}, item) where {D}
    @assert pathtable[address] == item
    return address
end

function findaddress(pathtable::PathTable, address::Address, item) where {D}
    for i in 1:size(pathtable, 1)
        if pathtable[i, address] == item
            return Address(i, address)
        end
    end
    return throw(KeyError(item))
end

function build_pathtable(toplevel::TopLevel{D}, ruleset::RuleSet) where {D}
    offset = getoffset(toplevel)
    @debug "Architecture Offset: $offset"
    # Get the dimensions of the addresses to build the array that is going to
    # hold the component table. Get the inside tuple for creation.
    dims = size(toplevel)
    table = fill(Path{Component}[], dims...)

    for (name, component) in toplevel.children
        # Collect full paths for all components that are mappable.
        paths = [
            catpath(name, p) for
            p in walk_children(component) if ismappable(ruleset, component[p])
        ]

        # Account for toplevel to array address offset
        table[getaddress(toplevel, name) + offset] = paths
    end

    # Expand the table to full-size
    fulldims = MapperCore.fullsize(toplevel, ruleset)
    return PathTable(table, fulldims)
end


text:
mutable struct Contact
    name::String
    phonenumber::Dict{Any,Any}
end

person = Contact("Jane Doe", Dict())
person.phonenumber["home"] = "212 555-1234"

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
Pkg.rm("AutomotiveDrivingModels.jl")
Pkg.rm("AutomotiveDrivingModels.jl")
Pkg.rm("AutoViz.jl")
Pkg.rm("AutoViz.jl")
Pkg.rm("NGSIM.jl")
Pkg.rm("NGSIM.jl")
Pkg.rm("ForwardNets.jl")
Pkg.rm("ForwardNets.jl")
Pkg.rm("Records.jl")
Pkg.rm("Records.jl")
Pkg.rm("VideoIO.jl")
Pkg.rm("VideoIO.jl")
Pkg.rm("Cairo.jl")
Pkg.rm("Cairo.jl")
Pkg.rm("Vec.jl")
Pkg.rm("Vec.jl")

Pkg.rm("AutomotiveDrivingModels.jl")
Pkg.rm("AutoViz.jl")
Pkg.rm("NGSIM.jl")
Pkg.rm("ForwardNets.jl")
Pkg.rm("Records.jl")
Pkg.rm("VideoIO.jl")
Pkg.rm("Cairo.jl")
Pkg.rm("Vec.jl")

Pkg.rm("AutomotiveDrivingModels.jl")
Pkg.rm("AutoViz.jl")
Pkg.rm("NGSIM.jl")
Pkg.rm("ForwardNets.jl")
Pkg.rm("Records.jl")
Pkg.rm("VideoIO.jl")
Pkg.rm("Cairo.jl")
Pkg.rm("Vec.jl")

max_stars_repo_name: yoshihikokuwahara/gail-driver

max_issues_repo_name: yoshihikokuwahara/gail-driver

max_forks_repo_name: yoshihikokuwahara/gail-driver


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

"""
    associate_team_member(project_id, project_role, user_arn)
    associate_team_member(project_id, project_role, user_arn, params::Dict{String,<:Any})

Adds an IAM user to the team for an AWS CodeStar project.

# Arguments
- `project_id`: The ID of the project to which you will add the IAM user.
- `project_role`: The AWS CodeStar project role that will apply to this user. This role
  determines what actions a user can take in an AWS CodeStar project.
- `user_arn`: The Amazon Resource Name (ARN) for the IAM user you want to add to the AWS
  CodeStar project.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"clientRequestToken"`: A user- or system-generated token that identifies the entity that
  requested the team member association to the project. This token can be used to repeat the
  request.
- `"remoteAccessAllowed"`: Whether the team member is allowed to use an SSH public/private
  key pair to remotely access project resources, for example Amazon EC2 instances.
"""
function associate_team_member(
    projectId, projectRole, userArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "AssociateTeamMember",
        Dict{String,Any}(
            "projectId" => projectId, "projectRole" => projectRole, "userArn" => userArn
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function associate_team_member(
    projectId,
    projectRole,
    userArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codestar(
        "AssociateTeamMember",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "projectId" => projectId,
                    "projectRole" => projectRole,
                    "userArn" => userArn,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_project(id, name)
    create_project(id, name, params::Dict{String,<:Any})

Creates a project, including project resources. This action creates a project based on a
submitted project request. A set of source code files and a toolchain template file can be
included with the project request. If these are not provided, an empty project is created.

# Arguments
- `id`: The ID of the project to be created in AWS CodeStar.
- `name`: The display name for the project to be created in AWS CodeStar.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"clientRequestToken"`: A user- or system-generated token that identifies the entity that
  requested project creation. This token can be used to repeat the request.
- `"description"`: The description of the project, if any.
- `"sourceCode"`: A list of the Code objects submitted with the project request. If this
  parameter is specified, the request must also include the toolchain parameter.
- `"tags"`: The tags created for the project.
- `"toolchain"`: The name of the toolchain template file submitted with the project
  request. If this parameter is specified, the request must also include the sourceCode
  parameter.
"""
function create_project(id, name; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "CreateProject",
        Dict{String,Any}("id" => id, "name" => name);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_project(
    id,
    name,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codestar(
        "CreateProject",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("id" => id, "name" => name), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_user_profile(display_name, email_address, user_arn)
    create_user_profile(display_name, email_address, user_arn, params::Dict{String,<:Any})

Creates a profile for a user that includes user preferences, such as the display name and
email address assocciated with the user, in AWS CodeStar. The user profile is not
project-specific. Information in the user profile is displayed wherever the user's
information appears to other users in AWS CodeStar.

# Arguments
- `display_name`: The name that will be displayed as the friendly name for the user in AWS
  CodeStar.
- `email_address`: The email address that will be displayed as part of the user's profile
  in AWS CodeStar.
- `user_arn`: The Amazon Resource Name (ARN) of the user in IAM.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"sshPublicKey"`: The SSH public key associated with the user in AWS CodeStar. If a
  project owner allows the user remote access to project resources, this public key will be
  used along with the user's private key for SSH access.
"""
function create_user_profile(
    displayName, emailAddress, userArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "CreateUserProfile",
        Dict{String,Any}(
            "displayName" => displayName,
            "emailAddress" => emailAddress,
            "userArn" => userArn,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_user_profile(
    displayName,
    emailAddress,
    userArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codestar(
        "CreateUserProfile",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "displayName" => displayName,
                    "emailAddress" => emailAddress,
                    "userArn" => userArn,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deletes a project, including project resources. Does not delete users associated with the
project, but does delete the IAM roles that allowed access to the project.

# Arguments
- `id`: The ID of the project to be deleted in AWS CodeStar.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"clientRequestToken"`: A user- or system-generated token that identifies the entity that
  requested project deletion. This token can be used to repeat the request.
- `"deleteStack"`: Whether to send a delete request for the primary stack in AWS
  CloudFormation originally used to generate the project and its resources. This option will
  delete all AWS resources for the project (except for any buckets in Amazon S3) as well as
  deleting the project itself. Recommended for most use cases.
"""
function delete_project(id; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "DeleteProject",
        Dict{String,Any}("id" => id);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_project(
    id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "DeleteProject",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("id" => id), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deletes a user profile in AWS CodeStar, including all personal preference data associated
with that profile, such as display name and email address. It does not delete the history
of that user, for example the history of commits made by that user.

# Arguments
- `user_arn`: The Amazon Resource Name (ARN) of the user to delete from AWS CodeStar.

"""
function delete_user_profile(userArn; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "DeleteUserProfile",
        Dict{String,Any}("userArn" => userArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_user_profile(
    userArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "DeleteUserProfile",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("userArn" => userArn), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Describes a project and its resources.

# Arguments
- `id`: The ID of the project.

"""
function describe_project(id; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "DescribeProject",
        Dict{String,Any}("id" => id);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_project(
    id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "DescribeProject",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("id" => id), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Describes a user in AWS CodeStar and the user attributes across all projects.

# Arguments
- `user_arn`: The Amazon Resource Name (ARN) of the user.

"""
function describe_user_profile(userArn; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "DescribeUserProfile",
        Dict{String,Any}("userArn" => userArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_user_profile(
    userArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "DescribeUserProfile",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("userArn" => userArn), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    disassociate_team_member(project_id, user_arn)
    disassociate_team_member(project_id, user_arn, params::Dict{String,<:Any})

Removes a user from a project. Removing a user from a project also removes the IAM policies
from that user that allowed access to the project and its resources. Disassociating a team
member does not remove that user's profile from AWS CodeStar. It does not remove the user
from IAM.

# Arguments
- `project_id`: The ID of the AWS CodeStar project from which you want to remove a team
  member.
- `user_arn`: The Amazon Resource Name (ARN) of the IAM user or group whom you want to
  remove from the project.

"""
function disassociate_team_member(
    projectId, userArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "DisassociateTeamMember",
        Dict{String,Any}("projectId" => projectId, "userArn" => userArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function disassociate_team_member(
    projectId,
    userArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codestar(
        "DisassociateTeamMember",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("projectId" => projectId, "userArn" => userArn),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Lists all projects in AWS CodeStar associated with your AWS account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum amount of data that can be contained in a single set of
  results.
- `"nextToken"`: The continuation token to be used to return the next set of results, if
  the results cannot be returned in one response.
"""
function list_projects(; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar("ListProjects"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET)
end
function list_projects(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "ListProjects", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

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

Lists resources associated with a project in AWS CodeStar.

# Arguments
- `project_id`: The ID of the project.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum amount of data that can be contained in a single set of
  results.
- `"nextToken"`: The continuation token for the next set of results, if the results cannot
  be returned in one response.
"""
function list_resources(projectId; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "ListResources",
        Dict{String,Any}("projectId" => projectId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_resources(
    projectId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codestar(
        "ListResources",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("projectId" => projectId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Gets the tags for a project.

# Arguments
- `id`: The ID of the project to get tags for.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: Reserved for future use.
- `"nextToken"`: Reserved for future use.
"""
function list_tags_for_project(id; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "ListTagsForProject",
        Dict{String,Any}("id" => id);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_tags_for_project(
    id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "ListTagsForProject",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("id" => id), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Lists all team members associated with a project.

# Arguments
- `project_id`: The ID of the project for which you want to list team members.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of team members you want returned in a response.
- `"nextToken"`: The continuation token for the next set of results, if the results cannot
  be returned in one response.
"""
function list_team_members(projectId; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "ListTeamMembers",
        Dict{String,Any}("projectId" => projectId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_team_members(
    projectId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codestar(
        "ListTeamMembers",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("projectId" => projectId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Lists all the user profiles configured for your AWS account in AWS CodeStar.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of results to return in a response.
- `"nextToken"`: The continuation token for the next set of results, if the results cannot
  be returned in one response.
"""
function list_user_profiles(; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "ListUserProfiles"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_user_profiles(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "ListUserProfiles", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    tag_project(id, tags)
    tag_project(id, tags, params::Dict{String,<:Any})

Adds tags to a project.

# Arguments
- `id`: The ID of the project you want to add a tag to.
- `tags`: The tags you want to add to the project.

"""
function tag_project(id, tags; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "TagProject",
        Dict{String,Any}("id" => id, "tags" => tags);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function tag_project(
    id,
    tags,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codestar(
        "TagProject",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("id" => id, "tags" => tags), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    untag_project(id, tags)
    untag_project(id, tags, params::Dict{String,<:Any})

Removes tags from a project.

# Arguments
- `id`: The ID of the project to remove tags from.
- `tags`: The tags to remove from the project.

"""
function untag_project(id, tags; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "UntagProject",
        Dict{String,Any}("id" => id, "tags" => tags);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function untag_project(
    id,
    tags,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codestar(
        "UntagProject",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("id" => id, "tags" => tags), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Updates a project in AWS CodeStar.

# Arguments
- `id`: The ID of the project you want to update.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"description"`: The description of the project, if any.
- `"name"`: The name of the project you want to update.
"""
function update_project(id; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "UpdateProject",
        Dict{String,Any}("id" => id);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_project(
    id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "UpdateProject",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("id" => id), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_team_member(project_id, user_arn)
    update_team_member(project_id, user_arn, params::Dict{String,<:Any})

Updates a team member's attributes in an AWS CodeStar project. For example, you can change
a team member's role in the project, or change whether they have remote access to project
resources.

# Arguments
- `project_id`: The ID of the project.
- `user_arn`: The Amazon Resource Name (ARN) of the user for whom you want to change team
  membership attributes.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"projectRole"`: The role assigned to the user in the project. Project roles have
  different levels of access. For more information, see Working with Teams in the AWS
  CodeStar User Guide.
- `"remoteAccessAllowed"`: Whether a team member is allowed to remotely access project
  resources using the SSH public key associated with the user's profile. Even if this is set
  to True, the user must associate a public key with their profile before the user can access
  resources.
"""
function update_team_member(
    projectId, userArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "UpdateTeamMember",
        Dict{String,Any}("projectId" => projectId, "userArn" => userArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_team_member(
    projectId,
    userArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codestar(
        "UpdateTeamMember",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("projectId" => projectId, "userArn" => userArn),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Updates a user's profile in AWS CodeStar. The user profile is not project-specific.
Information in the user profile is displayed wherever the user's information appears to
other users in AWS CodeStar.

# Arguments
- `user_arn`: The name that will be displayed as the friendly name for the user in AWS
  CodeStar.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"displayName"`: The name that is displayed as the friendly name for the user in AWS
  CodeStar.
- `"emailAddress"`: The email address that is displayed as part of the user's profile in
  AWS CodeStar.
- `"sshPublicKey"`: The SSH public key associated with the user in AWS CodeStar. If a
  project owner allows the user remote access to project resources, this public key will be
  used along with the user's private key for SSH access.
"""
function update_user_profile(userArn; aws_config::AbstractAWSConfig=global_aws_config())
    return codestar(
        "UpdateUserProfile",
        Dict{String,Any}("userArn" => userArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_user_profile(
    userArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codestar(
        "UpdateUserProfile",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("userArn" => userArn), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end


text:
# ---
# title: 929. Unique Email Addresses
# id: problem929
# author: Tian Jun
# date: 2020-10-31
# difficulty: Easy
# categories: String
# link: <https://leetcode.com/problems/unique-email-addresses/description/>
# hidden: true
# ---
#
# Every email consists of a local name and a domain name, separated by the @
# sign.
#
# For example, in `alice@leetcode.com`, `alice` is the local name, and
# `leetcode.com` is the domain name.
#
# Besides lowercase letters, these emails may contain `'.'`s or `'+'`s.
#
# If you add periods (`'.'`) between some characters in the **local name** part
# of an email address, mail sent there will be forwarded to the same address
# without dots in the local name.  For example, `"alice.z@leetcode.com"` and
# `"alicez@leetcode.com"` forward to the same email address.  (Note that this
# rule does not apply for domain names.)
#
# If you add a plus (`'+'`) in the **local name** , everything after the first
# plus sign will be  **ignored**. This allows certain emails to be filtered, for
# example `m.y+name@email.com` will be forwarded to `my@email.com`.  (Again,
# this rule does not apply for domain names.)
#
# It is possible to use both of these rules at the same time.
#
# Given a list of `emails`, we send one email to each address in the list.  How
# many different addresses actually receive mails?
#
#
#
# **Example 1:**
#
#
#
#     Input: ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
#     Output: 2
#     Explanation:  "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails
#
#
#
#
# **Note:**
#
#   * `1 <= emails[i].length <= 100`
#   * `1 <= emails.length <= 100`
#   * Each `emails[i]` contains exactly one `'@'` character.
#   * All local and domain names are non-empty.
#   * Local names do not start with a `'+'` character.
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
x = -11:11
y = sin.(x)
x = x[y .> 0]          # Only keep values of x where y=sin x is positive

# Example: Consider the matrix
A = rand(-10:10, 3, 10)

# Compute a boolean array with `true` if the column sums are >=0
pick = sum(A, dims=1) .≥ 0

# Create a new vector with only the columns of A given by the `pick` variable
# Note that since `pick` is a 2D vector (row vector), we use [:] before indexing
B = A[:, pick[:]]


text:
using DescriptorZoo
using Test, LinearAlgebra, BenchmarkTools
using JuLIP, JuLIP.Testing

@testset "DescriptorZoo.jl" begin
    include("exports.jl")
    include("test_acsf.jl")
    include("test_amp.jl")
    include("test_chsf.jl")
    include("test_mbtr.jl")
    include("test_soaplite.jl")
    include("test_dscribe_soap.jl")
    #include("test_dscribe_acsf.jl")
end


text:
module Flux

# Zero Flux Given

using Base: tail
using Zygote, MacroTools, Juno, Reexport, Statistics, Random
using MacroTools: @forward
@reexport using NNlib
using Zygote: Params, @adjoint, gradient, pullback
export gradient

export Chain, Dense, Maxout, RNN, LSTM, GRU, Conv, CrossCor, ConvTranspose, MaxPool, MeanPool,
       DepthwiseConv, Dropout, AlphaDropout, LayerNorm, BatchNorm, InstanceNorm, GroupNorm,
       SkipConnection, params, fmap, cpu, gpu, f32, f64

include("optimise/Optimise.jl")
using .Optimise
using .Optimise: @epochs
export SGD, Descent, ADAM, Momentum, Nesterov, RMSProp,
  ADAGrad, AdaMax, ADADelta, AMSGrad, NADAM,
  ADAMW, RADAM, InvDecay, ExpDecay, WeightDecay

using CUDAapi
if has_cuda()
  try
    using CuArrays
    @eval has_cuarrays() = true
  catch ex
    @warn "CUDA is installed, but CuArrays.jl fails to load" exception=(ex,catch_backtrace())
    @eval has_cuarrays() = false
  end
else
  has_cuarrays() = false
end

include("utils.jl")
include("onehot.jl")
include("functor.jl")

include("layers/stateless.jl")
include("layers/basic.jl")
include("layers/conv.jl")
include("layers/recurrent.jl")
include("layers/normalise.jl")

include("data/Data.jl")

include("deprecations.jl")

if has_cuarrays()
  include("cuda/cuda.jl")
end

end # module


text:
module JMcDM

# Dependencies
import DataFrames: DataFrame, DataFrameRow
import JuMP: @variable, @objective, @constraint
import JuMP: Model, MOI, optimize!, JuMP, objective_value
import GLPK

# for Pretty printing
# of MCDM results
import Base.show

# includes
include("types.jl")
include("utilities.jl")
include("topsis.jl")
include("vikor.jl")
include("electre.jl")
include("moora.jl")
include("dematel.jl")
include("ahp.jl")
include("nds.jl")
include("singlecriterion.jl")
include("game.jl")
include("dataenvelop.jl")
include("grey.jl")
include("saw.jl")
include("aras.jl")
include("wpm.jl")
include("waspas.jl")
include("edas.jl")
include("marcos.jl")
include("mabac.jl")
include("mairca.jl")
include("copras.jl")
include("promethee.jl")
include("cocoso.jl")
include("critic.jl")
include("entropy.jl")
include("codas.jl")

include("summary.jl")

include("mcdm.jl")
include("print.jl")

include("copeland.jl")

# export imported functions
export DataFrame

# export MCDM methods
export MCDMMethod
export ArasMethod
export CocosoMethod
export CodasMethod
export CoprasMethod
export CriticMethod
export EdasMethod
export ElectreMethod
export GreyMethod
export MabacMethod
export MaircaMethod
export MooraMethod
export PrometheeMethod
export SawMethod
export TopsisMethod
export VikorMethod
export WPMMethod
export WaspasMethod
export MarcosMethod

export MCDMSetting

# export MCDM types
export MCDMResult
export TopsisResult
export VikorResult
export ElectreResult
export MooraResult
export AHPConsistencyResult
export AHPResult
export NDSResult
export GreyResult
export SawResult
export ARASResult
export WPMResult
export WASPASResult
export EDASResult
export MARCOSResult
export MABACResult
export MAIRCAResult
export COPRASResult
export PrometheeResult
export CoCoSoResult
export CRITICResult
export EntropyResult
export CODASResult

# export game type
export GameResult

#  export SCDM types
export SCDMResult
export LaplaceResult
export MaximinResult
export MaximaxResult
export MinimaxResult
export MiniminResult
export SavageResult
export HurwiczResult
export MLEResult
export ExpectedRegretResult
export DataEnvelopResult

# export utility functions
export euclidean
export normalize
export colmaxs
export colmins
export unitize
export makeDecisionMatrix
export reverseminmax
export makeminmax

#  export MCDM tools
export topsis
export vikor
export electre
export moora
export dematel
export ahp_RI, ahp_consistency, ahp
export nds
export grey
export saw
export aras
export wpm
export waspas
export edas
export marcos
export mabac
export mairca
export copras
export promethee, prometLinear, prometVShape, prometUsual, prometQuasi, prometLevel
export cocoso
export critic
export entropy
export codas

#  export SCDM tools
export laplace
export maximin
export maximax
export minimax
export minimin
export savage
export hurwicz
export mle
export expectedregret

# export game solver
export game

# export data envelop
export dataenvelop

#  export summary function
export summary
export mcdm

# export Copeland module
import JMcDM.Copeland: copeland
export copeland

end # module

max_stars_repo_name: jbytecode/jMCDM

max_issues_repo_name: jbytecode/jMCDM

max_forks_repo_name: jbytecode/jMCDM


text:
using ApproxFun, SingularIntegralEquations, Test

import SingularIntegralEquations.HypergeometricFunctions: _₂F₁general

@testset "Hypergeometric function ₂F₁(a,b;c;z) against known transcendental cases" begin
    for z in (.9rand(Float64,10),10rand(ComplexF64,10))
        j=1
        for (a,b,c) in ((√2/e,1.3,1.3),(1.2,√3,1.2),
                        (-.4,.4,.5),(-.3,1.3,.5),(.35,.85,.5),
                        (.5,.5,1.5),(1.,1.,1.5),(.5,1.,1.5),(.3,.7,1.5),(.7,1.3,1.5),(.35,.85,1.5),
                        (1.,1.,2.),(3.,1.,2.),(-2.,1.,2.),(-3.,1.,2.),(1.,-4.,2.),
                        (2.,2.,4.),(1.,1.5,2.5))
            normj = 0.0
            for zi in z
                twoFone = _₂F₁(a,b,c,zi)
                aa,bb,cc = big(a),big(b),big(c)
                twoFonegeneral = convert(Complex{Float64},_₂F₁general(aa,bb,cc,big(zi)))
                norm(twoFone/twoFonegeneral-1) > sqrt(eps()) && println("This is ₂F₁($a,$b;$c;zi) - ₂F₁general($a,$b;$c;zi): ",norm(twoFone/twoFonegeneral-1),"   ",twoFone,"   ",twoFonegeneral,"   ",isfinite(twoFone),"   ",isfinite(twoFonegeneral)," this is zi: ",zi)
                normj += Float64(norm(twoFone/twoFonegeneral-1))
            end
            println("This is the cumulative error for Case $j: ",normj)
            j+=1
        end
    end
end


text:
# This file is a part of AstroLib.jl. License is MIT "Expat".
# Copyright (C) 2016 Mosè Giordano.

function _geo2mag(lat::T, long::T, pole_lat::T, pole_long::T) where {T<:AbstractFloat}
    r    = 1 # Distance from planet center.  Value unimportant -- just need a length for
             # conversion to rectangular coordinates
    sin_lat, cos_lat = sincos(deg2rad(lat))
    sin_long, cos_long = sincos(deg2rad(long))
    x    = r * cos_lat * cos_long
    y    = r * cos_lat * sin_long
    z    = r * sin_lat

    # Compute first rotation matrix: rotation around plane of the equator, from
    # the Greenwich meridian to the meridian containing the magnetic dipole
    # pole.
    sin_pole_long, cos_pole_long = sincos(pole_long)
    geolong2maglong = SMatrix{3,3}(cos_pole_long, -sin_pole_long, zero(T),
                                   sin_pole_long,  cos_pole_long, zero(T),
                                   zero(T),              zero(T),  one(T))

    # Second rotation: in the plane of the current meridian from geographic pole
    # to magnetic dipole pole.
    s, c = sincos(T(pi) / 2 - pole_lat)
    tomaglat = SMatrix{3,3}( c,       zero(T),       s,
                             zero(T),  one(T), zero(T),
                            -s,       zero(T),       c)
    out = tomaglat * geolong2maglong * SVector(x, y, z)

    maglat  = rad2deg(atan(out[3], hypot(out[1], out[2])))
    maglong = rad2deg(atan(out[2], out[1]))
    # I don't care about that one...just put it there for completeness' sake
    # magalt  = norm(out) - r
    return maglat, maglong
end

"""
    geo2mag(latitude, longitude[, year]) -> geomagnetic_latitude, geomagnetic_longitude

### Purpose ###

Convert from geographic to geomagnetic coordinates.

### Explanation ###

Converts from geographic (latitude, longitude) to geomagnetic (latitude,
longitude).  Altitude is not involved in this function.

### Arguments ###

* `latitude`: geographic latitude (North), in degrees.
* `longitude`: geographic longitude (East), in degrees.
* `year` (optional numerical argument): the year in which to perform conversion.
  If omitted, defaults to current year.

The coordinates can be passed as arrays of the same length.

### Output ###

The 2-tuple of magnetic (latitude, longitude) coordinates, in degrees.

If geographical coordinates are given as arrays, a 2-tuple of arrays of the same
length is returned.

### Example ###

Kyoto has geographic coordinates 35° 00' 42'' N, 135° 46' 06'' E, find its
geomagnetic coordinates in 2016:

```jldoctest
julia> using AstroLib

julia> geo2mag(ten(35,0,42), ten(135,46,6), 2016)
(36.86579228937769, -60.184060536651614)
```

### Notes ###

This function uses list of North Magnetic Pole positions provided by World
Magnetic Model (https://www.ngdc.noaa.gov/geomag/data/poles/NP.xy).

`mag2geo` converts geomagnetical coordinates to geographic coordinates.

Code of this function is based on IDL Astronomy User's Library.
"""
geo2mag(lat::Real, long::Real, year::Real=Dates.year(Dates.now())) =
    _geo2mag(promote(float(lat), float(long),
                     deg2rad(POLELATLONG[year][1]::AbstractFloat),
                     deg2rad(POLELATLONG[year][2]::AbstractFloat))...)

function geo2mag(lat::AbstractArray{LA}, long::AbstractArray{<:Real},
                 year::Real=Dates.year(Dates.now())) where {LA<:Real}
    @assert length(lat) == length(long)
    typela   = float(LA)
    maglat   = similar(lat, typela)
    maglong  = similar(lat, typela)
    polelat  = deg2rad(POLELATLONG[year][1])
    polelong = deg2rad(POLELATLONG[year][2])
    for i in eachindex(lat)
        maglat[i], maglong[i] =
            _geo2mag(promote(float(lat[i]), float(long[i]),
                             polelat, polelong)...)
    end
    return maglat, maglong
end


text:
module PicoQuant

include("backends.jl")

include("layer3.jl")
include("layer2.jl")
include("layer1.jl")
include("visualise.jl")
include("algorithms.jl")
include("mps.jl")

end # module


text:
using Documenter
using SpatioTemporalTraits

makedocs(;
    modules=[SpatioTemporalTraits],
    format=Documenter.HTML(),
    pages=["index.md"],
    repo="https://github.com/JuliaArrays/SpatioTemporalTraits.jl/blob/{commit}{path}#L{line}",
    sitename="SpatioTemporalTraits.jl",
)

deploydocs(
    repo = "github.com/JuliaArrays/SpatioTemporalTraits.jl.git",
)


text:
using UncertaintyQuantification, Random

Random.seed!(4183);

N = 10
normal = Normal(0, 0.005)

F = [5, 5, 10, 10, 15, 15, 20, 20, 25, 25]./1.02

noisesamples = [F[i]/387 + rand(normal) for i in 1:N]

observations = hcat(F,noisesamples)
Random.seed!()

function likelihood(x)
    rv = 0
    variation = var(observations[:,1]./observations[:,2])
    for i in 1:N
        rv += (observations[i,1]/observations[i,2] - x[1])^2
    end
    return exp(-rv/(2*variation))
 end

prior(x) = 1
priorsample(n) = rand(Uniform(1,1000),(n))

propdist = Normal(0, 1)
propdistsample() = [rand(propdist)]
propdistpdf(x) = pdf(propdist, x[1])

function term(sset, j)
    rv = true
    if j >= 2 rv = false end
    return rv
end

smcsample = smc(likelihood, prior, priorsample, propdistpdf, propdistsample, 5000, term)


text:
function AdaptiveStepsizeIntegrator(arg0::JString, arg1::jdouble, arg2::jdouble, arg3::Vector{jdouble}, arg4::Vector{jdouble})
    return AdaptiveStepsizeIntegrator((JString, jdouble, jdouble, Vector{jdouble}, Vector{jdouble}), arg0, arg1, arg2, arg3, arg4)
end

function AdaptiveStepsizeIntegrator(arg0::JString, arg1::jdouble, arg2::jdouble, arg3::jdouble, arg4::jdouble)
    return AdaptiveStepsizeIntegrator((JString, jdouble, jdouble, jdouble, jdouble), arg0, arg1, arg2, arg3, arg4)
end

function integrate(obj::ODEIntegrator, arg0::ExpandableODE, arg1::ODEState, arg2::jdouble)
    return jcall(obj, "integrate", ODEStateAndDerivative, (ExpandableODE, ODEState, jdouble), arg0, arg1, arg2)
end


text:
function matgen(n)
  tmp = 1.0 / n / n
  [ tmp * (i - j) * (i + j - 2) for i=1:n, j=1:n ]
end

function main()
  n = 100
  if length(ARGS) >= 1
    n = int(ARGS[1])
  end
  t = time()
  n = int(n / 2 * 2)
  a = matgen(n)
  b = matgen(n)
  c = a * b
  v = int(n/2) + 1
  println(c[v, v])
  println(time() - t)
end

main()

max_stars_repo_name: japgolly/kostya-benchmarks

max_issues_repo_name: japgolly/kostya-benchmarks

max_forks_repo_name: japgolly/kostya-benchmarks


text:
# Inspired from `SetProg/test/Test/square.jl`

using LinearAlgebra, Test

using SwitchOnSafety
using Polyhedra
const Sets = SetProg.Sets
using MultivariatePolynomials

function square_test(
    optimizer_constructor, variable::SetProg.AbstractVariable,
    set_test; kws...)
    □ = polyhedron(HalfSpace([1, 0], 1.0) ∩ HalfSpace([-1, 0], 1) ∩ HalfSpace([0, 1], 1) ∩ HalfSpace([0, -1], 1))
    for system in [
        ConstrainedContinuousIdentitySystem(2, □),
        ConstrainedDiscreteIdentitySystem(2, □)]

        set = invariant_set(system, optimizer_constructor, variable; verbose=0, kws...)
        set_test(set)
    end
end

const atol = 1e-4
const rtol = 1e-4

@testset "Homogeneous ellipsoid with $optimizer_constructor" for optimizer_constructor in sdp_factories
    square_test(
        optimizer_constructor, Ellipsoid(symmetric=true, dimension=2),
        ◯ -> begin
            @test ◯ isa Sets.Polar{Float64, Sets.Ellipsoid{Float64}}
            @test Sets.polar(◯).Q ≈ Symmetric([1.0 0.0; 0.0 1.0]) atol=atol rtol=rtol
        end, volume_heuristic = nth_root)
end

@testset "Non-homogeneous ellipsoid with $optimizer_constructor" for optimizer_constructor in sdp_factories
    square_test(
        optimizer_constructor, Ellipsoid(point=SetProg.InteriorPoint([0.0, 0.0])),
        ◯ -> begin
            @test ◯ isa Sets.PerspectiveDual{Float64, Sets.Householder{Float64, Sets.ShiftedEllipsoid{Float64}, Float64}}
            z = Sets.perspective_variable(◯)
            x, y = Sets.space_variables(◯)
            ◯_dual = Sets.perspective_dual(◯)
            @test ◯_dual.p ≈ -z^2 + x^2 + y^2 atol=atol rtol=rtol
            @test Sets._householder(◯_dual.h) ≈ [-1.0 0.0 0.0
                                                  0.0 1.0 0.0
                                                  0.0 0.0 1.0] atol=atol rtol=rtol
            @test ◯_dual.set.Q ≈ Symmetric([1.0 0.0; 0.0 1.0]) atol=atol rtol=rtol
            @test ◯_dual.set.b ≈ [0.0, 0.0] atol=atol rtol=rtol
            @test ◯_dual.set.β ≈ -1.0 atol=atol rtol=rtol
        end,
        volume_heuristic = nth_root)
end

@testset "Non-homogeneous quadratic with $optimizer_constructor" for optimizer_constructor in sdp_factories
    square_test(
        optimizer_constructor,
        PolySet(degree=2, convex=true, point=SetProg.InteriorPoint([0.0, 0.0])),
        ◯ -> begin
            @test ◯ isa Sets.PerspectiveDual{Float64, Sets.Householder{Float64, Sets.ConvexPolynomialSet{Float64,SetProg.Sets.MonoBasis,Float64}, Float64}}
            z = Sets.perspective_variable(◯)
            x, y = Sets.space_variables(◯)
            ◯_dual = Sets.perspective_dual(◯)
            @test ◯_dual.p ≈ -z^2 + x^2 + y^2 atol=atol rtol=rtol
        end,
        volume_heuristic = set -> L1_heuristic(set, [1.0, 1.0]))
end

const quartic_inner_poly = [3.1518541833100864, -0.1617384194869734]
const quartic_inner_obj = 6.447419478140056
const quartic_inner_α = 5.6567546886722795
const quartic_inner_convexity = [12.0, 0.0, quartic_inner_α, 0.0, quartic_inner_poly[1]+2quartic_inner_poly[2],
                                 quartic_inner_α, 8.48516455194103, 0.0, 0.0, 12.0]

@testset "Quartic inner homogeneous with $optimizer_constructor" for optimizer_constructor in sdp_factories
    square_test(
        optimizer_constructor,
        PolySet(symmetric=true, degree=4, dimension=2, convex=true),
        ◯ -> begin
            @test ◯ isa Sets.Polar{Float64, Sets.ConvexPolySet{Float64,SetProg.Sets.MonoBasis,Float64}}
            ◯_polar = Sets.polar(◯)
            @test ◯_polar.degree == 4
            x, y = variables(◯_polar.p)
            @test polynomial(◯_polar.p) ≈ x^4 + quartic_inner_convexity[5]*x^2*y^2 + y^4 atol=atol rtol=rtol
            convexity_proof = Sets.convexity_proof(◯)
            @test convexity_proof.n == 4
            @test convexity_proof.Q ≈ quartic_inner_convexity atol=atol rtol=rtol
        end,
        volume_heuristic = nth_root)
end


text:
using Nettle

testdict = Dict("abc" => "a9993e364706816aba3e25717850c26c9cd0d89d",
                "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" =>
                    "84983e441c3bd26ebaae4aa1f95129e5e54670f1",
                "a" ^ 1_000_000 => "34aa973cd4c4daa4f61eeb2bdbad27316534016f",)

for (text, expect) in testdict
    digest = hexdigest("sha1", text)
    if length(text) > 50 text = text[1:50] * "..." end
    println("# $text\n -> digest: $digest\n -> expect: $expect")
end


text:
using Test, ANSIColoredPrinters

@testset "colors" begin
    include("colors.jl")
end
@testset "PlainTextPrinter" begin
    include("plain.jl")
end
@testset "HTMLPrinter" begin
    include("html.jl")
end


text:
"""
    StackSet([itr])

Construct a `StackSet`, an `AbstractSet{Int}` which can only contains numbers
N:N+63. A `Stackset` is stored in memory as a `DigitSet` and an integer offset,
and is immutable

See also: [`StackSet`](@ref)
"""
struct StackSet <: AbstractStackSet
    set::DigitSet
    offset::Int # lowest value in set, 0 if set is empty

    StackSet(set::DigitSet, offset::Int, ::Unsafe) = new(set, offset)
end

StackSet(set::DigitSet, offset::Int) = normalized(StackSet(set, offset, unsafe))

function StackSet(set::DigitSet)
    offset = ifelse(isempty(set), 0, minimum(set, unsafe))
    return StackSet(DigitSet(set.x >>> (offset & 63)), offset, unsafe)
end

function DigitSet(set::StackSet)
    if (minimum(set, unsafe) < 0) | (maximum(set, unsafe) > (Sys.WORD_SIZE-1))
        throw_DigitSet_digit_err()
    end
    return DigitSet(set.set.x << (set.offset & 63))
end

Base.promote_rule(::Type{<:AbstractStackSet}, ::Type{<:AbstractStackSet}) = StackSet

function Base.:(==)(x::AbstractStackSet, y::AbstractStackSet)
    x_, y_ = promote(x, y)
    return x_ == y_
end

function Base.hash(x::StackSet, h::UInt)
    base = 0x30a9fa66b925af5a % UInt
    h = hash(base, h)
    h = hash(x.set, h)
    return hash(x.offset, h)
end

StackSet() = StackSet(DigitSet(), 0, unsafe)
Base.empty(x::StackSet) = StackSet()
Base.isempty(x::StackSet) = isempty(x.set)
Base.length(x::StackSet) = length(x.set)

function StackSet(itr)
    d = StackSet()
    for i in itr
        d = push(d, convert(Int, i))
    end
    d
end

@noinline function throw_StackSet_range_err()
    throw(ArgumentError("DigitSet can not contain values differing " *
                        "by more than $(Sys.WORD_SIZE-1)"))
end

function Base.iterate(s::StackSet, i::UInt=s.set.x)
    it = iterate(s.set, i)
    it === nothing && return nothing
    return it[1]+s.offset, it[2]
end

function new_offset(s::StackSet, x::Int)
    # Returns new offset for stackset when pushing x in, and the shift.
    # if s is empty, shift result is arbitrary.
    newoffset = min(s.offset, x)
    return ifelse(isempty(s), x, newoffset), (s.offset - newoffset)
end

function push(s::StackSet, x::Int, ::Unsafe)
    newoffset, lshift = new_offset(s, x)
    newset = push(DigitSet(s.set.x << (lshift & 63)), x-newoffset, unsafe)
    return StackSet(newset, newoffset, unsafe)
end

function push(s::StackSet, x::Int)
    newoffset, lshift = new_offset(s, x)
    !isempty(s) & (leading_zeros(s.set.x) < lshift) && throw_StackSet_range_err()
    newset = push(DigitSet(s.set.x << (lshift & 63)), x-newoffset)
    return StackSet(newset, newoffset, unsafe)
end

Base.maximum(x::StackSet, ::Unsafe) = maximum(x.set, unsafe) + x.offset
Base.maximum(x::StackSet) = maximum(x.set) + x.offset
Base.minimum(x::StackSet, ::Unsafe) = minimum(x.set, unsafe) + x.offset
Base.minimum(x::StackSet) = minimum(x.set) + x.offset
Base.in(x::Int, s::StackSet) = in(x-s.offset, s.set)

function Base.filter(pred, s::StackSet)
    r = DigitSet()
    for i in s.set
        pred(i+s.offset) && (r = push(r, i, unsafe))
    end
    normalized(StackSet(r, s.offset, unsafe))
end

delete(s::StackSet, v::Int) = StackSet(delete(s.set, v-s.offset), s.offset)
pop(s::StackSet, v::Int) = in(v, s) ? delete(s, v) : throw(KeyError(v))

function Base.intersect(x::StackSet, y::StackSet)
    new_x_set = trunc_offset_stackset(x, y)
    normalized(StackSet(intersect(new_x_set, y.set), y.offset, unsafe))
end

function Base.setdiff(x::StackSet, y::StackSet)
    new_y_set = trunc_offset_stackset(y, x)
    normalized(StackSet(setdiff(x.set, new_y_set), x.offset, unsafe))
end

# This shifts the from bits to match the to bits, truncating if necessary
function trunc_offset_stackset(from::StackSet, to::StackSet)
    return DigitSet(from.set.x >>> (to.offset - from.offset))
end

function normalized(s::StackSet)
    rshift = trailing_zeros(s.set.x)
    offset = ifelse(isempty(s), 0, s.offset + rshift)
    return StackSet(DigitSet(s.set.x >>> (rshift & 63)), offset, unsafe)
end

# Returns DigitSets both with the lowest set's offset
# throws an error if any information would be lost by bitshifts.
# It is assumed none of the sets are empty
@inline function offset_to_lower(smaller::StackSet, bigger::StackSet)
    lshift = unsigned(bigger.offset - smaller.offset)
    unsigned(leading_zeros(bigger.set.x)) < lshift && throw_StackSet_range_err()
    shifted = bigger.set.x << (lshift & 63)
    return smaller.set, DigitSet(shifted)
end

function Base.union(x::StackSet, y::StackSet)
    isempty(x) && return y
    isempty(y) && return x
    (smaller, bigger) = ifelse(x.offset < y.offset, (x, y), (y, x))
    sm_set, bg_set = offset_to_lower(smaller, bigger)
    return StackSet(union(sm_set, bg_set), smaller.offset, unsafe)
end

function Base.symdiff(x::StackSet, y::StackSet)
    isempty(x) && return y
    isempty(y) && return x
    (smaller, bigger) = ifelse(x.offset < y.offset, (x, y), (y, x))
    sm_set, bg_set = offset_to_lower(smaller, bigger)

    # Unlike for union, we need to normalize here, so no unsafe construction
    return StackSet(symdiff(sm_set, bg_set), smaller.offset)
end


text:
"""
    VectorizeBridge{T, S}

Transforms a constrained variable in `scalar_set_type(S, T)` where
`S <: VectorLinearSet` into a constrained vector of one variable in `S`. For
instance, `VectorizeBridge{Float64, MOI.Nonnegatives}` transforms a constrained
variable in `MOI.GreaterThan{Float64}` into a constrained vector of one
variable in `MOI.Nonnegatives`.
"""
mutable struct VectorizeBridge{T,S} <: AbstractBridge
    variable::MOI.VariableIndex
    vector_constraint::MOI.ConstraintIndex{MOI.VectorOfVariables,S}
    set_constant::T # constant in scalar set
end
function bridge_constrained_variable(
    ::Type{VectorizeBridge{T,S}},
    model::MOI.ModelLike,
    set::MOIU.ScalarLinearSet{T},
) where {T,S}
    set_constant = MOI.constant(set)
    variables, vector_constraint = MOI.add_constrained_variables(model, S(1))
    return VectorizeBridge{T,S}(variables[1], vector_constraint, set_constant)
end

function supports_constrained_variable(
    ::Type{VectorizeBridge{T}},
    ::Type{<:MOIU.ScalarLinearSet{T}},
) where {T}
    return true
end
function MOIB.added_constrained_variable_types(
    ::Type{VectorizeBridge{T,S}},
) where {T,S}
    return [(S,)]
end
function MOIB.added_constraint_types(::Type{<:VectorizeBridge})
    return Tuple{DataType,DataType}[]
end
function concrete_bridge_type(
    ::Type{<:VectorizeBridge{T}},
    S::Type{<:MOIU.ScalarLinearSet{T}},
) where {T}
    return VectorizeBridge{T,MOIU.vector_set_type(S)}
end

# Attributes, Bridge acting as a model
function MOI.get(bridge::VectorizeBridge, ::MOI.NumberOfVariables)
    return 1
end
function MOI.get(bridge::VectorizeBridge, ::MOI.ListOfVariableIndices)
    return [bridge.variable]
end
function MOI.get(
    ::VectorizeBridge{T,S},
    ::MOI.NumberOfConstraints{MOI.VectorOfVariables,S},
) where {T,S}
    return 1
end
function MOI.get(
    bridge::VectorizeBridge{T,S},
    ::MOI.ListOfConstraintIndices{MOI.VectorOfVariables,S},
) where {T,S}
    return [bridge.vector_constraint]
end

# References
function MOI.delete(model::MOI.ModelLike, bridge::VectorizeBridge)
    return MOI.delete(model, bridge.variable)
end

# Attributes, Bridge acting as a constraint

function MOI.get(
    model::MOI.ModelLike,
    ::MOI.ConstraintSet,
    bridge::VectorizeBridge{T,S},
) where {T,S}
    return MOIU.scalar_set_type(S, T)(bridge.set_constant)
end

function MOI.set(
    model::MOI.ModelLike,
    attr::MOI.ConstraintSet,
    bridge::VectorizeBridge,
    new_set::MOIU.ScalarLinearSet,
)
    # This would require modifing any constraint which uses the bridged
    # variable.
    return throw(MOI.SetAttributeNotAllowed(
        attr,
        "The variable `$(bridge.variable)` is bridged by the `VectorizeBridge`.",
    ))
end

function MOI.get(
    model::MOI.ModelLike,
    attr::MOI.ConstraintPrimal,
    bridge::VectorizeBridge,
)
    x = MOI.get(model, attr, bridge.vector_constraint)
    @assert length(x) == 1
    y = x[1]
    if !MOIU.is_ray(MOI.get(model, MOI.PrimalStatus(attr.N)))
        # If it is an infeasibility certificate, it is a ray and satisfies the
        # homogenized problem, see https://github.com/jump-dev/MathOptInterface.jl/issues/433
        # Otherwise, we need to add the set constant since the ConstraintPrimal
        # is defined as the value of the function and the set_constant was
        # removed from the original function
        y += bridge.set_constant
    end
    return y
end
function MOI.get(
    model::MOI.ModelLike,
    attr::MOI.ConstraintDual,
    bridge::VectorizeBridge,
)
    x = MOI.get(model, attr, bridge.vector_constraint)
    @assert length(x) == 1
    return x[1]
end

function MOI.get(
    model::MOI.ModelLike,
    attr::Union{MOI.VariablePrimal,MOI.VariablePrimalStart},
    bridge::VectorizeBridge,
)
    value = MOI.get(model, attr, bridge.variable)
    if !(
        attr isa MOI.VariablePrimal &&
        MOIU.is_ray(MOI.get(model, MOI.PrimalStatus(attr.N)))
    )
        value += bridge.set_constant
    end
    return value
end
function MOI.supports(
    model::MOI.ModelLike,
    attr::MOI.VariablePrimalStart,
    ::Type{<:VectorizeBridge},
)
    return MOI.supports(model, attr, MOI.VariableIndex)
end
function MOI.set(
    model::MOI.ModelLike,
    attr::MOI.VariablePrimalStart,
    bridge::VectorizeBridge,
    value,
)
    return MOI.set(model, attr, bridge.variable, value - bridge.set_constant)
end

function MOIB.bridged_function(bridge::VectorizeBridge{T}) where {T}
    func = MOI.SingleVariable(bridge.variable)
    return MOIU.operate(+, T, func, bridge.set_constant)
end
function unbridged_map(
    bridge::VectorizeBridge{T},
    vi::MOI.VariableIndex,
) where {T}
    func = MOIU.operate(-, T, MOI.SingleVariable(vi), bridge.set_constant)
    return (bridge.variable => func,)
end


text:
using Test, Random, LinearAlgebra, LuxurySparse

using Yao
using YaoArrayRegister: invorder
using YaoExtensions
using FFTW

@testset "QFT" begin
    num_bit = 5
    fftblock = QFTCircuit(num_bit)
    ifftblock = fftblock'
    reg = rand_state(num_bit)
    rv = copy(statevec(reg))

    @test Matrix(mat(chain(3, QFTCircuit(3) |> adjoint, QFTCircuit(3)))) ≈ IMatrix(1<<3)

    # test ifft
    reg1 = apply!(copy(reg), ifftblock)

    # permute lines (Manually)
    kv = fft(statevec(reg))/sqrt(length(rv))
    @test statevec(reg1) ≈ invorder(kv)

    # test fft
    reg2 = apply!(invorder!(copy(reg)), fftblock)
    kv = ifft(rv) * sqrt(length(rv))
    @test statevec(reg2) ≈ kv
end

@testset "QFTBlock" begin
    num_bit = 5
    qft = QFTCircuit(num_bit)
    iqft = adjoint(qft)
    qftblock = QFTBlock{num_bit}()
    iqftblock = QFTBlock{num_bit}() |> adjoint
    @test openbox(qftblock) == qft
    @test openbox(iqftblock) == iqft
    reg = rand_state(num_bit)

    @test Matrix(mat(chain(3, QFTBlock{3}() |> adjoint, QFTBlock{3}()))) ≈ IMatrix(1<<3)

    # permute lines (Manually)
    @test apply!(copy(reg), iqft) ≈ apply!(copy(reg), QFTBlock{num_bit}() |> adjoint)

    # test fft
    @test apply!(copy(reg), qft) ≈ apply!(copy(reg), qftblock)

    # regression test for nactive
    @test apply!(focus!(copy(reg), 1:3), QFTBlock{3}()) |> isnormalized
end


text:
include("../src/util.jl")
include("../src/LUMND.jl")

using .LUMND

d = 2
A = Ad(5,d) # n^d laplacian
N = size(A,1)
leaf = 5
lvl = 3 #Int64(ceil(log(N/leaf)/log(2)))
b = rand(N)
(subseps, hrch, dofs) = LUMND.mnd(A, lvl)
# @time tree = LUMND.factorize(A, lvl)
# @time x = LUMND.solve(tree, b)
# @time xref = A\b
# @show norm(A*x-b)


text:
using Distributed
using SeisIO, JLD2
# @everywhere include("./sac2jld2.jl")


text:
"""
normalized water saturation
"""
function sws(sw::Real, sor::Real, swc::Real)
  if sw>swc && sw<1-sor
    res=(sw-swc)/(1-sor-swc)
  elseif sw>=1-sor
    res=1.0
  elseif sw<=swc
    res=0.0
  end
  return res
end

"""
Oil relative permeability functions for oil-water system
"""
function kro(sw::Real, kro0::Real, sor::Real, swc::Real, no::Real)
  if swc<=sw<=1-sor
    res=kro0*((1-sw-sor)/(1-sor-swc))^no
  elseif 0.0<sw<swc
    res=1+(kro0-1)/swc*sw
  elseif sw>1-sor
    res=0.0
  elseif sw<=0.0
    res=1.0
  end
  return res
end

function dkrodsw(sw::Real, kro0::Real, sor::Real, swc::Real, no::Real)
  if swc<=sw<=1-sor
    res=-no*kro0/(1-sor-swc)*((1-sw-sor)/(1-sor-swc))^(no-1)
  elseif 0.0<sw<swc
    res=(kro0-1)/swc
  elseif sw>1-sor || sw<=0.0
    res=0.0
  end
  return res
end

"""
water rel-perm for oil-water system
"""
function krw(sw::Real, krw0::Real, sor::Real, swc::Real, nw::Real)
  if swc<=sw<=1-sor
    res=krw0*((sw-swc)/(1-sor-swc))^nw
  elseif 1-sor<sw<1.0
    res=-(1-krw0)/sor*(1.0-sw)+1.0
  elseif sw<swc
    res=0.0
  elseif sw>=1.0
    res=1.0
  end
  return res
end

function dkrwdsw(sw::Real, krw0::Real, sor::Real, swc::Real, nw::Real)
  if swc<=sw<=1-sor
    res=nw*krw0/(1-sor-swc)*((sw-swc)/(1-sor-swc))^(nw-1)
  elseif 1-sor<sw<1.0
    res=(1-krw0)/sor
  elseif sw<swc || sw>=1.0
    res=0.0
  end
  return res
end

"""
capillary pressure curve for drainage
"""
function pc_drain(sw::Real, pce::Real, swc::Real; labda::Real=2.4)
  pc0=1.0e7
  sw0=swc+(1-labda*log(pc0/pce)+sqrt((-1+labda*log(pc0/pce))^2+4*swc/(1-swc)))/2*(1-swc)
  if sw>sw0
    res=pce*((sw-swc)/(1-swc))^(-1.0/labda)
  elseif 0.0<=sw<=sw0
    pcs=pce*((sw0-swc)/(1-swc))^(-1.0/labda)
    res=exp((log(pcs)-log(pc0))/sw0*(sw-sw0)+log(pcs))
  elseif sw<0
    res=pc0
  else
    res=0.0
  end
end

function dpc_drain(sw::Real, pce::Real, swc::Real; labda::Real=2.4)
  pc0=1.0e7
  sw0=swc+(1-labda*log(pc0/pce)+sqrt((-1+labda*log(pc0/pce))^2+4*swc/(1-swc)))/2*(1-swc)
  if sw>sw0
    res=-1.0/((1-swc)*labda)*pce*((sw-swc)/(1-swc))^(-1.0/labda-1)
  elseif 0.0<=sw<=sw0
    res=-1.0/((1-swc)*labda)*pce*((sw0-swc)/(1-swc))^(-1.0/labda-1)
  else
    res=0.0
  end
end

function pc_imb(sw::Real, pce::Real, swc::Real, sor::Real;
  teta::Real=0.785, labda::Real=2.4, b::Real=0.6)
  pc1=pc_drain(sw, pce, swc, labda=labda)
  pc2=pc_drain(1-sw, pce, sor, labda=labda)
  return (0.5*(1+cos(teta)))^b*pc1-(0.5*(1-cos(teta)))^b*pc2
end

function dpc_imb(sw::Real, pce::Real, swc::Real, sor::Real; teta::Real=0.785, labda::Real=2.4, b::Real=0.6)
  dpc1=dpc_drain(sw, pce, swc, labda=labda)
  dpc2=dpc_drain(1-sw, pce, sor, labda=labda)
  return (0.5*(1+cos(teta)))^b*dpc1+(0.5*(1-cos(teta)))^b*dpc2
end

# all rel-perm functions for array Inputs -------------------------------------
function sws(sw::Array{Float64}, sor::Array{Float64}, swc::Array{Float64})
  res=zeros(size(sw))
  for i in eachindex(sw)
    res[i]=sws(sw[i], sor[i], swc[i])
  end
  return res
end

function kro(sw::Array{Float64}, kro0::Array{Float64}, sor::Array{Float64}, swc::Array{Float64}, no::Array{Float64})
  res=zeros(size(sw))
  for i in eachindex(sw)
    res[i]=kro(sw[i], kro0[i], sor[i], swc[i], no[i])
  end
  return res
end

function dkrodsw(sw::Array{Float64}, kro0::Array{Float64}, sor::Array{Float64}, swc::Array{Float64}, no::Array{Float64})
  res=zeros(size(sw))
  for i in eachindex(sw)
    res[i]=dkrodsw(sw[i], kro0[i], sor[i], swc[i], no[i])
  end
  return res
end

function krw(sw::Array{Float64}, krw0::Array{Float64}, sor::Array{Float64}, swc::Array{Float64}, nw::Array{Float64})
  res=zeros(size(sw))
  for i in eachindex(sw)
    res[i]=krw(sw[i], krw0[i], sor[i], swc[i], nw[i])
  end
  return res
end

function dkrwdsw(sw::Array{Float64}, krw0::Array{Float64}, sor::Array{Float64}, swc::Array{Float64}, nw::Array{Float64})
  res=zeros(size(sw))
  for i in eachindex(sw)
    res[i]=dkrwdsw(sw[i], krw0[i], sor[i], swc[i], nw[i])
  end
  return res
end

function pc_drain(sw::Array{Float64}, pce::Array{Float64}, swc::Array{Float64}; labda::Real=2.4)
  res=zeros(size(sw))
  for i in eachindex(sw)
    res[i]=pc_drain(sw[i], pce[i], swc[i], labda=labda)
  end
  return res
end

function dpc_drain(sw::Array{Float64}, pce::Array{Float64}, swc::Array{Float64}; labda::Real=2.4)
  res=zeros(size(sw))
  for i in eachindex(sw)
    res[i]=dpc_drain(sw[i], pce[i], swc[i], labda=labda)
  end
  return res
end

function pc_imb(sw::Array{Float64}, pce::Array{Float64}, swc::Array{Float64}, sor::Array{Float64},
  teta::Array{Float64}; labda::Real=2.4, b::Real=0.6)
  res=zeros(size(sw))
  for i in eachindex(sw)
    res[i]=pc_imb(sw[i], pce[i], swc[i], sor[i], teta=teta[i], labda=labda, b=b)
  end
  return res
end

function dpc_imb(sw::Array{Float64}, pce::Array{Float64}, swc::Array{Float64}, sor::Array{Float64},
  teta::Array{Float64}; labda::Real=2.4, b::Real=0.6)
  res=zeros(size(sw))
  for i in eachindex(sw)
    res[i]=dpc_imb(sw[i], pce[i], swc[i], sor[i], teta=teta[i], labda=labda, b=b)
  end
  return res
end

# sws=@(sw, sor, swc)((sw>swc).*(sw<1-sor).*(sw-swc)./(1-sor-swc)+(sw>=1-sor))
# kro=@(sw, kro0, sor, swc)((sw>=swc).*kro0.*(1-sws(sw, sor, swc)).^no+(sw<swc).*(1+(kro0-1)./swc.*sw))
# krw=@(sw, krw0, sor, swc)((sw<=1-sor).*krw0.*sws(sw, sor, swc).^nw+(sw>1-sor).*(-(1-krw0)./sor.*(1.0-sw)+1.0))
# dkrwdsw=@(sw, krw0, sor, swc)((sw<=1-sor).*nw.*krw0.*(1./(1-sor-swc)).*sws(sw, sor, swc).^(nw-1)+(sw>1-sor).*((1-krw0)./sor))
# dkrodsw=@(sw, kro0, sor, swc)((sw>=swc).*(-kro0.*no.*(1-sws(sw, sor, swc)).^(no-1))./(-swc-sor+1)+(sw<swc).*((kro0-1)./swc))

max_stars_repo_name: simulkade/peteng

max_issues_repo_name: simulkade/peteng

max_forks_repo_name: simulkade/peteng


text:
QPSolver = Union{MPB.AbstractMathProgSolver, Function}
get_solver(subsolver::MPB.AbstractMathProgSolver) = subsolver
get_solver(generator::Function)::MPB.AbstractMathProgSolver = generator()

mutable struct LQSolver{M <: MPB.AbstractLinearQuadraticModel, S <: MPB.AbstractMathProgSolver}
    lqmodel::M
    optimsolver::S

    function LQSolver(model::JuMP.Model, optimsolver::MPB.AbstractMathProgSolver)
        lqmodel = MPB.LinearQuadraticModel(optimsolver)
        solver = new{typeof(lqmodel), typeof(optimsolver)}(lqmodel, optimsolver)
        MPB.loadproblem!(solver.lqmodel, loadLP(model)...)
        MPB.setvartype!(lqmodel, model.colCat)
        return solver
    end
end

(solver::LQSolver)() = solver(rand(MPB.numvar(solver.lqmodel)))
function (solver::LQSolver)(x₀::AbstractVector)
    if applicable(MPB.setwarmstart!, solver.lqmodel, x₀)
        try
            MPB.setwarmstart!(solver.lqmodel, x₀)
        catch
            @warn "Could not set warm start for some reason"
        end
    end
    MPB.optimize!(solver.lqmodel)
    optimstatus = MPB.status(solver.lqmodel)
    !(optimstatus ∈ [:Optimal,:Infeasible,:Unbounded]) && error("LP could not be solved, returned status: ", optimstatus)
    return nothing
end

function getsolution(solver::LQSolver)
    n = MPB.numvar(solver.lqmodel)
    optimstatus = MPB.status(solver.lqmodel)
    if optimstatus == :Optimal
        return MPB.getsolution(solver.lqmodel)
    else
        @warn "LP was not solved to optimality, returned status: $optimstatus"
        return fill(NaN, n)
    end
end

function getobjval(solver::LQSolver)
    optimstatus = MPB.status(solver.lqmodel)
    if optimstatus == :Optimal
        return MPB.getobjval(solver.lqmodel)
    elseif optimstatus == :Infeasible
        return Inf
    elseif optimstatus == :Unbounded
        return -Inf
    else
        @warn "LP could not be solved, returned status: $optimstatus"
        return NaN
    end
end

function getredcosts(solver::LQSolver)
    cols = MPB.numvar(solver.lqmodel)
    optimstatus = MPB.status(solver.lqmodel)
    if optimstatus == :Optimal
        return try
            MPB.getreducedcosts(solver.lqmodel)[1:cols]
        catch
            fill(NaN, cols)
        end
    else
        @warn "LP was not solved to optimality. Return status: $optimstatus"
        return fill(NaN, cols)
    end
end

function getduals(solver::LQSolver)
    rows = MPB.numconstr(solver.lqmodel)
    optimstatus = MPB.status(solver.lqmodel)
    if optimstatus == :Optimal
        return try
            MPB.getconstrduals(solver.lqmodel)[1:rows]
        catch
            fill(NaN, rows)
        end
    elseif optimstatus ==:Infeasible
        return try
            MPB.getinfeasibilityray(solver.lqmodel)[1:rows]
        catch
            fill(NaN, rows)
        end
    else
        @warn "LP was not solved to optimality, and the model was not infeasible. Return status: $optimstatus"
        return fill(NaN, rows)
    end
end

status(solver::LQSolver) = MPB.status(solver.lqmodel)

function feasibility_problem!(solver::LQSolver)
    MPB.setobj!(solver.lqmodel, zeros(MPB.numvar(solver.lqmodel)))
    for i = 1:MPB.numconstr(solver.lqmodel)
        MPB.addvar!(solver.lqmodel, [i], [1.0], 0.0, Inf, 1.0)
        MPB.addvar!(solver.lqmodel, [i], [-1.0], 0.0, Inf, 1.0)
    end
end

function loadLP(m::JuMP.Model)
    l = m.colLower
    u = m.colUpper
    # Build objective
    # ==============================
    c = JuMP.prepAffObjective(m)
    c *= m.objSense == :Min ? 1 : -1
    # Build constraints
    # ==============================
    # Non-zero row indices
    I = Vector{Int}()
    # Non-zero column indices
    J = Vector{Int}()
    # Non-zero values
    V = Vector{Float64}()
    # Lower constraint bound
    lb = zeros(Float64,length(m.linconstr))
    # Upper constraint bound
    ub = zeros(Float64,length(m.linconstr))
    # Linear constraints
    for (i, constr) in enumerate(m.linconstr)
        coeffs = constr.terms.coeffs
        vars = constr.terms.vars
        @inbounds for (j,var) = enumerate(vars)
            if var.m == m
                push!(I, i)
                push!(J, var.col)
                push!(V, coeffs[j])
            end
        end
        lb[i] = constr.lb
        ub[i] = constr.ub
    end
    A = sparse(I, J, V, length(m.linconstr), m.numCols)
    return A,l,u,c,lb,ub,:Min
end