text:
#mlfunctions.jl - runs some special, accelerated ML functions.

macro unitrange_check(y, functionname)
  negative_error_text = "$functionname doesn't take negative values."
  toobig_error_text = "$functionname doesn't take values > 1"
  quote
    @s($y) < 0 && throw(ArgumentError($negative_error_text))
    ((@u($y) & @invertbit) != 0) && throw(ArgumentError($toobig_error_text))
  end
end

@doc """
  oneminus(::Posit)

  calculates the value of 1-y.

  This function is undefined for values > 1 or less than 0.
"""
oneminus(y::Posit) = oneminus_careful(y)
oneminus_sloppy(y::P) where {P <: Posit} = reinterpret(P, (@invertbit) - @u(y))
function oneminus_careful(y)
  @unitrange_check(y, :oneminus)
  oneminus_sloppy(y)
end

@doc """
  pseudologistic(::Posit)

  calculates the pseudo-logistic sigmoid curve for the Posit data type.
"""
pseudologistic(x::Posit) = pseudologistic_careful(x)
pseudologistic_sloppy(x::P) where {P <: Posit} = reinterpret(P, (@u(x) $ @signbit) >> 2)
function pseudologistic_careful(x::Posit)
  isfinite(x) || throw(ArgumentError("pseudologistic function is undefined for infinity"))
  __round(pseudologistic_sloppy(x))
end

@doc """
  delta_psl(::Posit)

  calculates the value dy/dx using the differential equation dy/dx = y(1 - y)

  This function is undefined for values > 1 or less than zero.
"""
delta_psl(y::Posit) = delta_psl_careful(y)
delta_psl_sloppy(y) = y * oneminus_sloppy(y)
function delta_psl_careful(y::Posit)
  @unitrange_check(y, :delta_psl)
  __round(delta_psl_sloppy(y))
end

@doc """
  pseudologcost(::Posit)

  calculates the pseudologcost function for the Posit data type.  The
  halfcost function is -log_x(1-y), here we estimate by simple expansion.

  This function is undefined for values > 1 or less than zero.
"""
pseudologcost(y::Posit) = pseudologcost_careful(y)
pseudologcost_sloppy(y::P) where {P <: Posit} = reinterpret(P, @u(y) << 1)
function pseudologcost_careful(y::Posit)
  @unitrange_check(y, :pseudologcost)
  __round(pseudologcost_sloppy(y))
end

@doc """
  pseudosoftplus(::Posit)

  calculates the pseudosoftplus function for the Posit data type.  The
  pseudosoftplus emulates ln(1 + e^x).

"""
pseudosoftplus(x::Posit) = pseudosoftplus_careful(x)
pseudosoftplus_sloppy(x::P) where {P <: Posit} = reinterpret(P, (@u(x) $ @signbit) >> 1)
@generated function pseudosoftplus_careful(x::Posit{N}) where {N}
  mask = @mask(N)
  quote
    __round(reinterpret(Posit{N}, @u(pseudosoftplus_sloppy(x)) & $mask))
  end
end

##### ETC

Base.randn(::Type{P},args::Integer...) where {P <: Posit} = P.(randn(args...))
Base.rand(::Type{P}, args::Integer...) where {P <: Posit} = P.(rand(args...))

max_issues_repo_name: MohHizzani/SigmoidNumbers

max_forks_repo_name: MohHizzani/SigmoidNumbers


text:
import Base: getindex, setindex!, ==, copy, show, print
using Base.Enums

mutable struct Board
    num_rows::Int
    num_cols::Int
    _grid::Matrix{IdType} # points to the gostring id
    _stringbuffer::GoStringBuffer # points the id to string
    _hash::Int
end

# External constructor
function Board(num_rows::Int, num_cols::Int)::Board
    emptymat = fill(0, num_rows, num_cols)
    stringbuffer = GoStringBuffer(Dict(IdType(0) => EMPTY_STRING), IdType(0))
    Board(num_rows, num_cols, emptymat, stringbuffer, EMPTY_BOARD_HASH)
end

# setters getters for dicts
grid(board::Board)::Matrix{IdType} = board._grid
is_on_grid(board::Board, p::Point)::Bool = checkbounds(Bool, grid(board), p.row, p.col)

stringbuffer(board::Board)::GoStringBuffer = board._stringbuffer
stringdict(board::Board)::Dict{IdType, GoString} = stringbuffer(board).dict
getpointid(board::Board, i::Int, j::Int)::IdType = board._grid[i, j]
getpointid(board::Board, p::Point)::IdType = getpointid(board, p.row, p.col)
setpointid!(board::Board, id::IdType, i::Int, j::Int)::Nothing = (board._grid[i, j] = id; nothing)
setpointid!(board::Board, id::IdType, p::Point)::Nothing = setpointid!(board, id, p.row, p.col)

getstring(board::Board, id::IdType)::GoString = stringdict(board)[id]
setstring!(board::Board, s::GoString, id::IdType)::Nothing = (setindex!(stringdict(board), s, id); nothing)
newid!(board::Board)::IdType = stringbuffer(board).lastid += IdType(1)

# advanced indexing (try not to use setindex)
Base.getindex(board::Board, i::Int, j::Int)::GoString = getstring(board, getpointid(board, i, j))
Base.getindex(board::Board, p::Point)::GoString = Base.getindex(board, p.row, p.col)
Base.setindex!(board::Board, string::GoString, i::Int, j::Int)::Nothing = (setstring!(board, string, getpointid(board, i, j)); nothing)
Base.setindex!(board::Board, string::GoString, p::Point)::Nothing = (Base.setindex!(board, string, p.row, p.col); nothing)

# equality
Base.:(==)(board1::Board, board2::Board)::Bool = (board1._grid == board2._grid)

# hashing
zobristhash(board::Board)::Int = board._hash
update_hash!(board::Board, i::Int, j::Int, player::Player)::Int = board._hash ⊻= HASH_CODE[i, j, player]
update_hash!(board::Board, p::Point, player::Player)::Int = update_hash!(board, p.row, p.col, player)

# copymethods
function copy(board::Board)::Board # useful for new iteration
    sb = stringbuffer(board)
    sbcopy = GoStringBuffer(Dict(k => copy(v) for (k, v) in sb.dict), sb.lastid)
    gridcopy = copy(grid(board))
    Board(board.num_rows, board.num_cols, gridcopy, sbcopy, zobristhash(board))
end

# function copyatpoint(board::Board, point::Point)::Board # useful for check valid move
#     id = grid(board)[point.row, point.col]
#     sb = stringbuffer(board)
#     sbcopy = StringBuffer(Dict(i => (i == id ? copy(v) : v) for (i, v) in sb.dict), sb.lastid)
#     gridcopy = copy(board._grid)
#     Board(board.num_rows, board.num_cols, gridcopy, sbcopy, board._hash)
# end

function remove_point!(board::Board, p::Point)::Nothing
    setpointid!(board, IdType(0), p)
end

function remove_string!(board::Board, string::GoString)::Nothing
    @assert !isvoid(string)
    for point in string.stones
        for nbr in nbrs(point)
            if is_on_grid(board, nbr)
                nbr_string = board[nbr]
                if isvoid(nbr_string)
                    continue
                elseif nbr_string !== string
                    add_liberty!(nbr_string, point)
                end
            end
        end
        remove_point!(board, point)
        update_hash!(board, point, string.color)
    end
    delete!(stringdict(board), string.id)
    nothing
end

function place_stone!(board::Board, player::Player, point::Point)::Nothing
    @assert is_on_grid(board, point)
    @assert isvoid(board[point])

    adjacent_same_color = Set{GoString}()
    adjacent_opposite_color = Set{GoString}()
    liberties = Set{Point}()

    for nbr in nbrs(point)
        if is_on_grid(board, nbr)
            nbr_string = board[nbr]
            if isvoid(nbr_string)
                push!(liberties, nbr)
            elseif nbr_string.color === player
                push!(adjacent_same_color, nbr_string)
            else
                push!(adjacent_opposite_color, nbr_string)
            end
        end
    end

    if isempty(adjacent_same_color)
        newstring_id = newid!(board)
        newstring = GoString(player, Set([point]), Set(liberties), newstring_id)
        setstring!(board, newstring, newstring_id)
        setpointid!(board, newstring_id, point)
    else
        samecolor_string = pop!(adjacent_same_color)
        newstring_id = samecolor_string.id
        newstring = GoString(player, Set([point]), Set(liberties), newstring_id)
        merge!(samecolor_string, newstring)
        setpointid!(board, newstring_id, point)

        # if we have more neighbors merge to previously found nbr
        for nbr_string in adjacent_same_color
            merge!(samecolor_string, nbr_string)
            for nbr_point in nbr_string.stones
                setpointid!(board, newstring_id, nbr_point)
            end
            delete!(stringdict(board), nbr_string.id)
        end
    end

    update_hash!(board, point, player)

    for opposite_color_string in adjacent_opposite_color
        remove_liberty!(opposite_color_string, point)
        if num_liberties(opposite_color_string) == 0
            remove_string!(board, opposite_color_string)
        end
    end
