text:
# Julia wrapper for header: /usr/include/scip/scip_datastructures.h
# Automatically generated using Clang.jl wrap_c

function SCIPcreateRealarray(scip, realarray)
    ccall((:SCIPcreateRealarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_REALARRAY}}), scip, realarray)
end

function SCIPfreeRealarray(scip, realarray)
    ccall((:SCIPfreeRealarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_REALARRAY}}), scip, realarray)
end

function SCIPextendRealarray(scip, realarray, minidx, maxidx)
    ccall((:SCIPextendRealarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_REALARRAY}, Cint, Cint), scip, realarray, minidx, maxidx)
end

function SCIPclearRealarray(scip, realarray)
    ccall((:SCIPclearRealarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_REALARRAY}), scip, realarray)
end

function SCIPgetRealarrayVal(scip, realarray, idx)
    ccall((:SCIPgetRealarrayVal, libscip), Cdouble, (Ptr{SCIP_}, Ptr{SCIP_REALARRAY}, Cint), scip, realarray, idx)
end

function SCIPsetRealarrayVal(scip, realarray, idx, val)
    ccall((:SCIPsetRealarrayVal, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_REALARRAY}, Cint, Cdouble), scip, realarray, idx, val)
end

function SCIPincRealarrayVal(scip, realarray, idx, incval)
    ccall((:SCIPincRealarrayVal, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_REALARRAY}, Cint, Cdouble), scip, realarray, idx, incval)
end

function SCIPgetRealarrayMinIdx(scip, realarray)
    ccall((:SCIPgetRealarrayMinIdx, libscip), Cint, (Ptr{SCIP_}, Ptr{SCIP_REALARRAY}), scip, realarray)
end

function SCIPgetRealarrayMaxIdx(scip, realarray)
    ccall((:SCIPgetRealarrayMaxIdx, libscip), Cint, (Ptr{SCIP_}, Ptr{SCIP_REALARRAY}), scip, realarray)
end

function SCIPcreateIntarray(scip, intarray)
    ccall((:SCIPcreateIntarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_INTARRAY}}), scip, intarray)
end

function SCIPfreeIntarray(scip, intarray)
    ccall((:SCIPfreeIntarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_INTARRAY}}), scip, intarray)
end

function SCIPextendIntarray(scip, intarray, minidx, maxidx)
    ccall((:SCIPextendIntarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_INTARRAY}, Cint, Cint), scip, intarray, minidx, maxidx)
end

function SCIPclearIntarray(scip, intarray)
    ccall((:SCIPclearIntarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_INTARRAY}), scip, intarray)
end

function SCIPgetIntarrayVal(scip, intarray, idx)
    ccall((:SCIPgetIntarrayVal, libscip), Cint, (Ptr{SCIP_}, Ptr{SCIP_INTARRAY}, Cint), scip, intarray, idx)
end

function SCIPsetIntarrayVal(scip, intarray, idx, val)
    ccall((:SCIPsetIntarrayVal, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_INTARRAY}, Cint, Cint), scip, intarray, idx, val)
end

function SCIPincIntarrayVal(scip, intarray, idx, incval)
    ccall((:SCIPincIntarrayVal, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_INTARRAY}, Cint, Cint), scip, intarray, idx, incval)
end

function SCIPgetIntarrayMinIdx(scip, intarray)
    ccall((:SCIPgetIntarrayMinIdx, libscip), Cint, (Ptr{SCIP_}, Ptr{SCIP_INTARRAY}), scip, intarray)
end

function SCIPgetIntarrayMaxIdx(scip, intarray)
    ccall((:SCIPgetIntarrayMaxIdx, libscip), Cint, (Ptr{SCIP_}, Ptr{SCIP_INTARRAY}), scip, intarray)
end

function SCIPcreateBoolarray(scip, boolarray)
    ccall((:SCIPcreateBoolarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_BOOLARRAY}}), scip, boolarray)
end

function SCIPfreeBoolarray(scip, boolarray)
    ccall((:SCIPfreeBoolarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_BOOLARRAY}}), scip, boolarray)
end

function SCIPextendBoolarray(scip, boolarray, minidx, maxidx)
    ccall((:SCIPextendBoolarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_BOOLARRAY}, Cint, Cint), scip, boolarray, minidx, maxidx)
end

function SCIPclearBoolarray(scip, boolarray)
    ccall((:SCIPclearBoolarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_BOOLARRAY}), scip, boolarray)
end

function SCIPgetBoolarrayVal(scip, boolarray, idx)
    ccall((:SCIPgetBoolarrayVal, libscip), UInt32, (Ptr{SCIP_}, Ptr{SCIP_BOOLARRAY}, Cint), scip, boolarray, idx)
end

function SCIPsetBoolarrayVal(scip, boolarray, idx, val)
    ccall((:SCIPsetBoolarrayVal, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_BOOLARRAY}, Cint, UInt32), scip, boolarray, idx, val)
end

function SCIPgetBoolarrayMinIdx(scip, boolarray)
    ccall((:SCIPgetBoolarrayMinIdx, libscip), Cint, (Ptr{SCIP_}, Ptr{SCIP_BOOLARRAY}), scip, boolarray)
end

function SCIPgetBoolarrayMaxIdx(scip, boolarray)
    ccall((:SCIPgetBoolarrayMaxIdx, libscip), Cint, (Ptr{SCIP_}, Ptr{SCIP_BOOLARRAY}), scip, boolarray)
end

function SCIPcreatePtrarray(scip, ptrarray)
    ccall((:SCIPcreatePtrarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_PTRARRAY}}), scip, ptrarray)
end

function SCIPfreePtrarray(scip, ptrarray)
    ccall((:SCIPfreePtrarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_PTRARRAY}}), scip, ptrarray)
end

function SCIPextendPtrarray(scip, ptrarray, minidx, maxidx)
    ccall((:SCIPextendPtrarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_PTRARRAY}, Cint, Cint), scip, ptrarray, minidx, maxidx)
end

function SCIPclearPtrarray(scip, ptrarray)
    ccall((:SCIPclearPtrarray, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_PTRARRAY}), scip, ptrarray)
end

function SCIPgetPtrarrayVal(scip, ptrarray, idx)
    ccall((:SCIPgetPtrarrayVal, libscip), Ptr{Cvoid}, (Ptr{SCIP_}, Ptr{SCIP_PTRARRAY}, Cint), scip, ptrarray, idx)
end

function SCIPsetPtrarrayVal(scip, ptrarray, idx, val)
    ccall((:SCIPsetPtrarrayVal, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_PTRARRAY}, Cint, Ptr{Cvoid}), scip, ptrarray, idx, val)
end

function SCIPgetPtrarrayMinIdx(scip, ptrarray)
    ccall((:SCIPgetPtrarrayMinIdx, libscip), Cint, (Ptr{SCIP_}, Ptr{SCIP_PTRARRAY}), scip, ptrarray)
end

function SCIPgetPtrarrayMaxIdx(scip, ptrarray)
    ccall((:SCIPgetPtrarrayMaxIdx, libscip), Cint, (Ptr{SCIP_}, Ptr{SCIP_PTRARRAY}), scip, ptrarray)
end

function SCIPcreateDisjointset(scip, djset, ncomponents)
    ccall((:SCIPcreateDisjointset, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_DISJOINTSET}}, Cint), scip, djset, ncomponents)
end

function SCIPfreeDisjointset(scip, djset)
    ccall((:SCIPfreeDisjointset, libscip), Cvoid, (Ptr{SCIP_}, Ptr{Ptr{SCIP_DISJOINTSET}}), scip, djset)
end

function SCIPcreateDigraph(scip, digraph, nnodes)
    ccall((:SCIPcreateDigraph, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_DIGRAPH}}, Cint), scip, digraph, nnodes)
end

function SCIPcopyDigraph(scip, targetdigraph, sourcedigraph)
    ccall((:SCIPcopyDigraph, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_DIGRAPH}}, Ptr{SCIP_DIGRAPH}), scip, targetdigraph, sourcedigraph)
end


text:
module TestCompression
using DataFrames, RData, Test

rdata_path = joinpath(dirname(@__FILE__), "data_v3")
df = DataFrame(num = [1.1, 2.2])

@testset "Loading compressed RData files" begin
    @testset "When the optional compression codecs are not loaded" begin
        @test_warn "Error encountered while loading" begin
            @test_throws CodecMissingError load(joinpath(rdata_path, "compressed_bzip2.rda"))
        end
        @test_warn "Error encountered while loading" begin
            @test_throws CodecMissingError load(joinpath(rdata_path, "compressed_xz.rda"))
        end
    end

    @testset "When the optional compression codecs are loaded" begin
        import CodecBzip2, CodecXz

        @test load(joinpath(rdata_path, "compressed_gzip.rda"))["df"] == df
        @test load(joinpath(rdata_path, "compressed_bzip2.rda"))["df"] == df
        @test load(joinpath(rdata_path, "compressed_xz.rda"))["df"] == df
        @test load(joinpath(rdata_path, "compressed_false.rda"))["df"] == df
    end
end

end

ext: jl


text:
module NET

import Graphs
using Graphs
using Graphs: AbstractGraphFormat

import Graphs: loadgraph, loadgraphs, savegraph

export NETFormat

struct NETFormat <: AbstractGraphFormat end
"""
    savenet(io, g, gname="g")

Write a graph `g` to an IO stream `io` in the [Pajek NET](http://gephi.github.io/users/supported-graph-formats/pajek-net-format/)
format. Return 1 (number of graphs written).
"""
function savenet(io::IO, g::Graphs.AbstractGraph, gname::String = "g")
    println(io, "*Vertices $(nv(g))")
    # write edges
    if is_directed(g)
        println(io, "*Arcs")
    else
        println(io, "*Edges")
    end
    for e in Graphs.edges(g)
        println(io, "$(src(e)) $(dst(e))")
    end
    return 1
end

