text:
function drawCurve(aMatrix, aParameterVector)

    n = length(aParameterVector)
    x = zeros(n, length(aMatrix[1,:]))
    for i = 1:n
	param = aParameterVector[i]
	aPoint, Diagonal, Last = decasteljau(aMatrix, param)
	x[i,:] = aPoint
    end

    x
end

function writeArrayForGnuplot(anArray, aFilename)
    writedlm(aFilename, anArray, '\t')
    anArray
end

function parametricCoordinates(functionsVector, pointsNumber)

    parameterVector = linspace(0, 1, pointsNumber)

    numberOfCoordinates = length(functionsVector)

    coordinates = zeros(pointsNumber, numberOfCoordinates)

    for i = 1:pointsNumber
	t = parameterVector[i]

	coord = zeros(numberOfCoordinates)'

	for j = 1:numberOfCoordinates
	    func = functionsVector[j]
	    coord[j] = func(t)
	end

	coordinates[i,:] = coord
    end

    coordinates

end

function decasteljau(controlPointsMatrix, t)
    n = length(controlPointsMatrix[:,1])
    Q = copy(controlPointsMatrix)

    Diagonal = copy(controlPointsMatrix)
    Last = copy(controlPointsMatrix)

    Diagonal[1,:] = Q[1,:]
    Last[1,:] = Q[n,:]

    for k = 1:n
	for i = 1:n-k
	    Q_i = Q[i,:]
	    Q_isucc = Q[i+1,:]
	    Q[i,:] = (1 - t)*Q_i + t*Q_isucc
	end

	if k < n
	    Diagonal[k+1,:] = Q[1,:]
	    Last[k+1,:] = Q[n-k,:]
	end
    end

    Q[1,:], Diagonal, Last
end

function increaseDegree(originalControlPoints)
    columns = length(originalControlPoints[1,:])
    sandbox = [
	       zeros(columns)';
	       copy(originalControlPoints);
	       zeros(columns)';
	       ]

    increasing = [
                  copy(originalControlPoints);
		  zeros(columns)'
	          ]

    n = length(originalControlPoints[:,1])

    for i=1:n+1
	ratio = (i-1)/(n)
	increasing[i,:] = ratio*sandbox[i,:] + (1 - ratio)*sandbox[i+1,:]
    end

    increasing
end

function junction_right(controlPoints, h_i, h_succ_i)

    lastControlPoint = controlPoints[end,:]
    lastButOneControlPoint = controlPoints[end - 1,:]
    lastButTwoControlPoint = controlPoints[end-2,:]

    intervalLengthSum = h_i + h_succ_i

    # in order to get continuity of degree zero
    continuityPoint = lastControlPoint

    # in order to get continuity of degree one
    tangentPoint = (intervalLengthSum*lastControlPoint - h_succ_i * lastButOneControlPoint) / h_i

    # in order to get continuity of degree two
    obsculatorPoint = tangentPoint - lastButOneControlPoint -
    (h_succ_i / h_i) * (lastButOneControlPoint - lastButTwoControlPoint) +
    (h_i / h_succ_i) * tangentPoint

    obsculatorPoint = (h_succ_i / h_i) * obsculatorPoint

    a_succ_i = tangentPoint + (h_i / h_succ_i) * (tangentPoint - obsculatorPoint)

    continuityPoint, tangentPoint, obsculatorPoint, a_succ_i
end

function junction_left(controlPoints, h_i, h_succ_i)

    firstControlPoint = controlPoints[1,:]
    secondControlPoint = controlPoints[2,:]
    thirdControlPoint = controlPoints[3,:]

    intervalLengthSum = h_i + h_succ_i

    # in order to get continuity of degree zero
    continuityPoint = firstControlPoint

    # in order to get continuity of degree one
    tangentPoint = (firstControlPoint - (h_i/ intervalLengthSum)*secondControlPoint) *
    (intervalLengthSum / h_succ_i)

    # in order to get continuity of degree two
    obsculatorPoint = tangentPoint *(1 + (h_succ_i / h_i)) - secondControlPoint -
    (h_i / h_succ_i) * (secondControlPoint - thirdControlPoint)

    obsculatorPoint = (h_i / h_succ_i) * obsculatorPoint

    a_i = tangentPoint + (h_succ_i / h_i) * (tangentPoint - obsculatorPoint)

    continuityPoint, tangentPoint, obsculatorPoint, a_i
end

function difference(controlPoints)
    n = length(controlPoints[:,1])
    derivativePoints = zeros(n-1, length(controlPoints[1,:]))

    for i=1:n-1
        derivativePoints[i,:] = controlPoints[i+1,:] - controlPoints[i,:]
    end

    derivativePoints
end

function derivative(differencePoints, param)
    n = length(differencePoints[:,1])
    value = zeros( length(differencePoints[1,:]))'
    B = i -> binomial(n, i) * (param^i) * ((1 - param)^(n - i))
    for i=1:n
        value = value + differencePoints[i,:]*B(i)
    end
    value * (n+1)
end

function polar(controlPoints, param, respect_to)

    n = length(controlPoints[:,1]) -1

    polarpoint = zeros(length(controlPoints[1,:]))'

    B = i -> binomial(n-1, i) * (param^i) * ((1 - param)^(n -1 - i))

    for i=1:n
        polarpoint += ((1-respect_to)*controlPoints[i,:] + respect_to*controlPoints[i+1,:])*B(i-1)
    end

    polarpoint
end

max_stars_repo_name: massimo-nocentini/cagd

max_issues_repo_name: massimo-nocentini/cagd

max_forks_repo_name: massimo-nocentini/cagd


text:
#######################################################################################
#                                     Docstrings                                      #
#######################################################################################
"""
    integrator(ds::DynamicalSystem [, u0]; diffeq...) -> integ
Return an integrator object that can be used to evolve a system interactively
using `step!(integ [, Δt])`. Optionally specify an initial state `u0`.

The state of this integrator is a vector.

* `diffeq...` are keyword arguments propagated into `init` of DifferentialEquations.jl.
  See [`trajectory`](@ref) for examples. Only valid for continuous systems.
"""
function integrator end

"""
    get_state(ds::DynamicalSystem)
Return the state of `ds`.

    get_state(integ [, i::Int = 1])
Return the state of the integrator, in the sense of the state of the dynamical system.

If the integrator is a [`parallel_integrator`](@ref), passing `i` will return
the `i`-th state. The function also correctly returns the true state of the system
for tangent integrators.
"""
get_state(integ) = integ.u

"""
    set_state!(integ, u [, i::Int = 1])
Set the state of the integrator to `u`, in the sense of the state of the
dynamical system. Works for any integrator (normal, tangent, parallel).

For parallel integrator, you can choose which state to set (using `i`).

Automatically does `u_modified!(integ, true)`.
"""
set_state!(integ, u) = (integ.u = u; u_modified!(integ, true))

"""
    tangent_integrator(ds::DynamicalSystem, Q0 | k::Int; kwargs...)
Return an integrator object that evolves in parallel both the system as well
as deviation vectors living on the tangent space, also called linearized space.

`Q0` is a *matrix* whose columns are initial values for deviation vectors. If
instead of a matrix `Q0` an integer `k` is given, then `k` random orthonormal
vectors are choosen as initial conditions.

## Keyword Arguments
* `u0` : Optional different initial state.
* `diffeq...` : Keyword arguments propagated into `init` of DifferentialEquations.jl.
  See [`trajectory`](@ref) for examples. Only valid for continuous systems.
  These keywords can also include `callback` for [event handling](http://docs.juliadiffeq.org/latest/features/callback_functions.html).

It is *heavily* advised to use the functions [`get_state`](@ref), [`get_deviations`](@ref),
[`set_state!`](@ref), [`set_deviations!`](@ref) to manipulate the integrator.

## Description

If ``J`` is the jacobian of the system then the *tangent dynamics* are
the equations that evolve in parallel the system as well as
a deviation vector (or matrix) ``w``:
```math
\\begin{aligned}
\\dot{u} &= f(u, p, t) \\\\
\\dot{w} &= J(u, p, t) \\times w
\\end{aligned}
```
with ``f`` being the equations of motion and ``u`` the system state.
Similar equations hold for the discrete case.
"""
function tangent_integrator end

"""
    get_deviations(tang_integ)
Return the deviation vectors of the [`tangent_integrator`](@ref) in a form
of a matrix with columns the vectors.
"""
function get_deviations end

"""
    set_deviations!(tang_integ, Q)
Set the deviation vectors of the [`tangent_integrator`](@ref) to `Q`, which must
be a matrix with each column being a deviation vector.

Automatically does `u_modified!(tang_integ, true)`.
"""
function set_deviations! end

"""
    parallel_integrator(ds::DynamicalSystem, states; kwargs...)
Return an integrator object that can be used to evolve many `states` of
a system in parallel at the *exact same times*, using `step!(integ [, Δt])`.

`states` are expected as vectors of vectors.

## Keyword Arguments
* `diffeq...` : Keyword arguments propagated into `init` of DifferentialEquations.jl.
  See [`trajectory`](@ref) for examples. Only valid for continuous systems.
  These keywords can also include `callback` for [event handling](http://docs.juliadiffeq.org/latest/features/callback_functions.html).

It is *heavily* advised to use the functions [`get_state`](@ref) and
[`set_state!`](@ref) to manipulate the integrator. Provide `i` as a second
argument to change the `i`-th state.
"""
function parallel_integrator end

"""
    trajectory(ds::DynamicalSystem, T [, u]; kwargs...) -> dataset

Return a dataset that will contain the trajectory of the system,
after evolving it for total time `T`, optionally starting from state `u`.
See [`Dataset`](@ref) for info on how to use this object.

A `W×D` dataset is returned, with `W = length(t0:Δt:T)` with
`t0:Δt:T` representing the time vector (*not* returned) and `D` the system dimension.

## Keyword Arguments
* `Δt` :  Time step of value output. For discrete systems it must be an integer.
  Defaults to `0.01` for continuous and `1` for discrete.
* `Ttr` : Transient time to evolve the initial state before starting saving states.
* `save_idxs`: Which variables to output in the dataset. By default all.
* `diffeq...` : Remaining keyword arguments are propagated to the solvers of
  DifferentialEquations.jl, see below. Only valid for continuous systems.

## DifferentialEquations.jl keyword arguments
Continuous dynamical systems are evolved via the solvers of DifferentialEquations.jl.
Functions in DynamicalSystems.jl allow keyword propagation to these solvers.
For example you could use `abstol = 1e-9`.
If you want to specify a solver, do so by using the keyword `alg`, e.g.:
`alg = Tsit5(), maxiters = 100000`. This requires you to have been first
`using OrdinaryDiffEq` to access the solvers. See the
`CDS_KWARGS` variable for the default values we use.
These keywords can also include `callback` for [event handling](http://docs.juliadiffeq.org/latest/features/callback_functions.html).

Keep in mind that the default solver is `SimpleATsit5`, which only supports
adaptive time-stepping. Use `(alg = SimpleTsit5(), dt = your_step_size)` as keywords
for a non-adaptive time stepping solver, which is mandatory in some situations
(such as e.g., calculating [`basins_of_attraction`](@ref) of a stroboscopic map).
You can also choose any other solver except `SimpleATsit5`, such as `Tsit5`, as long
as you turn off adaptive stepping, e.g.
`(alg = Tsit5(), adaptive = false, dt = your_step_size)`.
"""
function trajectory end