end

# ------------
struct GameState
    board::Board
    next_player::Player
    prev::Union{Nothing, GameState}
    prev_hashes::Set{Tuple{Player, Int}}
    last_move::Union{Nothing, Move}

    GameState(
            board::Board,
            next_player::Player,
            prev::Union{Nothing, GameState},
            last_move::Union{Nothing, Move}
    ) = begin
        ph = if (prev ≡ nothing)
            Set{Tuple{Player, Int}}()
        else
            newstate = Set([(prev.next_player, zobristhash(prev.board))])
            union(prev.prev_hashes, newstate)
        end
        new(board, next_player, prev, ph, last_move)
    end
end

new_game(num_rows::Int, num_cols::Int)::GameState = GameState(Board(num_rows, num_cols), black, nothing, nothing)
new_game(size::Int)::GameState = GameState(Board(size, size), black, nothing, nothing)

function is_over(game_state::GameState)::Bool
    last_move = game_state.last_move
    if last_move ≡ nothing
        return false
    elseif last_move.is_resign
        return true
    end

    second_last_move = game_state.prev.last_move
    if second_last_move ≡ nothing
        return false
    end

    return last_move.is_pass && second_last_move.is_pass
end

function apply_move(game_state::GameState, move::Move)::GameState
    if move.is_play
        next_board = copy(game_state.board)
        place_stone!(next_board, game_state.next_player, move.point)
    else
        next_board = game_state.board
    end

    return GameState(next_board, other(game_state.next_player), game_state, move)
end

function is_move_self_capture(game_state::GameState, player::Player, move::Move)::Bool
    !move.is_play && (return false)
    next_board = copy(game_state.board)
    place_stone!(next_board, player, move.point)
    newstring = next_board[move.point]
    return (num_liberties(newstring) == 0)
end

function does_move_violate_ko(game_state::GameState, player::Player, move::Move)::Bool
    if !move.is_play
        return false
    end
    next_board = copy(game_state.board)
    place_stone!(next_board, player, move.point)
    next_situation = (other(player), zobristhash(next_board))
    return (next_situation in game_state.prev_hashes)
end

function is_valid_move(game_state::GameState, move::Move)::Bool
    if is_over(game_state)
        return false
    elseif move.is_pass || move.is_resign
        return true
    else
        return isvoid(game_state.board[move.point]) &&
            !is_move_self_capture(game_state, game_state.next_player, move) &&
            !does_move_violate_ko(game_state, game_state.next_player, move)
    end
end

function legal_moves(game_state::GameState)::Vector{Move}
    moves = [pass_turn()]
    for r in 1:game_state.board.num_rows
        for c in 1:game_state.board.num_cols
            move = play((row=r, col=c))
            if is_valid_move(game_state, move)
                push!(moves, move)
            end
        end
    end
    return moves
end

ext: jl


text:
using Test
import GeoInterface, GDAL, ArchGDAL; const AG = ArchGDAL

@testset "Incomplete GeoInterface geometries" begin
    @test_logs (:warn, "unknown geometry type") GeoInterface.geotype(AG.creategeom(GDAL.wkbCircularString))
    @test_logs (:warn, "unknown geometry type") GeoInterface.geotype(AG.creategeom(GDAL.wkbCompoundCurve))
    @test_logs (:warn, "unknown geometry type") GeoInterface.geotype(AG.creategeom(GDAL.wkbCurvePolygon))
    @test_logs (:warn, "unknown geometry type") GeoInterface.geotype(AG.creategeom(GDAL.wkbMultiSurface))
    @test_logs (:warn, "unknown geometry type") GeoInterface.geotype(AG.creategeom(GDAL.wkbPolyhedralSurface))
    @test_logs (:warn, "unknown geometry type") GeoInterface.geotype(AG.creategeom(GDAL.wkbTIN))
    @test_logs (:warn, "unknown geometry type") GeoInterface.geotype(AG.creategeom(GDAL.wkbTriangle))
end

@testset "Create a Point" begin
    # Method 1
    AG.createpoint(100, 70) do point
        @test GeoInterface.geotype(point) == :Point
        @test isapprox(GeoInterface.coordinates(point), [100,70], atol=1e-6)
        @test AG.geomdim(point) == 0
        @test AG.getcoorddim(point) == 2
        AG.setcoorddim!(point, 3)
        @test AG.getcoorddim(point) == 3
        @test AG.isvalid(point) == true
        @test AG.issimple(point) == true
        @test AG.isring(point) == false
        @test AG.getz(point, 0) == 0

        @test sprint(print, AG.envelope(point)) == "GDAL.OGREnvelope(100.0, 100.0, 70.0, 70.0)"
        @test sprint(print, AG.envelope3d(point)) == "GDAL.OGREnvelope3D(100.0, 100.0, 70.0, 70.0, 0.0, 0.0)"
        @test AG.toISOWKB(point, GDAL.wkbNDR) == UInt8[0x01,0xe9,0x03,0x00,0x00,
        0x00,0x00,0x00,0x00,0x00,0x00,0x59,0x40,0x00,0x00,0x00,0x00,0x00,0x80,
        0x51,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]
        @test AG.toISOWKB(point, GDAL.wkbXDR) == UInt8[0x00,0x00,0x00,0x03,0xe9,
        0x40,0x59,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x51,0x80,0x00,0x00,0x00,
        0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]
        @test AG.toKML(point, "relativeToGround") == "<Point><altitudeMode>relativeToGround</altitudeMode><coordinates>100,70,0</coordinates></Point>"
        @test AG.toKML(point, "clampToGround") == "<Point><altitudeMode>clampToGround</altitudeMode><coordinates>100,70,0</coordinates></Point>"
        @test AG.toKML(point) == "<Point><coordinates>100,70,0</coordinates></Point>"
        @test AG.toJSON(point) == "{ \"type\": \"Point\", \"coordinates\": [ 100.0, 70.0, 0.0 ] }"
        AG.createpoint(100,70,0) do point2
            @test isapprox(GeoInterface.coordinates(point2), [100,70,0], atol=1e-6)
            @test AG.equals(point, point2) == true
        end
        AG.createpoint((100,70,0)) do point3
            @test AG.equals(point, point3) == true
        end
        AG.createpoint([100,70,0]) do point4
            @test AG.equals(point, point4) == true
        end
        point5 = AG.createpoint([100,70,0])
        @test AG.equals(point, point5) == true
        AG.flattento2d!(point)
        @test AG.getcoorddim(point) == 2
        @test AG.getnonlineargeomflag() == true
        AG.setnonlineargeomflag!(false)
        @test AG.getnonlineargeomflag() == false
        AG.setnonlineargeomflag!(true)
        @test AG.getnonlineargeomflag() == true
        AG.closerings!(point)
        @test AG.toJSON(point) == "{ \"type\": \"Point\", \"coordinates\": [ 100.0, 70.0 ] }"
    end

    # Method 2
    point = AG.createpoint(100, 70)
    @test AG.geomdim(point) == 0
    @test AG.getcoorddim(point) == 2
    AG.setcoorddim!(point, 3)
    @test AG.getcoorddim(point) == 3
    @test AG.isvalid(point) == true
    @test AG.issimple(point) == true
    @test AG.isring(point) == false
    @test AG.getz(point, 0) == 0
    @test sprint(print, AG.envelope(point)) == "GDAL.OGREnvelope(100.0, 100.0, 70.0, 70.0)"
    @test sprint(print, AG.envelope3d(point)) == "GDAL.OGREnvelope3D(100.0, 100.0, 70.0, 70.0, 0.0, 0.0)"
    @test AG.toISOWKB(point, GDAL.wkbNDR) == UInt8[0x01,0xe9,0x03,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x59,0x40,0x00,0x00,0x00,0x00,0x00,0x80,
    0x51,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]
    @test AG.toISOWKB(point, GDAL.wkbXDR) == UInt8[0x00,0x00,0x00,0x03,0xe9,
    0x40,0x59,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x51,0x80,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]
    @test AG.toKML(point, "relativeToGround") == "<Point><altitudeMode>relativeToGround</altitudeMode><coordinates>100,70,0</coordinates></Point>"
    @test AG.toKML(point, "clampToGround") == "<Point><altitudeMode>clampToGround</altitudeMode><coordinates>100,70,0</coordinates></Point>"
    @test AG.toKML(point) == "<Point><coordinates>100,70,0</coordinates></Point>"
    @test AG.toJSON(point) == "{ \"type\": \"Point\", \"coordinates\": [ 100.0, 70.0, 0.0 ] }"
    @test AG.equals(point, AG.createpoint(100,70,0)) == true
    @test AG.equals(point, AG.createpoint((100,70,0))) == true
    AG.flattento2d!(point)
    @test AG.getcoorddim(point) == 2
    @test AG.getnonlineargeomflag() == true
    AG.setnonlineargeomflag!(false)
    @test AG.getnonlineargeomflag() == false
    AG.setnonlineargeomflag!(true)
    @test AG.getnonlineargeomflag() == true
    AG.closerings!(point)
    @test AG.toJSON(point) == "{ \"type\": \"Point\", \"coordinates\": [ 100.0, 70.0 ] }"
