text:
@testset "learnbase" begin
    @testset "label return poslabel first" begin
        @test @inferred(nlabel(x for x in 1:2)) === 2
        @test @inferred(label(x for x in 1:2)) == [1,2]
        @test @inferred(label([3,1])) == [3,1]
        @test @inferred(label([2,1])) == [1,2]
        @test @inferred(label([false,true])) == [true,false]
        @test @inferred(label([-1,1,1,-1])) == [1,-1]
        @test @inferred(label([0,1,1,0])) == [1,0]
        @test @inferred(label([0.,1,1,0])) == [1,0]
        @test @inferred(label([0,1,1,2])) == [0,1,2]
        @test @inferred(poslabel([3,1])) === 3
        @test @inferred(poslabel([0 1 0 0; 1 0 1 0])) === 1
        @test @inferred(poslabel([2,1])) === 1
        @test @inferred(poslabel([false,true])) === true
        @test @inferred(poslabel([-1,1,1,-1])) === 1
        @test @inferred(poslabel([0,1,1,0])) === 1
        @test @inferred(poslabel([0.,1,1,0])) === 1.
        @test_throws ArgumentError poslabel([0,1,1,2])
        @test_throws ArgumentError poslabel([1,1,1,1])
        @test @inferred(neglabel([3,1])) === 1
        @test @inferred(neglabel([0 1 0 0; 1 0 1 0])) === 2
        @test @inferred(neglabel([2,1])) === 2
        @test @inferred(neglabel([false,true])) === false
        @test @inferred(neglabel([-1,1,1,-1])) === -1
        @test @inferred(neglabel([0,1,1,0])) === 0
        @test @inferred(neglabel([0.,1,1,0])) === 0.
        @test_throws ArgumentError neglabel([0,1,1,2])
        @test_throws ArgumentError neglabel([1,1,1,1])
    end

    @testset "label for array" begin
        @test_throws MethodError label(rand(2,2,3))
        @test_throws MethodError label([:yes :no; :yes :no])
        @test @inferred(label(rand(5,10))) == collect(1:5)
        @test @inferred(label(rand(5,10), ObsDim.First())) == collect(1:10)
        @test label(rand(5,10), obsdim=1) == collect(1:10)
    end
end

@testset "constructor" begin
    @testset "ambiguous" begin
        @test_throws ArgumentError labelenc([1,1,1])
        @test_throws ArgumentError labelenc((1,1,1))
    end

    @testset "FuzzyBinary" begin
        @test LabelEnc.FuzzyBinary <: MLLabelUtils.BinaryLabelEncoding
        @test @inferred(nlabel(LabelEnc.FuzzyBinary())) === 2
        @test @inferred(labeltype(LabelEnc.FuzzyBinary)) <: Any
        @test_throws MethodError label(LabelEnc.FuzzyBinary())
    end

    @testset "TrueFalse" begin
        @test LabelEnc.TrueFalse <: MLLabelUtils.BinaryLabelEncoding
        @test @inferred(nlabel(LabelEnc.TrueFalse)) === 2
        @test @inferred(labeltype(LabelEnc.TrueFalse)) <: Bool
        @test typeof(@inferred(LabelEnc.TrueFalse())) <: LabelEnc.TrueFalse
    end

    @testset "ZeroOne" begin
        @test LabelEnc.ZeroOne <: MLLabelUtils.BinaryLabelEncoding
        @test @inferred(nlabel(LabelEnc.ZeroOne)) === 2
        @test @inferred(nlabel(LabelEnc.ZeroOne{Float32})) === 2
        @test @inferred(labeltype(LabelEnc.ZeroOne)) == Number
        @test @inferred(labeltype(LabelEnc.ZeroOne{Float32})) <: Float32
        @test typeof(@inferred(LabelEnc.ZeroOne{Int,Float32}())) <: LabelEnc.ZeroOne{Int,Float32}
        @test typeof(@inferred(LabelEnc.ZeroOne())) <: LabelEnc.ZeroOne{Float64,Float64}
        @test typeof(@inferred(LabelEnc.ZeroOne(0))) <: LabelEnc.ZeroOne{Int,Int}
        @test typeof(@inferred(LabelEnc.ZeroOne(0.0))) <: LabelEnc.ZeroOne{Float64,Float64}
        @test typeof(@inferred(LabelEnc.ZeroOne(0.2))) <: LabelEnc.ZeroOne{Float64,Float64}
        @test typeof(@inferred(LabelEnc.ZeroOne(1.0))) <: LabelEnc.ZeroOne{Float64,Float64}
        @test typeof(@inferred(LabelEnc.ZeroOne(0.2f0))) <: LabelEnc.ZeroOne{Float32,Float32}
        @test_throws AssertionError LabelEnc.ZeroOne(1.1)
        @test_throws AssertionError LabelEnc.ZeroOne(-0.1)
        @test_throws MethodError LabelEnc.ZeroOne(String)
        @test typeof(@inferred(LabelEnc.ZeroOne(Float64))) <: LabelEnc.ZeroOne{Float64,Float64}
        @test typeof(@inferred(LabelEnc.ZeroOne(UInt8))) <: LabelEnc.ZeroOne{UInt8,Float64}
        @test typeof(@inferred(LabelEnc.ZeroOne(UInt8,0.1f0))) <: LabelEnc.ZeroOne{UInt8,Float32}
        @test LabelEnc.ZeroOne().cutoff === 0.5
        @test LabelEnc.ZeroOne(UInt8).cutoff === 0.5
        @test LabelEnc.ZeroOne(0.1).cutoff === 0.1
        @test LabelEnc.ZeroOne(0.8f0).cutoff === 0.8f0
    end

    @testset "MarginBased" begin
        @test LabelEnc.MarginBased <: MLLabelUtils.BinaryLabelEncoding
        @test @inferred(nlabel(LabelEnc.MarginBased)) === 2
        @test @inferred(nlabel(LabelEnc.MarginBased{Float32})) === 2
        @test @inferred(labeltype(LabelEnc.MarginBased)) == Number
        @test @inferred(labeltype(LabelEnc.MarginBased{Float32})) <: Float32
        @test typeof(@inferred(LabelEnc.MarginBased())) <: LabelEnc.MarginBased{Float64}
        @test typeof(@inferred(LabelEnc.MarginBased(Int))) <: LabelEnc.MarginBased{Int}
        @test typeof(@inferred(LabelEnc.MarginBased(Float64))) <: LabelEnc.MarginBased{Float64}
        @test_throws MethodError LabelEnc.MarginBased(String)
    end

    @testset "OneVsRest" begin
        @test LabelEnc.OneVsRest <: MLLabelUtils.BinaryLabelEncoding
        @test @inferred(nlabel(LabelEnc.OneVsRest)) === 2
        @test @inferred(nlabel(LabelEnc.OneVsRest{Float32})) === 2
        @test @inferred(labeltype(LabelEnc.OneVsRest)) == Any
        @test @inferred(labeltype(LabelEnc.OneVsRest{Symbol})) <: Symbol
        @test_throws MethodError LabelEnc.OneVsRest([1,2])
        @test_throws MethodError LabelEnc.OneVsRest(:yes, nothing)
        @test_throws MethodError LabelEnc.OneVsRest(:yes, "no")
        @test typeof(@inferred(LabelEnc.OneVsRest([1,2],[2,1])))  <: LabelEnc.OneVsRest{Vector{Int}}
        @test typeof(@inferred(LabelEnc.OneVsRest(:yes)))  <: LabelEnc.OneVsRest{Symbol}
        @test typeof(@inferred(LabelEnc.OneVsRest(:yes, :no)))  <: LabelEnc.OneVsRest{Symbol}
        @test typeof(@inferred(LabelEnc.OneVsRest(true)))  <: LabelEnc.OneVsRest{Bool}
        @test typeof(@inferred(LabelEnc.OneVsRest(true, false)))  <: LabelEnc.OneVsRest{Bool}
        @test typeof(@inferred(LabelEnc.OneVsRest("yes"))) <: LabelEnc.OneVsRest{String}
        @test typeof(@inferred(LabelEnc.OneVsRest("yes", "no"))) <: LabelEnc.OneVsRest{String}
        @test typeof(@inferred(LabelEnc.OneVsRest(1)))   <: LabelEnc.OneVsRest{Int}
        @test typeof(@inferred(LabelEnc.OneVsRest(1,4))) <: LabelEnc.OneVsRest{Int}
    end

    @testset "Indices" begin
        @test LabelEnc.Indices <: MLLabelUtils.LabelEncoding
        @test_throws ArgumentError nlabel(LabelEnc.Indices)
        @test @inferred(nlabel(LabelEnc.Indices{Float32,4})) === 4
        @test @inferred(labeltype(LabelEnc.Indices)) == Number
        @test @inferred(labeltype(LabelEnc.Indices{UInt8})) <: UInt8
        @test @inferred(labeltype(LabelEnc.Indices{UInt8,3})) <: UInt8
        @test_throws TypeError LabelEnc.Indices(Val{3.})
        @test typeof(@inferred(LabelEnc.Indices(Val{3}))) <: LabelEnc.Indices{Int,3}
        @test typeof(@inferred(LabelEnc.Indices(Val{2}))) <: LabelEnc.Indices{Int,2}
        @test typeof(@inferred(LabelEnc.Indices(Val{2}))) <: MLLabelUtils.BinaryLabelEncoding
        @test typeof(@inferred(LabelEnc.Indices(Float32,Val{5}))) <: LabelEnc.Indices{Float32,5}
        @test typeof(LabelEnc.Indices(3)) <: LabelEnc.Indices{Int,3}
        @test typeof(LabelEnc.Indices(3.)) <: LabelEnc.Indices{Int,3}
        @test typeof(LabelEnc.Indices(UInt8,3.)) <: LabelEnc.Indices{UInt8,3}
        @test typeof(LabelEnc.Indices(Float64,8)) <: LabelEnc.Indices{Float64,8}
    end

    @testset "OneOfK" begin
        @test LabelEnc.OneOfK <: MLLabelUtils.LabelEncoding
        @test_throws ArgumentError nlabel(LabelEnc.OneOfK)
        @test @inferred(nlabel(LabelEnc.OneOfK{Float32,4})) === 4
        @test @inferred(labeltype(LabelEnc.OneOfK)) == Number
        @test @inferred(labeltype(LabelEnc.OneOfK{UInt8})) <: UInt8
        @test @inferred(labeltype(LabelEnc.OneOfK{UInt8,3})) <: UInt8
        @test_throws TypeError LabelEnc.OneOfK(Val{3.})
        @test typeof(@inferred(LabelEnc.OneOfK(Val{3}))) <: LabelEnc.OneOfK{Int,3}
        @test typeof(@inferred(LabelEnc.OneOfK(Val{2}))) <: LabelEnc.OneOfK{Int,2}
        @test typeof(@inferred(LabelEnc.OneOfK(Val{2}))) <: MLLabelUtils.BinaryLabelEncoding
        @test typeof(@inferred(LabelEnc.OneOfK(Float32,Val{5}))) <: LabelEnc.OneOfK{Float32,5}
        @test typeof(LabelEnc.OneOfK(3)) <: LabelEnc.OneOfK{Int,3}
        @test typeof(LabelEnc.OneOfK(3.)) <: LabelEnc.OneOfK{Int,3}
        @test typeof(LabelEnc.OneOfK(UInt8,3.)) <: LabelEnc.OneOfK{UInt8,3}
        @test typeof(LabelEnc.OneOfK(Float64,8)) <: LabelEnc.OneOfK{Float64,8}
    end

    @testset "NativeLabels" begin
        @test LabelEnc.NativeLabels <: MLLabelUtils.LabelEncoding
        @test_throws ArgumentError nlabel(LabelEnc.NativeLabels)
        @test @inferred(nlabel(LabelEnc.NativeLabels{Float32,4})) === 4
        @test @inferred(labeltype(LabelEnc.NativeLabels)) == Any
        @test @inferred(labeltype(LabelEnc.NativeLabels{String})) <: String
        @test @inferred(labeltype(LabelEnc.NativeLabels{UInt8,3})) <: UInt8
        @test_throws TypeError LabelEnc.NativeLabels{Int,2.}([1,2])
        @test_throws AssertionError LabelEnc.NativeLabels{Int,3}([1,2])
        @test_throws AssertionError LabelEnc.NativeLabels([1,2],Val{3})
        @test typeof(LabelEnc.NativeLabels(1:3)) <: LabelEnc.NativeLabels{Int,3}
        @test typeof(LabelEnc.NativeLabels([5,2,3])) <: LabelEnc.NativeLabels{Int,3}
        @test typeof(LabelEnc.NativeLabels([:a,:b,:c,:d])) <: LabelEnc.NativeLabels{Symbol,4}
        @test typeof(@inferred(LabelEnc.NativeLabels{Int,3}(1:3))) <: LabelEnc.NativeLabels{Int,3}
        @test typeof(@inferred(LabelEnc.NativeLabels{Int,3}([5,2,3]))) <: LabelEnc.NativeLabels{Int,3}
        @test typeof(@inferred(LabelEnc.NativeLabels([5,2,3],Val{3}))) <: LabelEnc.NativeLabels{Int,3}
        @test typeof(@inferred(LabelEnc.NativeLabels{Symbol,4}([:a,:b,:c,:d]))) <: LabelEnc.NativeLabels{Symbol,4}
        @test typeof(@inferred(LabelEnc.NativeLabels([:a,:b,:c,:d],Val{4}))) <: LabelEnc.NativeLabels{Symbol,4}
        @test typeof(@inferred(LabelEnc.NativeLabels([1,2],Val{2}))) <: MLLabelUtils.BinaryLabelEncoding

        @test typeof(LabelEnc.NativeLabels(oov->0, 0:3)) <: LabelEnc.NativeLabels{Int,4}
        @test typeof(LabelEnc.NativeLabels(oov->:oov, [:oov, :a,:b,:c,:d])) <: LabelEnc.NativeLabels{Symbol,5}
        @test typeof(@inferred(LabelEnc.NativeLabels(oov->1, [1,2],Val{2}))) <: MLLabelUtils.BinaryLabelEncoding

        @test typeof(LabelEnc.NativeLabels(0, 0:3)) <: LabelEnc.NativeLabels{Int,4}
        @test typeof(LabelEnc.NativeLabels(:oov, [:oov, :a,:b,:c,:d])) <: LabelEnc.NativeLabels{Symbol,5}
        @test typeof(@inferred(LabelEnc.NativeLabels(1, [1,2],Val{2}))) <: MLLabelUtils.BinaryLabelEncoding
    end