# Util functions for `trajectory`
svector_access(::Nothing) = nothing
svector_access(x::AbstractArray) = SVector{length(x), Int}(x...)
svector_access(x::Int) = SVector{1, Int}(x)
obtain_access(u, ::Nothing) = u
obtain_access(u, i::SVector) = u[i]

ext: jl


text:
function iterative_policy_evaluation(env::AbsEnvironment, policy::Policy; Ɣ=0.9, V=nothing, verbose=false)
    states = getAllStates(env)
    if V == nothing
        V = Dict{AbsState, Float64}()
        for s in states; V[s] = 0.0; end
    end
    delta = 1.0

    eps = 1e-30
    threshold = Ɣ < 1.0 ? eps : eps * (1 - Ɣ) / (2*Ɣ)

    iteration = 0

    while delta > threshold
        delta = 0.0
        iteration += 1
        @inbounds for s in states
            v = V[s]
            total = 0.0
            @inbounds for (a,p) in actionsAndProbs(policy, s)
                @inbounds for (sprime, r, pp) in getSuccessors(s, a, env)
                    total += p * pp * (r + Ɣ * V[sprime])
                end
            end
            V[s] = total
            verbose && println("State: $(s), v: $(v), V: $(V[s])")
            delta = max(delta, abs(v - V[s]))
            verbose && println("Delta: $(delta)\n")
        end
    end

    verbose && println("Number of iterations: $(iteration)")
    return V
end

#Returns optimal policy and state values
function policy_iteration(env::AbsEnvironment; Ɣ=0.9, verbose=false, Vs=nothing, Ps=nothing)
    states = getAllStates(env)

    ### INITIALIZATION ###

    #An arbitrary value function and policy
    V = Dict{AbsState, Float64}()
    policy = Policy()

    for s in states
        V[s] = 0.0
        actionSet = getActions(s, env)
        a = shuffle(collect(actionSet))[1]
        policy.mapping[s] = [(a, 1.0)]#action & probability, i.e. deterministic policy
    end

    if verbose
        for s in states
            println("State: $(s), Value: $(V[s]), Action: $(policy.mapping[s][1][1])")
        end
    end

    policyStable = false
    iteration = 0
    while !policyStable
        ### POLICY EVALUATION ###
        Ps != nothing && push!(Ps, copy(policy.mapping))
        iterative_policy_evaluation(env, policy; Ɣ=Ɣ, V=V, verbose=verbose)
        Vs != nothing && push!(Vs, copy(V))
        ### GREEDY POLICY IMPROVEMENT ###
        policyStable = true
        verbose && println("Iteration: $(iteration)")
        iteration += 1
        for s in states
            aa = policy.mapping[s][1][1]
            m = -1e35
            verbose && println("Before Update - State: $(s), Action: $(aa)")
            for a in getActions(s, env)
                total = 0.0
                for (sprime, r, pp) in getSuccessors(s, a, env)
                    total += pp * (r + Ɣ * V[sprime])
                end
                if total > m
                    policy.mapping[s] = [(a, 1.0)]
                    m = total
                end
            end
            if !(policy.mapping[s][1][1] == aa)
                policyStable = false
            end

            verbose && println("After Update - State: $(s), Action: $(policy.mapping[s][1][1])")
        end
        if verbose
            for s in states
                println("State: $(s), Value: $(V[s]), Action: $(policy.mapping[s][1][1])")
            end

        end
    end
    println("Number of iterations: $iteration")
    policy, V
end

function synchronous_value_iteration(env::AbsEnvironment; Ɣ=0.9, verbose=false, Vs=nothing)
    #Initialize V
    V = Dict{AbsState, Float64}()
    states = getAllStates(env)
    for s in states; V[s] = 0.0; end

    #Value Iteration
    delta = 1.0
    eps = 1e-30
    threshold = Ɣ < 1.0 ? eps : eps * (1 - Ɣ) / (2*Ɣ)
    iteration = 0

    while delta > threshold
        delta = 0.0
        iteration += 1
        copyV = copy(V)
        for s in states
            v = V[s]
            m = -1e35
            for a in getActions(s, env)
                total = 0.0
                for (sprime, r, pp) in getSuccessors(s, a, env)
                    total += pp * (r + Ɣ * V[sprime])
                end

                if total > m
                    m = total
                end
            end
            copyV[s] = m
            verbose && println("State: $(s), v: $(v), V: $(copyV[s])")
            delta = max(delta, abs(v - copyV[s]))
            verbose && println("Delta: $(delta)\n")
        end
        for s in states; V[s] = copyV[s]; end
        Vs != nothing && push!(Vs, copy(V))
    end

    println("Number of iterations: $(iteration)")

    #Deterministic Policy
    policy = Policy()
    for s in states
        m = -1e35
        for a in getActions(s, env)
            total = 0.0
            for (sprime, r, pp) in getSuccessors(s, a, env)
                total += pp * (r + Ɣ * V[sprime])
            end
            if total > m
                policy.mapping[s] = [(a, 1.0)]
                m = total
            end
        end
    end
    return policy, V
end

function gauss_seidel_value_iteration(env::AbsEnvironment; Ɣ=0.9, verbose=false, Vs=nothing)
    #Initialize V
    V = Dict{AbsState, Float64}()
    states = getAllStates(env)
    for s in states; V[s] = 0.0; end
    #Value Iteration
    delta = 1.0
    eps = 1e-30
    threshold = Ɣ < 1.0 ? eps : eps * (1 - Ɣ) / (2*Ɣ)
    iteration = 0

    while delta > threshold
        delta = 0.0
        iteration += 1
        copyV = copy(V)
        updated = Set{AbsState}()
        for s in states
            v = V[s]
            m = -1e35
            for a in getActions(s, env)
                total = 0.0
                for (sprime, r, pp) in getSuccessors(s, a, env)
                    if sprime in updated
                        total += pp * (r + Ɣ * copyV[sprime])
                    else
                        total += pp * (r + Ɣ * V[sprime])
                    end
                end

                if total > m
                    m = total
                    copyV[s] = total
                end
            end
            push!(updated, s)
            verbose && println("State: $(s), v: $(v), V: $(copyV[s])")
            delta = max(delta, abs(v - copyV[s]))
            verbose && println("Delta: $(delta)\n")
        end
        for s in states; V[s] = copyV[s]; end
        Vs != nothing && push!(Vs, copy(V))
    end

    println("Number of iterations: $(iteration)")

    #Deterministic Policy
    policy = Policy()
    for s in states
        m = -1e35
        for a in getActions(s, env)
            total = 0.0
            for (sprime, r, pp) in getSuccessors(s, a, env)
                total += pp * (r + Ɣ * V[sprime])
            end
            if total > m
                policy.mapping[s] = [(a, 1.0)]
                m = total
            end
        end
    end
    return policy, V
end

max_stars_repo_name: ozanarkancan/ReinforcementLearning

max_issues_repo_name: ozanarkancan/ReinforcementLearning

max_forks_repo_name: ozanarkancan/ReinforcementLearning


text:
function ConvectiveAdjustmentNDE(NN, ds; iterations=nothing)
    weights, reconstruct = Flux.destructure(NN)

    T = ds["T"]
    wT = ds["wT"]
    FT = eltype(T)
    Nz = size(T, 3)
    Nt = size(T, 4)
    zc = znodes(T)
    zf = znodes(wT)
    times = T.times

    H = abs(zf[1]) # Domain depth/height
    τ = times[end]  # Simulation length

    Δẑ = diff(zc)[1] / H  # Non-dimensional grid spacing
    Dzᶜ = Dᶜ(Nz, Δẑ) # Differentiation matrix operator
    Dzᶠ = Dᶠ(Nz, Δẑ) # Differentiation matrix operator
    Dzᶜ = convert(Array{FT}, Dzᶜ)
    Dzᶠ = convert(Array{FT}, Dzᶠ)

    if isnothing(iterations)
        iterations = 1:length(times)
    end

    """
    Non-dimensional PDE is

        ∂T/∂t = - σ_wT/σ_T * τ/H * ∂/∂z(wT - K ∂T/∂z)

    where K = 0 if ∂T/∂z < 0 and K = 100 if ∂T/∂z > 0.
    """
    function ∂T∂t(T, p, t)
        weights = p[1:end-6]
        bottom_flux, top_flux, σ_T, σ_wT, H, τ = p[end-5:end]

        # Turbulent heat flux
        NN = reconstruct(weights)
        wT_interior = NN(T)
        wT = [bottom_flux; wT_interior; top_flux]
        ∂z_wT = Dzᶜ * wT

        # Convective adjustment
        ∂T∂z = Dzᶠ * T
        ∂z_K∂T∂z = Dzᶜ * min.(0, 10 * ∂T∂z)

        return σ_wT/σ_T * τ/H * (- ∂z_wT .+ ∂z_K∂T∂z)
    end

    tspan = FT.( (0.0, maximum(iterations) / Nt) )
    saveat = range(tspan[1], tspan[2], length=length(iterations))

    # See: https://github.com/SciML/DiffEqFlux.jl/blob/449efcecfc11f1eab65d0e467cf57db9f5a5dbec/src/neural_de.jl#L66-L67
    # We set the initial condition to `nothing`. Then we will set it to some actual initial condition when calling `solve`.
    ff = ODEFunction{false}(∂T∂t, tgrad=DiffEqFlux.basic_tgrad)
    return ODEProblem{false}(ff, nothing, tspan, saveat=saveat)
end


text:
# GPUArrays.jl interface

#
# Device functionality
#

## execution

struct CuArrayBackend <: AbstractGPUBackend end

struct CuKernelContext <: AbstractKernelContext end

@inline function GPUArrays.launch_heuristic(::CuArrayBackend, f::F, args::Vararg{Any,N};
                                            elements::Int, elements_per_thread::Int) where {F,N}
    kernel = @cuda launch=false f(CuKernelContext(), args...)

    # launching many large blocks) lowers performance, as observed with broadcast, so cap
    # the block size if we don't have a grid-stride kernel (which would keep the grid small)
    if elements_per_thread > 1
        launch_configuration(kernel.fun)
    else
        launch_configuration(kernel.fun; max_threads=256)
    end
end

@inline function GPUArrays.gpu_call(::CuArrayBackend, f::F, args::TT, threads::Int,
                                    blocks::Int; name::Union{String,Nothing}) where {F,TT}
    @cuda threads=threads blocks=blocks name=name f(CuKernelContext(), args...)
end

## on-device

# indexing

GPUArrays.blockidx(ctx::CuKernelContext) = blockIdx().x
GPUArrays.blockdim(ctx::CuKernelContext) = blockDim().x
GPUArrays.threadidx(ctx::CuKernelContext) = threadIdx().x
GPUArrays.griddim(ctx::CuKernelContext) = gridDim().x

# memory

@inline function GPUArrays.LocalMemory(::CuKernelContext, ::Type{T}, ::Val{dims}, ::Val{id}
                                      ) where {T, dims, id}
    ptr = CUDA._shmem(Val(id), T, Val(prod(dims)))
    CuDeviceArray(dims, reinterpret(LLVMPtr{T, AS.Shared}, ptr))
end

# synchronization

@inline GPUArrays.synchronize_threads(::CuKernelContext) = sync_threads()

#
# Host abstractions
#

GPUArrays.backend(::Type{<:CuArray}) = CuArrayBackend()