end

@testset "Testing construction of complex geometries" begin
    @test AG.toWKT(AG.createlinestring([1.,2.,3.], [4.,5.,6.])) == "LINESTRING (1 4,2 5,3 6)"
    AG.createlinestring([1.,2.,3.], [4.,5.,6.]) do geom
        @test GeoInterface.geotype(geom) == :LineString
        @test isapprox(GeoInterface.coordinates(geom), [[1,4],[2,5],[3,6]], atol=1e-6)
        @test AG.toWKT(geom) == "LINESTRING (1 4,2 5,3 6)"
        AG.closerings!(geom)
        @test AG.toWKT(geom) == "LINESTRING (1 4,2 5,3 6)"
        AG.setpoint!(geom, 1, 10, 10)
        @test AG.toWKT(geom) == "LINESTRING (1 4,10 10,3 6)"
    end
    AG.createlinestring([1.,2.,3.], [4.,5.,6.], [7.,8.,9.]) do geom
        @test AG.toWKT(geom) == "LINESTRING (1 4 7,2 5 8,3 6 9)"
        AG.setpoint!(geom, 1, 10, 10, 10)
        @test AG.toWKT(geom) == "LINESTRING (1 4 7,10 10 10,3 6 9)"
        AG.addpoint!(geom, 11, 11, 11)
        @test AG.toWKT(geom) == "LINESTRING (1 4 7,10 10 10,3 6 9,11 11 11)"
    end

    @test AG.toWKT(AG.createlinearring([1.,2.,3.], [4.,5.,6.])) == "LINEARRING (1 4,2 5,3 6)"
    AG.createlinearring([1.,2.,3.], [4.,5.,6.]) do geom
        # @test GeoInterface.geotype(geom) == :LinearRing
        @test isapprox(GeoInterface.coordinates(geom), [[1,4],[2,5],[3,6]], atol=1e-6)
        @test AG.toWKT(geom) == "LINEARRING (1 4,2 5,3 6)"
        AG.setpointcount!(geom, 5)
        @test AG.toWKT(geom) == "LINEARRING (1 4,2 5,3 6,0 0,0 0)"
        AG.empty!(geom)
        @test AG.toWKT(geom) == "LINEARRING EMPTY"
    end
    AG.createlinearring([1.,2.,3.], [4.,5.,6.], [7.,8.,9.]) do geom
        @test AG.toWKT(geom) == "LINEARRING (1 4 7,2 5 8,3 6 9)"
        AG.closerings!(geom)
        @test AG.toWKT(geom) == "LINEARRING (1 4 7,2 5 8,3 6 9,1 4 7)"
    end

    @test AG.toWKT(AG.createpolygon([1.,2.,3.], [4.,5.,6.])) == "POLYGON ((1 4,2 5,3 6))"
    AG.createpolygon([1.,2.,3.], [4.,5.,6.]) do geom
        @test GeoInterface.geotype(geom) == :Polygon
        @test isapprox(GeoInterface.coordinates(geom), [[[1,4],[2,5],[3,6]]], atol=1e-6)
        @test AG.toWKT(geom) == "POLYGON ((1 4,2 5,3 6))"
    end
    AG.createpolygon([1.,2.,3.], [4.,5.,6.], [7.,8.,9.]) do geom
        @test AG.toWKT(geom) == "POLYGON ((1 4 7,2 5 8,3 6 9))"
        AG.closerings!(geom)
        @test AG.toWKT(geom) == "POLYGON ((1 4 7,2 5 8,3 6 9,1 4 7))"
    end

    @test AG.toWKT(AG.createmultipoint([1.,2.,3.], [4.,5.,6.])) == "MULTIPOINT (1 4,2 5,3 6)"
    AG.createmultipoint([1.,2.,3.], [4.,5.,6.]) do geom
        @test GeoInterface.geotype(geom) == :MultiPoint
        @test isapprox(GeoInterface.coordinates(geom), [[1,4],[2,5],[3,6]], atol=1e-6)
        @test AG.toWKT(geom) == "MULTIPOINT (1 4,2 5,3 6)"
    end
    AG.createmultipoint([1.,2.,3.], [4.,5.,6.], [7.,8.,9.]) do geom
        @test AG.toWKT(geom) == "MULTIPOINT (1 4 7,2 5 8,3 6 9)"
    end

    @test AG.toWKT(AG.createmultipolygon(Vector{Vector{Tuple{Cdouble,Cdouble}}}[
        Vector{Tuple{Cdouble,Cdouble}}[
            [(0,0),(0,4),(4,4),(4,0)],
            [(1,1),(1,3),(3,3),(3,1)]],
        Vector{Tuple{Cdouble,Cdouble}}[
            [(10,0),(10,4),(14,4),(14,0)],
            [(11,1),(11,3),(13,3),(13,1)]]]
    )) == "MULTIPOLYGON (((0 0,0 4,4 4,4 0),(1 1,1 3,3 3,3 1)),((10 0,10 4,14 4,14 0),(11 1,11 3,13 3,13 1)))"
    AG.createmultipolygon(Vector{Vector{Tuple{Cdouble,Cdouble}}}[
                            Vector{Tuple{Cdouble,Cdouble}}[
                                [(0,0),(0,4),(4,4),(4,0)],
                                [(1,1),(1,3),(3,3),(3,1)]],
                            Vector{Tuple{Cdouble,Cdouble}}[
                                [(10,0),(10,4),(14,4),(14,0)],
                                [(11,1),(11,3),(13,3),(13,1)]]]) do geom
        @test GeoInterface.geotype(geom) == :MultiPolygon
        @test isapprox(
            GeoInterface.coordinates(geom), [
                [[[0,0],[0,4],[4,4],[4,0]], [[1,1],[1,3],[3,3],[3,1]]],
                [[[10,0],[10,4],[14,4],[14,0]], [[11,1],[11,3],[13,3],[13,1]]]
            ],
            atol=1e-6
        )
        @test AG.toWKT(geom) == "MULTIPOLYGON (((0 0,0 4,4 4,4 0),(1 1,1 3,3 3,3 1)),((10 0,10 4,14 4,14 0),(11 1,11 3,13 3,13 1)))"
    end

    AG.fromWKT("CURVEPOLYGON(CIRCULARSTRING(-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0),(-1 0,0 0.5,1 0,0 1,-1 0))") do geom
        @test AG.toWKT(AG.curvegeom(AG.lineargeom(geom, 0.5))) == "CURVEPOLYGON (CIRCULARSTRING (-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0),(-1 0,0.0 0.5,1 0,0 1,-1 0))"
        AG.lineargeom(geom, 0.5) do lgeom
            AG.curvegeom(lgeom) do clgeom
                @test AG.toWKT(clgeom) == "CURVEPOLYGON (CIRCULARSTRING (-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0),(-1 0,0.0 0.5,1 0,0 1,-1 0))"
            end
            @test AG.ngeom(AG.polygonize(AG.forceto(lgeom, GDAL.wkbMultiLineString))) == 2
            AG.forceto(lgeom, GDAL.wkbMultiLineString) do mlsgeom
                AG.polygonize(mlsgeom) do plgeom
                    @test AG.ngeom(plgeom) == 2
                end
            end
        end
    end