"""
    loadnet(io::IO, gname="graph")

Read a graph from IO stream `io` in the [Pajek NET](http://gephi.github.io/users/supported-graph-formats/pajek-net-format/)
format. Return the graph.
"""
function loadnet(io::IO, gname::String = "graph")
    line = readline(io)
    # skip comments
    while startswith(line, "%")
        line = readline(io)
    end
    n = parse(Int, match(r"\d+", line).match)
    for ioline in eachline(io)
        line = ioline
        (occursin(r"^\*Arcs", line) || occursin(r"^\*Edges", line)) && break
    end
    if occursin(r"^\*Arcs", line)
        g = Graphs.DiGraph(n)
    else
        g = Graphs.Graph(n)
    end
    while occursin(r"^\*Arcs", line)
        for ioline in eachline(io)
            line = ioline
            ms = collect(m.match for m in eachmatch(r"\d+", line, overlap=false))
            length(ms) < 2 && break
            add_edge!(g, parse(Int, ms[1]), parse(Int, ms[2]))
        end
    end
    while occursin(r"^\*Edges", line) # add edges in both directions
        for ioline in eachline(io)
            line = ioline
            ms = collect(m.match for m in eachmatch(r"\d+", line, overlap=false))
            length(ms) < 2 && break
            i1, i2 = parse(Int, ms[1]), parse(Int, ms[2])
            add_edge!(g, i1, i2)
            add_edge!(g, i2, i1)
        end
    end
    return g
end

loadgraph(io::IO, gname::String, ::NETFormat) = loadnet(io, gname)
loadgraphs(io::IO, ::NETFormat) = Dict("graph" => loadnet(io, "graph"))
savegraph(io::IO, g::AbstractGraph, gname::String, ::NETFormat) = savenet(io, g, gname)

end # module


text:
struct Workflow
    name::String
    files_to_create::Dict{String, String}
    files_to_delete::Set{String}
end


text:
using MySQL