text:
"""
GenX: An Configurable Capacity Expansion Model
Copyright (C) 2021,  Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
A complete copy of the GNU General Public License v2 (GPLv2) is available
in LICENSE.txt.  Users uncompressing this from an archive may not have
received this license file.  If not, see <http://www.gnu.org/licenses/>.
"""

@doc raw"""
	write_esr_revenue(path::AbstractString, inputs::Dict, setup::Dict, dfPower::DataFrame, dfESR::DataFrame)

Function for reporting the renewable/clean credit revenue earned by each generator listed in the input file. GenX will print this file only when RPS/CES is modeled and the shadow price can be obtained form the solver. Each row corresponds to a generator, and each column starting from the 6th to the second last is the total revenue earned from each RPS constraint. The revenue is calculated as the total annual generation (if elgible for the corresponding constraint) multiplied by the RPS/CES price. The last column is the total revenue received from all constraint. The unit is \$.
"""
function write_esr_revenue(path::AbstractString, inputs::Dict, setup::Dict, dfPower::DataFrame, dfESR::DataFrame)
	dfGen = inputs["dfGen"]
	dfESRRev = DataFrame(region = dfGen[!,:region], Resource = inputs["RESOURCES"], zone = dfGen[!,:Zone], Cluster = dfGen[!,:cluster], R_ID = dfGen[!,:R_ID])

	for i in 1:inputs["nESR"]
		dfESRRev =  hcat(dfESRRev, dfPower[1:end-1,:AnnualSum] .* dfGen[!,Symbol("ESR_$i")] * dfESR[i,:ESR_Price])
		# dfpower is in MWh already, price is in $/MWh already, no need to scale
		# if setup["ParameterScale"] == 1
		# 	#dfESRRev[!,:x1] = dfESRRev[!,:x1] * (1e+3) # MillionUS$ to US$
		# 	dfESRRev[!,:x1] = dfESRRev[!,:x1] * ModelScalingFactor # MillionUS$ to US$  # Is this right? -Jack 4/29/2021
		# end
		rename!(dfESRRev, Dict(:x1 => Symbol("ESR_$i")))
	end
	dfESRRev.AnnualSum = sum(eachcol(dfESRRev[:,6:inputs["nESR"]+5]))
	CSV.write(joinpath(path, "ESR_Revenue.csv"), dfESRRev)
	return dfESRRev
end

max_stars_repo_name: Betristor/LTESOM

max_issues_repo_name: Betristor/LTESOM

max_forks_repo_name: Betristor/LTESOM


text:
immutable Normal <: ContinuousUnivariateDistribution
    μ::Float64
    σ::Float64

    function Normal(μ::Real, σ::Real)
    	σ > zero(σ) || error("std.dev. must be positive")
    	new(float64(μ), float64(σ))
    end

    Normal(μ::Real) = Normal(float64(μ), 1.0)
    Normal() = Normal(0.0, 1.0)
end

typealias Gaussian Normal

## Support
@distr_support Normal -Inf Inf

## Properties
mean(d::Normal) = d.μ
median(d::Normal) = d.μ
mode(d::Normal) = d.μ

var(d::Normal) = abs2(d.σ)
std(d::Normal) = d.σ
skewness(d::Normal) = 0.0
kurtosis(d::Normal) = 0.0

entropy(d::Normal) = 0.5 * (log2π + 1.) + log(d.σ)

## Functions
zval(d::Normal, x::Float64) = (x - d.μ)/d.σ
xval(d::Normal, z::Float64) = d.μ + d.σ * z

pdf(d::Normal, x::Float64) = φ(zval(d,x))/d.σ
logpdf(d::Normal, x::Float64) = logφ(zval(d,x)) - log(d.σ)

cdf(d::Normal, x::Float64) = Φ(zval(d,x))
ccdf(d::Normal, x::Float64) = Φc(zval(d,x))
logcdf(d::Normal, x::Float64) = logΦ(zval(d,x))
logccdf(d::Normal, x::Float64) = logΦc(zval(d,x))

quantile(d::Normal, p::Float64) = xval(d, Φinv(p))
cquantile(d::Normal, p::Float64) = xval(d, -Φinv(p))
invlogcdf(d::Normal, p::Float64) = xval(d, logΦinv(p))
invlogccdf(d::Normal, p::Float64) = xval(d, -logΦinv(p))

gradlogpdf(d::Normal, x::Float64) = (d.μ - x) / d.σ^2

mgf(d::Normal, t::Real) = exp(t * d.μ + 0.5 * d.σ^2 * t^2)
cf(d::Normal, t::Real) = exp(im * t * d.μ - 0.5 * d.σ^2 * t^2)

## Sampling
rand(d::Normal) = d.μ + d.σ * randn()

## Fitting
immutable NormalStats <: SufficientStats
    s::Float64    # (weighted) sum of x
    m::Float64    # (weighted) mean of x
    s2::Float64   # (weighted) sum of (x - μ)^2
    tw::Float64    # total sample weight

    NormalStats(s::Real, m::Real, s2::Real, tw::Real) = new(float64(s), float64(m), float64(s2), float64(tw))
end

function suffstats{T<:Real}(::Type{Normal}, x::Array{T})
    n = length(x)

    # compute s
    s = x[1]
    for i = 2:n
        @inbounds s += x[i]
    end
    m = s / n

    # compute s2
    s2 = abs2(x[1] - m)
    for i = 2:n
        @inbounds s2 += abs2(x[i] - m)
    end

    NormalStats(s, m, s2, n)
end

function suffstats{T<:Real}(::Type{Normal}, x::Array{T}, w::Array{Float64})
    n = length(x)

    # compute s
    tw = w[1]
    s = w[1] * x[1]
    for i = 2:n
        @inbounds wi = w[i]
        @inbounds s += wi * x[i]
        tw += wi
    end
    m = s / tw

    # compute s2
    s2 = w[1] * abs2(x[1] - m)
    for i = 2:n
        @inbounds s2 += w[i] * abs2(x[i] - m)
    end

    NormalStats(s, m, s2, tw)
end

# Cases where μ or σ is known

immutable NormalKnownMu <: IncompleteDistribution
    μ::Float64
end

immutable NormalKnownMuStats <: SufficientStats
    μ::Float64      # known mean
    s2::Float64     # (weighted) sum of (x - μ)^2
    tw::Float64     # total sample weight
end

function suffstats{T<:Real}(g::NormalKnownMu, x::Array{T})
    μ = g.μ
    s2 = abs2(x[1] - μ)
    for i = 2:length(x)
        @inbounds s2 += abs2(x[i] - μ)
    end
    NormalKnownMuStats(g.μ, s2, float64(length(x)))
end

function suffstats{T<:Real}(g::NormalKnownMu, x::Array{T}, w::Array{Float64})
    μ = g.μ
    s2 = abs2(x[1] - μ) * w[1]
    tw = w[1]
    for i = 2:length(x)
        @inbounds wi = w[i]
        @inbounds s2 += abs2(x[i] - μ) * wi
        tw += wi
    end
    NormalKnownMuStats(g.μ, s2, tw)
end

immutable NormalKnownSigma <: IncompleteDistribution
    σ::Float64

    function NormalKnownSigma(σ::Float64)
        σ > 0.0 || throw(ArgumentError("σ must be a positive value."))
        new(σ)
    end
end

immutable NormalKnownSigmaStats <: SufficientStats
    σ::Float64      # known std.dev
    sx::Float64      # (weighted) sum of x
    tw::Float64     # total sample weight
end

function suffstats{T<:Real}(g::NormalKnownSigma, x::Array{T})
    NormalKnownSigmaStats(g.σ, sum(x), float64(length(x)))
end

function suffstats{T<:Real}(g::NormalKnownSigma, x::Array{T}, w::Array{T})
    NormalKnownSigmaStats(g.σ, dot(x, w), sum(w))
end

# fit_mle based on sufficient statistics

fit_mle(::Type{Normal}, ss::NormalStats) = Normal(ss.m, sqrt(ss.s2 / ss.tw))
fit_mle(g::NormalKnownMu, ss::NormalKnownMuStats) = Normal(g.μ, sqrt(ss.s2 / ss.tw))
fit_mle(g::NormalKnownSigma, ss::NormalKnownSigmaStats) = Normal(ss.sx / ss.tw, g.σ)

# generic fit_mle methods

function fit_mle{T<:Real}(::Type{Normal}, x::Array{T}; mu::Float64=NaN, sigma::Float64=NaN)
    if isnan(mu)
        if isnan(sigma)
            fit_mle(Normal, suffstats(Normal, x))
        else
            g = NormalKnownSigma(sigma)
            fit_mle(g, suffstats(g, x))
        end
    else
        if isnan(sigma)
            g = NormalKnownMu(mu)
            fit_mle(g, suffstats(g, x))
        else
            Normal(mu, sigma)
        end
    end
end

function fit_mle{T<:Real}(::Type{Normal}, x::Array{T}, w::Array{Float64}; mu::Float64=NaN, sigma::Float64=NaN)
    if isnan(mu)
        if isnan(sigma)
            fit_mle(Normal, suffstats(Normal, x, w))
        else
            g = NormalKnownSigma(sigma)
            fit_mle(g, suffstats(g, x, w))
        end
    else
        if isnan(sigma)
            g = NormalKnownMu(mu)
            fit_mle(g, suffstats(g, x, w))
        else
            Normal(mu, sigma)
        end
    end
end


text:
# Tests to make sure the Quantity array interface works as expected

@testset "similar" begin
    H = Stage(ts,randn(2))
    @test typeof(similar(H,5)) <: Stage
end

@testset "setindex" begin
    H = Stage(ts,randn(2))
    H[2] = (now(),500)
    @test quantity(H)[2] == 500
end

@testset "Range indexing" begin
    r = randn(2)
    H = Stage(ts,r)
    @test quantity(H[1:2]) == r
    @test typeof(H[1:2]) <: Stage
end


text:
# generated from AutoScalingTypeDict via AWS/src/codegen.jl
# do not edit, edit specification file and regenerate instead

type Activity <: AbstractAWSType
    activityId::Union{Void,String}
    autoScalingGroupName::Union{Void,String}
    cause::Union{Void,String}
    description::Union{Void,String}
    details::Union{Void,String}
    endTime::Union{Void,DateTime}
    progress::Union{Void,Int64}
    startTime::Union{Void,DateTime}
    statusCode::Union{Void,String}
    statusMessage::Union{Void,String}
    function Activity(;activityId=nothing, autoScalingGroupName=nothing, cause=nothing, description=nothing, details=nothing, endTime=nothing, progress=nothing, startTime=nothing, statusCode=nothing, statusMessage=nothing)
        new(activityId, autoScalingGroupName, cause, description, details, endTime, progress, startTime, statusCode, statusMessage)
    end
    Activity(pd) = parse_from_xml(Activity, AutoScalingTypeDict, pd)
end # Activity
export Activity

type AdjustmentType <: AbstractAWSType
    adjustmentType::Union{Void,String}
    function AdjustmentType(;adjustmentType=nothing)
        new(adjustmentType)
    end
    AdjustmentType(pd) = parse_from_xml(AdjustmentType, AutoScalingTypeDict, pd)
end # AdjustmentType
export AdjustmentType

type Alarm <: AbstractAWSType
    alarmARN::Union{Void,String}
    alarmName::Union{Void,String}
    function Alarm(;alarmARN=nothing, alarmName=nothing)
        new(alarmARN, alarmName)
    end
    Alarm(pd) = parse_from_xml(Alarm, AutoScalingTypeDict, pd)
end # Alarm
export Alarm