end

@testset "Testing remaining methods for geometries" begin
    geom1 = AG.createmultipolygon(Vector{Vector{Tuple{Cdouble,Cdouble}}}[
                            Vector{Tuple{Cdouble,Cdouble}}[
                                [(0,0),(0,4),(4,4),(4,0)],
                                [(1,1),(1,3),(3,3),(3,1)]],
                            Vector{Tuple{Cdouble,Cdouble}}[
                                [(10,0),(10,4),(14,4),(14,0)],
                                [(11,1),(11,3),(13,3),(13,1)]]])
    geom2 = AG.createmultipoint([1.,2.,3.], [4.,5.,6.], [7.,8.,9.])

    AG.closerings!(geom1)
    @test AG.disjoint(geom1, geom2) == false
    @test AG.touches(geom1, geom2) == true
    @test AG.crosses(geom1, geom2) == false
    @test AG.overlaps(geom1, geom2) == false

    @test AG.toWKT(AG.boundary(geom2)) == "GEOMETRYCOLLECTION EMPTY"
    AG.boundary(geom2) do result
        @test AG.toWKT(result) == "GEOMETRYCOLLECTION EMPTY"
    end

    @test AG.toWKT(AG.union(geom1, geom2)) == "GEOMETRYCOLLECTION (POINT (2 5 8),POINT (3 6 9),POLYGON ((0 0 8,0 4 8,4 4 8,4 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),POLYGON ((10 0 8,10 4 8,14 4 8,14 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)))"
    AG.union(geom1, geom2) do result
        @test AG.toWKT(result) == "GEOMETRYCOLLECTION (POINT (2 5 8),POINT (3 6 9),POLYGON ((0 0 8,0 4 8,4 4 8,4 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),POLYGON ((10 0 8,10 4 8,14 4 8,14 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)))"
        @test AG.hascurvegeom(result, true) == false
        @test AG.hascurvegeom(result, false) == false
    end

    @test AG.toWKT(AG.difference(geom1, geom2)) == "MULTIPOLYGON (((0 0 8,0 4 8,4 4 8,4 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),((10 0 8,10 4 8,14 4 8,14 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)))"
    AG.difference(geom1, geom2) do result
        @test AG.toWKT(result) == "MULTIPOLYGON (((0 0 8,0 4 8,4 4 8,4 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),((10 0 8,10 4 8,14 4 8,14 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)))"
        AG.segmentize!(result, 20)
        @test AG.toWKT(result) == "MULTIPOLYGON (((0 0 8,0 4 8,4 4 8,4 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),((10 0 8,10 4 8,14 4 8,14 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)))"
        AG.segmentize!(result, 2)
        @test AG.toWKT(result) == "MULTIPOLYGON (((0 0 8,0 2 8,0 4 8,2 4 8,4 4 8,4 2 8,4 0 8,2 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),((10 0 8,10 2 8,10 4 8,12 4 8,14 4 8,14 2 8,14 0 8,12 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)))"
    end

    @test AG.toWKT(AG.symdifference(geom1, geom2)) == "GEOMETRYCOLLECTION (POINT (2 5 8),POINT (3 6 9),POLYGON ((0 0 8,0 4 8,4 4 8,4 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),POLYGON ((10 0 8,10 4 8,14 4 8,14 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)))"
    AG.symdifference(geom1, geom2) do result
        @test GeoInterface.geotype(result) == :GeometryCollection
        @test AG.toWKT(result) == "GEOMETRYCOLLECTION (POINT (2 5 8),POINT (3 6 9),POLYGON ((0 0 8,0 4 8,4 4 8,4 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),POLYGON ((10 0 8,10 4 8,14 4 8,14 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)))"
        AG.removegeom!(result, 1)
        @test AG.toWKT(result) == "GEOMETRYCOLLECTION (POINT (2 5 8),POLYGON ((0 0 8,0 4 8,4 4 8,4 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),POLYGON ((10 0 8,10 4 8,14 4 8,14 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)))"
        AG.removeallgeoms!(result)
        @test AG.toWKT(result) == "GEOMETRYCOLLECTION EMPTY"
    end

    geom3 = AG.fromWKT("GEOMETRYCOLLECTION (POINT (2 5 8),POLYGON ((0 0 8,0 4 8,4 4 8,4 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),POLYGON ((10 0 8,10 4 8,14 4 8,14 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)), POINT EMPTY)")
    AG.clone(geom3) do geom4
        @test sprint(print, AG.clone(geom3)) == "Geometry: GEOMETRYCOLLECTION (POINT (2 5 8),POLYGON ((0 0 8, ... MPTY)"
        @test sprint(print, AG.clone(geom4)) == "Geometry: GEOMETRYCOLLECTION (POINT (2 5 8),POLYGON ((0 0 8, ... MPTY)"
    end
    AG.clone(AG.getgeom(geom3, 3)) do geom4
        @test sprint(print, geom4) == "Geometry: POINT EMPTY"
    end

    @test AG.toISOWKT(geom3) == "GEOMETRYCOLLECTION Z (POINT Z (2 5 8),POLYGON Z ((0 0 8,0 4 8,4 4 8,4 0 8,0 0 8),(1 1 8,3 1 8,3 3 8,1 3 8,1 1 8)),POLYGON Z ((10 0 8,10 4 8,14 4 8,14 0 8,10 0 8),(11 1 8,13 1 8,13 3 8,11 3 8,11 1 8)),POINT Z EMPTY)"
    AG.removegeom!(geom3, AG.ngeom(geom3)-1) # the JSON driver in GDAL 3.0 does not handle null geometries well yet
    @test AG.toJSON(geom3) == """{ "type": "GeometryCollection", "geometries": [ { "type": "Point", "coordinates": [ 2.0, 5.0, 8.0 ] }, { "type": "Polygon", "coordinates": [ [ [ 0.0, 0.0, 8.0 ], [ 0.0, 4.0, 8.0 ], [ 4.0, 4.0, 8.0 ], [ 4.0, 0.0, 8.0 ], [ 0.0, 0.0, 8.0 ] ], [ [ 1.0, 1.0, 8.0 ], [ 3.0, 1.0, 8.0 ], [ 3.0, 3.0, 8.0 ], [ 1.0, 3.0, 8.0 ], [ 1.0, 1.0, 8.0 ] ] ] }, { "type": "Polygon", "coordinates": [ [ [ 10.0, 0.0, 8.0 ], [ 10.0, 4.0, 8.0 ], [ 14.0, 4.0, 8.0 ], [ 14.0, 0.0, 8.0 ], [ 10.0, 0.0, 8.0 ] ], [ [ 11.0, 1.0, 8.0 ], [ 13.0, 1.0, 8.0 ], [ 13.0, 3.0, 8.0 ], [ 11.0, 3.0, 8.0 ], [ 11.0, 1.0, 8.0 ] ] ] } ] }"""

    AG.createmultilinestring([[[1.,4.], [2.,5.], [3.,6.], [1.,4.]]]) do geom4
        @test AG.toWKT(geom4) == "MULTILINESTRING ((1 4,2 5,3 6,1 4))"
        @test AG.toWKT(AG.polygonfromedges(geom4, 0.1)) == "POLYGON ((1 4,2 5,3 6,1 4))"
        AG.polygonfromedges(geom4, 0.1) do geom5
            @test AG.toWKT(geom5) == "POLYGON ((1 4,2 5,3 6,1 4))"
        end
    end

    @test AG.getgeomtype(AG.getgeom(geom3, 0)) == GDAL.wkbPoint25D
    @test AG.getgeomtype(AG.getgeom(geom3, 1)) == GDAL.wkbPolygon25D
    @test AG.getgeomtype(AG.getgeom(geom3, 2)) == GDAL.wkbPolygon25D
    @test sprint(print, AG.getgeom(geom3, 3)) == "NULL Geometry"
    AG.getgeom(geom3, 0) do geom4
        @test AG.getgeomtype(geom4) == GDAL.wkbPoint25D
    end
    AG.getgeom(geom3, 1) do geom4
        @test AG.getgeomtype(geom4) == GDAL.wkbPolygon25D
    end
    AG.getgeom(geom3, 2) do geom4
        @test AG.getgeomtype(geom4) == GDAL.wkbPolygon25D
    end
    AG.getgeom(geom3, 3) do geom4
        @test sprint(print, geom4) == "NULL Geometry"
    end