end

@testset "interface" begin
    @testset "FuzzyBinary" begin
        lm = LabelEnc.FuzzyBinary()
        @test labeltype(lm) <: Any
        @test_throws ArgumentError isposlabel(:yes, lm)
        @test_throws ArgumentError isposlabel("yes", lm)
        @test_throws ArgumentError isneglabel(:no, lm)
        @test_throws ArgumentError isneglabel("no", lm)
        @test @inferred(isposlabel(true, lm))  === true
        @test @inferred(isposlabel(false, lm)) === false
        @test @inferred(isposlabel(1, lm)) === true
        @test @inferred(isposlabel(0, lm)) === false
        @test @inferred(isposlabel(0.1, lm)) === true
        @test @inferred(isposlabel(0.5, lm)) === true
        @test @inferred(isposlabel(-1, lm))  === false
        @test @inferred(isneglabel(true, lm))  === false
        @test @inferred(isneglabel(false, lm)) === true
        @test @inferred(isneglabel(1, lm)) === false
        @test @inferred(isneglabel(0, lm)) === true
        @test @inferred(isneglabel(0.1, lm)) === false
        @test @inferred(isneglabel(0.5, lm)) === false
        @test @inferred(isneglabel(-1, lm))  === true
        @test @inferred(nlabel(lm)) === 2
        @test_throws MethodError poslabel(lm)
        @test_throws MethodError neglabel(lm)
        @test_throws MethodError label(lm)
    end

    @testset "TrueFalse" begin
        @test typeof(@inferred(labelenc([true,  false, true])))  <: LabelEnc.TrueFalse
        @test typeof(@inferred(labelenc([true,  true,  true])))  <: LabelEnc.TrueFalse
        @test typeof(@inferred(labelenc([false, false, false]))) <: LabelEnc.TrueFalse
        lm = LabelEnc.TrueFalse()
        @test labeltype(lm) <: Bool
        @test_throws MethodError isposlabel(1, lm)
        @test_throws MethodError isposlabel(1., lm)
        @test_throws MethodError isposlabel(:yes, lm)
        @test_throws MethodError isneglabel(0, lm)
        @test_throws MethodError isneglabel(0., lm)
        @test_throws MethodError isneglabel(:no, lm)
        @test @inferred(isposlabel(true, lm))  === true
        @test @inferred(isposlabel(false, lm)) === false
        @test @inferred(isneglabel(true, lm))  === false
        @test @inferred(isneglabel(false, lm)) === true
        @test @inferred(nlabel(lm))  === 2
        @test @inferred(poslabel(lm)) === true
        @test @inferred(neglabel(lm)) === false
        @test @inferred(label(lm)) == [true, false]
        @test eltype(@inferred(label(lm))) <: Bool
    end

    @testset "ZeroOne" begin
        for T in (Int, UInt8, Float32, Float64)
            for targets in (T[0,0,0], T[1,0,1], T[0,1,0])
                @testset "$targets" begin
                    lm = labelenc(targets)
                    @test labeltype(lm) <: T
                    @test typeof(lm) <: LabelEnc.ZeroOne{T,Float64}
                    @test lm.cutoff === 0.5
                    @test_throws MethodError isposlabel(:yes, lm)
                    @test_throws MethodError isneglabel(:neg, lm)
                    @test @inferred(isposlabel(true, lm))  === true
                    @test @inferred(isposlabel(false, lm)) === false
                    @test @inferred(isneglabel(true, lm))  === false
                    @test @inferred(isneglabel(false, lm)) === true
                    @test @inferred(isposlabel(one(T), lm))  === true
                    @test @inferred(isposlabel(zero(T), lm)) === false
                    @test @inferred(isneglabel(one(T), lm))  === false
                    @test @inferred(isneglabel(zero(T), lm)) === true
                    @test @inferred(nlabel(lm))  === 2
                    @test @inferred(poslabel(lm)) === T(1)
                    @test @inferred(neglabel(lm)) === T(0)
                    @test @inferred(label(lm)) == T[1, 0]
                    @test eltype(@inferred(label(lm))) <: T
                end
            end
        end
    end

    @testset "MarginBased" begin
        for T in (Int, Int8, Float32, Float64)
            for targets in (T[-1,-1,-1], T[1,-1,1], T[-1,1,-1])
                @testset "$targets" begin
                    lm = labelenc(targets)
                    @test labeltype(lm) <: T
                    @test typeof(lm) <: LabelEnc.MarginBased{T}
                    @test_throws MethodError isposlabel(:yes, lm)
                    @test_throws MethodError isneglabel(:neg, lm)
                    @test_throws MethodError isposlabel(true, lm)
                    @test_throws MethodError isneglabel(false, lm)
                    @test @inferred(isposlabel(zero(T), lm)) === true
                    @test @inferred(isposlabel(one(T), lm))  === true
                    @test @inferred(isposlabel(-one(T), lm)) === false
                    @test @inferred(isneglabel(one(T), lm))  === false
                    @test @inferred(isneglabel(-one(T), lm)) === true
                    @test @inferred(nlabel(lm))  === 2
                    @test @inferred(poslabel(lm)) === T(1)
                    @test @inferred(neglabel(lm)) === T(-1)
                    @test @inferred(label(lm)) == T[1, -1]
                    @test eltype(@inferred(label(lm))) <: T
                end
            end
        end
    end

    @testset "OneVsRest" begin
        @test_throws MethodError label(LabelEnc.OneVsRest(rand(2,2)))
        @test_throws MethodError label(LabelEnc.OneVsRest(rand(2)))
        for (pos, neg) in ((:pos, :not_pos),
                           ("pos", "not_pos"),
                           (true, false),
                           (false, true),
                           (0f0, 1f0),
                           (0x0, 0x01),
                           (2., 0.),
                           (2, 0),
                           (0, 1))
            @testset "pos=$pos, neg=$neg" begin
                lm = @inferred LabelEnc.OneVsRest(pos)
                @test labeltype(lm) <: typeof(pos)
                @test @inferred(label(lm)) == [pos, neg]
                @test @inferred(poslabel(lm)) === pos
                if typeof(neg) <: String
                    @test @inferred(neglabel(lm)) == neg
                else
                    @test @inferred(neglabel(lm)) === neg
                end
                @test @inferred(isposlabel(pos, lm)) === true
                @test @inferred(isposlabel(neg, lm)) === false
                @test @inferred(isneglabel(pos, lm)) === false
                @test @inferred(isneglabel(neg, lm)) === true
            end
        end
    end

    @testset "Indices" begin
        for T in (Int, UInt8, Int8, Float32, Float64)
            for targets in (T[1,2,1], T[2,1,2])
                @testset "binary $targets" begin
                    lm = labelenc(targets)
                    @test labeltype(lm) <: T
                    @test typeof(lm) <: LabelEnc.Indices{T,2}
                    @test_throws MethodError isposlabel(:yes, lm)
                    @test_throws MethodError isneglabel(:neg, lm)
                    @test_throws MethodError isposlabel(true, lm)
                    @test_throws MethodError isneglabel(false, lm)
                    @test @inferred(isposlabel(one(T), lm))  === true
                    @test @inferred(isposlabel(2one(T), lm)) === false
                    @test @inferred(isneglabel(one(T), lm))  === false
                    @test @inferred(isneglabel(2one(T), lm)) === true
                    @test @inferred(nlabel(lm))  === 2
                    @test @inferred(poslabel(lm)) === T(1)
                    @test @inferred(neglabel(lm)) === T(2)
                    @test @inferred(label(lm)) == T[1, 2]
                    @test eltype(@inferred(label(lm))) <: T
                end
            end
            for targets in (T[3,1,2,1], T[2,1,4,2])
                @testset "multiclass $targets" begin
                    lm = labelenc(targets)
                    @test labeltype(lm) <: T
                    @test typeof(lm) <: LabelEnc.Indices{T,Int(maximum(targets))}
                    @test_throws MethodError isposlabel(:yes, lm)
                    @test_throws MethodError isneglabel(:neg, lm)
                    @test_throws MethodError isposlabel(true, lm)
                    @test_throws MethodError isneglabel(false, lm)
                    @test_throws MethodError isposlabel(T(1),lm)
                    @test_throws MethodError isneglabel(T(2),lm)
                    @test_throws MethodError poslabel(lm)
                    @test_throws MethodError neglabel(lm)
                    @test @inferred(nlabel(lm)) === Int(maximum(targets))
                    @test @inferred(label(lm)) == Vector{T}(collect(1:maximum(targets)))
                    @test eltype(@inferred(label(lm))) <: T
                end
            end
        end
    end

    @testset "OneOfK" begin
        for T in (Int, UInt8, Int8, Float32, Float64)
            @testset "binary T = $T" begin
                lm = LabelEnc.OneOfK(T,2)
                @test labeltype(lm) <: T
                @test typeof(lm) <: LabelEnc.OneOfK{T,2}
                @test_throws MethodError isposlabel(:yes, lm)
                @test_throws MethodError isneglabel(:neg, lm)
                @test_throws MethodError isposlabel(true, lm)
                @test_throws MethodError isneglabel(false, lm)
                @test @inferred(isposlabel(1, lm)) === true
                @test @inferred(isposlabel(2, lm)) === false
                @test @inferred(isneglabel(1, lm)) === false
                @test @inferred(isneglabel(2, lm)) === true
                @test @inferred(nlabel(lm))  === 2
                @test @inferred(poslabel(lm)) == [1, 0]
                @test @inferred(neglabel(lm)) == [0, 1]
                @test @inferred(label(lm)) == [1, 2]
                @test eltype(@inferred(label(lm))) <: Int
                @test @inferred(isposlabel([.6,.4], lm)) === true
                @test @inferred(isposlabel([.3,.7], lm)) === false
                @test @inferred(isneglabel([.9,.1], lm)) === false
                @test @inferred(isneglabel([2,4], lm)) === true
                for R in (Bool, Int, Float64)
                    @test @inferred(isposlabel(R[1,0], lm)) === true
                    @test @inferred(isposlabel(R[0,1], lm)) === false
                    @test @inferred(isneglabel(R[1,0], lm)) === false
                    @test @inferred(isneglabel(R[0,1], lm)) === true
                end
            end
            @testset "multiclass T = $T" begin
                @test ind2label.([4,1], LabelEnc.OneOfK(5)) == [[0, 0, 0, 1, 0],[1, 0, 0, 0 ,0]]
                @test @inferred(ind2label(4, LabelEnc.OneOfK(5))) == [0, 0, 0, 1, 0]
                @test @inferred(label2ind([0,0,0,1,0], LabelEnc.OneOfK(5))) === 4
                @test @inferred(label2ind(4., LabelEnc.OneOfK(Float64,5))) === 4
                for K in (3,5)
                    lm = LabelEnc.OneOfK(T,K)
                    @test typeof(lm) <: LabelEnc.OneOfK{T,K}
                    @test_throws MethodError isposlabel(:yes, lm)
                    @test_throws MethodError isneglabel(:neg, lm)
                    @test_throws MethodError isposlabel(true, lm)
                    @test_throws MethodError isneglabel(false, lm)
                    @test_throws MethodError isposlabel(T(1),lm)
                    @test_throws MethodError isneglabel(T(2),lm)
                    @test_throws MethodError poslabel(lm)
                    @test_throws MethodError neglabel(lm)
                    @test @inferred(nlabel(lm)) === K
                    @test @inferred(label(lm)) == collect(1:K)
                    @test eltype(@inferred(label(lm))) <: Int
                end
            end
        end
    end

    @testset "NativeLabels" begin
        @testset "binary" begin
            let targets = split("yes yes no")
                lm = labelenc(targets)
                @test lm == labelenc(split("yes yes no"))
                @test labeltype(lm) <: eltype(targets)
                @test typeof(lm) <: MLLabelUtils.BinaryLabelEncoding
                @test typeof(lm) <: LabelEnc.NativeLabels{eltype(targets),length(unique(targets))}
                @test_throws KeyError label2ind(:yes, lm)
                @test_throws KeyError label2ind(2, lm)
                @test @inferred(label2ind("yes", lm)) === 1
                @test @inferred(label2ind("no", lm)) === 2
                @test @inferred(ind2label(1, lm)) == "yes"
                @test @inferred(ind2label(2, lm)) == "no"
            end
            for T in (Float64,Int,Float32)
                lm = labelenc(T[-2,3])
                @test labeltype(lm) <: T
                @test poslabel(lm) === T(3)
                @test neglabel(lm) === T(-2)
            end
            for targets in ([:yes,:no,:yes], ["yes","yes","no"], 3:-3:0, [3,-2], [1.4,1.3])
                lm = labelenc(targets)
                @test labeltype(lm) <: eltype(targets)
                @test typeof(lm) <: MLLabelUtils.BinaryLabelEncoding
                @test typeof(lm) <: LabelEnc.NativeLabels{eltype(targets),length(unique(targets))}
                @test @inferred(isposlabel(label(lm)[1], lm)) === true
                @test @inferred(isposlabel(label(lm)[2], lm)) === false
                @test @inferred(isposlabel(:nix, lm)) === false
                @test @inferred(isposlabel(1, lm)) === false
                @test @inferred(isposlabel(2, lm)) === false
                @test @inferred(isneglabel(label(lm)[1], lm)) === false
                @test @inferred(isneglabel(label(lm)[2], lm)) === true
                @test @inferred(isneglabel(:nix, lm)) === false
                @test @inferred(isneglabel(1, lm)) === false
                @test @inferred(isneglabel(2, lm)) === false
                @test lm.label == collect(unique(targets))
                @test @inferred(label(lm)) == collect(unique(targets))
                @test eltype(@inferred(label(lm))) <: eltype(targets)
                @test @inferred(nlabel(lm)) === length(unique(targets))

                @test ind2label.(label2ind.(targets, lm), lm) == collect(targets)
                @test ind2label.(Int16.(label2ind.(targets, lm)), lm) == collect(targets)
            end
        end
        @testset "multiclass"  begin
            for targets in ([:yes,:maybe,:no,:yes], ["yes","noidea","yes","no"], [1.2,3,2], rand(50))
                lm = labelenc(targets)
                @test typeof(lm) <: LabelEnc.NativeLabels{eltype(targets),length(unique(targets))}
                @test_throws MethodError isposlabel(:yes, lm)
                @test_throws MethodError isneglabel(:neg, lm)
                @test_throws MethodError isposlabel(true, lm)
                @test_throws MethodError isneglabel(false, lm)
                @test_throws MethodError isposlabel(1,lm)
                @test_throws MethodError isneglabel(2,lm)
                @test_throws MethodError poslabel(lm)
                @test_throws MethodError neglabel(lm)
                @test lm.label == unique(targets)
                @test @inferred(label(lm)) == unique(targets)
                @test eltype(@inferred(label(lm))) <: eltype(targets)
                @test @inferred(nlabel(lm)) === length(unique(targets))

                @test ind2label.(label2ind.(targets, lm), lm) == targets
                @test ind2label.(Int16.(label2ind.(targets, lm)), lm) == targets
            end
        end

        @testset "fallback" begin
            @testset "binary" begin
                @testset "neg" begin
                    lm = LabelEnc.NativeLabels(:no, [:yes, :no])
                    @test @inferred(isposlabel(:red, lm)) === false
                    @test @inferred(isneglabel(:blue, lm)) === true

                    @test ind2label.(label2ind.([:yes, :no, :fish, :yes], lm), lm) == ind2label.(label2ind.([:yes, :no, :no, :yes], lm), lm)
                end
                @testset "pos" begin
                    lm = LabelEnc.NativeLabels(oov->:yes, [:yes, :no])
                    @test @inferred(isposlabel(:red, lm)) === true
                    @test @inferred(isneglabel(:blue, lm)) === false

                    @test ind2label.(label2ind.([:yes, :no, :fish, :yes], lm), lm) == ind2label.(label2ind.([:yes, :no, :yes, :yes], lm), lm)
                end
            end
            @testset "multiclass" begin
                lm = LabelEnc.NativeLabels(["yes","no","maybe"]) do oov_lbl
                    new_lbl = lowercase(oov_lbl)
                    new_lbl == oov_lbl && throw(KeyError(oov_lbl)) # no change so still won't match
                    new_lbl
                end

                @test_throws KeyError label2ind("red", lm)
                @test_throws KeyError label2ind("BLUE", lm)
                @test  label2ind("Maybe", lm) == label2ind("maybe", lm)

                @test ind2label.(label2ind.(["yes", "maybe", "NO", "no"], lm), lm) == ind2label.(label2ind.(["yes", "maybe", "no", "no"], lm), lm)
            end
        end
    end