type EnabledMetric <: AbstractAWSType
    granularity::Union{Void,String}
    metric::Union{Void,String}
    function EnabledMetric(;granularity=nothing, metric=nothing)
        new(granularity, metric)
    end
    EnabledMetric(pd) = parse_from_xml(EnabledMetric, AutoScalingTypeDict, pd)
end # EnabledMetric
export EnabledMetric

type Instance <: AbstractAWSType
    availabilityZone::Union{Void,String}
    healthStatus::Union{Void,String}
    instanceId::Union{Void,String}
    launchConfigurationName::Union{Void,String}
    lifecycleState::Union{Void,String}
    protectedFromScaleIn::Union{Void,Bool}
    function Instance(;availabilityZone=nothing, healthStatus=nothing, instanceId=nothing, launchConfigurationName=nothing, lifecycleState=nothing, protectedFromScaleIn=nothing)
        new(availabilityZone, healthStatus, instanceId, launchConfigurationName, lifecycleState, protectedFromScaleIn)
    end
    Instance(pd) = parse_from_xml(Instance, AutoScalingTypeDict, pd)
end # Instance
export Instance

type SuspendedProcess <: AbstractAWSType
    processName::Union{Void,String}
    suspensionReason::Union{Void,String}
    function SuspendedProcess(;processName=nothing, suspensionReason=nothing)
        new(processName, suspensionReason)
    end
    SuspendedProcess(pd) = parse_from_xml(SuspendedProcess, AutoScalingTypeDict, pd)
end # SuspendedProcess
export SuspendedProcess

type TagDescription <: AbstractAWSType
    key::Union{Void,String}
    propagateAtLaunch::Union{Void,Bool}
    resourceId::Union{Void,String}
    resourceType::Union{Void,String}
    value::Union{Void,String}
    function TagDescription(;key=nothing, propagateAtLaunch=nothing, resourceId=nothing, resourceType=nothing, value=nothing)
        new(key, propagateAtLaunch, resourceId, resourceType, value)
    end
    TagDescription(pd) = parse_from_xml(TagDescription, AutoScalingTypeDict, pd)
end # TagDescription
export TagDescription

type AutoScalingGroup <: AbstractAWSType
    autoScalingGroupARN::Union{Void,String}
    autoScalingGroupName::Union{Void,String}
    availabilityZones::Union{Void,Array{String,1}}
    createdTime::Union{Void,DateTime}
    defaultCooldown::Union{Void,Int64}
    desiredCapacity::Union{Void,Int64}
    enabledMetrics::Union{Void,Array{EnabledMetric,1}}
    healthCheckGracePeriod::Union{Void,Int64}
    healthCheckType::Union{Void,String}
    instances::Union{Void,Array{Instance,1}}
    launchConfigurationName::Union{Void,String}
    loadBalancerNames::Union{Void,Array{String,1}}
    maxSize::Union{Void,Int64}
    minSize::Union{Void,Int64}
    newInstancesProtectedFromScaleIn::Union{Void,Bool}
    placementGroup::Union{Void,String}
    status::Union{Void,String}
    suspendedProcesses::Union{Void,Array{SuspendedProcess,1}}
    tags::Union{Void,Array{TagDescription,1}}
    targetGroupARNs::Union{Void,Array{String,1}}
    terminationPolicies::Union{Void,Array{String,1}}
    vPCZoneIdentifier::Union{Void,String}
    function AutoScalingGroup(;autoScalingGroupARN=nothing, autoScalingGroupName=nothing, availabilityZones=nothing, createdTime=nothing, defaultCooldown=nothing, desiredCapacity=nothing, enabledMetrics=nothing, healthCheckGracePeriod=nothing, healthCheckType=nothing, instances=nothing, launchConfigurationName=nothing, loadBalancerNames=nothing, maxSize=nothing, minSize=nothing, newInstancesProtectedFromScaleIn=nothing, placementGroup=nothing, status=nothing, suspendedProcesses=nothing, tags=nothing, targetGroupARNs=nothing, terminationPolicies=nothing, vPCZoneIdentifier=nothing)
        new(autoScalingGroupARN, autoScalingGroupName, availabilityZones, createdTime, defaultCooldown, desiredCapacity, enabledMetrics, healthCheckGracePeriod, healthCheckType, instances, launchConfigurationName, loadBalancerNames, maxSize, minSize, newInstancesProtectedFromScaleIn, placementGroup, status, suspendedProcesses, tags, targetGroupARNs, terminationPolicies, vPCZoneIdentifier)
    end
    AutoScalingGroup(pd) = parse_from_xml(AutoScalingGroup, AutoScalingTypeDict, pd)
end # AutoScalingGroup
export AutoScalingGroup

type AutoScalingInstanceDetails <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    availabilityZone::Union{Void,String}
    healthStatus::Union{Void,String}
    instanceId::Union{Void,String}
    launchConfigurationName::Union{Void,String}
    lifecycleState::Union{Void,String}
    protectedFromScaleIn::Union{Void,Bool}
    function AutoScalingInstanceDetails(;autoScalingGroupName=nothing, availabilityZone=nothing, healthStatus=nothing, instanceId=nothing, launchConfigurationName=nothing, lifecycleState=nothing, protectedFromScaleIn=nothing)
        new(autoScalingGroupName, availabilityZone, healthStatus, instanceId, launchConfigurationName, lifecycleState, protectedFromScaleIn)
    end
    AutoScalingInstanceDetails(pd) = parse_from_xml(AutoScalingInstanceDetails, AutoScalingTypeDict, pd)
end # AutoScalingInstanceDetails
export AutoScalingInstanceDetails

type Ebs <: AbstractAWSType
    deleteOnTermination::Union{Void,Bool}
    encrypted::Union{Void,Bool}
    iops::Union{Void,Int64}
    snapshotId::Union{Void,String}
    volumeSize::Union{Void,Int64}
    volumeType::Union{Void,String}
    function Ebs(;deleteOnTermination=nothing, encrypted=nothing, iops=nothing, snapshotId=nothing, volumeSize=nothing, volumeType=nothing)
        new(deleteOnTermination, encrypted, iops, snapshotId, volumeSize, volumeType)
    end
    Ebs(pd) = parse_from_xml(Ebs, AutoScalingTypeDict, pd)
end # Ebs
export Ebs

type BlockDeviceMapping <: AbstractAWSType
    deviceName::Union{Void,String}
    ebs::Union{Void,Ebs}
    noDevice::Union{Void,Bool}
    virtualName::Union{Void,String}
    function BlockDeviceMapping(;deviceName=nothing, ebs=nothing, noDevice=nothing, virtualName=nothing)
        new(deviceName, ebs, noDevice, virtualName)
    end
    BlockDeviceMapping(pd) = parse_from_xml(BlockDeviceMapping, AutoScalingTypeDict, pd)
end # BlockDeviceMapping
export BlockDeviceMapping

type MetricDimension <: AbstractAWSType
    name::Union{Void,String}
    value::Union{Void,String}
    function MetricDimension(;name=nothing, value=nothing)
        new(name, value)
    end
    MetricDimension(pd) = parse_from_xml(MetricDimension, AutoScalingTypeDict, pd)
end # MetricDimension
export MetricDimension

type CustomizedMetricSpecification <: AbstractAWSType
    dimensions::Union{Void,Array{MetricDimension,1}}
    metricName::Union{Void,String}
    namespace::Union{Void,String}
    statistic::Union{Void,String}
    unit::Union{Void,String}
    function CustomizedMetricSpecification(;dimensions=nothing, metricName=nothing, namespace=nothing, statistic=nothing, unit=nothing)
        new(dimensions, metricName, namespace, statistic, unit)
    end
    CustomizedMetricSpecification(pd) = parse_from_xml(CustomizedMetricSpecification, AutoScalingTypeDict, pd)
end # CustomizedMetricSpecification
export CustomizedMetricSpecification

type Filter <: AbstractAWSType
    name::Union{Void,String}
    values::Union{Void,Array{String,1}}
    function Filter(;name=nothing, values=nothing)
        new(name, values)
    end
    Filter(pd) = parse_from_xml(Filter, AutoScalingTypeDict, pd)
end # Filter
export Filter

type InstanceMonitoring <: AbstractAWSType
    enabled::Union{Void,Bool}
    function InstanceMonitoring(;enabled=nothing)
        new(enabled)
    end
    InstanceMonitoring(pd) = parse_from_xml(InstanceMonitoring, AutoScalingTypeDict, pd)
end # InstanceMonitoring
export InstanceMonitoring

type LaunchConfiguration <: AbstractAWSType
    associatePublicIpAddress::Union{Void,Bool}
    blockDeviceMappings::Union{Void,Array{BlockDeviceMapping,1}}
    classicLinkVPCId::Union{Void,String}
    classicLinkVPCSecurityGroups::Union{Void,Array{String,1}}
    createdTime::Union{Void,DateTime}
    ebsOptimized::Union{Void,Bool}
    iamInstanceProfile::Union{Void,String}
    imageId::Union{Void,String}
    instanceMonitoring::Union{Void,InstanceMonitoring}
    instanceType::Union{Void,String}
    kernelId::Union{Void,String}
    keyName::Union{Void,String}
    launchConfigurationARN::Union{Void,String}
    launchConfigurationName::Union{Void,String}
    placementTenancy::Union{Void,String}
    ramdiskId::Union{Void,String}
    securityGroups::Union{Void,Array{String,1}}
    spotPrice::Union{Void,String}
    userData::Union{Void,String}
    function LaunchConfiguration(;associatePublicIpAddress=nothing, blockDeviceMappings=nothing, classicLinkVPCId=nothing, classicLinkVPCSecurityGroups=nothing, createdTime=nothing, ebsOptimized=nothing, iamInstanceProfile=nothing, imageId=nothing, instanceMonitoring=nothing, instanceType=nothing, kernelId=nothing, keyName=nothing, launchConfigurationARN=nothing, launchConfigurationName=nothing, placementTenancy=nothing, ramdiskId=nothing, securityGroups=nothing, spotPrice=nothing, userData=nothing)
        new(associatePublicIpAddress, blockDeviceMappings, classicLinkVPCId, classicLinkVPCSecurityGroups, createdTime, ebsOptimized, iamInstanceProfile, imageId, instanceMonitoring, instanceType, kernelId, keyName, launchConfigurationARN, launchConfigurationName, placementTenancy, ramdiskId, securityGroups, spotPrice, userData)
    end
    LaunchConfiguration(pd) = parse_from_xml(LaunchConfiguration, AutoScalingTypeDict, pd)
end # LaunchConfiguration
export LaunchConfiguration

type LifecycleHook <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    defaultResult::Union{Void,String}
    globalTimeout::Union{Void,Int64}
    heartbeatTimeout::Union{Void,Int64}
    lifecycleHookName::Union{Void,String}
    lifecycleTransition::Union{Void,String}
    notificationMetadata::Union{Void,String}
    notificationTargetARN::Union{Void,String}
    roleARN::Union{Void,String}
    function LifecycleHook(;autoScalingGroupName=nothing, defaultResult=nothing, globalTimeout=nothing, heartbeatTimeout=nothing, lifecycleHookName=nothing, lifecycleTransition=nothing, notificationMetadata=nothing, notificationTargetARN=nothing, roleARN=nothing)
        new(autoScalingGroupName, defaultResult, globalTimeout, heartbeatTimeout, lifecycleHookName, lifecycleTransition, notificationMetadata, notificationTargetARN, roleARN)
    end
    LifecycleHook(pd) = parse_from_xml(LifecycleHook, AutoScalingTypeDict, pd)