end

@testset "Spatial Reference Systems" begin
    AG.read("data/point.geojson") do dataset
        layer = AG.getlayer(dataset, 0)
        AG.nextfeature(layer) do feature
            geom = AG.getgeom(feature)
            @test AG.toPROJ4(AG.getspatialref(geom)) == "+proj=longlat +datum=WGS84 +no_defs"
            AG.getspatialref(geom) do spatialref
                @test AG.toPROJ4(spatialref) == "+proj=longlat +datum=WGS84 +no_defs"
            end
        end
        AG.createpoint(1,2) do point
            @test sprint(print, AG.getspatialref(point)) == "NULL Spatial Reference System"
            AG.getspatialref(point) do spatialref
                @test sprint(print, spatialref) == "NULL Spatial Reference System"
            end
        end
    end

    AG.importEPSG(2927) do source; AG.importEPSG(4326) do target
        AG.createcoordtrans(source, target) do transform
            AG.fromWKT("POINT (1120351.57 741921.42)") do point
                @test AG.toWKT(point) == "POINT (1120351.57 741921.42)"
                AG.transform!(point, transform)
                @test GeoInterface.coordinates(point) ≈ [47.348801, -122.598135]
    end end end end
end


text:
__precompile__(true)
module SchroedingersSmoke

using GPUArrays
using GPUArrays: gpu_rand

include("MatlabPort.jl")
include("parallel.jl")
include("particles.jl")

end


text:
# https://github.com/plotly/dash-vtk
# Pkg.add(PackageSpec(url="https://github.com/plotly/dash-vtk.git"))
# add "https://github.com/plotly/dash-vtk.git"

using Dash, DashVtk, DashHtmlComponents

# app = dash()

# app.layout = html_div(style = (width = "100%", height = "calc(100vh - 16px)",)) do
#     vtk_view(
#         vtk_geometryrepresentation(
#             vtk_algorithm(
#                 vtkClass = "vtkConeSource",
#                 state = (resolution = 64, capping = false)
#             )
#         )
#     )
# end

xyz = Float64[]
for i in 1:10000
    push!(xyz, rand()) # x
    push!(xyz, rand()) # y
    push!(xyz, rand() * 0.01) # z
end

content = vtk_view(
    children = [
        vtk_geometryrepresentation(
            property = (pointSize = 3),
            children = [
                vtk_polydata(points=xyz, connectivity="points")
            ]
        )
    ]
)

app = dash()

app.layout = html_div(
    style = (width = "100%", height = "calc(100vh - 16px)",),
    children = [content]
)

run_server(app)


text:
using Test
using ExtensibleScheduler: Priority
using Dates

@testset "Priority Tests" begin

    @testset "Priority Equality" begin
        p1 = Priority(DateTime(2010, 1, 1), 0)
        p2 = Priority(DateTime(2010, 1, 1), 0)
        @test p1 == p2
    end

    @testset "Priority Inequality" begin
        @testset "Same DateTime" begin
            p1 = Priority(DateTime(2010, 1, 1), 0)
            p2 = Priority(DateTime(2010, 1, 1), 1)
            @test p1 != p2
        end

        @testset "Same priority level" begin
            p1 = Priority(DateTime(2010, 1, 1), 0)
            p2 = Priority(DateTime(2010, 1, 2), 0)
            @test p1 != p2
        end
    end

    @testset "Priority order" begin
        p1 = Priority(DateTime(2010, 1, 2), 0)
        p2 = Priority(DateTime(2010, 1, 1), 0)
        @test p2 > p1

        p1 = Priority(DateTime(2010, 1, 1), 1)
        p2 = Priority(DateTime(2010, 1, 1), 0)
        @test p2 > p1
    end
end


text:
using Test

include("test_lasso.jl")
include("test_logistic_l1.jl")
include("test_sharing.jl")


text:
export conf

module conf

file_name = ASCIIString
command = ""
quiet = false
verbose = 0
debug_mode = 0
home_path = ""
interactive = false
login = false
daemon_only = false
ncpu = 0
print_expr = ""
color_mode = false
eval_expr = false
no_exec = false
no_history = false
no_startup = false

end

# export file_name, command, quiet, verbose, debug_mode, home_path, interactive, login, daemon_only, ncpu, print_expr, color_mode, eval_expr, no_exec, no_history, no_startup

# function __init__()

# # end
# export Config
# module Config
# import ..info

# info("Configuring Mocha...")
# const use_cuda_key = "MOCHA_USE_CUDA"
# const use_native_extension_key = "MOCHA_USE_NATIVE_EXT"

# if haskey(ENV, use_cuda_key) && lowercase(ENV[use_cuda_key]) != "false"
#   info(" * CUDA       enabled ($use_cuda_key environment variable detected)")
#   const use_cuda = true
# else
#   info(" * CUDA       disabled by default")
#   const use_cuda = false
# end

# if haskey(ENV, use_native_extension_key) && lowercase(ENV[use_native_extension_key]) != "false"
#   info(" * Native Ext enabled ($use_native_extension_key environment variable detected)")
#   const use_native_extension = true
# else
#   info(" * Native Ext disabled by default")
#   const use_native_extension = false
# end
# info("Mocha configured, continue loading module...")

# end

# if Config.use_native_extension
#   include("native.jl")
# end

# include("macros.jl")
# include("base.jl")
# include("exception.jl")

# include("utils/blas.jl")
# include("utils/math.jl")
# include("utils/io.jl")
# include("utils/tensor.jl")
# include("utils/ref-count.jl")

# if Config.use_native_extension
#   include("utils/im2col-native.jl")
# else
#   include("utils/im2col.jl")
# end

# include("backend.jl")
# include("blob.jl")

# if Config.use_cuda
#   include("cuda/cuda.jl")
#   include("cuda/cublas.jl")
#   include("cuda/cudnn.jl")
#   include("cuda/backend.jl")
#   include("cuda/blob.jl")
#   include("cuda/utils/math.jl")
#   include("cuda/utils/padded-copy.jl")
#   include("cuda/utils/shifted-copy.jl")
# end

# include("initializers.jl")
# include("regularizers.jl")
# include("constraints.jl")
# include("neurons.jl")

# if Config.use_cuda
#   include("cuda/regularizers.jl")
#   include("cuda/constraints.jl")
#   include("cuda/neurons.jl")
# end
# # RawBlameHistory
# const POSSIBLE_AFFIXES = ["stem","prefix","suffix"]
# const RESTRICT_SEG_COUNTS = true
# const RESTRICT_TYPE_TAG_COUNTS = true
# const BOUNDARY_TOKEN = "~~"
# const MAX_SPANS = 4
# const MAX_AFFIX = 2
# const MODEL_STEM_POSITION = true
# const ALPHA_TAG_PRIOR = 0.1
# const ALPHA_EMISSION = 1e-5
# const ALPHA_TRANSITION = 1.0
# const CONFLICT_STEM_PROB = 1e-2
# const CONFLICT_LOG_ODDS = log(CONFLICT_STEM_PROB / (1.0 - CONFLICT_STEM_PROB))
# const ALPHA_SEG = 0.1
# const ALPHA_CLUSTER = .7
# const GAMMA_NUM_UNIQUE_SEGS = 1.0/10
# const GAMMA_SEG_LEN = 1.0/1.1
# const GAMMA_NUM_SEGS_PER_WORD = 1.0/3.0
# const GAMMA_AFFIX_PER_WORD = 1.0/2.0
# const LOG_GEOM_TRUNC_NUM_SEGS_PER_WORD = LogGeometricTruncated(GAMMA_NUM_SEGS_PER_WORD, MAX_SPANS)
# const LOG_GEOM_TRUNC_NUM_AFFIX_PER_WORD = LogGeometricTruncated(GAMMA_AFFIX_PER_WORD, MAX_AFFIX)
# const PAIRWISE_SUFFIX_LOGPROB = {nothing=>log(0.3), true=>log(0.6), false=>log(0.1)}
# const PAIRWISE_PREFIX_LOGPROB = {nothing=>log(0.05), true=>log(0.9), false=>log(0.05)}
# const USE_STEM_LENGTH_CONSTRAINT = true
# const X_GAMMA_NUM_UNIQUE_SEGS = {"stem"=>1e-4, "prefix"=>1.0/1.1, "suffix"=>1.0/1.1}
# const FROZEN_RE = r"^(\d)+"
# USER = get("USER")
# SHELL = get("SHELL")
# HOME = get("HOME")
# PATH = get("PATH")
# PWD = get("PWD")
# TERM = get("TERM")
# TMPDIR = get("TMPDIR")
# LANG = get("LANG")
# LC_ALL = get("LC_ALL")
# USER, SHELL, HOME, PATH, PWD, TERM, TMPDIR, LANG, LC_ALL,
# end

