text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "AWSCRT"
version = v"0.1.2"

# Collection of sources required to complete build
sources = [
	GitSource("https://github.com/awslabs/aws-c-mqtt.git", "dd09527354ea435812bf4be4bf9b32ba6a41c6a0"),
	GitSource("https://github.com/awslabs/aws-lc.git", "11b50d39cf2378703a4ca6b6fee9d76a2e9852d1"),
	GitSource("https://github.com/aws/s2n-tls.git", "0d41122bd2ca62a5de384b79c524dd48852b2071"),
	GitSource("https://github.com/awslabs/aws-c-common.git", "68f28f8df258390744f3c5b460250f8809161041"),
	GitSource("https://github.com/awslabs/aws-c-cal.git", "001007e36dddc5da47b8c56d41bb63e5fa9328d7"),
	GitSource("https://github.com/awslabs/aws-c-io.git", "59b4225bb87021d44d7fd2509b54d7038f11b7e7"),
	GitSource("https://github.com/awslabs/aws-c-compression.git", "5fab8bc5ab5321d86f6d153b06062419080820ec"),
	GitSource("https://github.com/awslabs/aws-c-http.git", "3f8ffda541eab815646f739cef2b350d6e7d5406"),
	GitSource("https://github.com/awslabs/aws-c-sdkutils.git", "e3c23f4aca31d9e66df25827645f72cbcbfb657a"),
	GitSource("https://github.com/awslabs/aws-c-auth.git", "e1b95cca6f2248c28b66ddb40bcccd35a59cb8b5"),
	GitSource("https://github.com/awslabs/aws-c-s3.git", "92067b1f44523e70337e0c5eb00b80c9cf10b941"),
	GitSource("https://github.com/awslabs/aws-checksums.git", "41df3031b92120b6d8127b7b7122391d5ac6f33f"),
	GitSource("https://github.com/awslabs/aws-c-event-stream.git", "e87537be561d753ec82e783bc0929b1979c585f8"),
	GitSource("https://github.com/awslabs/aws-c-iot.git", "e3ea832b032cd9db252822e3f2f9aeeeb8ad9a1d"),
	DirectorySource("./bundled"),
]

# Bash recipe for building across all platforms
script = raw"""
# Only need aws-lc and s2n-tls on linux and freebsd. macos and windows don't need it.
if [[ "${target}" =~ "linux" || "${target}" =~ "freebsd" ]]; then
	cd $WORKSPACE/srcdir/aws-lc

	# Patch for finding definition of AT_HWCAP2 for PowerPC
	atomic_patch -p1 "${WORKSPACE}/srcdir/patches/auxvec.patch"

	mkdir build && cd build
	cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
		-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
		-DBUILD_TESTING=OFF \
		-DCMAKE_BUILD_TYPE=Release \
		-DBUILD_SHARED_LIBS=OFF \
		-GNinja \
		..
	ninja -j${nproc}
	ninja install

	cd $WORKSPACE/srcdir/s2n-tls
	mkdir build && cd build
	cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
		-DCMAKE_PREFIX_PATH=${prefix} \
		-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
		-DBUILD_TESTING=OFF \
		-DCMAKE_BUILD_TYPE=Release \
		-DBUILD_SHARED_LIBS=OFF \
		-GNinja \
		..
	ninja -j${nproc}
	ninja install
fi

cd $WORKSPACE/srcdir/aws-c-common

# Patch for MinGW toolchain
atomic_patch -p1 "${WORKSPACE}/srcdir/patches/aws-c-common.patch"
find . -type f -exec sed -i 's/Windows.h/windows.h/g' {} +
find . -type f -exec sed -i 's/Shlwapi.h/shlwapi.h/g' {} +

mkdir build && cd build
if [[ "${target}" =~ "mingw" ]]; then
	winflags="-D_WIN32_WINNT=0x0601"
fi
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	${winflags} \
	..
cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-c-cal
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-c-io

# Patch for MinGW toolchain
find . -type f -exec sed -i 's/Windows.h/windows.h/g' {} +

mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-c-compression
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-c-http
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-c-mqtt
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-c-sdkutils
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
	cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-c-auth
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
	cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-checksums
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
	cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-c-event-stream
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-c-s3
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/aws-c-iot
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DBUILD_TESTING=OFF \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_SHARED_LIBS=OFF \
	..
cmake --build . -j${nproc} --target install

cd $WORKSPACE/srcdir/awscrt
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} \
	-DCMAKE_PREFIX_PATH=${prefix} \
	-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
	-DCMAKE_BUILD_TYPE=Release \
	..
cmake --build . -j${nproc} --target install

install_license ${WORKSPACE}/srcdir/license/LICENSE
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = filter(p -> !Sys.iswindows(p) && !Sys.isfreebsd(p), supported_platforms())

# The products that we will ensure are always built
products = [
	LibraryProduct("libawscrt", :libawscrt),
]

# Dependencies that must be installed before this package can be built
dependencies = [
	# TODO: this is needed only for Windows, but it looks like filtering
	# platforms for `HostBuildDependency` is broken
	HostBuildDependency("NASM_jll")
]

# Build the tarballs, and possibly a `build.jl` as well.
# Set lock_microarchitectures=false because aws-checksums uses the arch flag to specify the arch (-march=armv8-a+crc).
# gcc 4 is not supported because it doesn't export __ARM_ARCH
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat="1.6", preferred_gcc_version = v"5", lock_microarchitecture=false)

max_stars_repo_name: staticfloat/BinaryBuilderRepos

max_issues_repo_name: staticfloat/BinaryBuilderRepos

max_forks_repo_name: staticfloat/BinaryBuilderRepos


text:
using IntervalArithmetic
using Test
using StaticArrays
using Random

@testset "rand tests" begin

    X = 3..4
    for i in 1:100
        @test rand(X) ∈ X
    end

    Y = IntervalBox(3..4, 5..6)
    for i in 1:100
        @test rand(Y) ∈ Y
    end

    X = 3..4
    for i in 1:100
        @test rand(X,4)[(i%4)+1] ∈ X
    end

#     Y = IntervalBox(3..4, 5..6)
#     for i in 1:100
#         @test rand(Y,2)[(i%2)+1][(i%2)+1] ∈ Y[(i%2)+1]
#     end

    for T in (Float32, Float64, BigFloat)
        X = Interval{T}(3, 4)
        @test rand(X) isa T

        Y = IntervalBox(X, X)
        @test rand(Y) isa SVector{2,T}
    end

    for T in (Float32, Float64, BigFloat)
        X = Interval{T}(3, 7)
        Y = rand(X, 7)
        @test Y isa Array{T, 1}
        for x in Y
            @test x isa T
        end
    end
end

ext: jl


text:
@testset "moments" begin
    ind = rand([0,1], 10)
    @test sum(normalize_indicator(ind)) ≈ 1.

    Ind = diagm(ind)
    @test sum(normalize_indicator(Ind)) ≈ 1.

    @test to_indicator_matrix(ind) == Ind

    Ind = rand([0,1], 10, 10)
    @test sum(normalize_indicator(Ind, 1), dims=1) ≈ ones(Int64, 1, 10)
    @test sum(normalize_indicator(Ind, 2), dims=2) ≈ ones(Int64, 10)

    @test diag(union_diagonal!(Ind)) == ones(Int64, 10)

    ind = rand([0,1], 10)

    G = graph_filter(ind, 1)
    @test G isa SparseVector
    @test sum(G .!= 0) == sum(ind .!= 0)
    @test sum(G) ≈ 1.

    G = graph_filter(ind, 2)
    @test G isa SparseMatrixCSC
    @test sum(G .!= 0) == sum(ind .!= 0)
    @test sum(G) ≈ 1.

    adj = rand([0,1], 10, 10)

    G = graph_filter(adj, 1, dims=1)
    @test G isa SparseMatrixCSC
    @test sum(G .!= 0, dims=1) == sum(adj .!= 0, dims=1)
    @test sum(G, dims=1) ≈ ones(Int64, 1, 10)

    G = graph_filter(adj, 1, dims=2)
    @test G isa SparseMatrixCSC
    @test sum(G .!= 0, dims=2) == sum(adj .!= 0, dims=2)
    @test sum(G, dims=2) ≈ ones(Int64, 10)

    adj = [1 0 0; 1 0 1; 1 1 1]
    blocks = [diagm([1/3, 1/3, 1/3]), diagm([0, 0, 1]), diagm([0, 1/2, 1/2])]
    @test graph_filter(adj, 2, dims=1) == cat(blocks...,dims=(1,2))

    blocks = [diagm([1, 0, 0]), diagm([1/2, 0, 1/2]), diagm([1/3, 1/3, 1/3])]
    @test graph_filter(adj, 2, dims=2) == cat(blocks...,dims=(1,2))

    A = rand([0,1], 5, 5)
    X = rand(5, 10)
    @test size(moment(A, X, 1, dims=1)) == size(X)
    @test size(moment(A, Matrix(X'), 1, dims=2)) == size(X')
    # @test size(moment(A, X, 2, dims=1)) == (size(X, 1), 5*10)
    # @test size(moment(A, Matrix(X'), 2, dims=2)) == (5*10, size(X, 1))
end


text:
# ---
# title: 33. Search in Rotated Sorted Array
# id: problem33
# author: zhwang
# date: 2022-03-18
# difficulty: Medium
# categories: Array, Binary Search
# link: <https://leetcode.com/problems/search-in-rotated-sorted-array/description/>
# hidden: true
# ---
#
# You are given an integer array `nums` sorted in ascending order, and an
# integer `target`.
#
# Suppose that `nums` is rotated at some pivot unknown to you beforehand (i.e.,
# `[0,1,2,4,5,6,7]` might become `[4,5,6,7,0,1,2]`).
#
# _If`target` is found in the array return its index, otherwise, return `-1`._
#
#
#
# **Example 1:**
#
#
#
#     Input: nums = [4,5,6,7,0,1,2], target = 0
#     Output: 4
#
#
# **Example 2:**
#
#
#
#     Input: nums = [4,5,6,7,0,1,2], target = 3
#     Output: -1
#
#
# **Example 3:**
#
#
#
#     Input: nums = [1], target = 0
#     Output: -1
#
#
#
#
# **Constraints:**
#
#   * `1 <= nums.length <= 5000`
#   * `-10^4 <= nums[i] <= 10^4`
#   * All values of `nums` are **unique**.
#   * `nums` is guranteed to be rotated at some pivot.
#   * `-10^4 <= target <= 10^4`
#
#
## @lc code=start
using LeetCode

function search_left_border(left::Int, right::Int, key::Function)
    ## e.g. search_left_border(1, 10, >(3)) | returns 4
    while left <= right
        mid = left + (right - left) >> 1
        if key(mid) ## lies in the right part
            right = mid - 1
        else
            left = mid + 1
        end
    end
    return left
end

function search_in_rotated_array(nums::Vector{Int}, target::Int)::Int
    n, rightmost = length(nums), last(nums)
    if target > rightmost ## lies in the right side
        pos = search_left_border(1, n, i -> (nums[i] <= rightmost || nums[i] >= target))
        return pos <= n && nums[pos] == target ? pos - 1 : -1
    else
        pos = search_left_border(1, n, i -> (target <= nums[i] <= rightmost))
        return pos <= n && nums[pos] == target ? pos - 1 : -1
    end
end
## @lc code=end


text:
"""
    GroupBy(key, rf, [init])
    GroupBy(key, xf::Transducer, [step = right, [init]])