end # LifecycleHook
export LifecycleHook

type LoadBalancerState <: AbstractAWSType
    loadBalancerName::Union{Void,String}
    state::Union{Void,String}
    function LoadBalancerState(;loadBalancerName=nothing, state=nothing)
        new(loadBalancerName, state)
    end
    LoadBalancerState(pd) = parse_from_xml(LoadBalancerState, AutoScalingTypeDict, pd)
end # LoadBalancerState
export LoadBalancerState

type LoadBalancerTargetGroupState <: AbstractAWSType
    loadBalancerTargetGroupARN::Union{Void,String}
    state::Union{Void,String}
    function LoadBalancerTargetGroupState(;loadBalancerTargetGroupARN=nothing, state=nothing)
        new(loadBalancerTargetGroupARN, state)
    end
    LoadBalancerTargetGroupState(pd) = parse_from_xml(LoadBalancerTargetGroupState, AutoScalingTypeDict, pd)
end # LoadBalancerTargetGroupState
export LoadBalancerTargetGroupState

type MetricCollectionType <: AbstractAWSType
    metric::Union{Void,String}
    function MetricCollectionType(;metric=nothing)
        new(metric)
    end
    MetricCollectionType(pd) = parse_from_xml(MetricCollectionType, AutoScalingTypeDict, pd)
end # MetricCollectionType
export MetricCollectionType

type MetricGranularityType <: AbstractAWSType
    granularity::Union{Void,String}
    function MetricGranularityType(;granularity=nothing)
        new(granularity)
    end
    MetricGranularityType(pd) = parse_from_xml(MetricGranularityType, AutoScalingTypeDict, pd)
end # MetricGranularityType
export MetricGranularityType

type NotificationConfiguration <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    notificationType::Union{Void,String}
    topicARN::Union{Void,String}
    function NotificationConfiguration(;autoScalingGroupName=nothing, notificationType=nothing, topicARN=nothing)
        new(autoScalingGroupName, notificationType, topicARN)
    end
    NotificationConfiguration(pd) = parse_from_xml(NotificationConfiguration, AutoScalingTypeDict, pd)
end # NotificationConfiguration
export NotificationConfiguration

type PredefinedMetricSpecification <: AbstractAWSType
    predefinedMetricType::Union{Void,String}
    resourceLabel::Union{Void,String}
    function PredefinedMetricSpecification(;predefinedMetricType=nothing, resourceLabel=nothing)
        new(predefinedMetricType, resourceLabel)
    end
    PredefinedMetricSpecification(pd) = parse_from_xml(PredefinedMetricSpecification, AutoScalingTypeDict, pd)
end # PredefinedMetricSpecification
export PredefinedMetricSpecification

type ProcessType <: AbstractAWSType
    processName::Union{Void,String}
    function ProcessType(;processName=nothing)
        new(processName)
    end
    ProcessType(pd) = parse_from_xml(ProcessType, AutoScalingTypeDict, pd)
end # ProcessType
export ProcessType

type StepAdjustment <: AbstractAWSType
    metricIntervalLowerBound::Union{Void,Float64}
    metricIntervalUpperBound::Union{Void,Float64}
    scalingAdjustment::Union{Void,Int64}
    function StepAdjustment(;metricIntervalLowerBound=nothing, metricIntervalUpperBound=nothing, scalingAdjustment=nothing)
        new(metricIntervalLowerBound, metricIntervalUpperBound, scalingAdjustment)
    end
    StepAdjustment(pd) = parse_from_xml(StepAdjustment, AutoScalingTypeDict, pd)
end # StepAdjustment
export StepAdjustment

type TargetTrackingConfiguration <: AbstractAWSType
    customizedMetricSpecification::Union{Void,CustomizedMetricSpecification}
    disableScaleIn::Union{Void,Bool}
    predefinedMetricSpecification::Union{Void,PredefinedMetricSpecification}
    targetValue::Union{Void,Float64}
    function TargetTrackingConfiguration(;customizedMetricSpecification=nothing, disableScaleIn=nothing, predefinedMetricSpecification=nothing, targetValue=nothing)
        new(customizedMetricSpecification, disableScaleIn, predefinedMetricSpecification, targetValue)
    end
    TargetTrackingConfiguration(pd) = parse_from_xml(TargetTrackingConfiguration, AutoScalingTypeDict, pd)
end # TargetTrackingConfiguration
export TargetTrackingConfiguration

type ScalingPolicy <: AbstractAWSType
    adjustmentType::Union{Void,String}
    alarms::Union{Void,Array{Alarm,1}}
    autoScalingGroupName::Union{Void,String}
    cooldown::Union{Void,Int64}
    estimatedInstanceWarmup::Union{Void,Int64}
    metricAggregationType::Union{Void,String}
    minAdjustmentMagnitude::Union{Void,Int64}
    minAdjustmentStep::Union{Void,Int64}
    policyARN::Union{Void,String}
    policyType::Union{Void,String}
    scalingAdjustment::Union{Void,Int64}
    stepAdjustments::Union{Void,Array{StepAdjustment,1}}
    targetTrackingConfiguration::Union{Void,TargetTrackingConfiguration}
    function ScalingPolicy(;adjustmentType=nothing, alarms=nothing, autoScalingGroupName=nothing, cooldown=nothing, estimatedInstanceWarmup=nothing, metricAggregationType=nothing, minAdjustmentMagnitude=nothing, minAdjustmentStep=nothing, policyARN=nothing, policyType=nothing, scalingAdjustment=nothing, stepAdjustments=nothing, targetTrackingConfiguration=nothing)
        new(adjustmentType, alarms, autoScalingGroupName, cooldown, estimatedInstanceWarmup, metricAggregationType, minAdjustmentMagnitude, minAdjustmentStep, policyARN, policyType, scalingAdjustment, stepAdjustments, targetTrackingConfiguration)
    end
    ScalingPolicy(pd) = parse_from_xml(ScalingPolicy, AutoScalingTypeDict, pd)
end # ScalingPolicy
export ScalingPolicy

type ScheduledUpdateGroupAction <: AbstractAWSType
    autoScalingGroupName::Union{Void,String}
    desiredCapacity::Union{Void,Int64}
    endTime::Union{Void,DateTime}
    maxSize::Union{Void,Int64}
    minSize::Union{Void,Int64}
    recurrence::Union{Void,String}
    scheduledActionARN::Union{Void,String}
    scheduledActionName::Union{Void,String}
    startTime::Union{Void,DateTime}
    time::Union{Void,DateTime}
    function ScheduledUpdateGroupAction(;autoScalingGroupName=nothing, desiredCapacity=nothing, endTime=nothing, maxSize=nothing, minSize=nothing, recurrence=nothing, scheduledActionARN=nothing, scheduledActionName=nothing, startTime=nothing, time=nothing)
        new(autoScalingGroupName, desiredCapacity, endTime, maxSize, minSize, recurrence, scheduledActionARN, scheduledActionName, startTime, time)
    end
    ScheduledUpdateGroupAction(pd) = parse_from_xml(ScheduledUpdateGroupAction, AutoScalingTypeDict, pd)
end # ScheduledUpdateGroupAction
export ScheduledUpdateGroupAction

type Tag <: AbstractAWSType
    key::Union{Void,String}
    propagateAtLaunch::Union{Void,Bool}
    resourceId::Union{Void,String}
    resourceType::Union{Void,String}
    value::Union{Void,String}
    function Tag(;key=nothing, propagateAtLaunch=nothing, resourceId=nothing, resourceType=nothing, value=nothing)
        new(key, propagateAtLaunch, resourceId, resourceType, value)
    end
    Tag(pd) = parse_from_xml(Tag, AutoScalingTypeDict, pd)
end # Tag
export Tag


text:
using Libdl

const depsfile = joinpath(dirname(@__FILE__), "deps.jl")
if isfile(depsfile)
    rm(depsfile)
end

function write_depsfile(path)
    open(depsfile, "w") do f
        println(f, "const libcplex = \"$(escape_string(path))\"")
    end
end

function library_name(v)
    cpx_prefix = Sys.iswindows() ? "" : "lib"
    return "$(cpx_prefix)cplex$(v).$(Libdl.dlext)"
end

function try_local_installation()
    # Find the path to the CPLEX executable.
    cplex_path = try
        @static if Sys.isapple() || Sys.isunix()
            dirname(strip(read(`which cplex`, String)))
        elseif Sys.iswindows()
            dirname(strip(read(`where cplex`, String)))
        end
    catch
        nothing
    end

    # Iterate through a series of places where CPLEX could be found: either in
    # the path (directly the callable library or # the CPLEX executable) or from
    # an environment variable.
    cpxvers = [
        "128", "1280", "129", "1290", "12100"
    ]
    base_env = "CPLEX_STUDIO_BINARIES"

    libnames = String["cplex"]
    for v in reverse(cpxvers)
        name = library_name(v)
        push!(libnames, name)
        if cplex_path !== nothing
            push!(libnames, joinpath(cplex_path, name))
        end
        for env in [base_env, base_env * v]
            if !haskey(ENV, env)
                continue
            end
            for d in split(ENV[env], ';')
                push!(libnames, joinpath(d, name))
            end
        end
    end

    # Perform the actual search in the potential places.
    for l in libnames
        d = Libdl.dlopen_e(l)
        d == C_NULL && continue
        write_depsfile(Libdl.dlpath(d))
        @info("Using CPLEX found in location `$(l)`")
        return
    end
    error(
        "Unable to locate CPLEX installation. Note this must be downloaded " *
        "separately. See the CPLEX.jl README for further instructions."
    )
end

function try_travis_installation()
    url = ENV["SECRET_CPLEX_URL"]
    local_filename = joinpath(@__DIR__, "libcplex.so")
    download(url, local_filename)
    write_depsfile(local_filename)
end

if get(ENV, "TRAVIS", "false") == "true"
    try_travis_installation()
else
    try_local_installation()
end


text:
#=
Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.

For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.

In this example, assume nodes with the same value are the exact same node objects.

Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space.
=#
struct Node
    val::Int64
    next::Union{Nothing, Node}
end

function findintersect(A::Node, B::Node)
    all_nodes_A = Node[]
    current_node = A
    while !isnothing(current_node)
        push!(all_nodes_A, current_node)
        current_node = current_node.next
    end
    intersecting_node = B
    while !(intersecting_node in all_nodes_A)
        intersecting_node = intersecting_node.next
    end
    return intersecting_node
end

max_stars_repo_name: DominiqueCaron/daily-coding-problem

max_issues_repo_name: DominiqueCaron/daily-coding-problem

max_forks_repo_name: DominiqueCaron/daily-coding-problem


text:
module UnicodeFun

using REPL

# Here, we collect and reverse the REPL's latex autocompletion map.
const symbols_unsorted = [k[2:end] => v[1] for (k, v) in REPL.REPLCompletions.latex_symbols]

const latex_symbol_map = sort!(symbols_unsorted, by=(x)-> length(x[1]), rev=true)

include("sub_super_scripts.jl")
export to_superscript, to_subscript
export to_fraction, to_fraction_nl

include("fontstyles.jl")
export to_blackboardbold
export to_boldface
export to_italic
export to_caligraphic
export to_frakture
export to_underline
export to_overline

include("latex.jl")
export to_latex

include("roots.jl")
export to_root