max_stars_repo_name: tmaone/xsh

max_issues_repo_name: turing-complete/xsh

max_forks_repo_name: turing-complete/xsh


text:
using LinearAlgebra, StableRNGs, StatsModels, Test

import MixedModels: statsrank

xtx(X) = Symmetric(X'X, :U)  # creat the symmetric matrix X'X from X
LinearAlgebra.rank(F::LinearAlgebra.QRPivoted; tol=1e-8) = searchsortedlast(abs.(diag(F.R)), tol, rev=true);

const rng = StableRNG(4321234)

const simdat = (
    G = repeat('A':'T', inner=10),
    H = repeat('a':'e', inner=2, outer=20),
    U = repeat(0.:9, outer=20),
    V = repeat(-4.5:4.5, outer=20),
    Y = 0.1 * randn(rng, 200),
    Z = rand(rng, 200)
)

@testset "fullranknumeric" begin
    mm = modelmatrix(@formula(Y ~ 1 + U), simdat)
    r, pivot = statsrank(mm)
    @test pivot == 1:2
end

@testset "fullrankcategorical" begin
    mm = modelmatrix(@formula(Y ~ 1 + G*H), simdat)
    r, pivot = statsrank(mm)
    @test r == 100
    @test pivot == 1:100
end

@testset "dependentcolumn" begin
    mm = modelmatrix(@formula(Y ~ 1 + U + V + Z), simdat)
    r, pivot = statsrank(mm)
    perm = [1,2,4,3]
    @test r == 3
    @test pivot == perm
end

@testset "qr missing cells" begin
    mm = modelmatrix(@formula(Y ~ 1 + G*H), simdat)[5:end,:]
    r, pivot = statsrank(mm)
    @test r == 98
    # we no longer offer ordering guarantees besides preserving
    # relative order of linearly independent columns
    # and trying to keep the first column in the first position
    unpivoted = pivot[begin:r]
    @test unpivoted == sort(unpivoted)
end

@testset "zero columns in X" begin
    X = Matrix{Float64}(undef, 100, 0)
    r, pivot = statsrank(X)
    @test iszero(r)
    @test pivot == collect(axes(X, 2))
end


text:
module CommunalHelperInputFlagController

using ..Ahorn, Maple

@mapdef Entity "CommunalHelper/InputFlagController" Controller(
    x::Int,
    y::Int,
    flags::String="",
    toggle::Bool=true,
    resetFlags::Bool=false,
    delay::Float64=0.0,
    grabOverride::Bool=false,
)

const placements = Ahorn.PlacementDict(
    "Input Flag Controller (Communal Helper)" => Ahorn.EntityPlacement(
        Controller,
    ),
)

const sprite = "objects/CommunalHelper/inputFlagController/icon"

Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::Controller) = Ahorn.drawSprite(ctx, sprite, 0, 0)

Ahorn.selection(entity::Controller) = Ahorn.getSpriteRectangle(sprite, Ahorn.position(entity)...)

end


text:
using SubmodularMaximization
using POMDPs
using MCTS

grid_size = 10
iterations = 10

grid = Grid(grid_size, grid_size)
sensor = RangingSensor()

@show robot_state = random_state(grid)

histogram_filter = Filter(grid)

for horizon = 1:2
  problem = SingleRobotTargetTrackingProblem(grid, sensor, horizon,
                                             [histogram_filter])

  solution = solve_single_robot(problem, robot_state,
                                n_iterations = iterations)

  @show solution.action
  @show solution.trajectory

  if !in(solution.action, neighbors(grid, robot_state))
    println("Action is not valid")
  end
end

max_stars_repo_name: mcorah/MultiAgentSensing

max_issues_repo_name: mcorah/MultiAgentSensing

max_forks_repo_name: mcorah/MultiAgentSensing


text:
# QuantLib
__precompile__()
module QuantLib

# functions overridden from based
import Base.findprev, Base.findnext

function findprev(testf::Function, A::Vector, start::Int, val)
  for i = start:-1:1
    @inbounds testf(A[i], val) && return i
  end
  0
end

function findnext(testf::Function, A::Vector, start::Int, val)
  @inbounds for i = start:length(A)
    if testf(A[i], val)
      return i
    end
  end
  return 0
end

function upper_bound(vec::Vector{T}, x::T) where {T}
  if x > vec[end]
    return length(vec) + 1
  end
  found = searchsortedlast(vec, x)
  if found != length(vec)
    found += 1
  end

  return found
end

# Math module
include("math/Math.jl")

# Time module
include("time/Time.jl")

# MAIN MODULE CODE
using QuantLib.Math, QuantLib.Time
using Distributions

# Constants #
const basisPoint = 0.0001
const JQ_MAX = 1.79769e308
const JQ_MIN = 2.22507e-308
const M_SQRT2 = 1.41421356237309504880168872420969808   # sqrt(2)
const M_SQRT1_2 = 0.707106781186547524400844362104849039  # 1/sqrt(2)
const M_SQRTPI = 1.77245385090551602792981
const M_SQRT_2 = 0.7071067811865475244008443621048490392848359376887
const M_1_SQRTPI = 0.564189583547756286948