"""
    init_mysql_database(;host = "localhost", dbname="test",
    username="root", pswd="", mysql_code=nothing, overwrite=false)

Create a MySQL database using the code inside mysql_code

### Arguments

* `host`, `dbname`, `user`, `pswd`
* `mysql_code::ASCIIString`: String with MySQL code that crates all default tables
* `overwrite::Bool` : Flag, if true and dbname exists, it deletes it

### Output

* `con`: Database connection and table-column names map

"""
function init_mysql_database(;host = "localhost", dbname="test",
    username="root", pswd="", mysql_code=nothing, overwrite=false)

    # call shell to ensure the MySQL server is running
    # run(`mysql.server start`)

    # Connecting to MySQL, but not to a specific DB,
    # we then create DB we want
    con = mysql_connect(host, username, pswd)

    q = mysql_execute(con, "SHOW DATABASES LIKE '$dbname'; ")
    if length(q[1])>0
        if overwrite
            println("Set to overwrite MySQL database $dbname")
            mysql_execute(con, "DROP DATABASE IF EXISTS $dbname;")
        else
            con = mysql_connect(host, username, pswd, dbname)
            println("Connected to existing database")
            println("Con: ", con)
            return con
        end
    end

    mysql_execute(con, "CREATE DATABASE $dbname
        CHARACTER SET utf8 COLLATE utf8_unicode_ci;")
    con = mysql_connect(host, username, pswd, dbname)

    if mysql_code != nothing
        mysql_execute(con, mysql_code)
        println("Database $dbname created and initialized")
    else
        println("Empty Database Created")
    end

    return con
end

"""
    select_columns_mysql(con, table)

For a MySQL database, return an array of all columns in the given table
"""
function select_columns(con::MySQL.MySQLHandle, table)
    cols_query = mysql_execute(con, "SHOW COLUMNS FROM $table;")
    cols_query[1]
end

"""
    select_all_tables_mysql(con)

Return an array of all tables in a given MySQL database
"""
function select_all_tables(con::MySQL.MySQLHandle)
    tables_query = mysql_execute(con, "SHOW TABLES;")
    tables_query[1]
end

function print_error(con::MySQL.MySQLHandle)
    Base.showerror(STDOUT, MySQLInternalError(con))
    println("\n")
end

"""
    query_mysql(con, query_code)

Execute a mysql command
"""
function db_query(con::MySQL.MySQLHandle, query_code)
    try
        sel = mysql_execute(con, query_code)
        return sel
    catch
        throw(MySQLInternalError(con))
    end
end

function insert_row!{T}(con::MySQL.MySQLHandle, tablename, data_values::Dict{Symbol, T},
    colname_dict::Dict{ASCIIString, Array{ASCIIString, 1}}, verbose = false)

    table_cols = colname_dict[symbol(tablename)]
    table_cols_backticks = [string("`", x, "`") for x in table_cols]
    cols_string = join(table_cols_backticks, ", ")
    vals_string = assemble_vals(data_values, table_cols)
    lastid = -1

    try
        lastid = mysql_execute(con, "INSERT INTO `$tablename` ($cols_string) values $vals_string;
         SELECT LAST_INSERT_ID();")[2][1,1]
    catch e
        # Base.showerror(STDOUT, MySQLInternalError(con))
        println("\n")
        println("Warning: Row with values $vals_string not inserted into the table: $tablename")
        # throw(MySQLInternalError(con))
    end
    return lastid
end

"""
    insert_row!(db, tablename, values)
Insert a row of values into the specified table for a given a MySQL database handle

### Arguments:

* `db::MySQLDB`: Database object (connection and map)
* `data_values::Dict{ASCIIString, Any}`: Array of (string) values
* `verbose`: Print debugginh info
"""
function insert_row!{T}(con::MySQL.MySQLHandle, tablename, data_values::Dict{Symbol, T},
    verbose = false)

    cols_string, vals_string = assemble_cols_and_vals(data_values)
    lastid = -1
    try
        q = db_query(con, "INSERT INTO `$tablename` ($cols_string) values $vals_string;
        SELECT LAST_INSERT_ID();")
        lastid = q[2][1,1]
    catch
        if verbose
            println("Warning! Row with values $vals_string not inserted into the table: $tablename")
            Base.showerror(STDOUT, MySQLInternalError(con))
            println("\n")
        end
        # throw(MySQLInternalError(con))
    end
    return lastid
end


text: ç = 1

max_stars_repo_name: gabriel-doriath-dohler/pjulia

max_issues_repo_name: gabriel-doriath-dohler/pjulia

max_forks_repo_name: gabriel-doriath-dohler/pjulia


text:
import DataStructures:OrderedDict

"""
A column line is TAB separated, and is started with a single '#CHROM'
#CHROM  POS ID  REF ALT QUAL    FILTER  INFO    FORMAT  A   B   C   D
"""
function vcf_add_column_line(header::VcfHeader, columnline::ASCIIString)
    if !startswith(columnline, "#CHROM")
        error("column line should start with #CHROM: $columnline")
        return false
    end
    columnline = lstrip(rstrip(columnline), '#')
    columns = split(columnline, "\t")
    for col in columns
        vcf_add_column(header, ASCIIString(col))
    end
end

vcf_add_column(header::VcfHeader, column::ASCIIString) = push!(header.columns, column)

function vcf_write_columns(stream, header::VcfHeader)
    write(stream, "#", join(header.columns, "\t"), "\n")
end

"""
A meta information line of a VCF file is started with ##
##reference=file:///seq/references/1000GenomesPilot-NCBI36.fasta
##INFO=<ID=NS,Number=1,Type=Integer,Description="Number of Samples With Data">
"""
function vcf_add_meta_line(header::VcfHeader, metaline::ASCIIString)
    if !startswith(metaline, "##")
        error("metaline should start with ##: $metaline")
        return false
    end
    metaline = rstrip(metaline)
    pos = search(metaline, '=')
    if pos <= 0
        error("not a valid meta line: $metaline")
        return false
    end
    key = lstrip(metaline[1:pos-1], '#')
    meta = metaline[pos+1:length(metaline)]
    vcf_add_meta(header, key, meta)
end

function vcf_add_meta(header::VcfHeader, key::ASCIIString, meta::ASCIIString)
    props = vcf_parse_meta(meta)
    if key in keys(header.metas)
        push!(header.metas[key], props)
    else
        header.metas[key] = Array{Any, 1}()
        push!(header.metas[key], props)
    end
end

# parse: <ID=DP,Number=1,Type=Integer,Description="Read Depth">
function vcf_parse_meta(meta::ASCIIString)
    inner = rstrip(lstrip(meta, '<'), '>')
    if !startswith(meta, '<')
        return inner
    end
    propstrs = split(inner, ",")
    props = OrderedDict{ASCIIString, Any}()
    start = 1
    inquote = false
    afterslash = false
    for i in 1:length(inner)
        if inner[i] == '\\'
            afterslash = true
            continue
        else
            afterslash = false
        end
        if inner[i]=='"' && !afterslash
            inquote = !inquote
        end
        if inner[i]==',' && !inquote
            k, v = vcf_parse_prop(inner[start:i-1])
            start = i + 1
            if v != false
                props[k] = v
            end
        end
    end
    # the last prop
    if start < length(inner)
        k, v = vcf_parse_prop(inner[start:length(inner)])
        if v != false
            props[k] = v
        end
    end
    return props
end

# parse ID=DP
function vcf_parse_prop(prop::ASCIIString)
    prop = strip(prop)
    if !contains(prop, "=")
        return (false, false)
    end
    key, value = split(prop, "=")
    return (ASCIIString(key), ASCIIString(value))
end

function vcf_write_metas(stream, header::VcfHeader)
    for (key, meta) in header.metas
        for meta_props in meta
            line = vcf_make_line(key, meta_props)
            write(stream, line)
        end
    end
end

function vcf_make_line(key::ASCIIString, meta_props)
    # single value line
    # like: ##fileformat=VCFv4.0
    if typeof(meta_props)<:AbstractString
        return "##$key=$meta_props\n"
    end

    line = "##$key=<"
    for (k,v) in meta_props
        line *= "$k=$v,"
    end
    line = rstrip(line,',') * ">\n"
    return line
end

function vcf_parse_data_line(line, has_format, separator='\t')
    items = split(line, separator)
    if length(items) < 8
        return false
    end
    chrom = items[1]
    pos = parse(Int64, items[2])
    id = items[3]
    ref = items[4]
    alt = items[5]
    qual = items[6]
    filter = items[7]
    info = items[8]
    format = ""
    if length(items) >= 9
        if has_format
            format = items[9]
            samples_start = 10
        end
    end
    samples = ASCIIString[]
    for s = samples_start:length(items)
        push!(samples, items[s])
    end
    return Variant(chrom, pos, id, ref, alt, qual, filter, info, format, samples)
end


text:
using Dates: Day, Hour

warsaw = first(compile("Europe/Warsaw", tzdata["europe"]))

normal = DateTime(2015, 1, 1, 0)   # a 24 hour day in warsaw
spring = DateTime(2015, 3, 29, 0)  # a 23 hour day in warsaw
fall = DateTime(2015, 10, 25, 0)   # a 25 hour day in warsaw

# Unary plus
@test +ZonedDateTime(normal, warsaw) == ZonedDateTime(normal, warsaw)

# Period arithmetic
@test ZonedDateTime(normal, warsaw) + Day(1) == ZonedDateTime(normal + Day(1), warsaw)
@test ZonedDateTime(spring, warsaw) + Day(1) == ZonedDateTime(spring + Day(1), warsaw)
@test ZonedDateTime(fall, warsaw) + Day(1) == ZonedDateTime(fall + Day(1), warsaw)

@test ZonedDateTime(normal, warsaw) + Hour(24) == ZonedDateTime(normal + Hour(24), warsaw)
@test ZonedDateTime(spring, warsaw) + Hour(24) == ZonedDateTime(spring + Hour(25), warsaw)
@test ZonedDateTime(fall, warsaw) + Hour(24) == ZonedDateTime(fall + Hour(23), warsaw)

# Do the same calculations but backwards over the transitions.
@test ZonedDateTime(normal + Day(1), warsaw) - Day(1) == ZonedDateTime(normal, warsaw)
@test ZonedDateTime(spring + Day(1), warsaw) - Day(1) == ZonedDateTime(spring, warsaw)
@test ZonedDateTime(fall + Day(1), warsaw) - Day(1) == ZonedDateTime(fall, warsaw)

@test ZonedDateTime(normal + Day(1), warsaw) - Hour(24) == ZonedDateTime(normal, warsaw)
@test ZonedDateTime(spring + Day(1), warsaw) - Hour(23) == ZonedDateTime(spring, warsaw)
@test ZonedDateTime(fall + Day(1), warsaw) - Hour(25) == ZonedDateTime(fall, warsaw)

# Ensure that arithmetic around transitions works.
@test ZonedDateTime(spring, warsaw) + Hour(1) == ZonedDateTime(spring + Hour(1), warsaw)
@test ZonedDateTime(spring, warsaw) + Hour(2) == ZonedDateTime(spring + Hour(3), warsaw)
@test ZonedDateTime(fall, warsaw) + Hour(2) == ZonedDateTime(fall + Hour(2), warsaw, 1)
@test ZonedDateTime(fall, warsaw) + Hour(3) == ZonedDateTime(fall + Hour(2), warsaw, 2)

# Non-Associativity
explicit_hour_day = (ZonedDateTime(spring, warsaw) + Hour(24)) + Day(1)
explicit_day_hour = (ZonedDateTime(spring, warsaw) + Day(1)) + Hour(24)
implicit_hour_day = ZonedDateTime(spring, warsaw) + Hour(24) + Day(1)
implicit_day_hour = ZonedDateTime(spring, warsaw) + Day(1) + Hour(24)

@test explicit_hour_day == ZonedDateTime(2015, 3, 31, 1, warsaw)
@test explicit_day_hour == ZonedDateTime(2015, 3, 31, 0, warsaw)
@test implicit_hour_day == ZonedDateTime(2015, 3, 31, 0, warsaw)
@test implicit_day_hour == ZonedDateTime(2015, 3, 31, 0, warsaw)

# CompoundPeriod canonicalization interacting with period arithmetic. Since `spring_zdt` is
# a 23 hour day this means adding `Day(1)` and `Hour(23)` are equivalent.
spring_zdt = ZonedDateTime(spring, warsaw)
@test spring_zdt + Day(1) + Minute(1) == spring_zdt + Hour(23) + Minute(1)

# When canonicalization happens automatically `Hour(24) + Minute(1)` is converted into
# `Day(1) + Minute(1)`. Fixed in `JuliaLang/julia#19268`
@test spring_zdt + Hour(23) + Minute(1) < spring_zdt + Hour(24) + Minute(1)

# Arithmetic with a StepRange should always work even when the start/stop lands on
# ambiguous or non-existent DateTimes.
ambiguous = DateTime(2015, 10, 25, 2)   # Ambiguous hour in Warsaw
nonexistent = DateTime(2014, 3, 30, 2)  # Non-existent hour in Warsaw

range = ZonedDateTime(ambiguous - Day(1), warsaw):Hour(1):ZonedDateTime(ambiguous - Day(1) + Hour(1), warsaw)
@test range .+ Day(1) == ZonedDateTime(ambiguous, warsaw, 1):Hour(1):ZonedDateTime(ambiguous + Hour(1), warsaw)

range = ZonedDateTime(ambiguous - Day(1) - Hour(1), warsaw):Hour(1):ZonedDateTime(ambiguous - Day(1), warsaw)
@test range .+ Day(1) == ZonedDateTime(ambiguous - Hour(1), warsaw, 1):Hour(1):ZonedDateTime(ambiguous, warsaw, 2)

range = ZonedDateTime(nonexistent - Day(1), warsaw):Hour(1):ZonedDateTime(nonexistent - Day(1) + Hour(1), warsaw)
@test range .+ Day(1) == ZonedDateTime(nonexistent + Hour(1), warsaw):Hour(1):ZonedDateTime(nonexistent + Hour(1), warsaw)

range = ZonedDateTime(nonexistent - Day(1) - Hour(1), warsaw):Hour(1):ZonedDateTime(nonexistent - Day(1), warsaw)
@test range .+ Day(1) == ZonedDateTime(nonexistent - Hour(1), warsaw):Hour(1):ZonedDateTime(nonexistent - Hour(1), warsaw)


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

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

                     @variable(m, -88.40110862821636 <= q <= 80.25263273980681)

                     add_NL_constraint(m, :(sigmoid(-0.3402051397109518 + -0.28456924845213605*sigmoid(-0.42610478134649465 + 0.43223652991075534*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.5575457569666615*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + -0.7868073625875285*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.5078849457963623*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + -0.2883931154790984*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + 0.6888193490874222*sigmoid(-0.17528834888704425 + -0.1425247358809414*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + 0.07932201643104397*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.9443705506849667*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.7094815218028745*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + -0.7352206438426769*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + -0.026837640444652866*sigmoid(-0.005280183583000753 + 0.6172883711874637*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.07641401576689111*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.42701726221355685*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + -0.5680942985776078*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.9418726475599537*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + -0.08739699596173622*sigmoid(0.26121381489212014 + -0.018200625348021138*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.03849358234625422*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + -0.856604860683484*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.2143578715735437*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.706261759527687*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + 0.2360509887003217*sigmoid(-0.09690410604182231 + 0.6473593808554208*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.6752519993458765*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.771479525571356*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.8906247556095672*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.560146720685823*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5])))) + sigmoid(0.2351041904461102 + 0.11979579421065711*sigmoid(-0.42610478134649465 + 0.43223652991075534*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.5575457569666615*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + -0.7868073625875285*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.5078849457963623*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + -0.2883931154790984*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + -0.012124046222294904*sigmoid(-0.17528834888704425 + -0.1425247358809414*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + 0.07932201643104397*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.9443705506849667*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.7094815218028745*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + -0.7352206438426769*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + 0.704332995743346*sigmoid(-0.005280183583000753 + 0.6172883711874637*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.07641401576689111*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.42701726221355685*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + -0.5680942985776078*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.9418726475599537*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + 0.7162932434639226*sigmoid(0.26121381489212014 + -0.018200625348021138*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.03849358234625422*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + -0.856604860683484*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.2143578715735437*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.706261759527687*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + -0.3351546298978829*sigmoid(-0.09690410604182231 + 0.6473593808554208*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.6752519993458765*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.771479525571356*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.8906247556095672*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.560146720685823*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5])))) + sigmoid(-0.4731175976624935 + -0.5144698215629462*sigmoid(-0.42610478134649465 + 0.43223652991075534*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.5575457569666615*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + -0.7868073625875285*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.5078849457963623*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + -0.2883931154790984*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + -0.005430014157027596*sigmoid(-0.17528834888704425 + -0.1425247358809414*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + 0.07932201643104397*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.9443705506849667*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.7094815218028745*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + -0.7352206438426769*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + 0.05201762086802919*sigmoid(-0.005280183583000753 + 0.6172883711874637*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.07641401576689111*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.42701726221355685*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + -0.5680942985776078*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.9418726475599537*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + 0.06728299071980626*sigmoid(0.26121381489212014 + -0.018200625348021138*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.03849358234625422*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + -0.856604860683484*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.2143578715735437*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.706261759527687*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + -0.8893971601390014*sigmoid(-0.09690410604182231 + 0.6473593808554208*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.6752519993458765*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.771479525571356*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.8906247556095672*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.560146720685823*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5])))) + sigmoid(-0.8380258290664089 + 0.49770714260784343*sigmoid(-0.42610478134649465 + 0.43223652991075534*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.5575457569666615*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + -0.7868073625875285*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.5078849457963623*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + -0.2883931154790984*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + 0.732919146629087*sigmoid(-0.17528834888704425 + -0.1425247358809414*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + 0.07932201643104397*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.9443705506849667*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.7094815218028745*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + -0.7352206438426769*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + -0.2983691588163282*sigmoid(-0.005280183583000753 + 0.6172883711874637*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.07641401576689111*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.42701726221355685*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + -0.5680942985776078*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.9418726475599537*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + -0.6200389337758314*sigmoid(0.26121381489212014 + -0.018200625348021138*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.03849358234625422*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + -0.856604860683484*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.2143578715735437*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.706261759527687*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + -0.03199113104777407*sigmoid(-0.09690410604182231 + 0.6473593808554208*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.6752519993458765*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.771479525571356*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.8906247556095672*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.560146720685823*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5])))) + sigmoid(0.7168755118620993 + -0.38856981611164576*sigmoid(-0.42610478134649465 + 0.43223652991075534*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.5575457569666615*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + -0.7868073625875285*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.5078849457963623*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + -0.2883931154790984*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + 0.9818525806719265*sigmoid(-0.17528834888704425 + -0.1425247358809414*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + 0.07932201643104397*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.9443705506849667*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.7094815218028745*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + -0.7352206438426769*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + 0.9400532013818674*sigmoid(-0.005280183583000753 + 0.6172883711874637*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.07641401576689111*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.42701726221355685*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + -0.5680942985776078*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.9418726475599537*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + -0.928831604242299*sigmoid(0.26121381489212014 + -0.018200625348021138*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.03849358234625422*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + -0.856604860683484*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.2143578715735437*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.706261759527687*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5]))) + 0.6913287958041021*sigmoid(-0.09690410604182231 + 0.6473593808554208*sigmoid(-0.9360387382859474 + 0.27356363334073697*$(x[1]) + 0.5623428270051978*$(x[2]) + -0.9519487490584724*$(x[3]) + 0.5639775172803199*$(x[4]) + 0.8360124736609604*$(x[5])) + -0.6752519993458765*sigmoid(0.3895701371443887 + 0.5298392176190725*$(x[1]) + -0.9900818182438851*$(x[2]) + 0.9005096697487907*$(x[3]) + 0.008235253700211498*$(x[4]) + 0.03120241694369552*$(x[5])) + 0.771479525571356*sigmoid(0.7802421455771191 + -0.3899284089358539*$(x[1]) + -0.510799262552962*$(x[2]) + -0.16925880893067768*$(x[3]) + -0.7702701325797845*$(x[4]) + -0.21353502867805174*$(x[5])) + 0.8906247556095672*sigmoid(-0.4643333519515682 + -0.743154946296293*$(x[1]) + 0.08142803382004216*$(x[2]) + 0.8067509325852682*$(x[3]) + -0.6642228946665827*$(x[4]) + -0.03791136441363552*$(x[5])) + 0.560146720685823*sigmoid(0.6488423858989929 + -0.3655334329180211*$(x[1]) + 0.8449912783652063*$(x[2]) + -0.7635680273216123*$(x[3]) + 0.17014039681297044*$(x[4]) + -0.14496676502055283*$(x[5])))) - $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:
# Copyright 2018 Gandalf Software, Inc. (Scott Paul Jones)
# Licensed under MIT License, see LICENSE.md

function _cmp(::ByteCompare, a, b)
    asiz = ncodeunits(a)
    apnt = pointer(a)
    bsiz = ncodeunits(b)
    bpnt = pointer(b)
    asiz == bsiz && return apnt === bpnt ? 0 : _memcmp(apnt, bpnt, asiz)
    res = _memcmp(apnt, bpnt, min(asiz, bsiz))
    res < 0 ? -1 : res > 0 ? 1 : cmp(asiz, bsiz)
end

@inline adjust_utf16(ch) = ch - ifelse(ch < 0xe000, 0xb800, 0xe000)

_cmp_utf16(c1::UInt16, c2::UInt16) =
    ((c1 < 0xd800 || c2 < 0xd800)
     ? ifelse(c1 > c2, 1, -1)
     : ifelse(adjust_utf16(c1) > adjust_utf16(c2), 1, -1))

# This needs to handle the last word specially, if one is a surrogate pair and the other isn't
# It should be optimized to test at least 64 bits at a time for equality
function _memcmp16(apnt, bpnt, len)
    fin = bytoff(apnt, len)
    while apnt < fin
        (c1 = get_codeunit(apnt)) == (c2 = get_codeunit(bpnt)) || return _cmp_utf16(c1, c2)
        apnt += 2
        bpnt += 2
    end
    0
end

function _cmp(::UTF16Compare, a, b)
    asiz = ncodeunits(a)
    apnt = pointer(a)
    bsiz = ncodeunits(b)
    bpnt = pointer(b)
    if asiz < bsiz
        ifelse(_memcmp16(apnt, bpnt, asiz) <= 0, -1, 1)
    elseif asiz > bsiz
        ifelse(_memcmp16(apnt, bpnt, bsiz) < 0, -1, 1)
    elseif apnt != bpnt
        _memcmp16(apnt, bpnt, asiz)
    else
        0
    end
end

@inline _lenpntfin(str) = (ncodeunits(str), pointer(str), pointer(str) + sizeof(str))

@inline function _cpcmp(a::MaybeSub{T}, b) where {C<:CSE,T<:Str{C}}
    len, pnt, fin = _lenpntfin(a)
    pos = start(b)
    while pnt < fin
        done(b, pos) && return 1
        c1, pnt = _nextcp(C, pnt)
        ch, pos = next(b, pos)
        c2 = ch%UInt32
        c1 == c2 || return ifelse(c1 < c2, -1, 1)
    end
    ifelse(done(b, pos), 0, -1)
end

_cmp(::CodePointCompare, a::MaybeSub{<:Str}, b::AbstractString) = _cpcmp(a, b)
_cmp(::CodePointCompare, a::AbstractString, b::MaybeSub{<:Str}) = -_cpcmp(b, a)

function _cmp(::CodePointCompare,
              a::MaybeSub{S}, b::MaybeSub{T}) where {CSE1,CSE2,S<:Str{CSE1},T<:Str{CSE2}}
    len1, pnt1, fin1 = _lenpntfin(a)
    len2, pnt2, fin2 = _lenpntfin(b)
    while pnt1 < fin1
        pnt2 < fin2 || return 1
        c1, pnt1 = _nextcp(CSE1, pnt1)
        c2, pnt2 = _nextcp(CSE2, pnt2)
        c1 != c2 && return ifelse(c1 < c2, -1, 1)
    end
    ifelse(pnt2 < fin2, -1, 0)
end

cmp(a::MaybeSub{<:Str}, b::AbstractString)  = @preserve a _cmp(CompareStyle(a, b), a, b)
cmp(a::AbstractString,  b::MaybeSub{<:Str}) = @preserve b _cmp(CompareStyle(a, b), a, b)
cmp(a::MaybeSub{<:Str}, b::MaybeSub{<:Str}) = @preserve a b _cmp(CompareStyle(a, b), a, b)

# Todo: handle comparisons of UTF16 specially, to compare first non-matching character
# as if comparing Char to Char, to get ordering correct when dealing with > 0xffff non-BMP
# characters

@inline _fasteq(a, b) = (len = ncodeunits(a)) == ncodeunits(b) && _memcmp(a, b, len) == 0

function _cpeq(a::MaybeSub{T}, b) where {C<:CSE, T<:Str{C}}
    len, pnt, fin = _lenpntfin(a)
    pos = start(b)
    while pnt < fin
        done(b, pos) && return false
        c1, pnt = _nextcp(C, pnt)
        ch, pos = next(b, pos)
        c1 == codepoint(ch) || return false
    end
    true
end

_cpeq(a, b::MaybeSub{T}) where {C<:CSE, T<:Str{C}} = _cpeq(b, a)

function _cpeq(a::MaybeSub{<:Str{C1}}, b::MaybeSub{<:Str{C2}}) where {C1<:CSE, C2<:CSE}
    len1, pnt1, fin1 = _lenpntfin(a)
    len2, pnt2, fin2 = _lenpntfin(b)
    while pnt1 < fin1
        pnt2 < fin2 || return false
        c1, pnt1 = _nextcp(C1, pnt1)
        c2, pnt2 = _nextcp(C2, pnt2)
        c1 == c2 || return false
    end
    true
end

# This can be speeded up in the future with SSE/AVX instructions to unpack bytes,
# or to mask chunks of characters first to see if there are any too large in the wider of the two
function _wideneq(a::MaybeSub{S}, b::MaybeSub{T}) where {S<:Str,T<:Str}
    (len = ncodeunits(a)) == ncodeunits(b) || return false
    pnt1 = pointer(a)
    pnt2 = pointer(b)
    fin  = pnt1 + sizeof(a)
    while pnt1 < fin
        get_codeunit(pnt1) == get_codeunit(pnt2) || return false
        pnt1 += sizeof(codeunit(S))
        pnt2 += sizeof(codeunit(T))
    end
    true
end

_iseq(::NoCompare,        a, b) = false
_iseq(::ByteCompare,      a, b) = _fasteq(a, b)
_iseq(::WordCompare,      a, b) = _fasteq(a, b)
_iseq(::UTF16Compare,     a, b) = _fasteq(a, b)
_iseq(::WidenCompare,     a, b) = _wideneq(a, b)
_iseq(::ASCIICompare,     a, b) = _cpeq(a, b) # This can be optimized later
_iseq(::CodePointCompare, a, b) = _cpeq(a, b)

==(a::AbstractString,  b::MaybeSub{<:Str}) = @preserve b _iseq(EqualsStyle(a, b), a, b)
==(a::MaybeSub{<:Str}, b::AbstractString)  = @preserve a _iseq(EqualsStyle(a, b), a, b)
==(a::MaybeSub{<:Str}, b::MaybeSub{<:Str}) = @preserve a b _iseq(EqualsStyle(a, b), a, b)

isless(a::AbstractString,  b::MaybeSub{<:Str}) = cmp(a, b) < 0
isless(a::MaybeSub{<:Str}, b::AbstractString)  = cmp(a, b) < 0
isless(a::MaybeSub{<:Str}, b::MaybeSub{<:Str}) = cmp(a, b) < 0


text:
type SwapForwardMappings end

function coterminal_swap_forward_jacobian(::SwapForwardMappings, cs::CurveState)
  n = cs.numberOfRates
  f = cs.forwardRates
  tau = cs.rateTaus

  a = Vector{Float64}(n)
  for k in eachindex(a)
    a[k] = discount_ratio(cs, k, n+1) - 1.0
  end

  jacobian = zeros(n, n)
  for i = 1:n, j = i:n
    bi = coterminal_swap_annuity(cs, n+1, i)
    bj = coterminal_swap_annuity(cs, n+1, j)
    jacobian[i, j] = tau[j] / coterminal_swap_annuity(cs, j+1, i) + tau[j] / (1.0 + f[j] * tau[j]) * (-a[j] * bi + a[i] * bj) / (bi * bi)
  end

  return jacobian
end

function coterminal_swap_zed_matrix(sfm::SwapForwardMappings, cs::CurveState, displacement::Float64)
  n = cs.numberOfRates
  zMatrix = coterminal_swap_forward_jacobian(sfm, cs)

  f = cs.forwardRates
  sr = coterminal_swap_rates!(cs)

  for i = 1:n, j = i:n
    zMatrix[i, j] *= (f[j] + displacement) / (sr[i] + displacement)
  end

  return zMatrix
end


text:
using ThinModules

@thinmod module package_example
include("./c.jl")
include("./d.jl")
include("./b.jl")

end # module


text:
"""
    set_NUMBER_OF_WALKS(n)

Determine the number of independent trials to run.

Modify the global variable declared in PARAMETERS_.jl
"""
function set_NUMBER_OF_WALKS(n::Int=1000)
    global NUMBER_OF_WALKS = n
    nothing
end

"""
    set_MAX_STEPS_PER_WALK(s)

Determine when to give up on an unresolving random walk

Modify the global variable declared in PARAMETERS_.jl.
"""
function set_MAX_STEPS_PER_WALK(s::Int=1485604)
    global MAX_STEPS_PER_WALK = s
    nothing
end

"Generate a random seed between 1 to 4 digits long for many default arguments"
function randseed()::Int
    maxdigits = 4
    return trunc(Int, 10^maxdigits*rand())
end

"""
    run_sim!(data, seed) -> data::Dict{String,Integer}

Run generic HMCResearchRandomWalk. Include looping overhead and record data.
"""
function run_sim!(data::Dict{String,Integer}, seed::Int=randseed())
    Random.seed!(seed)
    float_arr_one = rand(NUMBER_OF_WALKS)
    float_arr_two = rand(NUMBER_OF_WALKS)
    avgStepsTaken = 0

    @showprogress 1 "Running simulation..." for i in 1:NUMBER_OF_WALKS
        peroxidexy = spawnrandompoint(float_arr_one[i], float_arr_two[i])
        steps_sofar = 0
        while peroxidexy != undef && steps_sofar < MAX_STEPS_PER_WALK
            peroxidexy, collision = one_step!(peroxidexy)
            if collision != "no collision"
                data[collision] += 1
            end
            steps_sofar += 1
        end
        avgStepsTaken += steps_sofar
        if steps_sofar >= MAX_STEPS_PER_WALK
            data["particles unresolved"] += 1
        end
    end

    avgStepsTaken = avgStepsTaken ÷ NUMBER_OF_WALKS
    data["avg steps taken"] = avgStepsTaken
    return data
end

max_stars_repo_name: s-y-wu/HMCResearchRandomWalks

max_issues_repo_name: s-y-wu/HMCResearchRandomWalks

max_forks_repo_name: s-y-wu/HMCResearchRandomWalks


text:
##### Beginning of file

module Hosts # Begin submodule RemoveLFS.Hosts

__precompile__(true)

import ..Types
import ..Utils

import ..delayederror

include(joinpath("BitbucketDstHost", "BitbucketDstHost.jl"))

include(joinpath("GitHubDstHost", "GitHubDstHost.jl"))

include(joinpath("GitLabDstHost", "GitLabDstHost.jl"))

end # End submodule RemoveLFS.Hosts

##### End of file


text:
##  SCRIPT NAME:   utilityW.jl
##  DATE:          March 2015
#
#   This script calculates the felicity the wife enjoys for every value
#   of her private consumption and the family level public consumption.
#
#
##  ALEXANDROS THELOUDIS, UCL

##  ---------------------------------------------------------------------------------------------

function utilityW(cW, K)

  utility = alphaCW*(cW^(1-gammaCW))/(1-gammaCW) + (1-alphaCW)*(K^(1-gammaKW))/(1-gammaKW)

  return utility

end

max_stars_repo_name: floswald/ucl-econ-julia

max_issues_repo_name: floswald/ucl-econ-julia

max_forks_repo_name: floswald/ucl-econ-julia


text:
function solve()
    as = [parse(Int, x) for x in split(readline())]
    minimum(as)
end

println(solve())

max_stars_repo_name: aishikawa/atcoder-julia

max_issues_repo_name: aishikawa/atcoder-julia

max_forks_repo_name: aishikawa/atcoder-julia


text:
module PowerSpectra

import ThreadPools: @qthreads
import Base.Threads: @threads
import UnsafeArrays: uview
import Combinatorics: permutations, combinations, with_replacement_combinations
import Healpix: HealpixMap, PolarizedHealpixMap, Alm, RingOrder, alm2cl, map2alm, numberOfAlms,
    RingInfo, getringinfo!, almIndex, alm2map, nside2npix, pix2ang, pix2vecRing,
    readMapFromFITS, nest2ring
import WignerFamilies: wigner3j_f!, WignerF, WignerSymbolVector, get_wigner_array
import FillArrays: Zeros, Ones
import OffsetArrays: OffsetArray, OffsetVector
import OffsetArrays
import StaticArrays: SA
import IdentityRanges: IdentityRange

using BandedMatrices
using LinearAlgebra
using Random
using CSV, DataFrames
using Lazy: @forward
using ReferenceImplementations
using LazyArtifacts
using FITSIO
# import Distributions: MvNormal
# import LoopVectorization: @avx

include("util.jl")
include("spectralarray.jl")
include("blockspectralmatrix.jl")
include("workspace.jl")
include("modecoupling.jl")
include("covariance.jl")
include("beam.jl")
include("exampledata.jl")

export IdentityRange
export mcm, decouple_covmat, mask!, scale!, master
export @spectra
export SpectralVector, SpectralArray, BlockSpectralMatrix
export spectralzeros, spectralones
export channelindex
export fitdipole, subtract_monopole_dipole!, nside2lmax
export CovField
export CovarianceWorkspace, coupledcov
export binning_matrix, read_commented_header
export synalm, synalm!
export SpectrumName

end

max_stars_repo_name: xzackli/PlanckCov

max_issues_repo_name: xzackli/PlanckCov


text:
# ---
# title: JuliaRL\_PPO\_Pendulum
# cover: assets/JuliaRL_PPO_Pendulum.png
# description: PPO applied to Pendulum
# date: 2021-05-22
# author: "[Jun Tian](https://github.com/findmyway)"
# ---

#+ tangle=true
using ReinforcementLearning
using StableRNGs
using Flux
using Flux.Losses
using Distributions

function RL.Experiment(
    ::Val{:JuliaRL},
    ::Val{:PPO},
    ::Val{:Pendulum},
    ::Nothing;
    save_dir = nothing,
    seed = 123,
)
    rng = StableRNG(seed)
    inner_env = PendulumEnv(T = Float32, rng = rng)
    A = action_space(inner_env)
    low = A.left
    high = A.right
    ns = length(state(inner_env))

    N_ENV = 8
    UPDATE_FREQ = 2048
    env = MultiThreadEnv([
        PendulumEnv(T = Float32, rng = StableRNG(hash(seed + i))) |>
        env -> ActionTransformedEnv(env, action_mapping = x -> clamp(x * 2, low, high)) for i in 1:N_ENV
    ])

    init = glorot_uniform(rng)

    agent = Agent(
        policy = PPOPolicy(
            approximator = ActorCritic(
                actor = GaussianNetwork(
                    pre = Chain(
                        Dense(ns, 64, relu; init = glorot_uniform(rng)),
                        Dense(64, 64, relu; init = glorot_uniform(rng)),
                    ),
                    μ = Chain(Dense(64, 1, tanh; init = glorot_uniform(rng)), vec),
                    logσ = Chain(Dense(64, 1; init = glorot_uniform(rng)), vec),
                ),
                critic = Chain(
                    Dense(ns, 64, relu; init = glorot_uniform(rng)),
                    Dense(64, 64, relu; init = glorot_uniform(rng)),
                    Dense(64, 1; init = glorot_uniform(rng)),
                ),
                optimizer = ADAM(3e-4),
            ) |> cpu,
            γ = 0.99f0,
            λ = 0.95f0,
            clip_range = 0.2f0,
            max_grad_norm = 0.5f0,
            n_epochs = 10,
            n_microbatches = 32,
            actor_loss_weight = 1.0f0,
            critic_loss_weight = 0.5f0,
            entropy_loss_weight = 0.00f0,
            dist = Normal,
            rng = rng,
            update_freq = UPDATE_FREQ,
        ),
        trajectory = PPOTrajectory(;
            capacity = UPDATE_FREQ,
            state = Matrix{Float32} => (ns, N_ENV),
            action = Vector{Float32} => (N_ENV,),
            action_log_prob = Vector{Float32} => (N_ENV,),
            reward = Vector{Float32} => (N_ENV,),
            terminal = Vector{Bool} => (N_ENV,),
        ),
    )

    stop_condition = StopAfterStep(50_000, is_show_progress=false)
    hook = TotalBatchRewardPerEpisode(N_ENV)
    Experiment(agent, env, stop_condition, hook, "# Play Pendulum with PPO")
end

#+ tangle=false
using Plots
using Statistics
pyplot() #hide
ex = E`JuliaRL_PPO_Pendulum`
run(ex)
n = minimum(map(length, ex.hook.rewards))
m = mean([@view(x[1:n]) for x in ex.hook.rewards])
s = std([@view(x[1:n]) for x in ex.hook.rewards])
plot(m,ribbon=s)
savefig("assets/JuliaRL_PPO_Pendulum.png") #hide

# ![](assets/JuliaRL_PPO_Pendulum.png)


text:
# This file was generated, do not modify it. # hide
using Gnuplot
x = -2π:0.001:2π
@gp(x, sin.(x),"w l t 'sin' lw 2 lc '#56B4E9'", "set grid",
    xrange = (-2π - 0.3, 2π + 0.3), yrange = (-1.1,1.1))
@gp(:-, x, cos.(x), "w l t 'cos' lw 2 lc rgb '#E69F00'")
save(term="pngcairo size 600,400", output="plt2_ex4.png") # hide


text:
function fringe_upper_bound(pomdp::RockSample, state::RockSampleState)
    if isterminal(pomdp, state)
        return 0.0
    end

    rock_set = rock_set_of(pomdp, state)
    n_good = 0
    while rock_set != 0
        n_good += rock_set & 1
        rock_set >>>= 1
    end

    # Assume a good rock is sampled at each step and an exit is made in the last
    if pomdp.discount < 1
        return 10. * (1 - (pomdp.discount^(n_good+1))) / (1 - pomdp.discount)
    else
        return 10. * (n_good + 1)
    end
end


text:
using PkgTest
using Test

@testset "PkgTest.jl" begin
    # Write your tests here.
end


text:
immutable Geometric <: DiscreteUnivariateDistribution
    p::Float64

    function Geometric(p::Real)
        zero(p) < p < one(p) || error("prob must be in (0, 1)")
    	@compat new(Float64(p))
    end

    Geometric() = Geometric(0.5) # Flips of a fair coin
end

@distr_support Geometric 0 Inf

### Parameters

succprob(d::Geometric) = d.p
failprob(d::Geometric) = 1.0 - d.p
params(d) = (d.p,)

### Statistics

mean(d::Geometric) = failprob(d) / succprob(d)

median(d::Geometric) = -fld(logtwo, log1p(-d.p)) - 1.0

mode(d::Geometric) = 0

var(d::Geometric) = (1.0 - d.p) / abs2(d.p)

skewness(d::Geometric) = (2.0 - d.p) / sqrt(1.0 - d.p)

kurtosis(d::Geometric) = 6.0 + abs2(d.p) / (1.0 - d.p)

entropy(d::Geometric) = (-xlogx(succprob(d)) - xlogx(failprob(d))) / d.p

### Evaluations

function pdf(d::Geometric, x::Int)
    if x >= 0
        p = d.p
        return p < 0.1 ? p * exp(log1p(-p) * x) : d.p * (1.0 - p)^x
    else
        return 0.0
    end
end

logpdf(d::Geometric, x::Int) = x >= 0 ? log(d.p) + log1p(-d.p) * x : -Inf

immutable RecursiveGeomProbEvaluator <: RecursiveProbabilityEvaluator
    p0::Float64
end

RecursiveGeomProbEvaluator(d::Geometric) = RecursiveGeomProbEvaluator(failprob(d))
nextpdf(s::RecursiveGeomProbEvaluator, p::Float64, x::Integer) = p * s.p0
_pdf!(r::AbstractArray, d::Geometric, rgn::UnitRange) = _pdf!(r, d, rgn, RecursiveGeomProbEvaluator(d))

function cdf(d::Geometric, x::Int)
    x < 0 && return 0.0
    p = succprob(d)
    n = x + 1
    p < 0.5 ? -expm1(log1p(-p)*n) : 1.0-(1.0-p)^n
end

function ccdf(d::Geometric, x::Int)
    x < 0 && return 1.0
    p = succprob(d)
    n = x + 1
    p < 0.5 ? exp(log1p(-p)*n) : (1.0-p)^n
end

logcdf(d::Geometric, x::Int) = x < 0 ? -Inf : log1mexp(log1p(-d.p) * (x + 1))

logccdf(d::Geometric, x::Int) =  x < 0 ? 0.0 : log1p(-d.p) * (x + 1)

quantile(d::Geometric, p::Float64) = invlogccdf(d, log1p(-p))

cquantile(d::Geometric, p::Float64) = invlogccdf(d, log(p))

invlogcdf(d::Geometric, lp::Float64) = invlogccdf(d, log1mexp(lp))

function invlogccdf(d::Geometric, lp::Float64)
    if (lp > 0.0) || isnan(lp)
        return NaN
    elseif isinf(lp)
        return Inf
    elseif lp == 0.0
        return 0.0
    end
    max(ceil(lp/log1p(-d.p))-1.0,0.0)
end

function mgf(d::Geometric, t::Real)
    p = succprob(d)
    p / (expm1(-t) + p)
end

function cf(d::Geometric, t::Real)
    p = succprob(d)
    # replace with expm1 when complex version available
    p / (exp(-t*im) - 1.0 + p)
end

### Sampling

rand(d::Geometric) = floor(Int,-randexp() / log1p(-d.p))

### Model Fitting

immutable GeometricStats <: SufficientStats
    sx::Float64
    tw::Float64

    @compat GeometricStats(sx::Real, tw::Real) = new(Float64(sx), Float64(tw))
end

suffstats{T<:Integer}(::Type{Geometric}, x::Array{T}) = GeometricStats(sum(x), length(x))

function suffstats{T<:Integer}(::Type{Geometric}, x::Array{T}, w::Array{Float64})
    n = length(x)
    if length(w) != n
        throw(ArgumentError("Inconsistent argument dimensions."))
    end
    sx = 0.
    tw = 0.
    for i = 1:n
        wi = w[i]
        sx += wi * x[i]
        tw += wi
    end
    GeometricStats(sx, tw)
end

fit_mle(::Type{Geometric}, ss::GeometricStats) = Geometric(1.0 / (ss.sx / ss.tw + 1.0))


text:
using DocumentFormat: format
using Test

@testset "All" begin
@testset "basic" begin
    @test format("a") == "a"
end
@testset "tuples" begin
    @test format("a,b") == "a, b"
    @test format("a ,b") == "a, b"
    @test format("a ,b,") == "a, b,"
    @test format("a ,b ,") == "a, b,"
    @test format("a , b ,") == "a, b,"
    @test format("(a,b)") == "(a, b)"
    @test format("(a ,b)") == "(a, b)"
    @test format("( a, b)") == "(a, b)"
    @test format("(a, b )") == "(a, b)"
    @test format("(a, b ,)") == "(a, b,)"
end
@testset "curly" begin
    @test format("X{a,b}") == "X{a,b}"
    @test format("X{ a,b}") == "X{a,b}"
    @test format("X{a ,b}") == "X{a,b}"
    @test format("X{a, b}") == "X{a,b}"
    @test format("X{a,b }") == "X{a,b}"
    @test format("X{a,b }") == "X{a,b}"
end
# @testset "unary ops" begin
#     @test format("! x") == "!x"
# end
@testset "binary ops" begin
    @test format("a+b*c") == "a + b * c"
    @test format("a +b*c") == "a + b * c"
    @test format("a+ b*c") == "a + b * c"
    @test format("a+b *c") == "a + b * c"
    @test format("a+b* c") == "a + b * c"
    @test format("a+b*c ") == "a + b * c "
    @test format("a:b") == "a:b"
    @test format("a : b") == "a:b"
    @test format("a: b") == "a:b"
    @test format("a :b") == "a:b"
    @test format("a:b:c") == "a:b:c"
    @test format("a :b:c") == "a:b:c"
    @test format("a: b:c") == "a:b:c"
    @test format("a:b :c") == "a:b:c"
    @test format("a:b: c") == "a:b:c"
    @test format("a:b:c ") == "a:b:c "
    @test format("a::b:: c") == "a::b::c"
    @test format("a :: b::c") == "a::b::c"
end

@testset "op chain" begin
    @test format("a+b+c+d") == "a + b + c + d"
end

@testset "comparison chain" begin
    @test format("a<b==c≥d") == "a < b == c ≥ d"
end

@testset "colon op" begin
    @test format("a:b:c") == "a:b:c"
    @test format("a:b:c") == "a:b:c"
    @test format("a:b:c") == "a:b:c"
    @test format("a:b:c") == "a:b:c"
    @test format("a:b:c") == "a:b:c"
    @test format("a:b:c") == "a:b:c"
end

# @testset "func call" begin
#     @test format("func(a, b, c)") == "func(a, b, c)"
#     @test format("func(a,b,c)") == "func(a, b, c)"
#     @test format("func(a,b,c,)") == "func(a, b, c,)"
#     @test format("func(a,b,c, )") == "func(a, b, c,)"
#     @test format("func( a,b,c    )") == "func(a, b, c)"
#     @test format("func(a, b, c) ") == "func(a, b, c) "
#     @test format("func(a, b; c)") == "func(a, b; c)"
#     @test format("func(  a, b; c)") == "func(a, b; c)"
#     @test format("func(a  ,b; c)") == "func(a, b; c)"
#     @test format("func(a=1,b; c=1)") == "func(a = 1, b; c = 1)"
# end

@testset "indents" begin
@testset "begin" begin
str = """
begin
    arg
end"""
    @test format("""
                begin
                arg
                end""") == str
    @test format("""
                begin
                    arg
                end""") == str
    @test format("""
                begin
                    arg
                end""") == str
    @test format("""
                begin
                        arg
                end""") == str
    str = """
    begin
        begin
            arg
        end
    end"""
    @test format("""
                begin
                begin
                arg
                end
                end""") == str
    @test format("""
                begin
                            begin
                arg
                end
                end""") == str
    @test format("""
                begin
                            begin
                arg
                        end
                end""") == str
end
end

@testset "quote" begin
    str = """
    quote
        arg
    end"""
    @test format("""
    quote
        arg
    end""") == str
    @test format("""
    quote
    arg
    end""") == str
    @test format("""
    quote
            arg
        end""") == str
end

@testset "for" begin
    str = """
    for iter = I
        arg
    end"""
    @test format("""
    for iter = I
        arg
    end""") == str
    @test format("""
    for iter = I
    arg
    end""") == str
    @test format("""
    for iter = I
      arg
    end""") == str

    str = """
    for iter = I, iter2 = I2
        arg
    end"""
    @test format("""
    for iter = I, iter2 = I2
        arg
    end""") == str
    @test format("""
    for iter = I, iter2 = I2
    arg
    end""") == str
    @test format("""
    for iter = I, iter2 = I2
            arg
        end""") == str
end

@testset "while" begin
    str = """
    while cond
        arg
    end"""
    @test format("""
    while cond
        arg
    end""") == str
    @test format("""
    while cond
    arg
    end""") == str
    @test format("""
    while cond
            arg
        end""") == str
end

@testset "let" begin
    str = """
    let x = X
        arg
    end"""
    @test format("""
    let x=X
        arg
    end""") == str
    @test format("""
    let x=X
    arg
    end""") == str
    @test format("""
    let x=X
        arg
    end""") == str
    str = """
    let x = X, y = Y
        arg
    end"""
    @test format("""
    let x = X, y = Y
        arg
    end""") == str
    @test format("""
    let x = X, y = Y
    arg
    end""") == str
end

@testset "struct" begin
    str = """
    struct name
        arg
    end"""
    @test format("""
    struct name
        arg
    end""") == str
    @test format("""
    struct name
    arg
    end""") == str
    @test format("""
    struct name
            arg
        end""") == str
end

@testset "mutable struct" begin
    str = """
    mutable struct name
        arg
    end"""
    @test format("""
    mutable struct name
        arg
    end""") == str
    @test format("""
    mutable struct name
    arg
    end""") == str
    @test format("""
    mutable struct name
            arg
        end""") == str
end

@testset "try-catch" begin
    str = """
    try
        arg
    catch
        arg
    end"""
    @test format("""
    try
        arg
    catch
        arg
    end""") == str
    @test format("""
    try
    arg
    catch
    arg
    end""") == str
    @test format("""
    try
            arg
        catch
            arg
        end""") == str
    str = """
    try
        arg
    catch
        arg
    end"""
    @test format("""
    try
        arg
    catch
        arg
    end""") == str
    @test format("""
    try
    arg
    catch
    arg
    end""") == str
    @test format("""
    try
            arg
        catch
            arg
        end""") == str

    str = """
    try
        arg
    catch err
        arg
    end"""
    @test format("""
    try
        arg
    catch err
        arg
    end""") == str
    @test format("""
    try
    arg
    catch err
    arg
    end""") == str
    @test format("""
    try
            arg
        catch err
            arg
        end""") == str
end

end


text:
@testset "Spherical tensors" begin
    @test system(TensorComponent(SphericalTensor(1), 1)) == OrbitalAngularMomentumSubSystem()
    @testset "Reduced matrix elements" begin
        for k = 0:6
            𝐂ᵏ = SphericalTensor(k)
            for (a,b) in [(0,k), (k,0), (1,k+1), (k+1,1)]
                @test !iszero(a, 𝐂ᵏ, b)
                # Since this is verbatim the definition of the reduced
                # matrix element, this is more a test of the tensor
                # DSL producing the correct code.
                @test rme(a, 𝐂ᵏ, b) ≈ AngularMomentumAlgebra.∏(b)*clebschgordan(b, 0, k, 0, a)
            end
        end
    end
    @testset "Components" begin
        𝐧 = SphericalTensor(1)
        for ℓ = 0:10
            for m = -ℓ:ℓ
                b = SpinOrbital(Orbital(:k, ℓ), m, half(1))
                for (±,∓) in [(+,-),(-,+)]
                    m′ = m ± 1
                    a = SpinOrbital(Orbital(:k, ℓ+1), m′, half(1))
                    @test dot(a, TensorComponent(𝐧, 0 ± 1), b) ≈ √((ℓ ± m + 1)*(ℓ ± m + 2)/
                                                                   (2*(2ℓ+1)*(2ℓ+3)))

                    m′ = m
                    a = SpinOrbital(Orbital(:k, ℓ+1), m′, half(1))
                    @test dot(a, TensorComponent(𝐧, 0), b) ≈ √((ℓ - m + 1)*(ℓ + m + 1)/
                                                               ((2ℓ+1)*(2ℓ+3)))

                    m′ = m ± 1
                    if abs(m′) ≤ ℓ-1
                        a = SpinOrbital(Orbital(:k, ℓ-1), m′, half(1))
                        @test dot(a, TensorComponent(𝐧, 0 ± 1), b) ≈ -√((ℓ ∓ m - 1)*(ℓ ∓ m)/
                                                                        (2*(2ℓ+1)*(2ℓ-1)))
                    end

                    m′ = m
                    if abs(m′) ≤ ℓ-1
                        a = SpinOrbital(Orbital(:k, ℓ-1), m′, half(1))
                        @test dot(a, TensorComponent(𝐧, 0), b) ≈ √((ℓ - m)*(ℓ + m)/
                                                                   ((2ℓ+1)*(2ℓ-1)))
                    end
                end
            end
        end
    end
end


text:
function _detect_variable_type(model::MOI.ModelLike, v::MOI.VariableIndex)
    # TODO: is this enough? Or should the code rather try all the countless possibilities for T in the calling functions (based on the constraint types that are used in the model)?
    if is_integer(model, v) || is_binary(model, v)
        return Int
    else
        return Float64
    end
end

# -----------------------------------------------------------------------------
# - Detect whether a variable or a function has some properties.
# -----------------------------------------------------------------------------

function is_integer(model::MOI.ModelLike, v::MOI.VariableIndex)
    c_idx = MOI.ConstraintIndex{MOI.VariableIndex, MOI.Integer}(v.value)
    return MOI.is_valid(model, c_idx)
end

function is_integer(model::MOI.ModelLike, f::MOI.ScalarAffineFunction{T}) where {T <: Real}
    v = MOIU.canonical(f)
    for t in v.terms
        if !isinteger(t.coefficient) || !is_integer(model, t.variable)
            return false
        end
    end
    return true
end

function is_binary(model::MOI.ModelLike, v::MOI.VariableIndex)
    c_idx = MOI.ConstraintIndex{MOI.VariableIndex, MOI.ZeroOne}(v.value)
    return MOI.is_valid(model, c_idx)
end

function is_binary(model::MOI.ModelLike, f::MOI.ScalarAffineFunction{T}) where {T <: Real}
    v = MOIU.canonical(f)

    # The sum of two variables cannot be ensured to be binary (at least, by
    # simple bound checking).
    if length(v.terms) > 1
        return false
    end

    # Two cases: either just a binary variable, or its complement.
    t = v.terms[1]
    if t.coefficient === one(T)
        return f.constant == zero(T) && is_binary(model, t.variable)
    elseif t.coefficient === -one(T)
        return f.constant == one(T) && is_binary(model, t.variable)
    else
        return false
    end
end

function has_lower_bound(model::MOI.ModelLike, v::MOI.ScalarAffineFunction{T}) where {T <: Real}
    for t in v.terms
        if t.coefficient == zero(T)
            continue
        end
        if !has_lower_bound(model, t.variable)
            return false
        end
    end
    return true
end

function has_lower_bound(model::MOI.ModelLike, v::MOI.VariableIndex)
    T = _detect_variable_type(model, v)

    # TODO: should infinite values be disregarded?

    # Check if the variable has an explicit lower bound.
    c_idx = MOI.ConstraintIndex{MOI.VariableIndex, MOI.GreaterThan{T}}(v.value)
    if MOI.is_valid(model, c_idx)
        return true
    end

    # Check if the variable has an interval.
    c_idx = MOI.ConstraintIndex{MOI.VariableIndex, MOI.Interval{T}}(v.value)
    if MOI.is_valid(model, c_idx)
        return true
    end

    # Booleans have an implicit lower bound.
    if is_binary(model, v)
        return true
    end

    return false
end

function has_upper_bound(model::MOI.ModelLike, v::MOI.ScalarAffineFunction{T}) where {T <: Real}
    for t in v.terms
        if t.coefficient == zero(T)
            continue
        end
        if !has_upper_bound(model, t.variable)
            return false
        end
    end
    return true
end

function has_upper_bound(model::MOI.ModelLike, v::MOI.VariableIndex)
    T = _detect_variable_type(model, v)

    # TODO: should infinite values be disregarded?

    # Check if the variable has an explicit upper bound.
    c_idx = MOI.ConstraintIndex{MOI.VariableIndex, MOI.LessThan{T}}(v.value)
    if MOI.is_valid(model, c_idx)
        return true
    end

    # Check if the variable has an interval.
    c_idx = MOI.ConstraintIndex{MOI.VariableIndex, MOI.Interval{T}}(v.value)
    if MOI.is_valid(model, c_idx)
        return true
    end

    # Booleans have an implicit upper bound.
    if is_binary(model, v)
        return true
    end

    return false
end

# function is_affine(::MOI.ModelLike, ::MOI.VariableIndex)
#     return true
# end

# function is_affine(::MOI.ModelLike, ::MOI.ScalarAffineFunction{T}) where {T}
#     return true
# end

# function is_affine(::MOI.ModelLike, ::MOI.VectorOfVariables)
#     return true
# end

# function is_affine(::MOI.ModelLike, ::MOI.VectorAffineFunction{T}) where {T}
#     return true
# end

# function is_affine(::MOI.ModelLike, ::Any)
#     return false
# end

# -----------------------------------------------------------------------------
# - Get some properties about a variable or a function.
# -----------------------------------------------------------------------------

function get_lower_bound(model::MOI.ModelLike, v::MOI.ScalarAffineFunction{T}) where {T <: Real}
    if !has_lower_bound(model, v)
        # Return -Inf, cast to the right type. typemin(Float64) is exactly
        # -Inf, the right values are returned for Float32 and for Float16.
        # No infinite available for other types than floats, though.
        return typemin(T)
    end

    lb = zero(T)
    for t in v.terms
        var_lb = get_lower_bound(model, t.variable)
        var_ub = get_upper_bound(model, t.variable)

        if t.coefficient == zero(T)
            continue
        elseif t.coefficient > zero(T)
            lb += t.coefficient * var_lb
        else # t.coefficient < zero(T)
            lb += t.coefficient * var_ub
        end
    end

    return lb
end

function get_lower_bound(model::MOI.ModelLike, v::MOI.VariableIndex)
    T = _detect_variable_type(model, v)

    # Booleans have an implicit lower bound.
    if is_binary(model, v)
        return 0
    end

    # Check if the variable has an explicit lower bound.
    c_idx = MOI.ConstraintIndex{MOI.VariableIndex, MOI.GreaterThan{T}}(
        v.value,
    )
    if MOI.is_valid(model, c_idx)
        return MOI.get(model, MOI.ConstraintSet(), c_idx).lower
    end

    # Check if the variable has an interval.
    c_idx = MOI.ConstraintIndex{MOI.VariableIndex, MOI.Interval{T}}(v.value)
    if MOI.is_valid(model, c_idx)
        return MOI.get(model, MOI.ConstraintSet(), c_idx).lower
    end

    return typemin(T)
end

function get_upper_bound(model::MOI.ModelLike, v::MOI.ScalarAffineFunction{T}) where {T <: Real}
    if !has_upper_bound(model, v)
        # Return Inf, cast to the right type. typemax(Float64) is exactly
        # Inf, the right values are returned for Float32 and for Float16.
        # No infinite available for other types than floats, though.
        return typemax(T)
    end

    ub = zero(T)
    for t in v.terms
        var_lb = get_lower_bound(model, t.variable)
        var_ub = get_upper_bound(model, t.variable)

        if t.coefficient == zero(T)
            continue
        elseif t.coefficient > zero(T)
            ub += t.coefficient * var_ub
        else # t.coefficient < zero(T)
            ub += t.coefficient * var_lb
        end
    end

    return ub
end

function get_upper_bound(model::MOI.ModelLike, v::MOI.VariableIndex)
    T = _detect_variable_type(model, v)

    # Booleans have an implicit upper bound.
    if is_binary(model, v)
        return 1
    end

    # Check if the variable has an explicit lower bound.
    c_idx = MOI.ConstraintIndex{MOI.VariableIndex, MOI.LessThan{T}}(
        v.value,
    )
    if MOI.is_valid(model, c_idx)
        return MOI.get(model, MOI.ConstraintSet(), c_idx).upper
    end

    # Check if the variable has an interval.
    c_idx = MOI.ConstraintIndex{MOI.VariableIndex, MOI.Interval{T}}(v.value)
    if MOI.is_valid(model, c_idx)
        return MOI.get(model, MOI.ConstraintSet(), c_idx).upper
    end

    return typemax(T)
end


text:
using ForwardDiff

#thresh = 1e-12

@testset "Derivative checks" begin

    ###################################
    # Test Jacobians
    ###################################

    @testset "Jacobian checks" begin

        # Quaternion to rotation matrix
        @testset "Jacobian (QuatRotation -> RotMatrix)" begin
            for i = 1:10    # do some repeats
                q = rand(QuatRotation)  # a random quaternion

                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(RotMatrix, q)
                FD_jac = ForwardDiff.jacobian(x -> SVector{9}(QuatRotation(x[1], x[2], x[3], x[4])),
                                              Rotations.params(q))

                # compare
                @test FD_jac ≈ R_jac
            end
        end

        # MRP to UnitQuternion
        @testset "Jacobian (MRP -> QuatRotation)" begin
            for i = 1:10    # do some repeats
                p = rand(MRP)  # a random MRP

                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(QuatRotation, p)
                FD_jac = ForwardDiff.jacobian(x -> (q = QuatRotation(MRP(x[1],x[2],x[3]));
                                                    Rotations.params(q)),
                                              SVector(p.x, p.y, p.z))

                # compare
                @test FD_jac ≈ R_jac
            end
        end

        @testset "Jacobian (MRP -> QuatRotation) [Corner Cases]" begin
            for p = [MRP(1.0, 0.0, 0.0), MRP(0.0, 1.0, 0.0), MRP(0.0, 0.0, 1.0)]
                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(QuatRotation, p)
                FD_jac = ForwardDiff.jacobian(x -> (q = QuatRotation(MRP(x[1],x[2],x[3]));
                                                    Rotations.params(q)),
                                              SVector(p.x, p.y, p.z))

                # compare
                @test FD_jac ≈ R_jac
            end
        end

        # MRP to QuatRotation
        @testset "Jacobian (QuatRotation -> MRP)" begin
            for i = 1:10    # do some repeats
                q = rand(QuatRotation)  # a random QuatRotation

                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(MRP, q)
                FD_jac = ForwardDiff.jacobian(x -> (p = MRP(QuatRotation(x[1], x[2], x[3], x[4]));
                                                    SVector(p.x, p.y, p.z)),
                                              Rotations.params(q))

                # compare
                @test FD_jac ≈ R_jac
            end
        end

        # MRP to rotation matrix
        @testset "Jacobian (MRP -> RotMatrix)" begin
            for i = 1:10    # do some repeats
                p = rand(MRP)  # a random MRP

                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(RotMatrix, p)
                FD_jac = ForwardDiff.jacobian(x -> SVector{9}(MRP(x[1], x[2], x[3])),
                                              SVector(p.x, p.y, p.z))

                # compare
                @test FD_jac ≈ R_jac
            end
        end

        ##############################
        # Jacobians for rotating stuff
        ##############################
#=
        # Quaternion multiplication
        @testset "Jacobian (Quaternion muliplication w.r.t. the right quaternion)" begin

            for i = 1:10    # do some repeats

                ql = quatrand()    # a random quaternion (should work for non-unit quaternions)
                qr = quatrand()    # a random quaternion (should work for non-unit quaternions)

                # transformation function
                J(X) = vec(ql * Quaternion(X...))

                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(ql, qr)
                FD_jac = ForwardDiff.jacobian(J, vec(qr))

                # compare
                @test all(abs(Matrix(R_jac) - FD_jac) .< thresh)

            end
        end

        @testset "Jacobian (Quaternion muliplication w.r.t. the left quaternion)" begin

            for i = 1:10    # do some repeats

                ql = quatrand()    # a random quaternion (should work for non-unit quaternions)
                qr = quatrand()    # a random quaternion (should work for non-unit quaternions)

                # transformation function
                J(X) = vec(Quaternion(X...) * qr)

                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(ql, qr, Val{false})
                FD_jac = ForwardDiff.jacobian(J, vec(ql))

                # compare
                @test all(abs(Matrix(R_jac) - FD_jac) .< thresh)

            end
        end =#

        # rotate a point by a RotMatrix
        @testset "Jacobian (RotMatrix rotation)" begin
            for i = 1:10    # do some repeats
                r = rand(RotMatrix{3,Float64})    # a random quaternion
                v = randn(SVector{3,Float64})

                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(r, v)
                FD_jac = ForwardDiff.jacobian(x -> RotMatrix(x)*v,
                                              SVector(r))

                # compare
                @test FD_jac ≈ R_jac
            end
        end

        # rotate a point by a quaternion
        @testset "Jacobian (QuatRotation rotation)" begin
            for i = 1:10    # do some repeats
                q = rand(QuatRotation)    # a random quaternion
                v = randn(SVector{3,Float64})

                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(q, v)
                FD_jac = ForwardDiff.jacobian(x -> QuatRotation(x[1], x[2], x[3], x[4])*v,
                                              Rotations.params(q))

                # compare
                @test FD_jac ≈ R_jac
            end
        end

        # rotate a point by a MRP
        @testset "Jacobian (MRP rotation)" begin
            for i = 1:10    # do some repeats
                p = rand(MRP)    # a random quaternion
                v = randn(SVector{3,Float64})

                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(p, v)
                FD_jac = ForwardDiff.jacobian(x -> MRP(x[1], x[2], x[3])*v,
                                              SVector(p.x, p.y, p.z))

                # compare
                @test FD_jac ≈ R_jac
            end
        end
#=
        # rotate a point by an MRP
        @testset "Jacobian (MRP rotation)" begin

            for i = 1:10    # do some repeats

                spq = SpQuat(nquatrand())    # a random quaternion
                X = randn(Vec{3,Float64})

                # transformation function
                J(spq) = Vector(rotate(SpQuat(spq...), X))

                # test jacobian to a Rotation matrix
                R_jac = Rotations.jacobian(spq, X)
                FD_jac = ForwardDiff.jacobian(J, vec(spq))

                # compare
                @test all(abs(Matrix(R_jac) - FD_jac) .< thresh)

            end
        end
=#

    end

    ###################################
    # Test Hessians
    ###################################
    #=
    @testset "Hessian checks" begin

        # SpQuat to Quaternion
        @testset "Hessian (SpQuat -> Quaternion)" begin

            for i = 1:10    # do some repeats

                q = nquatrand()                           # a random quaternion
                spq = Rotations.quat_to_spquat_naive(q)   # I want to test the full domain of SpQuats, not just the one with ||.|| < 1

                # test jacobian to a Rotation matrix
                R_hess = Rotations.hessian(Quaternion, spq)
                for d = 1:4
                    H(X) = vec(Quaternion(SpQuat(X...)))[d]   # transformation function
                    FD_hess = ForwardDiff.hessian(H, vec(spq))

                    # compare
                    @test all(abs(Matrix(R_hess[d]) - FD_hess) .< thresh)
                end
            end
        end

        # Quaternion to SpQuat
        @testset "Hessian (Quaternion -> SpQuat)" begin

            for i = 1:10    # do some repeats

                q = nquatrand()                           # a random quaternion

                # test jacobian to a Rotation matrix
                R_hess = Rotations.hessian(SpQuat, q)
                for d = 1:3
                    H(X) = vec(SpQuat(Quaternion(X...)))[d]   # transformation function
                    FD_hess = ForwardDiff.hessian(H, vec(q))

                    # compare
                    @test all(abs(Matrix(R_hess[d]) - FD_hess) .< thresh)
                end
            end
        end

        @testset "Hessian (Quaternion rotation)" begin

            for i = 1:10   # do some repeats

                q = nquatrand()    # a random quaternion
                X = randn(Vec{3,Float64})

                # transformation function
                R_hess = Rotations.hessian(q, X)

                for d = 1:3
                    H(q) = Vector(rotate(Quaternion(q...), X))[d]

                    # test
                    FD_hess = ForwardDiff.hessian(H, vec(q))

                    # compare
                    @test all(abs(Matrix(R_hess[d]) - FD_hess) .< thresh)
                end
            end
        end

        @testset "Hessian (SpQuat rotation)" begin

            for i = 1:10    # do some repeats

                q = nquatrand()    # a random quaternion
                spq = SpQuat(q)
                X = randn(Vec{3,Float64})

                # transformation function
                R_hess = Rotations.hessian(spq, X)

                for d = 1:3
                    H(spq) = Vector(rotate(SpQuat(spq...), X))[d]

                    # test
                    FD_hess = ForwardDiff.hessian(H, vec(spq))

                    # compare
                    @test all(abs(Matrix(R_hess[d]) - FD_hess) .< thresh)
                end
            end
        end
    end =#
end