end # module


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:4] <= 1)

                     @variable(m, -13.266290625856113 <= q <= 11.094199160852137)

                     add_NL_constraint(m, :(sigmoid(-0.2977454197977769 + 0.7722469146312885*sigmoid(0.9100824262656433 + 0.0704650714228956*sigmoid(-0.7110372864748489 + -0.3189000958940382*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.039301419137926175*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.19790129907631693*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.8966302258455006*sigmoid(0.7299768289984225 + 0.7045346620386517*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.8068588624409387*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + 0.8888276792068996*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.7890296052704904*sigmoid(-0.5099367345236407 + -0.3810722083004521*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.4850891682061631*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.158929561309892*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4])))) + 0.5815923034237733*sigmoid(-0.15598180224250147 + 0.7627892034632455*sigmoid(-0.7110372864748489 + -0.3189000958940382*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.039301419137926175*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.19790129907631693*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.6806349200893864*sigmoid(0.7299768289984225 + 0.7045346620386517*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.8068588624409387*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + 0.8888276792068996*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + -0.163059274878961*sigmoid(-0.5099367345236407 + -0.3810722083004521*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.4850891682061631*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.158929561309892*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4])))) + -0.731486602090937*sigmoid(-0.9577813343303001 + 0.660774759467007*sigmoid(-0.7110372864748489 + -0.3189000958940382*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.039301419137926175*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.19790129907631693*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + -0.16269598559087406*sigmoid(0.7299768289984225 + 0.7045346620386517*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.8068588624409387*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + 0.8888276792068996*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.9308521240523335*sigmoid(-0.5099367345236407 + -0.3810722083004521*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.4850891682061631*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.158929561309892*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))))) + sigmoid(0.23088458854123672 + 0.9025271253252471*sigmoid(0.9100824262656433 + 0.0704650714228956*sigmoid(-0.7110372864748489 + -0.3189000958940382*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.039301419137926175*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.19790129907631693*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.8966302258455006*sigmoid(0.7299768289984225 + 0.7045346620386517*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.8068588624409387*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + 0.8888276792068996*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.7890296052704904*sigmoid(-0.5099367345236407 + -0.3810722083004521*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.4850891682061631*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.158929561309892*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4])))) + 0.9612479731086991*sigmoid(-0.15598180224250147 + 0.7627892034632455*sigmoid(-0.7110372864748489 + -0.3189000958940382*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.039301419137926175*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.19790129907631693*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.6806349200893864*sigmoid(0.7299768289984225 + 0.7045346620386517*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.8068588624409387*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + 0.8888276792068996*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + -0.163059274878961*sigmoid(-0.5099367345236407 + -0.3810722083004521*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.4850891682061631*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.158929561309892*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4])))) + 0.9633061422344626*sigmoid(-0.9577813343303001 + 0.660774759467007*sigmoid(-0.7110372864748489 + -0.3189000958940382*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.039301419137926175*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.19790129907631693*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + -0.16269598559087406*sigmoid(0.7299768289984225 + 0.7045346620386517*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.8068588624409387*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + 0.8888276792068996*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.9308521240523335*sigmoid(-0.5099367345236407 + -0.3810722083004521*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.4850891682061631*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.158929561309892*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))))) + sigmoid(-0.8299198997441475 + 0.7709117851978275*sigmoid(0.9100824262656433 + 0.0704650714228956*sigmoid(-0.7110372864748489 + -0.3189000958940382*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.039301419137926175*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.19790129907631693*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.8966302258455006*sigmoid(0.7299768289984225 + 0.7045346620386517*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.8068588624409387*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + 0.8888276792068996*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.7890296052704904*sigmoid(-0.5099367345236407 + -0.3810722083004521*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.4850891682061631*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.158929561309892*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4])))) + 0.5338511667423695*sigmoid(-0.15598180224250147 + 0.7627892034632455*sigmoid(-0.7110372864748489 + -0.3189000958940382*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.039301419137926175*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.19790129907631693*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.6806349200893864*sigmoid(0.7299768289984225 + 0.7045346620386517*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.8068588624409387*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + 0.8888276792068996*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + -0.163059274878961*sigmoid(-0.5099367345236407 + -0.3810722083004521*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.4850891682061631*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.158929561309892*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4])))) + 0.3695524647159538*sigmoid(-0.9577813343303001 + 0.660774759467007*sigmoid(-0.7110372864748489 + -0.3189000958940382*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.039301419137926175*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.19790129907631693*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + -0.16269598559087406*sigmoid(0.7299768289984225 + 0.7045346620386517*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.8068588624409387*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + 0.8888276792068996*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))) + 0.9308521240523335*sigmoid(-0.5099367345236407 + -0.3810722083004521*sigmoid(0.8606897861111369 + 0.08970944375635792*$(x[1]) + 0.5451334799438907*$(x[2]) + -0.8811882246809297*$(x[3]) + -0.4223772070829366*$(x[4])) + 0.4850891682061631*sigmoid(0.47662806300654736 + 0.5011612847792533*$(x[1]) + 0.5521868073085425*$(x[2]) + 0.45455279409713745*$(x[3]) + -0.33071846313642217*$(x[4])) + -0.158929561309892*sigmoid(-0.45543581836352764 + -0.399986773274851*$(x[1]) + -0.07747330631488092*$(x[2]) + -0.8376058727182878*$(x[3]) + 0.18120897903061906*$(x[4]))))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
"""
$(SIGNATURES)
reads the high voltages of the wavesets saved in the hdf5 file
# Arguments
- `filename`: filename of h5 file
"""
function high_voltages(filename)
    h5 = h5open(filename, "r")
    high_voltages = keys(h5)
    close(h5)
    high_voltages
end

struct WaveSet
    waveforms
    v_gain
    h_int
    function WaveSet(filename, hv)
        waveforms_raw = h5read(filename, "$hv/waveforms")
        v_gain = h5read(filename, "$hv/waveform_info/v_gain")
        h_int = h5read(filename, "$hv/waveform_info/h_int")
        new(waveforms_raw .* v_gain, v_gain, h_int)
    end
end

"""
$(SIGNATURES)
calculates charges of waveforms of a waveset
# Arguments
- `waveforms => Matrix{Float64}`: waveforms
- `ped_min`: start of pedestal integration window
- `ped_max`: end of pedestal integration window
- `sig_min`: start of signal integration window
- `sig_min`: end of signal integration window
"""
function calculate_charges(waveforms, ped_min, ped_max, sig_min, sig_max)
    ped_sig_ratio = (ped_max - ped_min) / (sig_max - sig_min)
    pedestal = sum(waveforms[ped_min:ped_max, :], dims=1)
    charges = -(sum(waveforms[sig_min:sig_max, :], dims=1) - pedestal / ped_sig_ratio)
    vec(charges);
end

function bin_data(data, steprange::StepRangeLen)
    hist = append!(Histogram(steprange), data)
    edges = collect(hist.edges[1])
    x = edges .+ (edges[2] - edges[1]) / 2
    x = x[1:end-1]
    y = hist.weights
    x, y
end

struct ChargeDist
    x
    y
end

"""
    $(SIGNATURES)
    constructor
    # Arguments
    - `charges => Vector{Float64}`: charges from which charge distribution is
                                    constructed
    - `steprange => StepRangeLen`: steprange for binning of the charges
    """
function ChargeDist(charges, steprange::StepRangeLen)
    x, y = bin_data(charges, steprange)
    ChargeDist(x, y)
end

"""
    $(SIGNATURES)
    alternative constructor
    # Arguments
    - `charges => Vector{Float64}`: charges from which charge distribution is
                                    constructed
    - `bins => Integer`: number of bins for binning of the charges
    - `lower`: lower edge for binning of the charges; default: -1
    - `upper`: upper edge for binning of the charges; default: 1
    """
ChargeDist(charges, bins::Integer; lower=-1, upper=1) = ChargeDist(charges, range(lower, upper; length=bins+1))

abstract type FitResults end

struct PreFit <: FitResults
    μₚ
    σₚ
    Aₚ
    μₛ
    σₛ
    Aₛ
end

struct PMTRespFit <: FitResults
    μₚ
    σₚ
    μₛ
    σₛ
    nₚₑ
    A
end

struct PMTRespUapFit <: FitResults
    μₚ
    σₚ
    μₛ
    σₛ
    nₚₑ
    A
    μᵤₐₚ
    σᵤₐₚ
    Aᵤₐₚ
end

"""
    $(SIGNATURES)
    normalized gaussian function
"""
norm_gauss(x, p) = exp.(.-(x .- p[1]).^2/(2 .* p[2] .^ 2)) ./ sqrt.(2π) ./ p[2]

"""
    $(SIGNATURES)
    gaussian function
"""
gauss(x, p) = p[3] .* exp.(.-(x .- p[1]).^2/(2 .* p[2] .^ 2)) ./ sqrt.(2π) ./ p[2]

"""
    $(SIGNATURES)
    PMT response function
"""
function pmtresp(x, p)
    poisson = Poisson(abs(p[5]))
    n_gaussians = 10
    pedestal = pdf(poisson, 0) .* norm_gauss(x, [p[1], p[2]])
    signal = zeros(length(x))
    for i in 1:n_gaussians
        signal .+= pdf(poisson, i) .* norm_gauss(x, [p[3] .* i, sqrt(i) .* p[4]])
    end
    p[6] .* (pedestal .+ signal)
end

function pmtresp(x, fit::PMTRespFit)
    pmtresp(x, [fit.μₚ, fit.σₚ, fit.μₛ, fit.σₛ, fit.nₚₑ, fit.A])
end

"""
    $(SIGNATURES)
    PMT response function with under amplified pulses modification
"""
function pmtresp_uap(x, p)
    poisson = Poisson(abs(p[5]))
    n_gaussians = 10
    pedestal = pdf(poisson, 0) .* norm_gauss(x, [p[1], p[2]])
    signal = zeros(length(x))
    for i in 1:n_gaussians
        signal .+= pdf(poisson, i) .* norm_gauss(x, [p[3] .* i, sqrt(i) .* p[4]])
    end
    p[6] .* (pedestal .+ signal) .+ gauss(x, [p[7], p[8], p[9]])
end

function pmtresp_uap(x, fit::PMTRespUapFit)
    pmtresp_uap(x, [fit.μₚ, fit.σₚ, fit.μₛ, fit.σₛ, fit.nₚₑ, fit.A, fit.μᵤₐₚ, fit.σᵤₐₚ, fit.Aᵤₐₚ])
end

"""
    $(SIGNATURES)
    calculates maximum for baseline calculation of a set of waveforms
    # Arguments
    - `waveforms => Matrix{Float64}`: set of waveforms
"""
function baseline_max(waveforms::Matrix{Float64})
    floor(Int32, argmin(mean(waveforms, dims=2)).I[1] * 0.75)
end

"""
    $(SIGNATURES)
    subtracts baseline from a set of waveforms, i.e. sets baseline to 0
    # Arguments
    - `waveforms => Matrix{Float64}`: set of waveforms
    - `baseline_range => Tuple`: range in which mean of baseline is calculated
                                 (default: nothing => baseline_max is used to calculate range)
"""
function subtract_baseline(waveforms::Matrix{Float64}; baseline_range=nothing)
    if baseline_range==nothing
        baseline_range = (1, baseline_max(waveforms))
    end
    waveforms .- mean(waveforms[baseline_range[1]:baseline_range[2], :], dims=1)
end