export
    # abstract_types.jl
    LazyObject,

    Exercise, EarlyExercise, CompoundingType, TermStructure, YieldTermStructure, InterpolatedCurve, BootstrapTrait, Bootstrap, BootstrapHelper, BondHelper, RateHelper,
    FittingMethod, CashFlows, CashFlow, Coupon, CouponPricer, IborCouponPricer, Instrument, Bond, Swap, SwapType, PricingEngine, Duration, AbstractRate, Results,
    InterestRateIndex, AbstractCurrency, Parameter, CalibrationHelper, ShortRateModel, FdmMesher, OptionType, AbstractMarketModel, OptionletVolatilityStructure,

    # lazy.jl
    LazyMixin, calculate!, recalculate!,

    # Methods
    # methods/lattice.jl
    TreeLattice1D, Branching, TrinomialTree,

    # methods/binomial_tree.jl
    JarrowRudd, CoxRossRubinstein, AdditiveEQP, Trigeorgis, Tian, LeisenReimer, Joshi4,

    # methods/monte_carlo/utilities.jl
    NodeData,

    # methods/monte_carlo/generic_ls_regression.jl
    generic_longstaff_schwartz_regression!,

    # quotes/Quotes.jl
    Quote,

    # currencies/currencies.jl
    NullCurrency, Currency,

    # InterestRates.jl
    ContinuousCompounding, SimpleCompounding, CompoundedCompounding, SimpleThenCompounded, ModifiedDuration,
    InterestRate, discount_factor, compound_factor, equivalent_rate, implied_rate,

    # exercise.jl
    AmericanExercise, BermudanExercise, EuropeanExercise,

    # Indexes
    IborIndex, LiborIndex, fixing_date, maturity_date, fixing, forecast_fixing, euribor_index, usd_libor_index, update_termstructure, is_valid_fixing_date, add_fixing!,

    # cash_flows/cash_flows.jl
    CouponMixin, accrual_start_date, accrual_end_date, ref_period_start, ref_period_end, SimpleCashFlow, Leg, ZeroCouponLeg, IRRFinder, operator, amount, date, duration, yield, previous_cashflow_date,
    accrual_days, accrual_days, next_cashflow, has_occurred, accrued_amount, next_coupon_rate, maturity_date, initialize!,

    # cash_flows/fixed_rate_coupon.jl
    FixedRateCoupon, FixedRateLeg,

    # cash_flows/floating_rate_coupon.jl
    BlackIborCouponPricer, IborCoupon, IborLeg, update_pricer!,

    # instruments/Instruments.jl
    update_pricing_engine, LongPosition, ShortPosition,

    # instruments/bond.jl
    BondMixin, FixedRateBond, FloatingRateBond, ZeroCouponBond, value, get_settlement_days, get_settlement_date, notional, accrued_amount, yield, duration, npv, clean_price, dirty_price, accrued_amount,

    # instruments/payoff.jl
    Put, Call, PlainVanillaPayoff,

    # instruments/option.jl
    VanillaOption,

    # instruments/forward.jl
    ForwardRateAgreement, forward_rate, spot_value, forward_value, implied_yield,

    # instruments/callability_schedule.jl
    DirtyCall, CleanCall, Price, Callability, CallabilitySchedule,

    # instruments/callable_bond.jl
    CallableFixedRateBond,

    # instruments/claim.jl
    FaceValueClaim,

    # instruments/swap.jl
    Payer, Receiver, SwapResults, VanillaSwap, NonstandardSwap, CreditDefaultSwap, fair_rate, update_all_ts!,

    # Swap Index
    SwapIndex, EuriborSwapIsdaFixA,

    # instruments/swaption.jl
    SettlementCash, SettlementPhysical, Swaption, NonstandardSwaption, calibration_basket,

    # termstructures/bond_helpers.jl
    FixedRateBondHelper, implied_quote,

    # termstructures/rate_helpers.jl
    SwapRateHelper, DepositRateHelper, FraRateHelper, implied_quote,

    # termstructures/TermStructures.jl
    check_range, max_date, time_from_reference,

    # termstructures/yield_term_structure.jl
    NullYieldTermStructure, FlatForwardTermStructure, JumpDate, JumpTime, InterpolatedDiscountCurve,
    calculated!, discount, zero_rate, forward_rate, discount_impl,

    # termstructures/bootstrap_traits.jl
    Discount, HazardRate, guess, min_value_after, max_value_after,

    # termstructures/curve.jl
    PiecewiseYieldCurve, PiecewiseDefaultCurve, FittedBondDiscountCurve, FittingCost, NullCurve,
    max_date, discount, calculate!, initialize!, value, nodes, survival_probability, default_probability, default_density, hazard_rate,

    # termstructures/vol_term_structure.jl
    ConstantOptionVolatility, ConstantSwaptionVolatility,

    # termstructures/black_vol_term_structure.jl
    BlackConstantVol,

    # termstructures/bootstrap.jl
    IterativeBootstrap, initialize, quote_error,

    # termstructures/credit_helper.jl
    SpreadCDSHelper,

    # termstructures/credit
    InterpolatedHazardRateCurve,

    # termstructures/nonlinear_fitting_methods.jl
    ExponentialSplinesFitting, SimplePolynomialFitting, NelsonSiegelFitting, SvenssonFitting, CubicBSplinesFitting, discount_function, guess_size,

    # Process
    # process/stochastic_process/jl
    OrnsteinUhlenbeckProcess, GsrProcess, expectation, variance,

    # process/black_scholes_process.jl
    BlackScholesMertonProcess,

    # process/heston_process.jl
    HestonProcess,

    #process/bates_process.jl
    BatesProcess,

    # models/parameter.jl
    ConstantParameter, G2FittingParameter, HullWhiteFittingParameter,

    # models/calibration_helpers.jl
    NaiveBasketType, SwaptionHelper, implied_volatility!, add_times_to!, model_value!, update_pricing_engine!, underlying_swap!, # for swaptionHelper only

    # models/equity/heston_model.jl
    HestonModel,

    # models/equity/bates_model.jl
    BatesModel,

    # models/short_rate/short_rate.jl
    PrivateConstraint, test, calibrate!, func_values, value, get_params,

    # models/short_rate/two_factor.jl
    G2,

    # models/short_rate/one_factor.jl
    BlackKarasinski, HullWhite, GSR, calibrate_volatilities_iterative!, get_volatilities,

    # models/market_models/callability/exercise_value.jl
    NothingExerciseValue,

    # models/market_models/brownian_generators.jl
    SobolDiagonalOrdering, SobolBrownianGeneratorFactory, create,

    # models/market_models/evolution_description.jl
    EvolutionDescription, money_market_measure,

    # models/market_models/products/multistep/multiproduct_multistep.jl
    MultiStepInverseFloater, ExerciseAdapter,

    # models/market_models/products/multistep/call_specified_multiproduct.jl
    CallSpecifiedMultiProduct,

    # models/market_models/products/pathwise/pathwise_product_calls_specified.jl
    CallSpecifiedPathwiseMultiProduct,

    # models/market_models/products/composite_product.jl
    MarketModelComposite, add_product!, finalize!,

    # models/market_models/correlations/exponential_correlation.jl
    ExponentialForwardCorrelation,

    # models/market_models/modesl/flatvol.jl
    FlatVol,

    # models/market_models/callability/swap_rate_trigger.jl
    SwapRateTrigger,

    # models/market_models/callability/market_model_basis_system.jl
    SwapForwardBasisSystem,

    # models/market_models/callability/collect_node_data.jl
    collect_node_data!,

    # models/market_models/callability/ls_strategy.jl
    LongstaffSchwartzExerciseStrategy,

    # models/market_models/pathwise_greeks/vega_bump_cluster.jl
    VegaBumpCollection,

    # models/market_models/pathwise_greeks/bump_instrument_jacobian.jl
    VolatilityBumpInstrumentJacobianSwaption, VolatilityBumpInstrumentJacobianCap, OrthogonalizedBumpFinder, get_vega_bumps!,

    # models/market_models/pathwise/pathwise_product_inverse_floater.jl
    MarketModelPathwiseInverseFloater,

    # models/market_models/evolvers/lognormal_fwd_rate_pc.jl
    LogNormalFwdRatePc,

    # models/market_models/evolvers/lognormal_fwd_rate_euler.jl
    LogNormalFwdRateEuler,

    # models/market_models/accounting_engine.jl
    AccountingEngine, multiple_path_values!,

    # models/market_models/pathwise_accounting_engine.jl
    PathwiseVegasOuterAccountingEngine, multiple_path_values!,

    # methods - finite difference
    FdmG2Solver, FdmHullWhiteSolver, CrankNelson, FdmSolverDesc, Fdm2DimSolver, FdmG2Op, FdmMesherComposite, FdmSimpleProcess1dMesher, FdmAffineModelSwapInnerValue,
    Concentrating1dMesher,

    # methods - monte carlo
    MonteCarloModel, PathGenerator, add_samples!, Path,

    # pricing_engines/pricing_engines.jl
    DiscountingBondEngine, DiscountingSwapEngine, MidPointCdsEngine, TreeCallableFixedRateEngine,

    # pricing_engines/black_calculator.jl
    BlackCalculator, value, delta, vega,

    # pricing_engines/discretized_asset.jl
    DiscretizedSwaption, DiscretizedSwap,

    # pricing_engines/swaption_engines
    BlackSwaptionEngine, G2SwaptionEngine, JamshidianSwaptionEngine, TreeSwaptionEngine, FdG2SwaptionEngine, FdHullWhiteSwaptionEngine, Gaussian1DSwaptionEngine, Gaussian1DNonstandardSwaptionEngine,

    # pricing_engines/vanilla
    AnalyticEuropeanEngine, AnalyticHestonEngine, BatesEngine, BaroneAdesiWhaleyApproximationEngine, BjerksundStenslandApproximationEngine, IntegralEngine,
    FDEuropeanEngine, FDBermudanEngine, FDAmericanEngine, BinomialVanillaEngine, MCEuropeanEngine, MCAmericanEngine

# abstract types
include("abstract_types.jl")

# observer
include("observer.jl")

# lazy
include("lazy.jl")