end

@testset "islabelenc" begin
    for (lm, x, res) in (
            (LabelEnc.TrueFalse,[true,false,true,false,false,true],true),
            (LabelEnc.TrueFalse(),[true,false,true,false,false,true],true),
            (LabelEnc.TrueFalse(),Int32[1,0,1,0,0,1],false),
            (LabelEnc.ZeroOne,Int32[1,0,1,0,0,1],true),
            (LabelEnc.ZeroOne,Int64[1,0,1,0,0,1],true),
            (LabelEnc.ZeroOne{Int64},Int64[1,0,1,0,0,1],true),
            (LabelEnc.ZeroOne{Int32},Int64[1,0,1,0,0,1],false),
            (LabelEnc.ZeroOne,Float32[1,0,1,0,0,1],true),
            (LabelEnc.ZeroOne(),Float32[1,0,1,0,0,1],false),
            (LabelEnc.ZeroOne(),Float64[1,0,1,0,0,1],true),
            (LabelEnc.ZeroOne,[true,false,true,false,false,true],true),
            (LabelEnc.ZeroOne,[1,-1,1,-1,-1,1],false),
            (LabelEnc.ZeroOne,[1,0,1,2,0,1],false),
            (LabelEnc.MarginBased,Int32[1,-1,1,-1,-1,1],true),
            (LabelEnc.MarginBased,Int64[1,-1,1,-1,-1,1],true),
            (LabelEnc.MarginBased,Float32[1,-1,1,-1,-1,1],true),
            (LabelEnc.MarginBased{Float32},Float32[1,-1,1,-1,-1,1],true),
            (LabelEnc.MarginBased{Float64},Float32[1,-1,1,-1,-1,1],false),
            (LabelEnc.MarginBased(),Float32[1,-1,1,-1,-1,1],false),
            (LabelEnc.MarginBased(Float32),Float32[1,-1,1,-1,-1,1],true),
            (LabelEnc.MarginBased(),Float64[1,-1,1,-1,-1,1],true),
            (LabelEnc.MarginBased,[1,-1,1,0,-1,1],false),
            (LabelEnc.MarginBased,[1,0,1,0,0,1],false),
            (LabelEnc.MarginBased,[true,false,true,false,false,true],false),
            (LabelEnc.Indices(2),Int[1,2,1,2,2,1],true),
            (LabelEnc.Indices(2),Int[1,2,1,3,2,1],false),
            (LabelEnc.Indices(3),Int[1,2,1,3,2,1],true),
            (LabelEnc.Indices(2),Int[1,1,1,0,1,1],false),
            (LabelEnc.Indices,Int[1,1,1,0,1,1],false),
            (LabelEnc.Indices{Int},Float64[1,2,1,3,2,1],false),
            (LabelEnc.Indices{Float64},Float64[1,2,1,3,2,1],true),
            (LabelEnc.Indices,Float64[1,2,1,3,2,1],true),
            (LabelEnc.Indices,Float64[1,2,1,2,2,1],true),
            (LabelEnc.Indices(2),Float64[1,2,1,2,2,1],false),
            (LabelEnc.OneVsRest(:yes),[:yes,:no,:yes,:maybe,:no,:yes],true),
            (LabelEnc.OneVsRest(:ye),[:yes,:no,:yes,:maybe,:no,:yes],false),
            (LabelEnc.OneVsRest(:ye),[1,2,1,2,2,1],false),
            (LabelEnc.NativeLabels([:a,:b]),[:a,:b,:a,:b,:b,:a],true),
            (LabelEnc.NativeLabels([:a,:b]),[:a,:c,:a,:b,:b,:a],false),
            (LabelEnc.OneOfK,[1 0 1 0 0 1; 0 1 0 1 1 1],false),
            (LabelEnc.OneOfK{Float64},[1 0 1 0 0 1; 0 1 0 1 1 0],false),
            (LabelEnc.OneOfK(Int,3),[1 0 1 0 0 1; 0 1 0 1 1 0],false),
            (LabelEnc.OneOfK,[1 0 1 0 0 .1; 0 1 0 1 1 0],false),
        )
        # check is the format is correctly recognized
        @testset "$lm $x -> $res" begin
            @test @inferred(islabelenc(x, lm)) == res
        end
    end
end