"""
    $(SIGNATURES)
    calculates transit times of a set of waveforms
    # Arguments
    - `waveforms => Matrix{Float64}`: set of waveforms
    - `threshold`: first pass of threshold => transit time
"""
function calculate_transit_times(waveforms::Matrix{Float64}, threshold)
    waveforms = waveforms .- mean(waveforms[1:baseline_max(waveforms), :], dims=1)
    n, m = size(waveforms)
    transit_times = zeros(m)
    for j in 1:m
        for i in 1:n
            value = waveforms[i,j]
            if value < threshold
                transit_times[j] = i - 1
                break
            end
        end
    end
    transit_times[transit_times .!= 0]
end

"""
    $(SIGNATURES)
    shifts waveforms by its minimum and calculates mean waveform
    # Arguments
    - `waveforms => Matrix{Float64}`: set of waveforms
"""
function mean_waveform(waveforms::Matrix{Float64})
    a, b = size(waveforms)
    shifted_waveforms = Matrix{Float64}(undef, a, b)
    for j in 1:b
        minval, minidx = findmin(waveforms[:, j])
        for i in 1:a
            shift = floor(Int32, a/2)
            shifted_i = i - minidx + shift
            if shifted_i > a
                shifted_waveforms[shifted_i - a, j] = waveforms[i, j]
            elseif shifted_i < 1
                shifted_waveforms[shifted_i + a, j] = waveforms[i, j]
            else
                shifted_waveforms[shifted_i, j] = waveforms[i, j]
            end
        end
    end
    vec(mean(shifted_waveforms, dims=2))
end

"""
    $(SIGNATURES)
    simulations PMT charge spectrum with Poisson distributed
    secondary emission coefficients at each dynode
    # Arguments
    - `nₚₑ`: mean number of photoelectrons
    - `N`: number of simulated charges
    - `σₚ`: Gaussian sigma of pedestal (default: 1e5)
    - `secs`: secondary emission coefficients
              (default: (7, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5))
"""
function simulate_charges(nₚₑ, N;
                          σₚ=1e5,
                          secs=(7, 4.5, 4.5, 4.5, 4.5,
                                4.5, 4.5, 4.5, 4.5, 4.5))
    charges = Float64[]
    for i in 1:N
        pes = rand(Poisson(nₚₑ))
        gaussian = Normal(0., σₚ)
        if pes == 0
            push!(charges, rand(gaussian))
        else
            charge = 0
            for i in 1:pes
                e = rand(Poisson(secs[1]))
                for i in 2:10
                    e = rand(Poisson(e * secs[i]))
                end
                charge += e
            end
            push!(charges, charge + rand(gaussian))
        end
    end
    charges
end


text:
# Rational Quadratic Isotropic Covariance Function

@doc """
# Description
Constructor for the isotropic Rational Quadratic kernel (covariance)

k(x,x') = σ²(1+(x-x')ᵀ(x-x')/2αℓ²)^{-α}
# Arguments:
* `ll::Float64`: Log of length scale ℓ
* `lσ::Float64`: Log of the signal standard deviation σ
* `lα::Float64`: Log of shape parameter α
""" ->
type RQIso <: Isotropic
    ℓ2::Float64      # Length scale
    σ2::Float64      # Signal std
    α::Float64       # shape parameter
    RQIso(ll::Float64, lσ::Float64, lα::Float64) = new(exp(2*ll), exp(2*lσ), exp(lα))
end

function set_params!(rq::RQIso, hyp::Vector{Float64})
    length(hyp) == 3 || throw(ArgumentError("Rational Quadratic function has three parameters"))
    rq.ℓ2, rq.σ2, rq.α = exp(2.0*hyp[1]), exp(2.0*hyp[2]), exp(hyp[3])
end

get_params(rq::RQIso) = Float64[log(rq.ℓ2)/2.0, log(rq.σ2)/2.0, log(rq.α)]
get_param_names(rq::RQIso) = [:ll, :lσ, :lα]
num_params(rq::RQIso) = 3

metric(rq::RQIso) = SqEuclidean()
cov(rq::RQIso, r::Float64) = rq.σ2*(1.0+r/(2.0*rq.α*rq.ℓ2)).^(-rq.α)

function grad_kern(rq::RQIso, x::Vector{Float64}, y::Vector{Float64})
    r = distance(rq, x, y)

    g1 = rq.σ2*(r/rq.ℓ2)*(1.0+r/(2*rq.α*rq.ℓ2))^(-rq.α-1.0)       # dK_d(log ℓ)
    g2 = 2.0*rq.σ2*(1+r/(2*rq.α*rq.ℓ2))^(-rq.α)                   # dK_d(log σ)
    part = (1.0+r/(2*rq.α*rq.ℓ2))
    g3 = rq.σ2*part^(-rq.α)*(r/(2*rq.ℓ2*part)-rq.α*log(part))*rq.α  # dK_d(log α)
    return [g1,g2,g3]
end

function grad_stack!(stack::AbstractArray, rq::RQIso, X::Matrix{Float64}, data::IsotropicData)
    nobsv = size(X,2)
    R = distance(rq, X, data)

    for i in 1:nobsv, j in 1:i
        # Check these derivatives!
        @inbounds stack[i,j,1] = rq.σ2*((R[i,j])/rq.ℓ2)*(1.0+(R[i,j])/(2*rq.α*rq.ℓ2))^(-rq.α-1.0)  # dK_d(log ℓ)dK_dℓ
        @inbounds stack[i,j,2] = 2.0*rq.σ2*(1+(R[i,j])/(2*rq.α*rq.ℓ2))^(-rq.α) # dK_d(log σ)

        part = (1.0+R[i,j]/(2*rq.α*rq.ℓ2))
        @inbounds stack[i,j,3] = rq.σ2*part^(-rq.α)*((R[i,j])/(2*rq.ℓ2*part)-rq.α*log(part))*rq.α  # dK_d(log α)

        @inbounds stack[j,i,1] = stack[i,j,1]
        @inbounds stack[j,i,3] = stack[i,j,3]
        @inbounds stack[j,i,2] = stack[i,j,2]
    end
    return stack
end


text:
#let's make sure our boolean operations behave.

#NOT
@test_string "Wire{7:0v}(0b01101011)" string(~Wire(0b10010100))

#AND
@test_string "Wire{7:0v}(0b10000100)" Wire(0b10010100) & Wire(0b10100110)

#OR
@test_string "Wire{7:0v}(0b10110110)" Wire(0b10010100) | Wire(0b10100110)


text:
function getCAndP(cls)
    if isa(cls, Symbol)
        C, P = cls, [:Any]
    elseif cls.head == :curly
        C, P = cls, [:Any]
    elseif cls.head == :call
        C = cls.args[1]
        P = cls.args[2:end]
    else
        error("getCAndP: case not handled")
    end
    return C, P
end

function getAbstractCls(cls)
    abs = x::Symbol -> x==:Any ? :Any : Symbol(string("Abstract", cls))
    if isa(cls, Array)
        return map(abs, cls)
    else
        return abs(cls)
    end
end

function copyFields(ParentClsNameLst, ClsFields)
    res = Vector{Expr}()
    for parent in ParentClsNameLst
        conflict = intersect(res, ClsFields[parent])
        if length(conflict)!=0
            warn(join(conflict, ", ") * " in $patent overwritten")
        end
        res = union(res, ClsFields[parent])
    end
    return res
end


text:
module MaxHelpingHandCustomMemorialWithDreamingAttribute

using ..Ahorn, Maple

@mapdef Entity "MaxHelpingHand/CustomMemorialWithDreamingAttribute" CustomMemorialWithDreamingAttribute(x::Integer, y::Integer,
    dreaming::Bool=false, dialog::String="MEMORIAL", sprite::String="scenery/memorial/memorial", spacing::Integer=16)

const placements = Ahorn.PlacementDict(
    "Custom Memorial (Dreaming) (max480's Helping Hand)" => Ahorn.EntityPlacement(
        CustomMemorialWithDreamingAttribute,
        "point",
        Dict{String, Any}(
            "dreaming" => true
        )
    ),
    "Custom Memorial (Not Dreaming) (max480's Helping Hand)" => Ahorn.EntityPlacement(
        CustomMemorialWithDreamingAttribute
    )
)

sprite = "scenery/memorial/memorial"

function Ahorn.selection(entity::CustomMemorialWithDreamingAttribute)
    x, y = Ahorn.position(entity)

    spriteName = get(entity.data, "sprite", sprite)
    customSprite = Ahorn.getSprite(spriteName, "Gameplay")

    if customSprite.width == 0 || customSprite.height == 0
        return Ahorn.Rectangle(x - 4, y - 4, 8, 8)

    else
        return Ahorn.getSpriteRectangle(spriteName, x, y, jx=0.5, jy=1.0)
    end
end

function Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::CustomMemorialWithDreamingAttribute, room::Maple.Room)
    spriteName = get(entity.data, "sprite", sprite)

    Ahorn.drawSprite(ctx, spriteName, 0, 0, jx=0.5, jy=1.0)
end

end

max_stars_repo_name: Kitty-Cats/MaxHelpingHand

max_issues_repo_name: Kitty-Cats/MaxHelpingHand

max_forks_repo_name: Kitty-Cats/MaxHelpingHand


text:
struct LinearTransformation{T}
    s::T         # Scaling
    R::Matrix{T} # Rotation
    b::Vector{T} # Bias

    function LinearTransformation(s::T, R::Matrix{T}, b::Vector{T}) where T <: Real
        new{T}(s, R, b)
    end
end

function Base.show(io::IO, ::MIME"text/plain", tr::LinearTransformation)
    print("s = ")
    show(io, "text/plain", tr.s)
    println()
    print("R = ")
    show(io, "text/plain", tr.R)
    println()
    print("b = ")
    show(io, "text/plain", tr.b)
end

"""
    apply(tr::LinearTransformation, X::Matrix{T}) where T <: Real

Apply a linear transformation (scaling, rotation, and bias) to the matrix X.
"""
function apply(tr::LinearTransformation, X::Matrix{T}) where T <: Real
    # Xᶜ = X * V(size(X, 2)) # Centers the (columns of the) matrix
    # return broadcast(+, tr.s * tr.R * Xᶜ, tr.b)
    return broadcast(+, tr.s * tr.R * X, tr.b)
end

"""
    apply(tr::LinearTransformation, X::Embedding{T}) where T <: Real

Apply a linear transformation (scaling, rotation, and bias) to the Embedding X.
"""
function apply(tr::LinearTransformation, X::Embedding{T}) where T <: Real
    X.X = apply(tr, X.X)
    return X
end

"""
    apply(tr::LinearTransformation, X::Matrix{T}, x::Vector{T}) where T <: Real

Apply an out-of-sample linear transformation (scaling, rotation, and bias) to the vector x,
where the transformation has been computed for the matrix X.
"""
function apply(tr::LinearTransformation, X::Vector{T}) where T<:Real
    return broadcast(+, tr.s * tr.R * X, tr.b)
end

"""
    procrustes(X::Embedding{T}, Y::Matrix{T}) where T <: Real

Compute the optimal scaling, rotation, and translation for X to match Y in the least
squares sense. X should be the same size as Y.

The algorithm to find the optimal rotation and translation is also known as Kabsch algorithm.

---

    procrustes(X::AbstractMatrix{T}, Y::Matrix{T}) where T <: Real

Compute the optimal scaling, rotation, and translation for X to match Y in the least
squares sense. X should be the same size as Y.

The algorithm to find the optimal rotation and translation is also known as Kabsch algorithm.

# References

    1. Dokmanic, I., Parhizkar, R., Ranieri, J., & Vetterli, M. (2015). Euclidean
       distance matrices: essential theory, algorithms, and applications.
       IEEE Signal Processing Magazine, 32(6), 12-30.
"""
function procrustes(X::Embedding{T1}, Y::AbstractMatrix{T2}) where {T1 <: Real, T2 <: Real}
    X.X, transform = procrustes(X.X, Y)
    return X, transform