# methods
include("methods/lattice.jl")
include("methods/bsm_lattice.jl")
include("methods/binomial_tree.jl")
include("methods/monte_carlo/utilities.jl")
include("methods/monte_carlo/brownian_bridge.jl")
include("methods/monte_carlo/generic_ls_regression.jl")

# Quotes ----------------------------
include("quotes/Quotes.jl")

# Currencies -----------------------
include("currencies/currencies.jl")

# Interest Rates ---------------------------------
include("InterestRates.jl")

# Exercise---------------------------------
include("exercise.jl")

# Indexes
include("indexes/indexes.jl")

# Cash Flows ------------------------------------
include("cash_flows/cash_flows.jl")
include("cash_flows/fixed_rate_coupon.jl")
include("cash_flows/floating_rate_coupon.jl")

# Instruments ------------------------
include("instruments/Instruments.jl")
# bond
include("instruments/bond.jl")
include("instruments/payoff.jl")
include("instruments/option.jl")
include("instruments/forward.jl")
include("instruments/callability_schedule.jl")
include("instruments/callable_bond.jl")
include("instruments/claim.jl")
include("instruments/swap.jl")
include("indexes/swap_index.jl") # need this here because swap index needs to know what a VanillaSwap is
include("instruments/swaption.jl")

# Term Structures -----------------------------------
include("termstructures/TermStructures.jl")
include("termstructures/curve.jl")
# helpers
include("termstructures/yield/bond_helpers.jl")
include("termstructures/yield/rate_helpers.jl")
include("termstructures/credit/credit_helpers.jl")
# bootstrapping
include("termstructures/bootstrap/bootstrap_traits.jl")
include("termstructures/bootstrap/bootstrap.jl")
# yield term structures
include("termstructures/yield/yield_term_structure.jl")
include("termstructures/yield/piecewise_yield_curve.jl")
include("termstructures/yield/fitted_bond_curve.jl")
include("termstructures/yield/nonlinear_fitting_methods.jl")
include("termstructures/yield/discount_curve.jl")
# volatility
include("termstructures/volatility/vol_term_structure.jl")
include("termstructures/volatility/black_vol_term_structure.jl")
include("termstructures/volatility/callable_bond_vol_structure.jl")
# credit
include("termstructures/credit/piecewise_default_curve.jl")
include("termstructures/credit/interpolated_hazard_rate_curve.jl")

# process
include("process/discretization.jl")
include("process/stochastic_process.jl")
include("process/black_scholes_process.jl")
include("process/heston_process.jl")
include("process/bates_process.jl")

# Models ---------------------------------
include("models/parameter.jl")
include("models/calibration_helpers.jl")
include("models/models.jl")
include("models/equity/heston_model.jl")
include("models/equity/bates_model.jl")
include("models/short_rate/short_rate.jl")
include("models/short_rate/two_factor.jl")
include("models/short_rate/one_factor/one_factor.jl")
include("models/short_rate/one_factor/black_karasinski.jl")
include("models/short_rate/one_factor/hull_white.jl")
include("models/short_rate/one_factor/gsr.jl")
include("models/market_models/utilities.jl")
include("models/market_models/evolution_description.jl")
include("models/market_models/brownian_generators.jl")
include("models/market_models/swap_forward_mappings.jl")
include("models/market_models/products/multistep/multiproduct_multistep.jl")
include("models/market_models/products/multistep/call_specified_multiproduct.jl")
include("models/market_models/products/composite_product.jl")
include("models/market_models/products/pathwise/pathwise_product_calls_specified.jl")
include("models/market_models/products/pathwise/pathwise_product_cashrebate.jl")
include("models/market_models/products/pathwise/rate_pseudo_root_jacobian.jl")
include("models/market_models/products/pathwise/pathwise_product_inverse_floater.jl")
include("models/market_models/models/flatvol.jl")
include("models/market_models/correlations/time_homogeneous_forward_correlation.jl")
include("models/market_models/correlations/exponential_correlation.jl")
include("models/market_models/callability/swap_rate_trigger.jl")
include("models/market_models/callability/exercise_value.jl")
include("models/market_models/callability/market_model_basis_system.jl")
include("models/market_models/callability/collect_node_data.jl")
include("models/market_models/pathwise_greeks/vega_bump_cluster.jl")
include("models/market_models/pathwise_greeks/swaption_pseudo_derivative.jl")
include("models/market_models/pathwise_greeks/bump_instrument_jacobian.jl")
include("models/market_models/callability/ls_strategy.jl")
include("models/market_models/curve_state.jl")
include("models/market_models/drift_computation.jl")
include("models/market_models/market_models.jl")
include("models/market_models/evolvers/lognormal_fwd_rate_euler.jl")
include("models/market_models/evolvers/lognormal_fwd_rate_pc.jl")
include("models/market_models/accounting_engine.jl")
include("models/market_models/pathwise_accounting_engine.jl")

# Finite Difference method
include("methods/finite_differences/fd_boundary_condition.jl")
include("methods/finite_differences/fd_pde.jl")
include("methods/finite_differences/fd_bsm_operator.jl")
include("methods/finite_differences/fd_layout.jl")
include("methods/finite_differences/fd_step_condition.jl")
include("methods/finite_differences/fd_mesher.jl")
include("methods/finite_differences/fd_calc.jl")
include("methods/finite_differences/fd_operator.jl")
include("methods/finite_differences/fd_scheme.jl")
include("methods/finite_differences/fd_model.jl")
include("methods/finite_differences/fd_solvers.jl")

# Monte Carlo method
include("methods/monte_carlo/path.jl")
include("methods/monte_carlo/sample.jl")
include("methods/monte_carlo/path_generator.jl")
include("methods/monte_carlo/lsm_basis_system.jl")
include("methods/monte_carlo/monte_carlo_model.jl")

# Pricing Engines ------------------------
include("pricing_engines/pricing_engines.jl")
include("pricing_engines/discretized_asset.jl")
include("pricing_engines/black_calculator.jl")
include("pricing_engines/black_formula.jl")
include("pricing_engines/mc_simulation.jl")
include("pricing_engines/lattice_shortrate_model_engine.jl")
include("pricing_engines/bond/discretized_bond.jl")
include("pricing_engines/bond/discounting_bond_engine.jl")
include("pricing_engines/bond/black_callable_bond_engine.jl")
include("pricing_engines/bond/tree_callable_bond_engine.jl")
include("pricing_engines/swap/discounting_swap_engine.jl")
include("pricing_engines/swap/discretized_swap.jl")
include("pricing_engines/credit/midpoint_cds_engine.jl")
include("pricing_engines/swaptions/swaption_engine.jl")
include("pricing_engines/swaptions/discretized_swaption.jl")
include("pricing_engines/swaptions/black_swaption_engine.jl")
include("pricing_engines/swaptions/G2_swaption_engine.jl")
include("pricing_engines/swaptions/fdg2_swaption_engine.jl")
include("pricing_engines/swaptions/fd_hullwhite_swaption_engine.jl")
include("pricing_engines/swaptions/jamshidian_swaption_engine.jl")
include("pricing_engines/swaptions/tree_swaption_engine.jl")
include("pricing_engines/swaptions/gaussian1d_swaption_engine.jl")
include("pricing_engines/swaptions/gaussian1d_nonstandard_swaption_engine.jl")
include("pricing_engines/vanilla/discretized_vanilla_option.jl")
include("pricing_engines/vanilla/analytic_european_engine.jl")
include("pricing_engines/vanilla/analytic_heston_engine.jl")
include("pricing_engines/vanilla/bates_engine.jl")
include("pricing_engines/vanilla/barone_adesi_whaley_engine.jl")
include("pricing_engines/vanilla/bjerksund_stensland_engine.jl")
include("pricing_engines/vanilla/integral_engine.jl")
include("pricing_engines/vanilla/fd_vanilla_engine.jl")
include("pricing_engines/vanilla/binomial_engine.jl")
include("pricing_engines/vanilla/mc_european_engine.jl")
include("pricing_engines/vanilla/mc_american_engine.jl")

# # Helpers NOW IN TERM STRUCTURE
# include("helpers/bond_helpers.jl")

mutable struct Settings
  evaluation_date::Date
  counter::Int
end

settings = Settings(Date(0), 0)

function set_eval_date!(sett::Settings, d::Date)
  sett.evaluation_date = d
end

export Settings, settings, set_eval_date!

end