@testset "islabelenc OneOfK" begin
    x2 = [1 0 1 0 0 1; 0 1 0 1 1 0]
    x3 = [1 0 0 0 0 1; 0 1 0 1 0 0; 0 0 1 0 1 0]
    for (dst_lm, dst_x) in (
            (LabelEnc.OneOfK,Array{Int32}(x3)),
            (LabelEnc.OneOfK{Float32},Array{Float32}(x3)),
            (LabelEnc.OneOfK(Bool,3),Array{Bool}(x3)),
            (LabelEnc.OneOfK,Array{Bool}(x2)),
            (LabelEnc.OneOfK{Float32},Array{Float32}(x2)),
            (LabelEnc.OneOfK(UInt8,2),Array{UInt8}(x2)),
        )
        # check is the format is correctly recognized
        @test @inferred(islabelenc(dst_x, dst_lm)) == true
        @test @inferred(islabelenc(dst_x', dst_lm)) == false
        @test @inferred(islabelenc(dst_x, dst_lm, obsdim = 2)) == true
        @test @inferred(islabelenc(dst_x', dst_lm, obsdim = 1)) == true
        @test @inferred(islabelenc(dst_x, dst_lm, ObsDim.Last())) == true
        @test @inferred(islabelenc(dst_x', dst_lm, ObsDim.First())) == true
        @test @inferred(islabelenc(dst_x', dst_lm, obsdim = 2)) == false
        @test @inferred(islabelenc(dst_x, dst_lm, obsdim = 1)) == false
        @test @inferred(islabelenc(dst_x', dst_lm, ObsDim.Last())) == false
        @test @inferred(islabelenc(dst_x, dst_lm, ObsDim.First())) == false
    end
end


text:
import Base: length, setindex!

export
    BitAssignment,
    vars,
    names,
    length,
    setindex!,
    isfilled

struct BitAssignment
    vars::Vector{AbstractVariable}
    assigned_zeros::Vector{Vector{Bool}} # which are known to be zero
    assigned_ones::Vector{Vector{Bool}}  # which are known to be one

    function BitAssignment(vars::Vector{<:AbstractVariable})
        # vars has different names
        @assert length(unique(name.(vars))) == length(vars)

        vars = sort(collect(unique(vars)))
        lengths = length.(vars)

        new(AbstractVariable[vars...], [fill(false, l) for l=lengths], [fill(false, l) for l=lengths])
    end
end

BitAssignment(v::AbstractVariable) = BitAssignment([v])
vars(a::BitAssignment) = a.vars
names(a::BitAssignment) = name.(vars(a))
length(a::BitAssignment) = sum(length.(vars(a)))

# syntax
# x = BitVar("x")
# a = BitAssignment(x)
# a["x"] = 1
# a["x"] = nothing (clear variable, always possible)
# a["xx", 1, 2] = nothing (if xx is matrix variable)
function Base.setindex!(a::BitAssignment, val::Union{Integer,Nothing}, s::String, I::Vararg)
    @assert val == 0 || val == 1 || val == nothing
    ind = findfirst(x -> name(x) == s, vars(a))
    @assert ind != nothing
    var = vars(a)[ind]
    if typeof(var) <: BitVar
        @assert length(I) == 0 "Too many arguments" # we forbid extra elements
        if val == nothing
            a.assigned_zeros[ind][1] = false
            a.assigned_ones[ind][1] = false
        elseif val == 0
            a.assigned_zeros[ind][1] = true
            a.assigned_ones[ind][1] = false
        else
            a.assigned_ones[ind][1] = true
            a.assigned_zeros[ind][1] = false
        end
    elseif typeof(var) <: BitVarArray
        @assert false "TBD"
    end
    a
end

function isfilled(a::BitAssignment)
    for (v1, v2) in zip(a.assigned_zeros, a.assigned_ones)
        if !all(v1 .| v2)
            return false
        end
    end
    false
end

ext: jl


text:
using POMDPModels
using Test

# test ranked_actions for vanilla
solver = MCTSSolver(n_iterations=n_iter, depth=depth, exploration_constant=ec, enable_tree_vis=true)
mdp = LegacyGridWorld()

policy = solve(solver, mdp)

state = GridWorldState(1,1)

a = action(policy, state)

ranked = MCTS.ranked_actions(policy, state)

@test first(ranked[1]) == a

# test ranked_actions for dpw
solver = DPWSolver(n_iterations=n_iter, depth=depth, exploration_constant=ec)
mdp = LegacyGridWorld()

policy = solve(solver, mdp)

state = GridWorldState(1,1)

a = action(policy, state)

ranked = MCTS.ranked_actions(policy, state)

@test first(ranked[1]) == a


text:
# ## Data

using CSV
using DataFrames
using StatsFuns
using Turing

import TuringModels

file_path = joinpath(TuringModels.project_root, "data", "UCBadmit.csv")
df = CSV.read(file_path, DataFrame; delim=';')

# ## Model

@model m_pois(admit, reject) = begin
   α₁ ~ Normal(0,100)
   α₂ ~ Normal(0,100)

   for i ∈ 1:length(admit)
       λₐ = exp(α₁)
       λᵣ = exp(α₂)
       admit[i] ~ Poisson(λₐ)
       reject[i] ~ Poisson(λᵣ)
   end
end;

# ## Output

chains = sample(m_pois(df.admit, df.reject), NUTS(0.65), 1000)

# \defaultoutput{}

# ## Original output

m_10_yyt_result = "
    mean   sd 5.5% 94.5% n_eff Rhat
 a1 4.99 0.02 4.95  5.02  2201    1
 a2 5.44 0.02 5.41  5.47  2468    1
";


text:
"""
    PrimitiveIO{T} <: Construct{T}

Construct based on primitive read/write.
"""
struct PrimitiveIO{T} <: Construct{T} end

# primitive numbers
for type in (Bool, Char, UInt8, UInt16, UInt32, UInt64, UInt128, Int8, Int16, Int32, Int64, Int128, Float16, Float32, Float64)
    @eval Construct(::Type{$type}) = PrimitiveIO{$type}()
end

deserialize(::PrimitiveIO{T}, s::IO; contextkw...) where {T} = read(s, T)
serialize(::PrimitiveIO{T}, s::IO, c::T; contextkw...) where {T} = write(s ,c)
estimatesize(::PrimitiveIO{T}; contextkw...) where {T} = sizeof(T)
estimatesize(::PrimitiveIO{Char}; contextkw...) = Interval{UInt}(1, 4)


text:
addprocs(2)
using Images, Base.Test, Color
# Normally "using Images" would suffice, but since Images has
# already been loaded by the time this file runs, that yields
# a no-op. So we have to force the workers to load it manually.
# See https://github.com/JuliaLang/julia/issues/3674
@sync for p in workers()
    @spawnat p eval(Expr(:using, :Images))   # FIXME: on 0.4 you can say :(using Images) directly
end

# Issue #287
@everywhere function test287(img)
    return 0;
end
Imgs = Array(Images.Image{RGB{Float64}}, 2);
Imgs[1] = convert(Images.Image{RGB}, rand(100, 100, 3));
Imgs[2] = convert(Images.Image{RGB}, rand(100, 100, 3));

let Imgs = Imgs;
    ret = pmap(i -> test287(Imgs[i]), 1:2);
    @test ret == Any[0,0]
end


text:
######################################################################
# greedyp2.jl
#
# like greedyp, but uses cheap entropy
######################################################################
export GreedyP2
mutable struct GreedyP2 <: Policy
    actions::Vector{Action}
    lambda::Float64
    d::Float64
end
function GreedyP2(max_step::Real, n::Int, headings=0; stay=true)
    GreedyP2(make_action_list(max_step, n, headings, stay=stay), 10.0, 15.0)
end
function GreedyP2(x::Vehicle, n::Int, headings=0; stay=true)
    GreedyP2(make_action_list(x.max_step, n, headings, stay=stay), 10.0,15.0)
end

# loop over all actions.
# The one with smallest expected entropy is best
# We know this depends on sensor
function action(m::SearchDomain, x::Vehicle, o, f::AbstractFilter, p::GreedyP2)
    best_score = -Inf
    best_a = (0.0, 0.0, 0.0)

    # propagate target dynamics forward
    f2 = deepcopy(f)
    predict!(f2)

    db = zeros(50,50)

    for a in p.actions
        # find out where a will take you
        xp = new_pose(m, x, a)

        # TODO: this only works for FOV
        score = 0.0
        for o = 0:1
            f2 = deepcopy(f)
            update!(f2, xp, o)
            #ce = cheap_entropy2(f2._b, db, m.length)
            ce = cheap_entropy2(f2, m.length, 50)

            penalty = p.lambda * nmac_penalty(f2, xp, p.d)

            score -= p_obs(f, xp, o) * (ce + penalty)
        end

        if score > best_score
            best_score = score
            best_a = a
        end
    end

    #println("best_mi = ", best_mi, ", best_p = ", best_p)
    #c = covariance(f2)
    #ev = eigvals(c)
    #e1 = ev[1]
    #e2 = ev[2]
    #println("c = ", covariance(f))
    #println("e1 = ", e1, ", e2 = ", e2)
    #println("ce = ", cheap_entropy(f, 200.0, 40))
    return best_a
end


text:
function suffix(T)
    if T == Bool
        return "BOOL"
    elseif T == Int8
        return "INT8"
    elseif T == UInt8
        return "UINT8"
    elseif T == Int16
        return "INT16"
    elseif T == UInt16
        return "UINT16"
    elseif T == Int32
        return "INT32"
    elseif T == UInt32
        return "UINT32"
    elseif T == Int64
        return "INT64"
    elseif T == UInt64
        return "UINT64"
    elseif  T == Float32
        return "FP32"
    elseif T == Float64
        return "FP64"
    elseif T == ComplexF32
        return "FC32"
    elseif T == ComplexF64
        return "FC64"
    else
        error("Not a valid GrB data type")
    end
end

function towrappertype(T)
    if T == Bool
        return :Bool
    elseif T == Int8
        return :Int8
    elseif T == UInt8
        return :UInt8
    elseif T == Int16
        return :Int16
    elseif T == UInt16
        return :UInt16
    elseif T == Int32
        return :Int32
    elseif T == UInt32
        return :UInt32
    elseif T == Int64
        return :Int64
    elseif T == UInt64
        return :UInt64
    elseif  T == Float32
        return :Cfloat
    elseif T == Float64
        return :Cdouble
    elseif T == ComplexF32
        return :GxB_FC32_t
    elseif T == ComplexF64
        return :GxB_FC64_t
    else
        error("Not a valid GrB data type")
    end
end

grb_ptr(x::Abstract_GrB_Struct) = x.p

function toGrB_Type(T)
    if T == Bool
        return BOOL
    elseif T == Int8
        return INT8
    elseif T == UInt8
        return UINT8
    elseif T == Int16
        return INT16
    elseif T == UInt16
        return UINT16
    elseif T == Int32
        return INT32
    elseif T == UInt32
        return UINT32
    elseif T == Int64
        return INT64
    elseif T == UInt64
        return UINT64
    elseif  T == Float32
        return FP32
    elseif T == Float64
        return FP64
    elseif  T == ComplexF32
        return FC32
    elseif T == ComplexF64
        return FC64
    else
        error("Not a valid GrB data type")
    end
end

function load_global(str, type = Cvoid)
    x =
    try
        dlsym(SSGraphBLAS_jll.libgraphblas_handle, str)
    catch e
        print("Symbol not available: " * str * "\n $e")
        return C_NULL
    end
    return unsafe_load(cglobal(x, Ptr{type}))
end

function splitconstant(str)
    return String.(split(str, "_"))
end

isGxB(name) = name[1:3] == "GxB"

# This is a bad idea. If someone sees this remind me to remove it or document it.
function arrrrgh()
    eval(:(Base.show(io::IO, a::Unsigned) = print(io, Int(a))))
end

#This requires a lot of cleanup. It's clunky, inelegant, and likely error prone.
#Don't yet know enough about macros/MacroTools to make this nice.
#First order of business would be reducing the repetition.
#Second, it would be quite nice to add transpose options here, rather than manually
#
#To do this processing needs to be moved outside the quotes.
#Can the capture statement be shortened?
macro kwargs(ex)
    @capture(ex, (f_(xs__; xs2__) = body_) | (f_(xs__; xs2__) where {T_} = body_) |
    (function f_(xs__; xs2__) body_ end) | (function f_(xs__; xs2__) where {T_} body_ end) |
    (f_(xs__) = body_) | (f_(xs__) where {T_} = body_) |
    (function f_(xs__) body_ end) | (function f_(xs__) where {T_} body_ end))
    if T === nothing
        if xs2 !== nothing
            result = quote
                function $(esc(f))($(map(esc, xs)...);
                    $(map(esc, xs2)...), mask = C_NULL, accum = C_NULL, desc = Descriptors.NULL)
                    $(esc(body))
                end
            end
        else
            result = quote
                function $(esc(f))($(map(esc, xs)...);
                    mask = C_NULL, accum = C_NULL, desc = Descriptors.NULL)
                    $(esc(body))
                end
            end
        end
    else
        if xs2 !== nothing
            result = quote
                function $(esc(f))($(map(esc, xs)...); $(map(esc, xs2)...);
                    mask = C_NULL, accum = C_NULL, desc = Descriptors.NULL) where {$(esc(T))}
                    $(esc(body))
                end
            end
        else
            result = quote
                function $(esc(f))($(map(esc, xs)...);
                    mask = C_NULL, accum = C_NULL, desc = Descriptors.NULL) where {$(esc(T))}
                    $(esc(body))
                end
            end
        end
    end
    result.args[2].args[2].args[1] = __source__
    result.args[2].args[2].args[2] = __source__
    #These are rather naughty, and could lead to bugs.
    # My goal is to keep @which and error line number happy.
    #TODO: Have a wizard look at this.
    return result
end


text:
module Dorayaki

include("config.jl")
include("func.jl")
include("var.jl")
include("gradient.jl")
include("layers.jl")
include("utils.jl")

include("functions/arithmetic.jl")
include("functions/activation.jl")
include("functions/basicmath.jl")
include("functions/loss.jl")
include("functions/tensor.jl")
include("functions/reduction.jl")

end


text:
using RCall

x = 1:10
@rput x
@rget x
@test isa(x,Vector{Int})
@test all(x .== 1:10)

y = "foo"
@rput x y
@rget x y::Array{String}
@test isa(y,Vector{String})
@test y[1] == "foo"

@test RCall.render("x = 1")[1] == "x = 1"

@test RCall.render("x = \$y")[1] == "x = `#JL`\$`y`"

@test RCall.render("x = \$(rand(1))")[2]["(rand(1))"] == :(rand(1))

@test_throws RCall.RParseError RCall.render("x = ]")

@test_throws RCall.RParseIncomplete RCall.render("x = \$(begin")

@test_throws Meta.ParseError RCall.render("x = \$(begin)")

@test_throws RCall.RParseIncomplete RCall.render("x = ")

@test RCall.render("x = 1\ny = \$a")[1] == "x = 1\ny = `#JL`\$`a`"

@test rcopy(R"sum($[7,1,3])") == sum([7,1,3])

@test_throws Exception R"""a = $(error("foo"))"""

if rcopy(reval("isTRUE(l10n_info()\$`UTF-8`)"))

@test RCall.render("x = 'β'")[1] == "x = 'β'"

@test RCall.render("x = \$β")[2]["β"] == :β

@test RCall.render("x = 1\nβ = \$a")[1] == "x = 1\nβ = `#JL`\$`a`"

else

@test_throws RCall.RParseError RCall.render("x = \$β")

end


text:
if !isdefined(:LOG_OUTPUT)
    global LOG_OUTPUT=STDOUT
end

function open_logfile(fn::String)
    global LOG_OUTPUT=open(fn,"w")
end

function close_logfile()
    close(LOG_OUTPUT)
end

function lprintln(s::String)
    write(LOG_OUTPUT, "$s\n")
end

function flush_log()
    flush(LOG_OUTPUT)
end


text:
export bissect_Cub
function bissect_Cub(h :: AbstractNLPModel;
                    t1 :: Float64 = h.meta.x0[1],
                    t2 :: Float64 = 100.0,
                    tol :: Float64 = 1e-7,
                    maxiter :: Int = 50,
                    verbose :: Bool = false)

    (length(h.meta.x0) > 1) && warn("Not a 1-D problem ")
  (tₐ, tᵦ) = trouve_intervalle(h, t1, 2.5)

  γ = 0.8; t = tᵦ; tₚ = tₐ; tqnp = tₐ
  hₖ = 0; hkm1 = 0; gkm1 = 0; hₚ = 0
  iter = 0

  hₖ = obj(h, [t])[1]; gₖ = grad(h, [t])[1]
  hkm1 = obj(h, [tqnp])[1]; gkm1 = grad(h, [tqnp])[1]

  verbose &&
    @printf(" iter        tₚ        t         dN         ")
  verbose &&
    @printf("gₖ          gplus        \n")
  verbose &&
    @printf(" %7.2e %7.2e %7.2e  %7.2e  %7.2e  %7.2e\n",
             iter, tₚ, t, 0.0, gₖ,  0.0)

  while ((abs(gₖ) > tol) && (iter < maxiter)) || (iter == 0)
    s = t - tqnp; y = gₖ - gkm1; α = -s
    z = gₖ + gkm1 + 3 * (hₖ - hkm1) / α
    discr = z^2 - gₖ * gkm1; denom = gₖ + gkm1 + 2 * z
    if (discr > 0.0) && (abs(denom) > eps(Float64))
      #si on peut on utilise l'interpolation cubique
      w = sqrt(discr)
      dN = -s * (gₖ + z + sign(α) * w) / (denom)
    else #on se rabat sur une étape de sécante
      dN = -gₖ * s / y
    end

    if ((tₚ - t) * dN > 0.0) & (dN / (tₚ - t) < γ)
      tplus = t + dN
      hplus = obj(h, [tplus])[1]
      gplus = grad(h, [tplus])[1]
      verbose && println("N")
    else
      tplus = (t + tₚ) / 2
      hplus = obj(h, [tplus])[1]
      gplus = grad(h, [tplus])[1]
      verbose && println("B")
    end

    if t > tₚ
      if gplus < 0.0
        tₚ = t; tqnp = t; t = tplus
      else
        tqnp = t; t = tplus
      end
    else
      if gplus > 0.0
        tₚ = t; tqnp = t; t = tplus
      else
        tqnp = t; t = tplus
      end
    end

    #mise à jour des valeurs
    hkm1 = hₖ; gkm1 = gₖ; hₖ = hplus; gₖ = gplus
    iter = iter + 1
    verbose &&
        @printf(" %7.2e %7.2e %7.2e  %7.2e  %7.2e  %7.2e\n",
                iter, tₚ, t, dN, gₖ, gplus)
  end

  topt = t
  gopt = grad(h, [topt])[1]
  status = :NotSolved
  (abs(gopt) < tol) && (status = :Optimal)
  (iter >= maxiter) && (status = :Tired)
  tired = iter > maxiter
  optimal = abs(gopt) < tol
  return (topt, obj(h, [topt])[1], norm(gopt, Inf), iter, optimal, tired, status, h.counters.neval_obj, h.counters.neval_grad, h.counters.neval_hess)

end # function


text:
macro c(ret_type, func, arg_types, lib)
  local args_in = Any[ symbol(string('a',x)) for x in 1:length(arg_types.args) ]
  quote
    $(esc(func))($(args_in...)) = ccall( ($(string(func)), $(Expr(:quote, lib)) ), $ret_type, $arg_types, $(args_in...) )
  end
end

macro ctypedef(fake_t,real_t)
  quote
    typealias $fake_t $real_t
  end
end

type crypto_generichash_blake2b_state
  h::Void
  t::Void
  f::Void
  buf::Void
  buflen::size_t
  last_node::uint8_t
end
@ctypedef crypto_generichash_state crypto_generichash_blake2b_state
type crypto_onetimeauth_poly1305_implementation
  implementation_name::Ptr{Void}
  onetimeauth::Ptr{Void}
  onetimeauth_verify::Ptr{Void}
end
type randombytes_implementation
  implementation_name::Ptr{Void}
  random::Ptr{Void}
  stir::Ptr{Void}
  uniform::Ptr{Void}
  buf::Ptr{Void}
  close::Ptr{Void}
end


text:
module LibOSXNative

#import Base: error, size
using Images, Color, Images.ColorTypes, FixedPointNumbers, Compat

export imread

imread(io::IOStream) = imread(readbytes(io))

function imread(b::Array{Uint8,1})
  data = CFDataCreate(b)
  imgsrc = CGImageSourceCreateWithData(data)
  CFRelease(data)
  read_and_release_imgsrc(imgsrc)
end

function imread(filename)
    myURL = CFURLCreateWithFileSystemPath(abspath(filename))
    imgsrc = CGImageSourceCreateWithURL(myURL)
    CFRelease(myURL)
    read_and_release_imgsrc(imgsrc)
end

## core, internal function
function read_and_release_imgsrc(imgsrc)
    imgsrc == C_NULL && return nothing

    # Get image information
    imframes = convert(Int,CGImageSourceGetCount(imgsrc))
    if imframes == 0
        # Bail out to ImageMagick
        warn("OSX reader found no frames")
        CFRelease(imgsrc)
        return nothing
    end
    dict = CGImageSourceCopyPropertiesAtIndex(imgsrc, 0)
    imheight = CFNumberGetValue(CFDictionaryGetValue(dict, "PixelHeight"), Int16)
    imwidth = CFNumberGetValue(CFDictionaryGetValue(dict, "PixelWidth"), Int16)
    isindexed = CFBooleanGetValue(CFDictionaryGetValue(dict, "IsIndexed"))
    if isindexed
        # Bail out to ImageMagick
        warn("OSX reader: indexed color images not implemented")
        CFRelease(imgsrc)
        return nothing
    end
    hasalpha = CFBooleanGetValue(CFDictionaryGetValue(dict, "HasAlpha"))

    pixeldepth = CFNumberGetValue(CFDictionaryGetValue(dict, "Depth"), Int16)
    # Colormodel is one of: "RGB", "Gray", "CMYK", "Lab"
    colormodel = CFStringGetCString(CFDictionaryGetValue(dict, "ColorModel"))
    if colormodel == ""
        # Bail out to ImageMagick
        warn("OSX reader found empty colormodel string")
        CFRelease(imgsrc)
        return nothing
    end
    imtype = CFStringGetCString(CGImageSourceGetType(imgsrc))
    alphacode, storagedepth = alpha_and_depth(imgsrc)

    # Get image description string
    imagedescription = ""
    if imtype == "public.tiff"
        tiffdict = CFDictionaryGetValue(dict, "{TIFF}")
        imagedescription = tiffdict != C_NULL ?
            CFStringGetCString(CFDictionaryGetValue(tiffdict, "ImageDescription")) : nothing
    end
    CFRelease(dict)

    # Allocate the buffer and get the pixel data
    sz = imframes > 1 ? (convert(Int,imwidth), convert(Int,imheight), convert(Int,imframes)) : (convert(Int,imwidth), convert(Int,imheight))
    T = pixeldepth <= 8 ? Ufixed8 : Images.ufixedtype[pixeldepth]
    if colormodel == "Gray" && alphacode == 0 && storagedepth == 1
        buf = Array(Gray{T}, sz)
        fillgray!(reinterpret(T, buf, tuple(sz...)), imgsrc)
    elseif colormodel == "Gray" && in(alphacode, [1, 3])
        buf = Array(GrayAlpha{T}, sz)
        fillgrayalpha!(reinterpret(T, buf, tuple(2, sz...)), imgsrc)
    elseif colormodel == "Gray" && in(alphacode, [2, 4])
        # Not sure these exist out in the wild
        error("Unexpected GrayAlpha image layout: alpha is before intensity")
    elseif colormodel == "RGB" && in(alphacode, [1, 3])
        buf = Array(RGBA{T}, sz)
        fillcolor!(reinterpret(T, buf, tuple(4, sz...)), imgsrc, storagedepth)
    elseif colormodel == "RGB" && in(alphacode, [2, 4])
        buf = Array(ARGB{T}, sz)
        fillcolor!(reinterpret(T, buf, tuple(4, sz...)), imgsrc, storagedepth)
    elseif colormodel == "RGB" && alphacode == 0
        buf = Array(RGB{T}, sz)
        fillcolor!(reinterpret(T, buf, tuple(3, sz...)), imgsrc, storagedepth)
    elseif colormodel == "RGB" && in(alphacode, [5, 6])
        buf = alphacode == 5 ? Array(RGB4{T}, sz) : Array(RGB1{T}, sz)
        fillcolor!(reinterpret(T, buf, tuple(4, sz...)), imgsrc, storagedepth)
    else
        warn("Unknown colormodel ($colormodel) and alphacode ($alphacode) found by OSX reader")
        CFRelease(imgsrc)
        return nothing
    end
    CFRelease(imgsrc)

    # Set the image properties
    prop = @compat Dict(
        "spatialorder" => ["x", "y"],
        "pixelspacing" => [1, 1],
        "imagedescription" => imagedescription,
        "suppress" => Set(Any["imagedescription"])
    )
    if imframes > 1
        prop["timedim"] = ndims(buf)
    end
    Image(buf, prop)
end

function alpha_and_depth(imgsrc)
    CGimg = CGImageSourceCreateImageAtIndex(imgsrc, 0)  # Check only first frame
    alphacode = CGImageGetAlphaInfo(CGimg)
    bitspercomponent = CGImageGetBitsPerComponent(CGimg)
    bitsperpixel = CGImageGetBitsPerPixel(CGimg)
    CGImageRelease(CGimg)
    # Alpha codes documented here:
    # https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/CGImage/Reference/reference.html#//apple_ref/doc/uid/TP30000956-CH3g-459700
    # Dividing bits per pixel by bits per component tells us how many
    # color + alpha slices we have in the file.
    alphacode, convert(Int,div(bitsperpixel, bitspercomponent))
end

function fillgray!{T}(buffer::AbstractArray{T, 2}, imgsrc)
    imwidth, imheight = size(buffer, 1), size(buffer, 2)
    CGimg = CGImageSourceCreateImageAtIndex(imgsrc, 0)
    imagepixels = CopyImagePixels(CGimg)
    pixelptr = CFDataGetBytePtr(imagepixels, eltype(buffer))
    imbuffer = pointer_to_array(pixelptr, (imwidth, imheight), false)
    buffer[:, :] = imbuffer
    CFRelease(imagepixels)
    CGImageRelease(CGimg)
end

# Image stack
function fillgray!{T}(buffer::AbstractArray{T, 3}, imgsrc)
    imwidth, imheight, nimages = size(buffer, 1), size(buffer, 2), size(buffer, 3)
    for i in 1:nimages
        CGimg = CGImageSourceCreateImageAtIndex(imgsrc, i - 1)
        imagepixels = CopyImagePixels(CGimg)
        pixelptr = CFDataGetBytePtr(imagepixels, T)
        imbuffer = pointer_to_array(pixelptr, (imwidth, imheight), false)
        buffer[:, :, i] = imbuffer
        CFRelease(imagepixels)
        CGImageRelease(CGimg)
    end
end

function fillgrayalpha!(buffer::AbstractArray{Uint8, 3}, imgsrc)
    imwidth, imheight = size(buffer, 2), size(buffer, 3)
    CGimg = CGImageSourceCreateImageAtIndex(imgsrc, 0)
    imagepixels = CopyImagePixels(CGimg)
    pixelptr = CFDataGetBytePtr(imagepixels, Uint16)
    imbuffer = pointer_to_array(pixelptr, (imwidth, imheight), false)
    buffer[1, :, :] = imbuffer & 0xff
    buffer[2, :, :] = div(imbuffer & 0xff00, 256)
    CFRelease(imagepixels)
    CGImageRelease(CGimg)
end
fillgrayalpha!(buffer::AbstractArray{Ufixed8, 3}, imgsrc) = fillgrayalpha!(reinterpret(Uint8, buffer), imgsrc)

function fillcolor!{T}(buffer::AbstractArray{T, 3}, imgsrc, nc)
    imwidth, imheight = size(buffer, 2), size(buffer, 3)
    CGimg = CGImageSourceCreateImageAtIndex(imgsrc, 0)
    imagepixels = CopyImagePixels(CGimg)
    pixelptr = CFDataGetBytePtr(imagepixels, T)
    imbuffer = pointer_to_array(pixelptr, (nc, imwidth, imheight), false)
    buffer[:, :, :] = imbuffer
    CFRelease(imagepixels)
    CGImageRelease(CGimg)
end

function fillcolor!{T}(buffer::AbstractArray{T, 4}, imgsrc, nc)
    imwidth, imheight, nimages = size(buffer, 2), size(buffer, 3), size(buffer, 4)
    for i in 1:nimages
        CGimg = CGImageSourceCreateImageAtIndex(imgsrc, i - 1)
        imagepixels = CopyImagePixels(CGimg)
        pixelptr = CFDataGetBytePtr(imagepixels, T)
        imbuffer = pointer_to_array(pixelptr, (nc, imwidth, imheight), false)
        buffer[:, :, :, i] = imbuffer
        CFRelease(imagepixels)
        CGImageRelease(CGimg)
    end
end

## OSX Framework Wrappers ######################################################

const foundation = Libdl.find_library(["/System/Library/Frameworks/Foundation.framework/Resources/BridgeSupport/Foundation"])
const imageio = Libdl.find_library(["/System/Library/Frameworks/ImageIO.framework/ImageIO"])

const kCFNumberSInt8Type = 1
const kCFNumberSInt16Type = 2
const kCFNumberSInt32Type = 3
const kCFNumberSInt64Type = 4
const kCFNumberFloat32Type = 5
const kCFNumberFloat64Type = 6
const kCFNumberCharType = 7
const kCFNumberShortType = 8
const kCFNumberIntType = 9
const kCFNumberLongType = 10
const kCFNumberLongLongType = 11
const kCFNumberFloatType = 12
const kCFNumberDoubleType = 13
const kCFNumberCFIndexType = 14
const kCFNumberNSIntegerType = 15
const kCFNumberCGFloatType = 16
const kCFNumberMaxType = 16

# Objective-C and NS wrappers
oms{T}(id, uid, ::Type{T}=Ptr{Void}) =
    ccall(:objc_msgSend, T, (Ptr{Void}, Ptr{Void}), id, selector(uid))

ogc{T}(id, ::Type{T}=Ptr{Void}) =
    ccall((:objc_getClass, "Cocoa.framework/Cocoa"), Ptr{Void}, (Ptr{Uint8}, ), id)

selector(sel::String) = ccall(:sel_getUid, Ptr{Void}, (Ptr{Uint8}, ), sel)

NSString(init::String) = ccall(:objc_msgSend, Ptr{Void},
                               (Ptr{Void}, Ptr{Void}, Ptr{Uint8}, Uint64),
                               oms(ogc("NSString"), "alloc"),
                               selector("initWithCString:encoding:"), init, 1)

NSLog(str::String, obj) = ccall((:NSLog, foundation), Ptr{Void},
                                (Ptr{Void}, Ptr{Void}), NSString(str), obj)

NSLog(str::String) = ccall((:NSLog, foundation), Ptr{Void},
                           (Ptr{Void}, ), NSString(str))

NSLog(obj::Ptr) = ccall((:NSLog, foundation), Ptr{Void}, (Ptr{Void}, ), obj)

# Core Foundation
# General
CFRetain(CFTypeRef::Ptr{Void}) = CFTypeRef != C_NULL &&
    ccall(:CFRetain, Void, (Ptr{Void}, ), CFTypeRef)

CFRelease(CFTypeRef::Ptr{Void}) = CFTypeRef != C_NULL &&
    ccall(:CFRelease, Void, (Ptr{Void}, ), CFTypeRef)

function CFGetRetainCount(CFTypeRef::Ptr{Void})
    CFTypeRef == C_NULL && return 0
    ccall(:CFGetRetainCount, Clonglong, (Ptr{Void}, ), CFTypeRef)
end

CFShow(CFTypeRef::Ptr{Void}) = CFTypeRef != C_NULL &&
    ccall(:CFShow, Void, (Ptr{Void}, ), CFTypeRef)

function CFCopyDescription(CFTypeRef::Ptr{Void})
    CFTypeRef == C_NULL && return C_NULL
    ccall(:CFCopyDescription, Ptr{Void}, (Ptr{Void}, ), CFTypeRef)
end

#CFCopyTypeIDDescription(CFTypeID::Cint) = CFTypeRef != C_NULL &&
#    ccall(:CFCopyTypeIDDescription, Ptr{Void}, (Cint, ), CFTypeID)

function CFGetTypeID(CFTypeRef::Ptr{Void})
    CFTypeRef == C_NULL && return nothing
    ccall(:CFGetTypeID, Culonglong, (Ptr{Void}, ), CFTypeRef)
end

CFURLCreateWithString(filename) =
    ccall(:CFURLCreateWithString, Ptr{Void},
          (Ptr{Void}, Ptr{Void}, Ptr{Void}), C_NULL, NSString(filename), C_NULL)

CFURLCreateWithFileSystemPath(filename::String) =
    ccall(:CFURLCreateWithFileSystemPath, Ptr{Void},
          (Ptr{Void}, Ptr{Void}, Cint, Bool), C_NULL, NSString(filename), 0, false)

# CFDictionary
CFDictionaryGetKeysAndValues(CFDictionaryRef::Ptr{Void}, keys, values) =
    CFDictionaryRef != C_NULL &&
    ccall(:CFDictionaryGetKeysAndValues, Void,
          (Ptr{Void}, Ptr{Ptr{Void}}, Ptr{Ptr{Void}}), CFDictionaryRef, keys, values)

function CFDictionaryGetValue(CFDictionaryRef::Ptr{Void}, key)
    CFDictionaryRef == C_NULL && return C_NULL
    ccall(:CFDictionaryGetValue, Ptr{Void},
          (Ptr{Void}, Ptr{Void}), CFDictionaryRef, key)
end

CFDictionaryGetValue(CFDictionaryRef::Ptr{Void}, key::String) =
    CFDictionaryGetValue(CFDictionaryRef::Ptr{Void}, NSString(key))

# CFNumber
function CFNumberGetValue(CFNum::Ptr{Void}, numtype)
    CFNum == C_NULL && return nothing
    out = Cint[0]
    ccall(:CFNumberGetValue, Bool, (Ptr{Void}, Cint, Ptr{Cint}), CFNum, numtype, out)
    out[1]
end

CFNumberGetValue(CFNum::Ptr{Void}, ::Type{Int8}) =
    CFNumberGetValue(CFNum, kCFNumberSInt8Type)

CFNumberGetValue(CFNum::Ptr{Void}, ::Type{Int16}) =
    CFNumberGetValue(CFNum, kCFNumberSInt16Type)

CFNumberGetValue(CFNum::Ptr{Void}, ::Type{Int32}) =
    CFNumberGetValue(CFNum, kCFNumberSInt32Type)

CFNumberGetValue(CFNum::Ptr{Void}, ::Type{Int64}) =
    CFNumberGetValue(CFNum, kCFNumberSInt64Type)

CFNumberGetValue(CFNum::Ptr{Void}, ::Type{Float32}) =
    CFNumberGetValue(CFNum, kCFNumberFloat32Type)

CFNumberGetValue(CFNum::Ptr{Void}, ::Type{Float64}) =
    CFNumberGetValue(CFNum, kCFNumberFloat64Type)

CFNumberGetValue(CFNum::Ptr{Void}, ::Type{Uint8}) =
    CFNumberGetValue(CFNum, kCFNumberCharType)

#CFBoolean
CFBooleanGetValue(CFBoolean::Ptr{Void}) =
    CFBoolean != C_NULL &&
    ccall(:CFBooleanGetValue, Bool, (Ptr{Void}, ), CFBoolean)

# CFString
function CFStringGetCString(CFStringRef::Ptr{Void})
    CFStringRef == C_NULL && return ""
    buffer = Array(Uint8, 1024)  # does this need to be bigger for Open Microscopy TIFFs?
    res = ccall(:CFStringGetCString, Bool, (Ptr{Void}, Ptr{Uint8}, Uint, Uint16),
                CFStringRef, buffer, length(buffer), 0x0600)
    res == C_NULL && return ""
    return bytestring(convert(Ptr{Uint8}, buffer))
end

# These were unsafe, can return null pointers at random times.
# See Apple Developer Docs
#CFStringGetCStringPtr(CFStringRef::Ptr{Void}) =
#    ccall(:CFStringGetCStringPtr, Ptr{Uint8}, (Ptr{Void}, Uint16), CFStringRef, 0x0600)
#
#getCFString(CFStr::Ptr{Void}) = CFStringGetCStringPtr(CFStr) != C_NULL ?
#    bytestring(CFStringGetCStringPtr(CFStr)) : ""

# Core Graphics
# CGImageSource
CGImageSourceCreateWithURL(myURL::Ptr{Void}) =
    ccall((:CGImageSourceCreateWithURL, imageio), Ptr{Void}, (Ptr{Void}, Ptr{Void}), myURL, C_NULL)

CGImageSourceCreateWithData(data::Ptr{Void}) =
    ccall((:CGImageSourceCreateWithData, imageio), Ptr{Void}, (Ptr{Void}, Ptr{Void}), data, C_NULL)

CGImageSourceGetType(CGImageSourceRef::Ptr{Void}) =
    ccall(:CGImageSourceGetType, Ptr{Void}, (Ptr{Void}, ), CGImageSourceRef)

CGImageSourceGetStatus(CGImageSourceRef::Ptr{Void}) =
    ccall(:CGImageSourceGetStatus, Uint32, (Ptr{Void}, ), CGImageSourceRef)

CGImageSourceGetStatusAtIndex(CGImageSourceRef::Ptr{Void}, n) =
    ccall(:CGImageSourceGetStatusAtIndex, Int32,
          (Ptr{Void}, Csize_t), CGImageSourceRef, n) #Int32?

CGImageSourceCopyProperties(CGImageSourceRef::Ptr{Void}) =
    ccall(:CGImageSourceCopyProperties, Ptr{Void},
          (Ptr{Void}, Ptr{Void}), CGImageSourceRef, C_NULL)

CGImageSourceCopyPropertiesAtIndex(CGImageSourceRef::Ptr{Void}, n) =
    ccall(:CGImageSourceCopyPropertiesAtIndex, Ptr{Void},
          (Ptr{Void}, Csize_t, Ptr{Void}), CGImageSourceRef, n, C_NULL)

CGImageSourceGetCount(CGImageSourceRef::Ptr{Void}) =
    ccall(:CGImageSourceGetCount, Csize_t, (Ptr{Void}, ), CGImageSourceRef)

CGImageSourceCreateImageAtIndex(CGImageSourceRef::Ptr{Void}, i) =
    ccall(:CGImageSourceCreateImageAtIndex, Ptr{Void},
          (Ptr{Void}, Uint64, Ptr{Void}), CGImageSourceRef, i, C_NULL)

# CGImageGet
CGImageGetAlphaInfo(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetAlphaInfo, Uint32, (Ptr{Void}, ), CGImageRef)

CGImageGetBitmapInfo(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetBitmapInfo, Uint32, (Ptr{Void}, ), CGImageRef)

CGImageGetBitsPerComponent(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetBitsPerComponent, Csize_t, (Ptr{Void}, ), CGImageRef)

CGImageGetBitsPerPixel(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetBitsPerPixel, Csize_t, (Ptr{Void}, ), CGImageRef)

CGImageGetBytesPerRow(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetBytesPerRow, Csize_t, (Ptr{Void}, ), CGImageRef)

CGImageGetColorSpace(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetColorSpace, Uint32, (Ptr{Void}, ), CGImageRef)

CGImageGetDecode(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetDecode, Ptr{Float64}, (Ptr{Void}, ), CGImageRef)

CGImageGetHeight(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetHeight, Csize_t, (Ptr{Void}, ), CGImageRef)

CGImageGetRenderingIntent(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetRenderingIntent, Uint32, (Ptr{Void}, ), CGImageRef)

CGImageGetShouldInterpolate(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetShouldInterpolate, Bool, (Ptr{Void}, ), CGImageRef)

CGImageGetTypeID() =
    ccall(:CGImageGetTypeID, Culonglong, (),)

CGImageGetWidth(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetWidth, Csize_t, (Ptr{Void}, ), CGImageRef)

CGImageRelease(CGImageRef::Ptr{Void}) =
    ccall(:CGImageRelease, Void, (Ptr{Void}, ), CGImageRef)

# Get pixel data
# See: https://developer.apple.com/library/mac/qa/qa1509/_index.html
CGImageGetDataProvider(CGImageRef::Ptr{Void}) =
    ccall(:CGImageGetDataProvider, Ptr{Void}, (Ptr{Void}, ), CGImageRef)

CGDataProviderCopyData(CGDataProviderRef::Ptr{Void}) =
    ccall(:CGDataProviderCopyData, Ptr{Void}, (Ptr{Void}, ), CGDataProviderRef)

CopyImagePixels(inImage::Ptr{Void}) =
    CGDataProviderCopyData(CGImageGetDataProvider(inImage))

CFDataGetBytePtr{T}(CFDataRef::Ptr{Void}, ::Type{T}) =
    ccall(:CFDataGetBytePtr, Ptr{T}, (Ptr{Void}, ), CFDataRef)

CFDataGetLength(CFDataRef::Ptr{Void}) =
    ccall(:CFDataGetLength, Ptr{Int64}, (Ptr{Void}, ), CFDataRef)

CFDataCreate(bytes::Array{Uint8,1}) =
  ccall(:CFDataCreate,Ptr{Void},(Ptr{Void},Ptr{Uint8},Csize_t),C_NULL,bytes,length(bytes))

end # Module


text:
const FAKE_CONCEPTNET = """
5 5
/c/en/this 1 2 3 4 5
/c/en/is -1 -2 -3 -4 -5
/c/en/# 1 1 1 1 1
/c/fr/etre 6 7 8 9 10
/c/fr/# 2 2 2 2 2
"""
@testset "Conceptnet-2-WordVectors" begin
    filepath, io = mktemp()
    write(io, FAKE_CONCEPTNET)
    close(io)
    cptnet = load_embeddings(filepath)
    for lang in keys(cptnet.embeddings)
        wv = conceptnet2wv(cptnet, lang)
        _, _, data_type = typeof(cptnet).parameters
        @test wv isa WordVectors{String, data_type, Int}
        @test length(wv.vocab) == length(cptnet.embeddings[lang])
        @test size(wv.vectors, 1) == cptnet.width
        for word in keys(cptnet.embeddings[lang])
            @test cptnet[lang, word] == get_vector(wv, word)
        end
    end
end

max_stars_repo_name: zgornel/EmbeddingsAnalysis

max_issues_repo_name: zgornel/EmbeddingsAnalysis

max_forks_repo_name: zgornel/EmbeddingsAnalysis


text:
using AffineTransforms
import Base.inv

type ReduceDimensions{T, N, M}
    scalefwd :: Matrix{T}
    offset :: Vector{T}
end

ReduceDimensions{T, N}(aff :: AffineTransform{T, N}) = ReduceDimensions{T, N, M}(aff.tscalefwd, aff.offset)

function ReduceDimensions(index :: Integer, dimension :: Integer, ndims :: Integer)
    scalefwd = zeros(Int, ndims, ndims-1)
    for ix in 1:ndims-1
        scalefwd[ix + (ix >= dimension), ix] = 1
    end
    offset = zeros(Int, ndims)
    offset[dimension] = index
    ReduceDimensions{Int, ndims, ndims-1}(scalefwd, offset)
end

ndims_in{T, N, M}(::ReduceDimensions{T, N, M}) = M
ndims_out{T, N, M}(::ReduceDimensions{T, N, M}) = N
ndims_in{T, N}(::AffineTransform{T, N}) = N
ndims_out{T, N}(::AffineTransform{T, N}) = N

*{T, S, N, M}(rd :: ReduceDimensions{T, N, M}, aff :: AffineTransform{S, M}) = ReduceDimensions{typeof(one(T) + one(S)), N, M}(rd.scalefwd * aff.scalefwd, rd.offset + rd.scalefwd * aff.offset)
*{T, S, N, M}(aff :: AffineTransform{T, N}, rd :: ReduceDimensions{S, N, M}) = ReduceDimensions{typeof(one(T) + one(S)), N, M}(aff.scalefwd * rd.scalefwd, aff.offset + aff.scalefwd * rd.offset)
*{T, S, N, M, L}(rd_f :: ReduceDimensions{T, N, M}, rd_s :: ReduceDimensions{S, M, L}) = ReduceDimensions{typeof(one(T) + one(S)), N, L}(rd_f.scalefwd * rd_s.scalefwd, rd_f.offset + rd_f.scalefwd * rd_s.offset)
*{T, N, M}(rd :: ReduceDimensions{T, N, M}, i :: Number) = rd * tformscale(i, M)
*{T, N, M}(i :: Number, rd :: ReduceDimensions{T, N, M}) = tformscale(i, N) * rd
*(rd :: ReduceDimensions, x :: AbstractVector) = rd.scalefwd * x + rd.offset

inv(aff :: AffineTransform) = AffineTransform(inv(aff.scalefwd), inv(aff.scalefwd) * -aff.offset)
*{T, N}(aff :: AffineTransform{T, N}, i :: Number) = aff * AffineTransforms.tformscale(i, N)
*{T, N}(i :: Number, aff :: AffineTransform{T, N}) = tformscale(i, N) * aff

type ComposeTransform
    first
    second
end

inv(comp :: ComposeTransform) = inv(comp.second) * inv(con.first)
*(comp :: ComposeTransform, x :: AbstractVector) = comp.first * (comp.second * x)

typealias AnyTransform Union(AffineTransform, Number, ComposeTransform)

# composing transforms
*(comp :: ComposeTransform, other :: AffineTransform) = ComposeTransform(comp.first, (comp.second * other))
*(other :: AnyTransform, comp :: ComposeTransform) = ComposeTransform((other * comp.first), comp.second)
*(a :: AnyTransform, b :: AnyTransform) = ComposeTransform(a, b)

index_to_transform(ndims, dimension, index :: Integer) = index_to_transform(ndims, dimension, index:index)
function index_to_transform(ndims, dimension, index :: Range)
    offset = zeros(Float64, ndims)
    offset[dimension] = start(index) - step(index)
    aff = eye(Float64, ndims)
    aff[dimension, dimension] =  step(index)
    AffineTransform(aff, offset)
end

function inds_to_transform(ndims, inds...)
    trans = tformeye(ndims)
    for dim in 1:ndims
        if dim <= size(inds, 1)
            trans = trans * index_to_transform(ndims_in(trans), dim + ndims_in(trans) - ndims, inds[dim])
        end
    end
    trans
end


text:
function Base.append!(a::IndicesVector, b::AbstractVector)
    append_index!(a, b)
    append!(parent(a), b)
    return a
end


text:
# Fractals
# TODO: fat Cantor sets, Smith-Volterra-Cantor sets, asymmetric Cantor sets...

export cantor, thincantor, thinnercantor, thinnestcantor

# α is width, n is number of levels

# Standard Cantor set removes the middle third at every level
cantor{T}(d::Domain{T},n::Int) = cantor(d,n,3)

function cantor{T}(d::Interval{T},n::Int,α::Number)
    a,b = d.a,d.b
    if n == 0
        return d
    else
        d = Interval{T}(zero(T),one(T))
        C = d/α ∪ (α-1+d)/α
        for k=2:n
            C = C/α ∪ (α-1+C)/α
        end
        return a+(b-a)*C
    end
end

# Thin Cantor set removes the middle n/(n+2)th at the nth level

thincantor{T}(d::Domain{T},n::Int) = thincantor(d,n,3)

function thincantor{T}(d::Interval{T},n::Int,α::Number)
    a,b = d.a,d.b
    if n == 0
        return d
    else
        d = Interval{T}(zero(T),one(T))
        C = d/(α+n-1) ∪ (α+n-2+d)/(α+n-1)
        for k=n-1:-1:1
            C = C/(α+k-1) ∪ (α+k-2+C)/(α+k-1)
        end
        return a+(b-a)*C
    end
end

thinnercantor{T}(d::Domain{T},n::Int) = thinnercantor(d,n,3)

function thinnercantor{T}(d::Interval{T},n::Int,α::Number)
    a,b = d.a,d.b
    if n == 0
        return d
    else
        d = Interval{T}(zero(T),one(T))
        C = d/α^n ∪ (α^n-1+d)/α^n
        for k=n-1:-1:1
            C = C/α^k ∪ (α^k-1+C)/α^k
        end
        return a+(b-a)*C
    end
end

thinnestcantor{T}(d::Domain{T},n::Int) = thinnestcantor(d,n,3)

function thinnestcantor{T}(d::Interval{T},n::Int,α::Number)
    a,b = d.a,d.b
    if n == 0
        return d
    else
        d = Interval{T}(zero(T),one(T))
        C = d/α^(2^(n-1)) ∪ (α^(2^(n-1))-1+d)/α^(2^(n-1))
        for k=n-1:-1:1
            C = C/α^(2^(k-1)) ∪ (α^(2^(k-1))-1+C)/α^(2^(k-1))
        end
        return a+(b-a)*C
    end
end

function cantor{T,V}(d::Circle{T,V},n::Int,α::Number)
    c,r = d.center,d.radius
    α = convert(promote_type(real(T),V,typeof(α)),α)
    if n == 0
        return d
    else
        C = cantor(Interval{T}(),n,α)
        return UnionDomain(map(d->Arc(c,r,(d.a+1/2α)π,(d.b+1/2α)π),C[1:div(length(C),2)])) ∪ UnionDomain(map(d->Arc(c,r,(d.a-1/2α)π,(d.b-1/2α)π),C[div(length(C),2)+1:length(C)]))
    end
end


text:
#Ost - "E6" - восток, Nord - "N8" - север, West - "W4" - запад, Sud - "S2" - юг
"""
main_function1!(r::Robot) это главная функция которая рисует крест на поле использует три функции описанные внизу,
но алгоритм выполнения следующий цикл for перебирает 4 стороны: Nord, Sud, West, Ost дальше каждый элемент side передается в
функции putmarkers!, move_by_markers, inverse после выполнения цикла появляет крест из маркеров и в изначальной позиции ставится маркер
"""
function main_function1!(r)
    for side in [Nord, Sud, West, Ost]
        putmarkers!(r, side)
        move_by_markers(r, inverse(side))
    end
    putmarker!(r)
end
"""
putmarkers!(r::Robot, side::HorizonSide) - пока нет перегоротки в переданам направлении side::HorizonSide делает шаг в заданном направлении и ставит маркер
"""
function putmarkers!(r, side)
    while !isborder(r, side)
        move!(r, side)
        putmarker!(r)
    end
end
"""
move_by_markers(r::Robot, side::HorizonSide) - пока есть маркер в клетке с роботом он делает в шаг в заданном направлении
"""
function move_by_markers(r, side)
    while ismarker(r)==true
        move!(r, side)
    end
end
"""
inverse(side::HorizonSide) - получает переданую в функцию side преобразовывает её в Int значение то есть Nord = 0,
West = 1, Sud = 2, Ost = 3 потом преобразовывает в сторону противоположную : допустим, что в функцию передано напрвление West после преобразование в значения Int
West = 1 после к этого к этому числу прибавляется 2 и берется остаток от деления на число 4 то есть 3 и это сторона Ost, а эта сторона противоположна стороне West
"""
function inverse(side)
    HorizonSide(mod(Int(side)+2, 4))
end


text:
# include("datastructs_module.jl")

# module btr # to be removed
# using ..datastructs # to be removed

abstract type AbstractTree
end

abstract type AbstractTreeNode
end

abstract type AbstractBinaryTree <: AbstractTree
end

abstract type AbstractBinaryTreeNode <: AbstractTreeNode
end

mutable struct BinaryTreeNode{T} <: AbstractBinaryTreeNode
    parent::BinaryTreeNode
    left::BinaryTreeNode
    right::BinaryTreeNode
    data::T

    function BinaryTreeNode{T}(content::T) where {T}
        obj = new()
        # obj.left = undef;
        # obj.right = undef;
        obj.data = content
        return obj
    end
    function BinaryTreeNode{T}() where {T}
        obj = new()
        return obj
    end
end

function BinaryTreeNode(content::T) where {T}
    return BinaryTreeNode{T}(content::T)
end

function BinaryTreeNode()
    return BinaryTreeNode(undef)
end

function has_left_child(node::BinaryTreeNode)
    return isdefined(node, :left)
end

function has_right_child(node::BinaryTreeNode)
    return isdefined(node, :right)
end

function Base.eltype( ::Type{ <: BinaryTreeNode{T}} ) where {T}
    return T
end

function Base.isempty(node::BinaryTreeNode)
    return node.data == undef
end

function Base.show(io::IO, node::BinaryTreeNode{T}) where {T}
    println("BinaryTreeNode{$(T)}")
    print("data: ")
    show(node.data)
    print("\n")

    print("\t  left:")
    if isdefined(node, :left)
        show(node.left.data)
    else
        print(" not_defined\n")
    end
    print("\n")

    print("\t  right:")
    if isdefined(node, :right)
        show(node.right.data)
    else
        print(" not_defined\n")
    end

end

# function is_root(node::BinaryTreeNode)
#     return !isdefined(node, :parent)
# end

function is_root(tree::T, node::N) where {T <: AbstractBinaryTree, N <: AbstractBinaryTreeNode}
    # this doesnt work for red black tree
    # return !isdefined(node, :parent)
    return tree.node == node
end

mutable struct BinaryTree{T} <: AbstractBinaryTree
    count::Int64
    node::BinaryTreeNode{T}

    function BinaryTree{T}(content::T) where {T}
        count_ = 1
        node_ = BinaryTreeNode{T}(content)
        return new(count_, node_)
    end
    function BinaryTree{T}() where {T}
        count_ = 1
        node_ = BinaryTreeNode{T}()
        return new(count_, node_)
    end
end

function BinaryTree(content::T) where {T}
    return BinaryTree{T}(content::T)
end

# function is_nil(tree, node.left)
# end

function search(tree::T, key) where {T <: AbstractBinaryTree}
    node = tree.node
    while node.data != key
        if node.data < key
            if isdefined(node, :left)
                next_node = node.left
            else
                break
            end
        else
            if isdefined(node, :right)
                next_node = node.right
            else
                break
            end
        end
        node = next_node
    end
    return node
end

function inorder_tree_walk(tree::T, fcn = show) where {T <: AbstractBinaryTree}
    node = tree.node
    return inorder_tree_walk(node, fcn, 1)
end

function inorder_tree_walk(tree::T, node::N, fcn = show, depth = 1) where {T <: AbstractBinaryTree, N <: AbstractBinaryTreeNode}
    if isdefined(node, :left) # && !is_nil(tree, node.left)
        child = node.left
        inorder_tree_walk(tree, child, fcn, depth+1)
    end
    fcn(node, depth)
    if isdefined(node, :right) # && !is_nil(tree, node.right)
        child = node.right
        inorder_tree_walk(tree, child, fcn, depth+1)
    end
end

function preorder_tree_walk(tree::T, fcn = show) where {T <: AbstractBinaryTree}
    node = tree.node
    return preorder_tree_walk(node, fcn, 1)
end

function preorder_tree_walk(tree::T, node::N, fcn = show, depth = 1) where {T <: AbstractBinaryTree, N <: AbstractBinaryTreeNode}

    fcn(node, depth)
    if isdefined(node, :left) # && !is_nil(tree, node.left)
        child = node.left
        preorder_tree_walk(tree, child, fcn, depth+1)
    end
    if isdefined(node, :right) # && !is_nil(tree, node.right)
        child = node.right
        preorder_tree_walk(tree, child, fcn, depth+1)
    end
end

function tree_minimum(tree::T) where {T <: AbstractBinaryTree}
    node = tree.node
    return tree_minimum(node)
end

function tree_minimum(node::N) where {N <: AbstractBinaryTreeNode}
    while isdefined(node, :left)
        node = node.left
    end
    return node
end

function tree_maximum(tree::N) where {N <: AbstractBinaryTree}
    node = tree.node
    return tree_maximum(node)
end

function tree_maximum(node::N) where {N <: AbstractBinaryTreeNode}
    while isdefined(node, :right)
        node = node.right
    end
    return node
end

function successor(node::N) where {N <: AbstractBinaryTreeNode}
    if isdefined(node, :right)
        return tree_minimum(node.right)
    end
    orig_node = node
    while true
        if isdefined(node, :parent)
            parent = node.parent
            if node == parent.left
                node = parent
                break
            end
            node = parent;
        else
            # the node is the greatest element in that array
            node = orig_node
            break
        end
    end
    return node
end

function predecessor(node::N) where {N <: AbstractBinaryTreeNode}

    if isdefined(node, :left)
        return tree_maximum(node.left)
    end
    orig_node = node
    while true
        if isdefined(node, :parent)
            parent = node.parent
            if node == parent.right
                node = parent
                break
            end
            node = parent;
        else
            # the node is the greatest element in that array
            node = orig_node
            break
        end
    end
    return node

end

function Base.insert!(tree::T, new_node::N) where {T <: BinaryTree, N <: BinaryTreeNode}
    # data must have < operation
    node   = tree.node
    parent = node

    to_left  = false
    to_right = false

    while true
        if new_node.data < node.data
            if isdefined(node, :left)
                child = node.left
            else
                parent = node
                to_left = true
                break
            end
        else
            if isdefined(node, :right)
                child = node.right
            else
                parent = node
                to_right = true
                break
            end
        end
        parent = node
        node   = child
    end

    new_node.parent = parent
    if to_left
        parent.left = new_node
    end
    if to_right
        parent.right = new_node
    end

    tree.count += 1

    return tree
end

function transplant!(tree::T, old_node::N, new_node::N) where {T <: BinaryTree, N <: BinaryTreeNode}
    if isdefined(old_node, :parent)
        parent = old_node.parent
        if old_node == parent.left
            parent.left = new_node
        else
            parent.right = new_node
        end
        new_node.parent = parent
    else
        tree.node = new_node
    end

    return tree
end

function remove!(tree::T, node::N) where {T <: BinaryTree, N <: BinaryTreeNode}

    if !isdefined(node, :left) && !isdefined(node, :right)
        if isdefined(node, :parent)
            parent = node.parent
            if node == parent.left
                parent.left = undef
            else
                parent.right = undef
            end
        end
    end

    if !isdefined(node, :left)

        transplant!(tree, node, node.right)

    elseif !isdefined(node, :right)

        transplant!(tree, node, node.left)

    else

        y = tree_minimum(node.right)
        if y.parent != node
            transplant!(tree, node, y)
            y.right = node.right
            y.right.parent = isdefined(node, :parent) ? node.parent : undef
        end

        transplant!(tree, node, y)
        y.left = node.left
        y.left.parent = isdefined(node, :parent) ? node.parent : undef

    end

    tree.count -= 1

    return tree
end

function Base.show(io::IO, tree::BinaryTree{T}) where {T}
    println("BinaryTree{$(T)} with properties")
    println(" \t count: $(tree.count)")
    print(" \t node: ")
    show(tree.node)
    print("\n\n")
end

function tree_view(tree::TreeType) where { TreeType <: AbstractBinaryTree}
    println("$(TreeType)} with properties")
    println(" \t count: $(tree.count)")
    preorder_tree_walk(tree, tree.node, tree_node_show, 1)
    println("\n")
end

function show_node(node::BinaryTreeNode)
    show(node.data)
end

function tree_node_show(node::T, depth = 1, show_fcn = show_node) where {T <: AbstractTreeNode}
    ws = "    "^(depth-1)
    print(ws, "Node: ")
    show_fcn(node)
    print("\n")
end

function depth_first_search(tree::TreeType;
    visited_fcn = do_nothing,
    push_fcn = do_nothing) where {TreeType <: AbstractBinaryTree}

    n        = tree.count
    depths   = zeros(Int, n)
    NodeType = typeof(tree.node)
    nodes    = Vector{NodeType}(undef, n)

    init_size    = div(n, 2)
    helper       = TreeSearchHelper(1, false)
    node_stack   = Stack{NodeType}(init_size)
    helper_stack = Stack{TreeSearchHelper}(init_size)
    push!(node_stack,   tree.node)
    push!(helper_stack, helper)

    index = 0
    while !isempty(node_stack)

        node   = pop!(node_stack)
        helper = pop!(helper_stack)

        if helper.visited

            index        += 1
            nodes[index]  = node
            depths[index] = helper.depth

            # call the callback function
            visited_fcn(node, helper.depth, helper.visited)
        else

            # add the same node once again
            helper = TreeSearchHelper(helper.depth, true)
            push!(node_stack,   node)
            push!(helper_stack, helper)

            # add the children
            next_depth = helper.depth + 1
            visited    = false

            if has_left_child(node)
                push!(node_stack,   node.left)
                push!(helper_stack, TreeSearchHelper(next_depth, visited))

                push_fcn(node.left, next_depth, visited)
            end

            if has_right_child(node)
                push!(node_stack,   node.right)
                push!(helper_stack, TreeSearchHelper(next_depth, visited))

                push_fcn(node.right, next_depth, visited)
            end
        end

    end

    return (nodes, depths)
end

function breadth_first_search(tree::TreeType;
    visited_fcn = do_nothing,
    push_fcn = do_nothing) where {TreeType <: AbstractBinaryTree}

    n        = tree.count
    depths   = zeros(Int, n)
    NodeType = typeof(tree.node)
    nodes    = Vector{NodeType}(undef, n)

    init_size    = div(n, 2)
    helper       = TreeSearchHelper(1, false)
    node_queue   = Queue{NodeType}(init_size)
    helper_queue = Queue{TreeSearchHelper}(init_size)
    push!(node_queue,   tree.node)
    push!(helper_queue, helper)

    index = 0
    while !isempty(node_queue)

        node   = pop!(node_queue)
        helper = pop!(helper_queue)

        # println("Popped: ")
        # show(node)

        if helper.visited
            index        += 1
            nodes[index]  = node
            depths[index] = helper.depth

            # call the callback function
            visited_fcn(node, helper.depth, helper.visited)
        else

            # add the same node once again
            helper = TreeSearchHelper(helper.depth, true)
            push!(node_queue,   node)
            push!(helper_queue, helper)

            # add the children
            next_depth = helper.depth + 1
            visited    = false

            if has_left_child(node)
                push!(node_queue,   node.left)
                push!(helper_queue, TreeSearchHelper(next_depth, visited))

                push_fcn(node.left, next_depth, visited)
            end

            if has_right_child(node)
                push!(node_queue,   node.right)
                push!(helper_queue, TreeSearchHelper(next_depth, visited))

                push_fcn(node.left, next_depth, visited)
            end
        end

    end

    return (nodes, depths)
end

# end # to be removed

max_stars_repo_name: HomoModelicus/julia

max_issues_repo_name: HomoModelicus/julia

max_forks_repo_name: HomoModelicus/julia


text:
using Statistics, LinearAlgebra, SolveDSGE

# this block reads and processes the file, leave it be
#process_model("CK.txt")
const dsge = retrieve_processed_model("CK_processed.txt")

# solve model and simulate data
function dgp(θ, dsge, reps, rndseed=1234)
    p, ss = ParamsAndSS(θ)
    dsge = assign_parameters(dsge, p)
    scheme = PerturbationScheme(ss, 1.0, "third")
    solution = solve_model(dsge, scheme)
    burnin = 200
    nobs = 160
    data = simulate(solution, ss[1:3], reps*(burnin+nobs); rndseed = rndseed)
    # the next returns reps data sets, in an array of arrays
    data = [data[4:8, (nobs+burnin)*i-(nobs+burnin)+1+burnin:i*(nobs+burnin)]' for i = 1:reps]
end

function bad_data(data)
    any(isnan.(data)) || any(isinf.(data)) || any(std(data,dims=1) .==0.0) || any(data .< 0.0)
end

# this gives a vector of vectors, each a statistic drawn at the parameter value
function auxstat(θ, reps)
    auxstat.(dgp(θ, dsge, reps, rand(1:Int64(1e12))))
end

# These are the candidate auxiliary statistics for ABC estimation of
# the simple DSGE model of Creel and Kristensen (2013)
function auxstat(data)
    # check for nan, inf, no variation, or negative, all are reasons to reject
    if bad_data(data)
        return zeros(39)
    else
        # known parameters
        α = 0.33
        δ = 0.025
        # recover capital (see notes)
        hours = data[:,3]
        intrate = data[:,4]
        wages = data[:,5]
        capital = α /(1.0-α )*hours.*wages./intrate
        # treat all variables
        logdata = log.([data capital])[2:end,:]
        # logs
        logoutput = logdata[:,1];   # output
        logcons = logdata[:,2];     # consumption
        loghours = logdata[:,3];    # hours
        logintrate = logdata[:,4];  # intrate
        logwages = logdata[:,5];    # wages
        logcapital = logdata[:,6]
        # rho1, sig1
        e = logoutput-α*logcapital-(1.0-α)*loghours
        y = e[2:end]
        x = e[1:end-1]
        rho1 = cor(x,y)
        u = y-x*rho1
        sig1 = sqrt(u'*u/size(u,1))
        Z = vcat(rho1, sig1)
        # gam, rho2, sig2 (1/MRS=wage)
        x = [ones(size(logcons,1)) logcons]
        b = x\logwages
        e = logwages-x*b
        y = e[2:end]
        x = e[1:end-1]
        rho2 = cor(y,x)
        u = y-x*rho2
        sig2 = sqrt(u'*u/size(u,1))
        Z = vcat(Z, b, rho2, sig2)
        # standard devs. and correlations
        m = mean(logdata, dims=1)
        s = std(logdata, dims=1)
        d = (logdata .- m) ./s # keep means and std. devs., the VAR uses standardized and normalized
        # AR(1)
        maxlag = 1
        y = d[2:end,:]
        x = d[1:end-1,:]
        n = size(y,1)
        rhos = zeros(6)
        es = zeros(n,6)
        for i = 1:6
            rho = x[:,i]\y[:,i]
            rhos[i] = rho
            es[:,i] = y[:,i]-rho.*x[:,i]
        end
        varv = vech(cov(es)) # AR(1) error covariance elements
        Z = vcat(Z, m[:], s[:], varv)
    end
    Z
end

function vech(x)
    k = size(x,1)
    a = zeros(Int((k^2-k)/2 + k))
    m = 1
    for i = 1:k
        for j = 1:i
            a[m] = x[i,j]
            m += 1
        end
    end
    a
end

function TrueParameters()
 [
 0.99,  # β
 2.0,   # γ
 0.9,   # ρ₁
 0.02,  # σ₁
 0.7,   # ρ₂
 0.01,  # σ₂
 8.0/24.0]  # nss
end

function PriorSupport()
    lb = [0.95, 0.0, 0.0, 0.0, 0.0, 0.0, 6.0/24.0]
    ub = [0.995, 5.0, 0.995, 0.1, 0.995, 0.1, 9.0/24.0]
    lb,ub
end

function PriorDraw()
    lb, ub = PriorSupport()
    θ = (ub-lb).*rand(size(lb,1)) + lb
end

function InSupport(θ)
    lb,ub = PriorSupport()
    all(θ .>= lb) & all(θ .<= ub)
end

function Prior(θ)
    InSupport(θ) ? 1.0 : 0.0
end

function ParamsAndSS(params)
    α = 0.33
    δ = 0.025
    β, γ, ρ₁, σ₁, ρ₂, σ₂, nss = params
    c1 = ((1/β  + δ - 1)/α)^(1/(1-α))
    kss = nss/c1
    iss = δ*kss
    yss = kss^α * nss^(1-α)
    css = yss - iss;
    MUCss = css^(-γ)
    rss = α * kss^(α-1) * nss^(1-α)
    wss = (1-α)* (kss)^α * nss^(-α)
    MULss = wss*MUCss
    ψ =  (css^(-γ)) * (1-α) * (kss^α) * (nss^(-α))
    p = [β, γ, ρ₁ , σ₁, ρ₂, σ₂, ψ]
    ss = [0.0, 0.0, kss, yss, css, nss, rss, wss, MUCss, MULss]
    return p, ss
end

max_stars_repo_name: mcreel/Econometrics

max_issues_repo_name: mcreel/Econometrics

max_forks_repo_name: mcreel/Econometrics


text:
# Primal Finite Elasticity (Saint-Venant)
# ========================
function a_PFE((u,v),(ut,vt),(ϕ,φ),ρ,λ,μ,dΩ)
  ∫( ϕ⋅ut - ϕ⋅v +
     φ⋅(ρ*vt) + (∇(φ) ⊙ Pₛᵥ_Ωs(λ,μ,u)) )dΩ
end
function da_PFE_dx((u,v),(du,dv),(ϕ,φ),ρ,λ,μ,dΩ)
  ∫( 0.0*(du⋅ϕ) - (ϕ⋅dv) +
     0.0*(φ⋅(ρ*dv)) + (∇(φ) ⊙ dPₛᵥ_Ωs_du(λ,μ,u,du)) )dΩ
end
function da_PFE_dxt((dut,dvt),(ϕ,φ),ρ,dΩ)
  ∫( dut⋅ϕ + φ⋅(ρ*dvt) )dΩ
end
function l_PFE((ϕ,φ),f₁,f₂,t,dΩ)
  ∫( ϕ⋅f₁(t) + φ⋅f₂(t) )dΩ
end


text:
using Test
using SymDiff

@test differentiate(:(1*x), :x) == :(0*x + 1*1)
@test differentiate(:(x*x), :x) == :(1*x + x*1)


text:
for N in [Float64, Float32, Rational{Int}]
    H1 = BallInf(N[0, 0], N(1))
    H2 = BallInf(N[0, 0], N(2))

    # strict inclusion
    for (X, Y) in [(H1, H2)]
        res, w = ⊂(X, Y, true)
        @test X ⊂ Y && res && w ∈ Y && w ∉ X
    end

    # no strict inclusion
    for (X, Y) in [(H1, H1), (H2, H1)]
        res, w = ⊂(X, Y, true)
        @test !(X ⊂ Y) && !res && w == N[]
    end
end


text:
function plotgwr(A,C)
if size(A,1) == 147 || size(A,1) == 150
    A = rebuild(A);
end

row,col = findnz(C);
ax = A[1,row];
ay = A[2,row];
bx = A[1,col];
by = A[2,col];

X = reshape([ax;bx;NaN*ones(size(ax))],size(ax,2)*3,1)';
Y = reshape([ay;by;NaN*ones(size(ax))],size(ax,2)*3,1)';

if size(A,1)>=3&size(A,1)<75&size(A,1)!=72
    az = A(3,row);
    bz = A(3,col);
    Z = reshape([az;bz;NaN*ones(size(ax))],size(ax,2)*3,1)';
    plot3(X,Y,Z, 'b')
elseif size(A,1) == 75||size(A,1) == 72
    if size(A,1) == 72
        tdskel = zeros(24,3,size(A,2));
        for k = 1:size(A,2)
            for i=1:3
                for j=1:24
                    tdskel(j,i,k) = A(j+24*(i-1),k);
                end
            end
        end
        tdskel = cat(1,zeros(1,3,size(A,2)), tdskel);
    else
        tdskel = zeros(25,3,size(A,2));
        for k = 1:size(A,2)
            for i=1:3
                for j=1:25
                    tdskel(j,i,k) = A(j+25*(i-1),k);
                end
            end
        end
    end
    if all(size(tdskel) != [25,3,size(A,2)])
        error("wrong skeleton building procedure!")
    end
    #q = size(squeeze(tdskel(1,:,row)),2);

    moresticks = [];

    #moresticks = zeros(3,3*size(row));
    for i=1:size(tdskel,1)
        for j=1:size(row)
            moresticks = cat(2,moresticks,[tdskel(i,:,row(j));tdskel(i,:,col(j)); [NaN NaN NaN]]');
        end
    end

    SK = skeldraw(A(:,1),0);
    for i = 2:size(A,2)
       SK = [SK,skeldraw(A(:,i),0)];
    end
    T = [SK,moresticks];
    plot3(T(1,:),T(2,:),T(3,:))

else
    plot(X',Y', "b")
end
#set(gca,"box","off")
end
function rebuild(A)
a = size(A,1)/3;
c = size(A,2);

B = reshape(A,a,3,c);

if a == 49
    A = B(1:24,:,:);
    A = reshape(A,72,c);
else
    error("not implemented for this size")
end
return A
end


text:
using PhysicalConstants, Measurements, Unitful
using Test

import PhysicalConstants.CODATA2014: α, atm, c_0, e, ε_0, h, ħ, µ_0

@testset "Base" begin
    @test ustrip(big(h)) == big"6.626070040e-34"
    @test setprecision(BigFloat, 768) do; precision(ustrip(big(c_0))) end == 768
    @test measurement(h) === measurement(h)
    @test iszero(measurement(α) - measurement(α))
    @test isone(measurement(BigFloat, atm) / measurement(BigFloat, atm))
    @test iszero(measurement(BigFloat, ħ) - (measurement(BigFloat, h) / 2big(pi)))
    @test isone(measurement(BigFloat, ħ) / (measurement(BigFloat, h) / 2big(pi)))
end

@testset "Utils" begin
    @test c_0.val === ustrip(float(c_0))
    @test_throws ErrorException h.foo
end

@testset "Promotion" begin
    x = @inferred(inv(μ_0 * c_0 ^ 2))
    T = promote_type(typeof(ε_0), typeof(x))
    u = u"A^2 * kg^-1 * m^-3 * s^4"
    @test promote_type(typeof(α), BigInt) === BigFloat
    @test promote_type(typeof(α), typeof(1u"m/cm")) === Float64
    @test T === Quantity{Float64, dimension(x), typeof(u)}
    @test convert(T, ε_0) === (ε_0 / unit(ε_0)) * u
    @test convert(Float32, α) === float(Float32, α)
    @test uconvert(u"cm/s", c_0) === uconvert(u"cm/s", float(c_0))
end

@testset "Maths" begin
    @testset "$cst" for cst in (PhysicalConstants.CODATA2014,
                                PhysicalConstants.CODATA2018)
        @test cst.α ≈ @inferred(cst.e^2/(4 * cst.pi * cst.ε_0 * cst.ħ * cst.c_0))
        @test @inferred(cst.α + 2) ≈ 2 + float(cst.α)
        @test @inferred(5 + cst.α) ≈ float(cst.α) + 5
        @test @inferred(cst.α + 2.718) ≈ 2.718 + float(cst.α)
        @test @inferred(-3.14 + cst.α) ≈ float(cst.α) - 3.14
        @test cst.ε_0 ≈ @inferred(1 / (cst.μ_0 * cst.c_0 ^ 2))
        @test @inferred(big(0) + cst.α) == big(cst.α)
        @test @inferred(cst.α * 1.0) == float(cst.α)
        @test (pi ^ 2 * cst.k_B ^ 4) / (60 * cst.ħ ^ 3 * cst.c_0 ^ 2) ≈
            cst.σ atol = measurement(cst.σ).val.err * unit(cst.σ)
    end
end

@testset "Show" begin
    @test repr(c_0) ==
        "Speed of light in vacuum (c_0)
Value                         = 2.99792458e8 m s^-1
Standard uncertainty          = (exact)
Relative standard uncertainty = (exact)
Reference                     = CODATA 2014"
    @test repr(α) ==
        "Fine-structure constant (α)
Value                         = 0.0072973525664
Standard uncertainty          = 1.7e-12
Relative standard uncertainty = 2.3e-10
Reference                     = CODATA 2014"
    @test repr(e) ==
        "Elementary charge (e)
Value                         = 1.6021766208e-19 C
Standard uncertainty          = 9.8e-28 C
Relative standard uncertainty = 6.1e-9
Reference                     = CODATA 2014"
    @test repr(ħ) ==
        "Planck constant over 2pi (ħ)
Value                         = 1.0545718001391127e-34 J s
Standard uncertainty          = 1.2891550390443523e-42 J s
Relative standard uncertainty = 1.2e-8
Reference                     = CODATA 2014"
end