end

function procrustes!(X::Embedding{T1}, Y::AbstractMatrix{T2}) where {T1 <: Real, T2 <: Real}
    X, _ = procrustes(X, Y)
end

function procrustes(X::Matrix{T1}, Y::AbstractMatrix{T2}) where {T1 <: Real, T2 <: Real}
    # We *could* implement this for size(X) != size(Y) if needed...
    @assert size(X) == size(Y) "X and Y must be the same size"

    # Find the number of columns
    n = size(X, 2) # Number of columns in X
    m = size(Y, 2) # Number of columns in Y

    # Center both embeddings (so that the sum of their columns is the zeros vector)
    # The subscript for c is not defined in unicode :-(, so we use superscripts
    Xᶜ = X * V(n) # Centers the (columns of the) Embedding
    Yᶜ = Y * V(m) # Centers the (columns of the) Embedding

    # We use the SVD to find the optimal rotation matrix
    U, S, W = svd(Xᶜ * Yᶜ')
    R = W * U' # Optimal rotation matrix

    # We can now find the best scaling, after the embeddings are centered and
    # have the same orientation. The scaling is found by solving min_s ||s * X - Y||_F^2
    s = norm(Yᶜ) / norm(Xᶜ)

    # We finally compute the bias
    b = Y * ones(m)/m # Equivalent to mean(Y, dims=2), the mean over the columns of Y

    transform = LinearTransformation(s, R, dropdims(- s * R * mean(X, dims=2) + b, dims=2))
    # We finally scale, rotate, and translate the embedding X to match Y as best as possible
    return apply(transform, X), transform
end

function mse(X::Embedding{T}, Y::AbstractMatrix{T}) where T <: Real
    return norm(X.X - Y)^2/(nitems(X) * ndims(X))
end

function mse(X::AbstractMatrix{T}, Y::AbstractMatrix{T}) where T <: Real
    return norm(X.X - Y)^2/(nitems(X) * ndims(X))
end


text:
facts("Sensors") do

    fname = joinpath(dirname(@__FILE__), "..", "..", "data", "test.sfp")
    s = read_sfp(fname)

    context("Read file") do

        s = read_sfp(fname)
        @fact length(s) --> 3
    end

    context("Show") do

        show(s)
        show(s[1])
    end

    context("Info") do

        @fact label(s) --> ["Fp1", "Fpz", "Fp2"]
        @fact label(s[1]) --> "Fp1"
        @fact labels(s) --> ["Fp1", "Fpz", "Fp2"]
        @fact labels(s[1]) --> "Fp1"

        @fact EEG.x(s) --> [-27.747648, -0.085967, 27.676888]
        @fact EEG.x(s[1]) --> -27.747648

        @fact EEG.y(s) --> [98.803864, 103.555275, 99.133354]
        @fact EEG.y(s[1]) --> 98.803864

        @fact EEG.z(s) --> [34.338360, 34.357265, 34.457005]
        @fact EEG.z(s[1]) --> 34.338360
    end

    context("Matching") do

        a, b = match_sensors(s, ["Fp1", "Fp2"])

    end

    context("Leadfield matching") do

        L = ones(4, 3, 5)
        L[:, :, 2] = L[:, :, 2] * 2
        L[:, :, 3] = L[:, :, 3] * 3
        L[:, :, 4] = L[:, :, 4] * 4
        L[:, :, 5] = L[:, :, 5] * 5

        L, idx = match_sensors(L, ["meh", "Cz", "Fp1", "Fp2", "eh"], ["Fp2", "Cz"])

        @fact size(L) --> (4, 3, 2)
        @fact L[:, :, 1] --> ones(4, 3) * 4
        @fact L[:, :, 2] --> ones(4, 3) * 2
        @fact idx --> [4, 2]

    end

    context("Standard sets") do

        @fact length(EEG_64_10_20) --> 64
        @fact length(EEG_Vanvooren_2014) --> 18
        @fact length(EEG_Vanvooren_2014_Left) --> 9
        @fact length(EEG_Vanvooren_2014_Right) --> 9

    end

end


text:
module TestModelAPI

using Test
using MLJBase
import MLJModelInterface
using ..Models
using Distributions
using StableRNGs
using JLSO

rng = StableRNG(661)

@testset "predict_*" begin
    X = (x = rand(rng, 5),)
    yfinite = categorical(collect("abaaa"))
    ycont = float.(1:5)

    clf = ConstantClassifier()
    fitresult, _, _ = MLJBase.fit(clf, 1, X, yfinite)
    @test predict_mode(clf, fitresult, X)[1] == 'a'
    @test_throws ArgumentError predict_mean(clf, fitresult, X)
    @test_throws ArgumentError predict_median(clf, fitresult, X)

    rgs = ConstantRegressor()
    fitresult, _, _ = MLJBase.fit(rgs, 1, X, ycont)
    @test predict_mean(rgs, fitresult, X)[1] == 3
    @test predict_median(rgs, fitresult, X)[1] == 3
    @test_throws ArgumentError predict_mode(rgs, fitresult, X)
end

end
true


text:
#!/usr/bin/env julia

using MIToS.Utils.Scripts

Args = parse_commandline(
    # TO DO ----------------------------------------------------------------------
    ["--distance", "-d"],
    Dict(
        :help => "The distance to be calculated, options: All, Heavy, CA, CB",
        :arg_type => ASCIIString,
        :default => "All"
    ),
    ["--format", "-f"],
    Dict(
        :help => "Format of the PDB file: It should be PDBFile or PDBML",
        :arg_type => ASCIIString,
        :default => "PDBFile"
    ),
    ["--model", "-m"],
    Dict(
        :help => "The model to be used, * for all",
        :arg_type => ASCIIString,
        :default => "1"
    ),
    ["--chain", "-c"],
    Dict(
        :help => "The chain to be used, * for all",
        :arg_type => ASCIIString,
        :default => "*"
    ),
    ["--group", "-g"],
    Dict(
        :help => "Group of atoms to be used, should be ATOM, HETATM or * for all",
        :arg_type => ASCIIString,
        :default => "*"
    ),
    ["--inter", "-i"],
    Dict(
        :help => "Calculate inter chain distances",
        :action => :store_true
    ),
    # Keywords...
    description="""
    Calculates residues distance and writes them into a *.distances.csv.gz gzipped file.
    """,
    output=".distances.csv.gz"
    # ----------------------------------------------------------------------------
    )

set_parallel(Args["parallel"])

@everywhere begin

    const args = remotecall_fetch(1,()->Args)

    import MIToS.Utils.Scripts: script

    # TO DO ----------------------------------------------------------------------
    using MIToS.PDB
    # ----------------------------------------------------------------------------

    function script(input::Union{Base.LibuvStream,  AbstractString},
                    args,
                    fh_out::Union{Base.LibuvStream, IO})
        # TO DO ------------------------------------------------------------------
        println(fh_out, "# MIToS ", Pkg.installed("MIToS"), " Distances.jl ", now())
        println(fh_out, "# used arguments:")
        for (key, value) in args
            println(fh_out, "# \t", key, "\t\t", value)
        end
        println(fh_out, "model_i,chain_i,group_i,pdbe_i,number_i,name_i,model_j,chain_j,group_j,pdbe_j,number_j,name_j,distance")
        dtyp = ascii(args["distance"])
        form = ascii(args["format"])
        if form == "PDBFile"
            res = readorparse(input, PDBFile)
        elseif form == "PDBML"
            res = readorparse(input, PDBML)
        else
            throw(ErrorException("--format should be PDBFile or PDBML."))
        end
        res = residues(res, ascii(args["model"]), ascii(args["chain"]), ascii(args["group"]), "*")
        N = length(res)
        inter = !Bool(args["inter"])
        for i in 1:(N-1)
            for j in (i+1):N
                @inbounds res1 = res[i]
                @inbounds res2 = res[j]
                if inter && res1.id.chain != res2.id.chain
                    continue
                end
                dist = distance(res1, res2, criteria=dtyp)
                println(fh_out, res1.id.model, ",", res1.id.chain, ",", res1.id.group, ",", res1.id.PDBe_number, ",", res1.id.number, ",", res1.id.name, ",",
                        res2.id.model, ",", res2.id.chain, ",", res2.id.group, ",", res2.id.PDBe_number, ",", res2.id.number, ",", res2.id.name, ",",
                        dist )
            end
        end
        # ------------------------------------------------------------------------
    end

end

runscript(args)


text:
using CxxWrap

module JuliaCv
  using CxxWrap
  @wrapmodule(joinpath("/home/clynamen/software/sources/opencv/build/lib/julia/","cv2.so"))

  function __init__()
    @initcxx
  end
end

using .JuliaCv

# Call greet and show the result
#@show CppHello.greet()
print(JuliaCv.OGL_TEXTURE2D_RGBA)

max_stars_repo_name: clynamen/opencv

max_issues_repo_name: clynamen/opencv

max_forks_repo_name: clynamen/opencv


text:
using Base.Test, EPInference

@testset "imp.sampling" begin include("impsampl_test.jl") end


text:
using Hydra, Test

@testset "Features" begin
  include("features.jl")
end


text:
"""
    diagonal(A)

Get the diagonal of a 2d array of floats. This just calls the base diag
function.

# Arguments

- A = 2d array of floats

# Value

1d array of floats

"""
function diagonal(A::AbstractArray{Float64,2})

    return diag(A)
end

"""
    diagonal(A)

Get the diagonal of a 1d array of floats. Behaves like an identity function
(returns itself).

# Arguments

- A = 1d array of floats

# Value

1d array of floats

# Some notes

Originally intended for use when A is a 1 by 1 array, so may have unintended
consequences for a 1d array of length > 1.

"""
function diagonal(A::AbstractArray{Float64,1})

    return A
end

"""
    diagonal(A)

Get the diagonal of a single scalar (float) value. Behaves like an identity
function (returns itself).

# Arguments

- A = floating scalar

# Value

Floating scalar

"""
function diagonal(A::Float64)

    return A
end

"""
    kron_diag(A, B)

Compute the diagonal of the Kronecker product of arrays or scalars

# Arguments

- A = square 2d array of floats, a 1d array of floats, or a scalar
- B = square 2d array of floats, a 1d array of floats, or a scalar

# Value

2d array of floats

"""
function kron_diag(A, B)

    # Get the diagonals of A and B
    diagA = diagonal(A)
    diagB = diagonal(B)

    # Pre-allocate array to store resulting diagonal
    result = Array{Float64}(undef, length(diagB), length(diagA))
    # Iterate through all elements of diagonals and perform pairwise
    # multiplication
    for i in 1:length(diagA)
        result[:,i] .= diagA[i]*diagB
    end

    return result
end


text:
module TestRequest
	import HTTP: Layer, request, Response

	abstract type TestLayer{Next <: Layer} <: Layer{Next} end
	export TestLayer, request

	function request(::Type{TestLayer{Next}}, io::IO, req, body; kw...)::Response where Next
		return request(Next, io, req, body; kw...)
	end
end