Group the input stream by a function `key` and then fan-out each group
of key-value pairs to the reducing function `rf`.

For example, if `GroupBy` is used as in:

    Map(upstream) |> GroupBy(key, rf, init) |> Map(downstream)

then the "function signatures" would be:

    upstream(_) :: V
    key(::V) :: K
    rf(::Y, ::Pair{K, V}) ::Y
    downstream(::Dict{K, Y})

That is to say,

* Ouput of the `upstream` is fed into the function `key` that produces
  the group key (of type `K`).

* For each new group key, a new transducible process is started with
  the initial state `init :: Y`.  Pass [`OnInit`](@ref) or
  [`CopyInit`](@ref) object to `init` for creating a dedicated
  (possibly mutable) state for each group.

* After one "nested" reducing function `rf` is called, the
  intermediate result dictionary (of type `Dict{K, Y}`) accumulating
  the current and all preceding results is then fed into the
  `downstream`.

See also `groupreduce` in
[SplitApplyCombine.jl](https://github.com/JuliaData/SplitApplyCombine.jl).

!!! compat "Transducers.jl 0.3"

    New in version 0.3.

# Examples
```jldoctest
julia> using Transducers
       using BangBang  # for `push!!`

julia> foldl(right, GroupBy(string, Map(last), push!!), [1, 2, 1, 2, 3])
Transducers.GroupByViewDict{String,Array{Int64,1},…} with 3 entries:
  "1" => [1, 1]
  "2" => [2, 2]
  "3" => [3]
```

Note that the reduction stops if one of the group returns a
[`reduced`](@ref).  This can be used, for example, to find if there is
a group with a sum grater than 3 and stop the computation as soon as
it is find:

```jldoctest; setup = :(using Transducers)
julia> result = transduce(
           GroupBy(
               string,
               Map(last) |> Scan(+) |> ReduceIf(x -> x > 3),
           ),
           right,
           nothing,
           [1, 2, 1, 2, 3],
       );

julia> result isa Reduced
true

julia> unreduced(result)
Transducers.GroupByViewDict{String,Any,…} with 2 entries:
  "1" => 2
  "2" => 4
```
"""
struct GroupBy{K, R, T} <: Transducer
    key::K
    rf::R
    init::T
end

function GroupBy(key, xf::Transducer, step = right, init = DefaultInit)
    rf = _reducingfunction(xf, step; init = init)
    return GroupBy(key, rf, init)
end

GroupBy(key, rf) = GroupBy(key, _asmonoid(rf), DefaultInit)

# `GroupByViewDict` wraps a dictionary whose values are the
# (composite) states of the reducing function and provides a view such
# that the its values are the state/result/accumulator of the bottom
# reducing function.
struct GroupByViewDict{K,V,S<:DefaultInitOf,D<:AbstractDict{K}} <: AbstractDict{K,V}
    state::D
end

# https://github.com/JuliaLang/julia/issues/30751
_typesubtract(::Type{Larger}, ::Type{Smaller}) where {Larger,Smaller} =
    _typesubtract_impl(Smaller, Larger)
_typesubtract_impl(::Type{T}, ::Type{T}) where {T} = Union{}
_typesubtract_impl(::Type{T}, ::Type{Union{T,S}}) where {S,T} = S
_typesubtract_impl(::Type, ::Type{S}) where {S} = S

function GroupByViewDict(state::AbstractDict{K,V0}, xf::GroupBy) where {K,V0}
    S = typeof(DefaultInit(_realbottomrf(xf.rf)))
    V = _typesubtract(V0, S)
    return GroupByViewDict{K,V,S,typeof(state)}(state)
end

struct _NoValue end

Base.IteratorSize(::Type{<:GroupByViewDict}) = Base.SizeUnknown()
function Base.iterate(dict::GroupByViewDict{<:Any,<:Any,S}, state = _NoValue()) where {S}
    y = state isa _NoValue ? iterate(dict.state) : iterate(dict.state, state)
    y === nothing && return nothing
    while true
        (k, v), state = y
        v isa S || return (k => unwrap_all(unreduced(v))), state
        y = iterate(dict.state, state)
        y === nothing && return nothing
    end
end

Base.length(dict::GroupByViewDict) = count(true for _ in dict)
function Base.showarg(io::IO, dict::GroupByViewDict, _toplevel)
    print(io, GroupByViewDict, '{', keytype(dict), ',', valtype(dict), ",…}")
end

function Base.getindex(dict::GroupByViewDict{<:Any,<:Any,S}, key) where {S}
    value = unwrap_all(unreduced(dict.state[key]))
    value isa S && throw(KeyError(key))
    return value
end

function start(rf::R_{GroupBy}, result)
    gstate = Dict{Union{},Union{}}()
    return wrap(rf, gstate, start(inner(rf), result))
end

complete(rf::R_{GroupBy}, result) = complete(inner(rf), unwrap(rf, result)[2])

@inline function next(rf::R_{GroupBy}, result, input)
    wrapping(rf, result) do gstate, iresult
        key = xform(rf).key(input)
        gstate, somegr = modify!!(gstate, key) do value
            if value === nothing
                gr0 = start(xform(rf).rf, xform(rf).init)
            else
                gr0 = something(value)
            end
            return Some(next(xform(rf).rf, gr0, key => input))  # Some(gr)
        end
        gr = something(somegr)
        iresult = next(inner(rf), iresult, GroupByViewDict(gstate, xform(rf)))
        if gr isa Reduced && !(iresult isa Reduced)
            return gstate, reduced(complete(inner(rf), iresult))
        else
            return gstate, iresult
        end
    end
end

function combine(rf::R_{GroupBy}, a, b)
    gstate_a, ira = unwrap(rf, a)
    gstate_b, irb = unwrap(rf, b)
    gstate_c = mergewith!!(gstate_a, gstate_b) do ua, ub
        combine(xform(rf).rf, ua, ub)
    end
    irc = combine(inner(rf), ira, irb)
    irc = next(inner(rf), irc, GroupByViewDict(gstate_c, xform(rf)))
    return wrap(rf, gstate_c, irc)
end


text:
using Feather
using DataFrames
using LightGraphs
using GraphIO
using ParserCombinator

data = Feather.read(
    joinpath("experiments", "test_run_grid", "agents", "adata.feather")
)

graph = LightGraphs.loadgraph(
    joinpath("experiments", "test_run_grid", "graphs", "rep_01.gml"),
    GraphIO.GML.GMLFormat()
)

connected_comps = LightGraphs.connected_components(graph)
connected_comps_by_size = [length(i) for i in connected_comps]
# SizeBiggestComponent
maximum(connected_comps_by_size)
# SeperateComponents
length(connected_comps)

data

# StubbornCount in data
# NetworkType in data
# UniqueCultures -> aggregate from Culture
# SeperateComponents
# ExcessZeros -> aggregate from Culture

function aggregate()

end

function read_raw_data()
end

max_stars_repo_name: JohannesNakayama/axelrodnet

max_issues_repo_name: JohannesNakayama/axelrodnet

max_forks_repo_name: JohannesNakayama/axelrodnet


text:
module actionlib
using Cxx

__action_srvs = []

# Server

"""
    SimpleActionServer(name::String, action_spec)

Constructor for a SimpleActionServer.
"""
function SimpleActionServer(name::String, action_spec)
    push!(__action_srvs, icxx"""
        return new actionlib::SimpleActionServer<$(action_spec)>($(pointer(name)), false);
    """)
    return last(__action_srvs)
end

"""
    SimpleActionServer(name::String, action_spec, auto_start::Bool)

Constructor for a SimpleActionServer.
"""
function SimpleActionServer(name::String, action_spec, auto_start::Bool)
    push!(__action_srvs, icxx"""
        return new actionlib::SimpleActionServer<$(action_spec)>($(pointer(name)), $(auto_start));
    """)
    return last(__action_srvs)
end

"""
   registerGoalCallback(action_server, callback)

Allows users to register a callback to be invoked when a new goal is available.
"""
function registerGoalCallback(action_server::Cxx.CxxCore.CppPtr, callback)
    icxx"""
        boost::function<void ()> cpp_execute_cb = [&]() {
            $:(callback()::Nothing;nothing);
        };
        $action_server->registerGoalCallback(cpp_execute_cb);
    """
end

"""
    registerPreemptCallback(action_server, callback)

Allows users to register a callback to be invoked when a new preempt request is available.
"""
function registerPreemptCallback(action_server::Cxx.CxxCore.CppPtr, callback)
    icxx"""
        boost::function<void ()> cpp_execute_cb = [&]() {
            $:(callback()::Nothing;nothing);
        };
        $action_server->registerPreemptCallback(cpp_execute_cb);
    """
end

"""
    acceptNewGoal(action_server)

Accepts a new goal when one is available. The status of this goal is set to active upon acceptance, and the status of any previously active goal is set to preempted. Preempts received for the new goal between checking if isNewGoalAvailable or invocation of a goal callback and the acceptNewGoal call will not trigger a preempt callback. This means, isPreemptRequested should be called after accepting the goal even for callback-based implementations to make sure the new goal does not have a pending preempt request.
"""
acceptNewGoal(action_server::Cxx.CxxCore.CppPtr) = icxx" return &*$action_server->acceptNewGoal();"

"""
    start(action_server)

Explicitly start the action server, used it auto_start is set to false.
"""
start(action_server::Cxx.CxxCore.CppPtr) = @cxx action_server->start()

"""
    isActive(action_server)

Allows polling implementations to query about the status of the current goal.
"""
isActive(action_server::Cxx.CxxCore.CppPtr) = @cxx action_server->isActive()

"""
    isNewGoalAvailable(action_server)

Allows polling implementations to query about the availability of a new goal.
"""
isNewGoalAvailable(action_server::Cxx.CxxCore.CppPtr) = @cxx action_server->isNewGoalAvailable()

"""
    isPreemptRequested(action_server)

Allows polling implementations to query about preempt requests.
"""
isPreemptRequested(action_server::Cxx.CxxCore.CppPtr) = @cxx action_server->isPreemptRequested()

"""
    shutdown(action_server)

Explicitly shutdown the action server.
"""
shutdown(action_server::Cxx.CxxCore.CppPtr) = @cxx action_server->shutdown()

"""
    setAborted(action_server)

Sets the status of the active goal to aborted.
"""
setAborted(action_server::Cxx.CxxCore.CppPtr) = @cxx action_server->setAborted()

"""
    setAborted(action_server, result, text::String)

Sets the status of the active goal to aborted.
"""
setAborted(action_server::Cxx.CxxCore.CppPtr, result::Cxx.CxxCore.CppPtr, text::String) = icxx"$action_server->setAborted(*$result, $(pointer(text)));"

"""
    setPreempted(action_server)

Sets the status of the active goal to preempted.
"""
setPreempted(action_server::Cxx.CxxCore.CppPtr) = @cxx action_server->setPreempted()

"""
    setPreempted(action_server, result, text::String)

Sets the status of the active goal to preempted.
"""
setPreempted(action_server::Cxx.CxxCore.CppPtr, result::Cxx.CxxCore.CppPtr, text::String) = icxx"$action_server->setPreempted(*$result, $(pointer(text)));"

"""
    setSucceeded(action_server)

Sets the status of the active goal to succeeded.
"""
setSucceeded(action_server::Cxx.CxxCore.CppPtr) = @cxx action_server->setSucceeded()

"""
    setSucceeded(action_server, result, text::String)

Sets the status of the active goal to succeeded.
"""
setSucceeded(action_server::Cxx.CxxCore.CppPtr, result::Cxx.CxxCore.CppPtr, text::String) = icxx"$action_server->setSucceeded(*$result, $(pointer(text)));"

"""
    publishFeedback(action_server, feedback)

Publishes feedback for a given goal.
"""
publishFeedback(action_server::Cxx.CxxCore.CppPtr, feedback::Cxx.CxxCore.CppPtr) = icxx"$action_server->publishFeedback(*$feedback);"

# Client

"""
    SimpleActionClient(name::String, action_spec, spin::Bool)

Simple constructor.
"""
function SimpleActionClient(name::String, action_spec, spin::Bool)
    icxx"""
        return new actionlib::SimpleActionClient<$(action_spec)>($(pointer(name)), $spin);
    """
end

"""
    SimpleActionClient(name::String, action_spec)

Simple constructor.
"""
function SimpleActionClient(name::String, action_spec)
    icxx"""
        return new actionlib::SimpleActionClient<$(action_spec)>($(pointer(name)));
    """
end

"""
    cancelAllGoals(action_client)

Cancel all goals currently running on the action server.
"""
cancelAllGoals(action_client::Cxx.CxxCore.CppPtr) = @cxx action_client->cancelAllGoals()

"""
    cancelGoal(action_client)

Cancel the goal that we are currently pursuing.
"""
cancelGoal(action_client::Cxx.CxxCore.CppPtr) = @cxx action_client->cancelGoal()

"""
    isServerConnected(action_client)

Checks if the action client is successfully connected to the action server.
"""
isServerConnected(action_client::Cxx.CxxCore.CppPtr) = @cxx action_client->isServerConnected()

"""
    stopTrackingGoal(action_client)

Stops tracking the state of the current goal. Unregisters this goal's callbacks.
"""
stopTrackingGoal(action_client::Cxx.CxxCore.CppPtr) = @cxx action_client->stopTrackingGoal()

"""
    waitForResult(action_client)

Blocks until this goal finishes.
"""
waitForResult(action_client::Cxx.CxxCore.CppPtr) = @cxx action_client->waitForResult()

"""
    waitForResult(action_client, timeout)

Blocks until this goal finishes.
"""
waitForResult(action_client::Cxx.CxxCore.CppPtr, timeout::Cxx.CxxCore.CppPtr{Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N} where N,(false, false, false)}) = @cxx action_client->waitForResult(*(timeout))

waitForResult(action_result::Cxx.CxxCore.CppPtr, timeout::Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N where N}) = @cxx action_client->waitForResult(timeout)

"""
    waitForServer(action_client)

Waits for the ActionServer to connect to this client.
"""
waitForServer(action_client::Cxx.CxxCore.CppPtr) = @cxx action_client->waitForServer()

"""
    waitForServer(action_client, timeout)

Waits for the ActionServer to connect to this client.
"""
waitForServer(action_client::Cxx.CxxCore.CppPtr, timeout::Cxx.CxxCore.CppPtr{Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N} where N,(false, false, false)}) = @cxx action_client->waitForServer(*(timeout))

waitForServer(action_result::Cxx.CxxCore.CppPtr, timeout::Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N where N}) = @cxx action_client->waitForServer(timeout)

"""
    sendGoal(action_client, goal)

Sends a goal to the ActionServer, and also registers callbacks.
"""
sendGoal(action_client::Cxx.CxxCore.CppPtr, goal::Cxx.CxxCore.CppPtr) = icxx"$action_client->sendGoal(*$goal);"

"""
    sendGoalAndWait(action_client, goal, ex_timeout, pr_timeout)

Sends a goal to the ActionServer, and waits until the goal completes or a timeout is exceeded.
"""
sendGoalAndWait(action_client::Cxx.CxxCore.CppPtr, goal::Cxx.CxxCore.CppPtr, ex_timeout::Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N where N}, pr_timeout::Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N where N}) = icxx"$action_client->sendGoalAndWait(*$goal, $ex_timeout, $pr_timeout);"

sendGoalAndWait(action_client::Cxx.CxxCore.CppPtr, goal::Cxx.CxxCore.CppPtr, ex_timeout::Cxx.CxxCore.CppPtr{Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N} where N,(false, false, false)}, pr_timeout::Cxx.CxxCore.CppPtr{Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N} where N,(false, false, false)}) = icxx"$action_client->sendGoalAndWait(*$goal, *$ex_timeout, *$pr_timeout);"

sendGoalAndWait(action_client::Cxx.CxxCore.CppPtr, goal::Cxx.CxxCore.CppPtr, ex_timeout::Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N where N}, pr_timeout::Cxx.CxxCore.CppPtr{Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N} where N,(false, false, false)}) = icxx"$action_client->sendGoalAndWait(*$goal, $ex_timeout, *$pr_timeout);"

sendGoalAndWait(action_client::Cxx.CxxCore.CppPtr, goal::Cxx.CxxCore.CppPtr, ex_timeout::Cxx.CxxCore.CppPtr{Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N} where N,(false, false, false)}, pr_timeout::Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("ros::Duration")},(false, false, false)},N where N}) = icxx"$action_client->sendGoalAndWait(*$goal, *$ex_timeout, $pr_timeout);"

# TODO this returns a bad_alloc quite frequently...
"""
    getResult(action_client)

Get the Result of the current goal.
"""
getResult(action_client::Cxx.CxxCore.CppPtr) = icxx"return &*$action_client->getResult();"

"""
    getState(action_client)

Get the state information for this goal.
"""
getState(action_client::Cxx.CxxCore.CppPtr) = @cxx action_client->getState()

"""
    getText(state)

Returns the text field of the state.
"""
getText(state::Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("actionlib::SimpleClientGoalState")},(false, false, false)},N }where N) = unsafe_string(@cxx state->getText())

"""
    isDone(state)

Determine if goal is done executing (ie. reached a terminal state).
"""
isDone(state::Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("actionlib::SimpleClientGoalState")},(false, false, false)},N }where N) = @cxx state->isDone()

"""
    toString(state)

Convert the state to a string. Useful when printing debugging information.
"""
toString(state::Cxx.CxxCore.CppValue{Cxx.CxxCore.CxxQualType{Cxx.CxxCore.CppBaseType{Symbol("actionlib::SimpleClientGoalState")},(false, false, false)},N }where N) = unsafe_string(@cxx state->toString())

end


text:
module VeldhuisData

wing = Dict{String,Union{Int, String, Float64, Vector{Float64}, Array{Float64,2}}}()
wing["span"] = 1.28 # m
wing["area"] = 0.3074 # m^2
wing["chord_root"] = 0.24 # m
wing["chord_tip"] = 0.24 # m
wing["mac"] = 0.24 # m
wing["airfoil"] = "NACA 64_2-015A"
wing["chords"] = [0.0 wing["chord_root"]; 1.0 wing["chord_tip"]]
wing["chords"][:,1] .*= wing["span"]/2
wing["twists"] = [0.0 0.0; 1.0 0.0]

rotor = Dict{String,Union{Int, String, Float64, Vector{Float64}, Array{Float64,2}}}()
rotor["Nblades"] = 4
rotor["2y/b"] = 0.469
rotor["y"] = rotor["2y/b"] * wing["span"] / 2 # m
rotor["radius"] = 0.118 # m - at the tip
rotor["diameter"] = rotor["radius"] * 2 # m - at the tip
rotor["radius_hub"] = 0.0163 # m
rotor["diameter_hub"] = rotor["radius_hub"] * 2 # m
rotor["r/R vs chord/R"] = [0.206897 0.15571575695159628 #! For now I just copied these over from the Epema Data since Veldhuis doesn't give info on his rotors
                            0.23119777158774377 0.15571575695159628
                            0.24373259052924792 0.15489186405767247
                            0.254874651810585 0.15427394438722963
                            0.2646239554317549 0.1536560247167868
                            0.2771587743732591 0.152832131822863
                            0.28690807799442897 0.15242018537590113
                            0.29944289693593307 0.1515962924819773
                            0.31058495821727017 0.15097837281153448
                            0.32033426183844016 0.1505664263645726
                            0.33008356545961004 0.14994850669412974
                            0.34122562674094703 0.1493305870236869
                            0.35027855153203336 0.14871266735324407
                            0.3621169916434541 0.14809474768280123
                            0.3746518105849582 0.14747682801235837
                            0.3857938718662953 0.14685890834191553
                            0.39484679665738176 0.14644696189495365
                            0.4032033426183844 0.14582904222451082
                            0.41364902506963797 0.14562306900102984
                            0.42479108635097473 0.14582904222451082
                            0.43454038997214484 0.14603501544799175
                            0.44846796657381605 0.1462409886714727
                            0.4623955431754875 0.14624098867147267
                            0.4798050139275766 0.14644696189495363
                            0.4972144846796658 0.14665293511843458
                            0.5097493036211699 0.14665293511843458
                            0.5250696378830083 0.1474768280123584
                            0.5181058495821728 0.1470648815653965
                            0.5376044568245125 0.14809474768280123
                            0.5536211699164346 0.14891864057672502
                            0.5682451253481894 0.14953656024716785
                            0.5793871866295265 0.15015447991761072
                            0.5919220055710307 0.1505664263645726
                            0.6016713091922006 0.15097837281153448
                            0.6142061281337048 0.1515962924819773
                            0.6267409470752089 0.1518022657054583
                            0.6406685236768802 0.15200823892893922
                            0.6559888579387188 0.15221421215242015
                            0.6740947075208914 0.15262615859938206
                            0.6866295264623956 0.152832131822863
                            0.6991643454038998 0.1532440782698249
                            0.7103064066852367 0.1532440782698249
                            0.7207520891364904 0.15345005149330587
                            0.7381615598885793 0.15303810504634396
                            0.756267409470752 0.15242018537590113
                            0.7743732590529246 0.15200823892893922
                            0.7862116991643455 0.1518022657054583
                            0.7889972144846799 0.1518022657054583
                            0.7924791086350975 0.1511843460350154
                            0.7966573816155988 0.15036045314109164
                            0.8077994428969361 0.1480947476828012
                            0.8217270194986074 0.1454170957775489
                            0.83983286908078 0.1419155509783728
                            0.8565459610027856 0.1388259526261586
                            0.8586350974930362 0.1384140061791967
                            0.8607242339832869 0.13779608650875386
                            0.8662952646239553 0.13553038105046342
                            0.8746518105849582 0.13223480947476826
                            0.8837047353760447 0.12852729145211123
                            0.8920612813370473 0.12523171987641607
                            0.8990250696378829 0.1223480947476828
                            0.9059888579387186 0.11946446961894952
                            0.9129526462395544 0.11658084449021626
                            0.91991643454039 0.113697219361483
                            0.9317548746518106 0.10875386199794025
                            0.9366295264623955 0.10628218331616889
                            0.9456824512534819 0.10175077239958805
                            0.953342618384401 0.09763130792996907
                            0.9610027855153204 0.09351184346035016
                            0.9658774373259055 0.09083419155509764
                            0.9721448467966572 0.08692070030895985
                            0.9770194986072421 0.08362512873326469
                            0.9811977715877437 0.08074150360453139
                            0.9860724233983288 0.07765190525231722
                            0.9902506963788301 0.07456230690010296
                            0.9937325905292481 0.07209062821833162
                            0.998607242339833 0.06920700308959835
                            1.0 0.06817713697219355]

rotor["r/R vs twist"] = [0.206897  52.6519
                          0.231782  52.6519
                          0.254709  51.5181
                          0.272959  50.5684
                          0.290999  49.6514
                          0.308355  48.7413
                          0.325711  47.8624
                          0.34396   46.9143
                          0.359896  46.0206
                          0.377252  45.1761
                          0.394608  44.2941
                          0.411964  43.4694
                          0.431143  42.4781
                          0.446501  41.7411
                          0.463856  40.87
                          0.480862  40.0688
                          0.498218  39.2055
                          0.516415  38.325
                          0.534507  37.5021
                          0.552705  36.631
                          0.570797  35.7754
                          0.588153  34.9354
                          0.606192  34.0759
                          0.625284  33.2219
                          0.643376  32.4775
                          0.661416  31.6888
                          0.680507  30.8908
                          0.698599  30.113
                          0.716639  29.3438
                          0.735573  28.7137
                          0.756242  28.0557
                          0.775386  27.4763
                          0.79432   26.9007
                          0.814621  26.3477
                          0.833765  25.8429
                          0.854066  25.2976
                          0.87321   24.8006
                          0.891776  24.3386
                          0.909566  23.9081
                          0.926505  23.4784
                          0.942502  23.0943
                          0.959858  22.6918
                          0.979055  22.3024
                          1.0       21.9829]

setup = Dict{String,Union{Int, String, Float64, Vector{Float64}, Array{Float64,2}}}()
setup["Vinf"] = 50.0 # m/s
setup["wing_aoa1"] = 0.0*pi/180 # deg.
setup["wing_aoa2"] = 4.0*pi/180 # deg.
setup["J"] = 0.85

results = Dict{String,Union{Int, String, Float64, Vector{Float64}, Array{Float64,2}}}()

results["normalized cl distribution 0 deg aoa rotors on"] = [0.09619921363040625 0.029354838709677367
                                                            .17404980340760133 0.032258064516128976
                                                            .25111402359108773 0.04193548387096771
                                                            .28256880733944946 0.04290322580645156
                                                            .31402359108781134 0.09612903225806448
                                                            .34469200524246375 0.08903225806451609
                                                            .3753604193971165 0.08032258064516125
                                                            .4076015727391874 0.04999999999999995
                                                            .5287024901703797 -0.025161290322580687
                                                            .5601572739187416 -0.05774193548387102
                                                            .59161205766710346 -0.07806451612903226
                                                            .6230668414154652 -0.08354838709677423
                                                            .6537352555701176 -0.04548387096774195
                                                            .6859764089121887 -0.021290322580645227
                                                            .7473132372214937 -0.018709677419354864
                                                            .8102228047182172 -0.013548387096774195
                                                            .8707732634338137 -0.010967741935483832
                                                            .9179554390563564 -0.008387096774193525]

results["normalized cl distribution 4 deg aoa rotors on"] = [0.09772047626521212 0.36487438017230045
                                                            .17456214395697152 0.3699581337937061
                                                            .25141017429406453 0.3776505720018155
                                                            .2836038871521223 0.3770728438055406
                                                            .3151982388197718 0.4307570275417708
                                                            .3466386144703521 0.42131104427976984
                                                            .37734219579132215 0.4097793858774725
                                                            .4093806601032445 0.3455497537656257
                                                            .52987516489855814 0.2482967198442424
                                                            .56206378764034916 0.24563204397860466
                                                            .59276864149038595 0.23462212249364806
                                                            .6242090171409665 0.22517613923164698
                                                            .6557779182272824 0.2684255846210621
                                                            .6872221114650627 0.2605448121110834
                                                            .7486521796302029 0.24687275981862233
                                                            .8122608175575076 0.2264143100135313
                                                            .8736476197343806 0.19500320253148462
                                                            .9203952475281122 0.16153059796140856]

end #module

max_stars_repo_name: byuflowlab/AircraftSystems

max_issues_repo_name: byuflowlab/AircraftSystems

max_forks_repo_name: byuflowlab/AircraftSystems


text:
function MinimalT1(S)
    Min = S[1].LB;
    Ind = 1;
    for i = 2:length(S)
        if S[i].LB <= Min
            Min = S[i].LB;
            Ind = i;
        end
    end
    return Ind,Min;
end


text:
using Parameters, LinearAlgebra, DataStructures, Plots, Distributions, Random, StatsBase
import Base: push!, isless, show

include("event.jl")
    include("state/state.jl")
        include("state/totals/total_state.jl")
        include("state/tracking/job.jl")
        include("state/tracking/tracked_state.jl")
        include("state/full_tracking/full_job.jl")
        include("state/full_tracking/full_tracked_state.jl")
include("simulation.jl")
include("output.jl")

#run_default_sims(lambda_range = 1:0.1:5, max_time = 10^5)
#run_tracking_sim(get_scenarios()[1], 3)
#run_default_no_tracking(lambda_range = 1:0.5:5, max_time = 10^7)


text:
"""
    @test_reference filename expr [by] [kw...]

Tests that the expression `expr` with reference `filename` using
equality test strategy `by`.

The pipeline of `test_reference` is:

1. preprocess `expr`
2. read and preprocess `filename`
3. compare the results using `by`
4. if test fails in an interactive session (e.g, `include(test/runtests.jl)`), an interactive dialog will be trigered.

Arguments:

* `filename::String`: _relative_ path to the file that contains the macro invocation.
* `expr`: the actual content used to compare.
* `by`: the equality test function. By default it is `isequal` if not explicitly stated.

# Types

The file-extension of `filename`, as well as the type of the
result of evaluating `expr`, determine how contents are processed and
compared. The contents is treated as:

* Images when `expr` is an image type, i.e., `AbstractArray{<:Colorant}`;
* SHA256 when `filename` endswith `*.sha256`;
* Text as a fallback.

## Images

Images are compared _approximately_ using a different `by` to ignore most encoding
and decoding errors. The default function is generated from [`psnr_equality`](@ref).

The file can be either common image files (e.g., `*.png`), which are handled by
`FileIO`, or text-coded `*.txt` files, which is handled by `ImageInTerminal`.
Text-coded image has less storage requirements and also allows to view the
reference file in a simple terminal using `cat`.

## SHA256

The hash of the `expr` and content of `filename` are compared.

!!! tip

    This is useful for a convenient low-storage way of making
    sure that the return value doesn't change for selected test
    cases.

## Fallback

Simply test the equality of `expr` and the contents of `filename` without any
preprocessing.

# Examples

```julia
# store as string using ImageInTerminal with encoding size (5,10)
@test_reference "camera.txt" testimage("cameraman") size=(5,10)

# using folders in the relative path is allowed
@test_reference "references/camera.png" testimage("cameraman")

# Images can also be stored as hash. Note however that this
# can only check for equality (no tolerance possible)
@test_reference "references/camera.sha256" testimage("cameraman")

# test images with custom psnr threshold
@test_reference "references/camera.png" testimage("cameraman") by=psnr_equality(20)

# test number with absolute tolerance 10
@test_reference "references/string3.txt" 1338 by=(ref, x)->isapprox(ref, x; atol=10)
```
"""
macro test_reference(reference, actual, kws...)
    dir = Base.source_dir()
    expr = :(test_reference(abspath(joinpath($dir, $(esc(reference)))), $(esc(actual))))
    for kw in kws
        (kw isa Expr && kw.head == :(=)) || error("invalid signature for @test_reference")
        k, v = kw.args
        push!(expr.args, Expr(:kw, k, esc(v)))
    end
    expr
end

function test_reference(
    filename::AbstractString, raw_actual;
    by = nothing, render = nothing, kw...)

    test_reference(query_extended(filename), raw_actual, by, render; kw...)
end

function test_reference(
    file::File{F},
    raw_actual::T,
    equiv=nothing,
    rendermode=nothing;
    kw...) where {F <: DataFormat, T}

    path = file.filename
    dir, filename = splitdir(path)

    # infer the default rendermode here
    # since `nothing` is always passed to this method from
    # test_reference(filename::AbstractString, raw_actual; kw...)
    if rendermode === nothing
        rendermode = default_rendermode(F, raw_actual)
    end

    actual = _convert(F, raw_actual; kw...)
    # preprocessing when reference file doesn't exists
    if !isfile(path)
        @info("Reference file for \"$filename\" does not exist. It will be created")
        # TODO: move encoding out from render
        render(rendermode, raw_actual)

        mkpath(dir)
        savefile(file, actual)

        @info("Please run the tests again for any changes to take effect")
        return nothing # skip current test case
    end

    # file exists
    reference = loadfile(T, file)

    if equiv === nothing
        # generally, `reference` and `actual` are of the same type after preprocessing
        equiv = default_equality(reference, actual)
    end

    if equiv(reference, actual)
        @test true # to increase test counter if reached
    else
        # post-processing when test fails
        println("Test for \"$filename\" failed.")
        render(rendermode, reference, actual)

        if !isinteractive()
            error("You need to run the tests interactively with 'include(\"test/runtests.jl\")' to update reference images")
        end

        if !input_bool("Replace reference with actual result (path: $path)?")
            @test false
        else
            savefile(file, actual)
            @info("Please run the tests again for any changes to take effect")
        end
    end
end


text:
function extractinfofromconfig( config_path::String,
    molecule_names::Vector{String}) where T <: Real

    N_compounds = length(molecule_names)

    # read.
    file_strings = readlines(config_path)

    cs_delta_group = Vector{Vector{Vector{Float64}}}(undef, N_compounds)
    #λ_group_labels = Vector{Vector{Vector{Int}}}(undef, N_compounds)

    for n = 1:N_compounds

        cs_delta_group[n] = extractmoleculeinfofromconfig(file_strings,
                                    molecule_names[n], config_path)
    end

    return cs_delta_group#, λ_group_labels
end

function condenseΔcsconfig(cs_delta_group::Vector{Vector{Vector{T}}}) where T
    #
    out = Vector{Vector{T}}(undef, length(cs_delta_group))

    for n = 1:length(cs_delta_group)
        out[n] = Vector{T}(undef, length(cs_delta_group[n]))

        for i = 1:length(cs_delta_group[n])
            out[n][i] = cs_delta_group[n][i][1]
        end
    end

    return out
end

function extractmoleculeinfofromconfig( file_strings,
                                        name::String,
                                        file_label::String) where T <: Real

    # find the block of text for the input name.
    text_buffer = findblock(file_strings, name, "end compound", file_label)
    if isempty(text_buffer)
        println("Error processing config file.")
        return Vector{Vector{Float64}}(undef, 0), Vector{Vector{Int}}(undef, 0)
    end

    # get the number of groups.
    N_groups = length(filter(xx->occursin("Group",xx), text_buffer))

    # get default set up.
    cs_delta_group = Vector{Vector{Float64}}(undef, N_groups)
    #λ_group_labels = Vector{Vector{Int}}(undef, N_groups)

    for i = 1:N_groups

        # update position.
        cs_buffer = findblock(text_buffer, "Group $(i)", "end group", "Group $(i)")
        if isempty(cs_buffer)
            return Vector{Vector{Float64}}(undef, 0), Vector{Vector{Int}}(undef, 0)
        end
        N_cs = length(cs_buffer)

        cs_delta_group[i] = Vector{Float64}(undef, N_cs)
        #λ_group_labels[i] = Vector{Int}(undef, N_cs)

        for k = 1:length(cs_buffer)
            tokens = split(cs_buffer[k], (':',','))
            cs_delta_group[i][k] = tryparse(Float64, tokens[2])
            #λ_group_labels[i][k] = tryparse(Int, tokens[3])
        end
    end

    return cs_delta_group#, λ_group_labels
end


text:
export @static_string, alloc_string

macro static_string(str)
    quote
        $_static_string(Val(Symbol($str)))
    end
end

@generated function _static_string(::Val{Str}) where Str
    Context() do ctx
        T_pint8 = LLVM.PointerType(LLVM.Int8Type(ctx))

        # create functions
        param_types = LLVMType[]
        llvm_f, _ = create_function(T_pint8, param_types)
        mod = LLVM.parent(llvm_f)

        # generate IR
        Builder(ctx) do builder
            entry = BasicBlock(llvm_f, "entry"; ctx)
            position!(builder, entry)

            str = globalstring_ptr!(builder, string(Str))
            ret!(builder, str)
        end

        call_function(llvm_f, Ptr{Int8}, Tuple{})
    end
end

# from AMDGPU
@inline @generated function alloc_string(::Val{str}) where str
    Context() do ctx
        T_pint8 = LLVM.PointerType(LLVM.Int8Type(ctx))
        llvm_f, _ = create_function(T_pint8)
        Builder(ctx) do builder
            entry = BasicBlock(llvm_f, "entry"; ctx)
            position!(builder, entry)
            str_ptr = globalstring_ptr!(builder, String(str))
            ptr = addrspacecast!(builder, str_ptr, T_pint8)
            ret!(builder, ptr)
        end
        call_function(llvm_f, LLVMPtr{UInt8})
    end
end


text:
#i64o-comparison.jl
#comparison operators on SuperInts

#note that the less than function walks UP the array (decreasing significance)
#seeking evidence definitively asserting the relationship between a and b.  if
#the cell at the examined significance is equal, then the algorithm moves to the
#next significant cell and seeks a decesion for that.  If all of the cells are
#equal then it spits out false.

import Base: <, >, <=, >=, ==, !=

function <{FSS}(a::ArrayNum{FSS}, b::ArrayNum{FSS})
  for idx = 1:__cell_length(FSS)
    (a.a[idx] < b.a[idx]) && return true
    (a.a[idx] > b.a[idx]) && return false
  end
  return false
end

function >{FSS}(a::ArrayNum{FSS}, b::ArrayNum{FSS})
  for idx = 1:__cell_length(FSS)
    (a.a[idx] > b.a[idx]) && return true
    (a.a[idx] < b.a[idx]) && return false
  end
  return false
end

function <={FSS}(a::ArrayNum{FSS}, b::ArrayNum{FSS})
  for idx = 1:__cell_length(FSS)
    (a.a[idx] < b.a[idx]) && return true
    (a.a[idx] > b.a[idx]) && return false
  end
  return true
end

function >={FSS}(a::ArrayNum{FSS}, b::ArrayNum{FSS})
  for idx = 1:__cell_length(FSS)
    (a.a[idx] > b.a[idx]) && return true
    (a.a[idx] < b.a[idx]) && return false
  end
  return true
end

doc"""
  `Unums.lessthanwithubit(a::UInt64, b::UInt64, fsize::UInt16, orequal = false)`
  `Unums.lessthanwithubit(a::ArrayNum, b::ArrayNum, fisize::UInt16, orequal = false)`
  checks to make sure that a is less than b, even if a has a ubit value of fsize.
  you can do an 'orequal' which returns less than or equal.
"""
function lessthanwithubit(a::UInt64, b::UInt64, fsize::UInt16, orequal::Bool = false)
  mask = mask_top(fsize) #first generate the mask corresponding to the int.

  orequal && return ((a & mask) <= (b & mask))

  return ((a & mask) < (b & mask))
end
function lessthanwithubit{FSS}(a::ArrayNum{FSS}, b::ArrayNum{FSS}, fsize::UInt16, orequal::Bool = false)
  #compute the last cell we need to scan.
    middle_spot = div(fsize, 0x0040) + 1
    middle_size = fsize % 0x0040
    for idx = 1:(middle_spot - 1)
      @inbounds begin
        a.a[idx] > b.a[idx] && return false
        a.a[idx] < b.a[idx] && return true
      end
    end

    @inbounds res = lessthanwithubit(a.a[middle_spot], b.a[middle_spot], middle_size, orequal)
    return res
end

################################################################################
# cmpplusubit - checks to see if two fractions with ubits have the same exterior
# value.

doc"""
  `Unums.__check_cmpplusubit_ordered(FSS, a, b, a_fsize, b_fsize)`
  checks to make sure the a_fsize and b_fsize values parameters are correct
  prior to being passed to cmpplus_ubit_ordered.
"""
function __check_cmpplusubit_ordered(a, b, a_fsize::UInt16, b_fsize::UInt16)
  (div(a_fsize, 0x0040) < div(b_fsize, 0x0040)) || throw(ArgumentError("cmpplusubit_ordered called with improper fsize ordering."))
end

doc"""
  `Unums.cmpplusubit_ordered(a::ArrayNum, b::ArrayNum, a_fsize, b_fsize)`
  compares two ubit arraynums and sees if they have equivalent outer bounds.
  Prerequisite:  a_fsize and b_fsize fall in different array cells.
"""
@dev_check function cmpplusubit_ordered{FSS}(a::ArrayNum{FSS}, b::ArrayNum{FSS}, a_fsize, b_fsize)
  middle_spot_a = div(a_fsize, 0x0040) + 1
  middle_spot_b = div(b_fsize, 0x0040) + 1
  middle_size_a = a_fsize % 0x0040
  middle_size_b = b_fsize % 0x0040

  for idx = 1:(middle_spot_a - 1)
    @inbounds (a.a[idx] != b.a[idx]) && return false
  end
  #do with middle_spot_a
  @inbounds (a.a[middle_spot_a] + (t64 >> middle_size_a)) != (b.a[middle_spot_a] + o64) && return false
  for idx = (middle_spot_a + 1):(middle_spot_b - 1)
    @inbounds (b.a[idx] != f64) && return false
  end
  #do with middle_spot_b
  @inbounds (b.a[middle_spot_b] != top_mask(middle_size_b)) && return false
  return true
end

doc"""
  `Unums.__check_cmpplusubit_matched(FSS, a, b, a_fsize, b_fsize)`
  checks to make sure the a_fsize and b_fsize values parameters are correct
  prior to being passed to matched.
"""
function __check_cmpplusubit_matched(a, b, a_fsize::UInt16, b_fsize::UInt16)
  (div(a_fsize, 0x0040) == div(b_fsize, 0x0040)) || throw(ArgumentError("cmpplusubit_matched called with mismatched fsize."))
end

doc"""
  `Unums.cmpplusubit_ordered(a::ArrayNum, b::ArrayNum, a_fsize, b_fsize)`
  compares two ubit arraynums and sees if they have equivalent outer bounds.
"""
@dev_check function cmpplusubit_matched{FSS}(a::ArrayNum{FSS}, b::ArrayNum{FSS}, a_fsize, b_fsize)
  middle_spot = div(a_fsize, 0x0040) + 1
  middle_size_a = a_fsize % 0x0040
  middle_size_b = b_fsize % 0x0040

  for idx = 1:(middle_spot - 1)
    @inbounds (a.a[idx] != b.a[idx]) && return false
  end
  @inbounds cmpplusubit(a.a[middle_spot], b.a[middle_spot], middle_size_a, middle_size_b)
end

function cmpplusubit(a::UInt64, b::UInt64, a_fsize::UInt16, b_fsize::UInt16)
  a + (t64 >> a_fsize) == b + (t64 >> b_fsize)
end
function cmpplusubit{FSS}(a::ArrayNum{FSS}, b::ArrayNum{FSS}, a_fsize::UInt16, b_fsize::UInt16)
  middle_spot_a = div(a_fsize, 0x0040) + 1
  middle_spot_b = div(b_fsize, 0x0040) + 1

  if (middle_spot_a > middle_spot_b)
    cmpplusubit_ordered(b, a, b_fsize, a_fsize)
  elseif (middle_spot_a == middle_spot_b)
    cmpplusubit_matched(a, b, a_fsize, b_fsize)
  else #middle_spot_b > middle_spot_a
    cmpplusubit_ordered(a, b, a_fsize, b_fsize)
  end
end

function !={FSS}(a::ArrayNum{FSS}, b::ArrayNum{FSS})
  for idx = 1:__cell_length(FSS)
    @inbounds (a.a[idx] != b.a[idx]) && return true
  end
  return false
end

function =={FSS}(a::ArrayNum{FSS}, b::ArrayNum{FSS})
  for idx = 1:__cell_length(FSS)
    @inbounds (a.a[idx] != b.a[idx]) && return false
  end
  return true
end

function same_till_fsize(n1::UInt64, n2::UInt64, s::UInt16)
  (s == z16) && return true

  fsize_mask = mask_top(s - o16)

  (n1 & fsize_mask) == (n2 & fsize_mask)
end
function same_till_fsize{FSS}(n1::ArrayNum{FSS}, n2::ArrayNum{FSS}, s::UInt16)
  middle_cell = div(s, 0x0040) + o16
  middle_size = s % 0x0040
  for idx = 1:middle_cell - 1
    @inbounds (n1.a[idx] != n2.a[idx]) && return false
  end
  @inbounds return same_till_fsize(n1.a[middle_cell], n2.a[middle_cell], middle_size)
end

function common_fsize(n1::UInt64, n2::UInt64)
  clz(n1 $ n2) - o16
end
function common_fsize{FSS}(n1::ArrayNum{FSS}, n2::ArrayNum{FSS})
  done = false
  sumsofar = z16
  for idx = 1:__cell_length(FSS)
    @inbounds current_count = clz(n1[idx] $ n2[idx])
    sumsofar += current_count
    current_count == 64 || return (sumsofar - o16)
  end
end

max_stars_repo_name: REX-Computing/unumjl

max_issues_repo_name: REX-Computing/unumjl

max_forks_repo_name: REX-Computing/unumjl


text:
using Distributions

function _split_classifcation_error_loss(y::Vector, X::DataFrame, obs_row_indcs::Vector{Int}, column_indcs::Vector{Int}, weights::Vector)
    best = NO_BEST
    best_val = -Inf
    X = X[obs_row_indcs, :]
    y = y[obs_row_indcs]

    for j in column_indcs
        keep_row = !isna(X[:, j])                # use only non-NA values
        x_obs = convert(Vector, X[keep_row, j])
        y_obs = y[keep_row]
        wgts_obs = weights[keep_row]

        if length(unique(x_obs)) ≥ 100
            domain_j = quantile(x_obs, linspace(0.01, 0.99, 99))
        else
            domain_j = sort(unique(x_obs))
        end

        for thresh in domain_j[2:end]
            cur_split = x_obs .< thresh
            value = _classifcation_error_loss(y_obs[cur_split], wgts_obs[cur_split]) + _classifcation_error_loss(y_obs[!cur_split], wgts_obs[!cur_split])
            if value > best_val
                best_val = value
                best = (j, thresh)
            end
        end
    end
    return best
end

# This method is dispatched when weights are omitted. This
# allows us to compute the loss function 5x faster
function _split_classifcation_error_loss(y::Vector, X::DataFrame, obs_row_indcs::Vector{Int}, column_indcs::Vector{Int})
    best = NO_BEST
    best_val = -Inf
    X = X[obs_row_indcs, :]
    y = y[obs_row_indcs]

    println(size(X))
    println(column_indcs)

    for j in column_indcs
        keep_row = !isna(X[:, j])
        x_obs = convert(Vector, X[keep_row, j])
        y_obs = y[keep_row]

        if length(unique(x_obs)) ≥ 100
            domain_j = quantile(x_obs, linspace(0.01, 0.99, 99))
        else
            domain_j = sort(unique(x_obs))
        end

        for thresh in domain_j[2:end]
            cur_split = x_obs .< thresh
            value = _classifcation_error_loss(y_obs[cur_split]) + _classifcation_error_loss(y_obs[!cur_split])
            if value > best_val
                best_val = value
                best = (j, thresh)
            end
        end
    end
    return best
end

#
# n = 1000
# p = 20
# X = DataFrame(randn(n, p));
# y = rand([true, false], n);
# wgt = ones(Int, n);
#
# @time _split_classifcation_error_loss(y, X, collect(1:n), collect(1:p), wgt)
#
#
#
#
# @time surrogate_splits(y, X, collect(1:n), collect(1:p), 5, wgt)

function add_missing(dat::DataFrame, pr)
    d = Bernoulli(pr)
    X = copy(dat)
    n, p = size(X)
    for j = 1:p
        X[:, j] = convert(DataArray{Any, 1}, X[:, j])
        for i = 1:n
            if rand(d) == 1
                X[i, j] = NA
            end
        end
    end
    return X
end

#


text:
# coding: utf-8

# # Run Validation

# In[1]:

include("validation.jl")
models = load_models()
modelnames = sort!(collect(keys(models)), rev=true)

# In[2]:

#for model in modelnames
    #validate(models[model], save=true, modelname=model)
    #println(model)
#end

# # Visualize Policy

# In[3]:

using AutoViz, Interact, Reel

# In[4]:

env_dict = Dict("trajdata_indeces" => [1],
                       "use_playback_reactive" => true,
                       "extract_core" => true,
                       "extract_temporal" => false,
                       "extract_well_behaved" => true,
                       "extract_neighbor_features" => false,
                       "extract_carlidar_rangerate" => true,
                       "carlidar_nbeams" => 20,
                       "roadlidar_nbeams" => 0,
                       "roadlidar_nlanes" => 2,
                       "nsteps" => 100,
                       "carlidar_max_range" => 100.0,
                       "roadlidar_max_range" => 100.0,
"model_all" => false)
simparams = Auto2D.gen_simparams(1, env_dict)

# In[7]:

# simparams.driver_model = Auto2D.load_gru_driver("./models/Dec11/policy_temp0_100.h5", 319);
simparams.driver_model = Auto2D.load_gru_driver("policy_gail.h5", 499);
#model = models["bc_mlp"]
model = models["gail_gru"]
reset(simparams)
simstate = simparams.simstates[1]
trajdata = simparams.trajdatas[simstate.trajdata_index]
reset_hidden_state!(model)
empty!(simstate.rec)

if Symbol("gru") in fieldnames(model.net)
    model.net[:gru].h_prev = zeros(length(model.net[:gru].h_prev))
end
AutomotiveDrivingModels.observe!(model, simparams, simstate.scene, trajdata.roadway, simstate.egoid)
sim_rec = SceneRecord(200, 0.1)
for t = 1:200
    ego_action = rand(model)
    a = clamp(ego_action.a, -5.0, 3.0)
    ω = clamp(ego_action.ω, -0.1, 0.1)
    step(simparams, [a, ω])
    AutomotiveDrivingModels.observe!(model, simparams, simstate.scene, trajdata.roadway, simstate.egoid)
    update!(sim_rec, simstate.scene)
end

# In[8]:

scene = simparams.simstates[1].scene
egoid = simparams.simstates[1].egoid
trajdata = simparams.trajdatas[1]
frames = Reel.Frames(MIME("image/png"), fps=10)
for pastframe in -length(sim_rec)+1 : 0
    push!(frames, render(get!(scene, sim_rec, pastframe), trajdata.roadway, cam=CarFollowCamera(egoid, 4.0),car_colors=Dict{Int,Colorant}(egoid=>COLOR_CAR_EGO)))
end
Reel.write("validation.gif",frames)


text:
n = 32
c1 = Channel(n)

for _ in 1:n
    put!(c1,"foo")
end

for _ in 1:n
    data = take!(c1)
    println(data)
end


text:
"""
  LineSearch(scheme, linesearcher)
"""
struct LineSearch{S, LS, K}
  scheme::S
  linesearcher::LS
  scaling::K
end
LineSearch() = LineSearch(DBFGS(), Backtracking(), InitialScaling(ShannoPhua()))
LineSearch(m) = LineSearch(m, Backtracking(), InitialScaling(ShannoPhua()))
LineSearch(m, ls) = LineSearch(m, ls, InitialScaling(ShannoPhua()))

hasprecon(ls::LineSearch) = hasprecon(modelscheme(ls))
summary(ls::LineSearch) = summary(modelscheme(ls))*" with "*summary(algorithm(ls))

function initial_preconditioner(approach::LineSearch, x)
  method = modelscheme(approach)
  initial_preconditioner(method, x, hasprecon(method))
end

modelscheme(ls::LineSearch) = ls.scheme
algorithm(ls::LineSearch) = ls.linesearcher
include("conjugategradient.jl")
export ConjugateGradient

include("quasinewton.jl")
include("limitedquasinewton.jl")


text:
module RankingWrapper

using JavaCall

const Class = @jimport java.lang.Class
const Enum = @jimport java.lang.Enum
const JString = @jimport java.lang.String
const NaNStrategy = @jimport org.hipparchus.stat.ranking.NaNStrategy
const NaturalRanking = @jimport org.hipparchus.stat.ranking.NaturalRanking
const Object = @jimport java.lang.Object
const Optional = @jimport java.util.Optional
const RandomGenerator = @jimport org.hipparchus.random.RandomGenerator
const RankingAlgorithm = @jimport org.hipparchus.stat.ranking.RankingAlgorithm
const TiesStrategy = @jimport org.hipparchus.stat.ranking.TiesStrategy

export NaNStrategy
export NaturalRanking
export RankingAlgorithm
export TiesStrategy
export compare_to
export describe_constable
export equals
export get_class
export get_declaring_class
export get_nan_strategy
export get_ties_strategy
export hash_code
export name
export notify
export notify_all
export ordinal
export rank
export to_string
export value_of
export values
export wait

include("na_n_strategy.jl")
include("natural_ranking.jl")
include("ranking_algorithm.jl")
include("ties_strategy.jl")

end


text:
using Test
using MPI: mpiexec

# Do the MPI tests first so we do not have mpi running inside MPI
@testset "mpivec tests" begin
    @test mpiexec() do cmd
        run(`$cmd -n 4 julia --project mpivec.jl`)
        true
    end
end

include("lib.jl")
include("init.jl")
include("options.jl")
include("vec.jl")
include("mat.jl")