text:
using HighFrequencyCovariance
using Test

# Run tests

println("Test combining of covariance matrices")
@time @test include("main_tests_combine.jl")

println("Test finding nearest correlation matrix")
@time @test include("test_31_Higham.jl")

println("Test on syncronous observations")
@time @test include("main_tests_syncronous.jl")

println("Test on asyncronous observations")
@time @test include("main_tests_asyncronous.jl")

println("Test on Convenience Functions")
@time @test include("main_tests_convenienceFunctions.jl")


text:
# weak key dictionaries

type WeakKeyDict{K,V} <: Associative{K,V}
    ht::Dict{Any,V}
    lock::Threads.RecursiveSpinLock
    finalizer::Function

    function WeakKeyDict()
        t = new(Dict{Any,V}(), Threads.RecursiveSpinLock(), identity)
        t.finalizer = function(k)
            # when a weak key is finalized, remove from dictionary if it is still there
            islocked(t) && return finalizer(k, t.finalizer)
            delete!(t, k)
        end
        return t
    end
end
WeakKeyDict() = WeakKeyDict{Any,Any}()

islocked(wkh::WeakKeyDict) = islocked(wkh.lock)
lock(f, wkh::WeakKeyDict) = lock(f, wkh.lock)
trylock(f, wkh::WeakKeyDict) = trylock(f, wkh.lock)

function setindex!{K}(wkh::WeakKeyDict{K}, v, key)
    k = convert(K, key)
    finalizer(k, wkh.finalizer)
    lock(wkh) do
        wkh.ht[WeakRef(k)] = v
    end
    return wkh
end

function getkey{K}(wkh::WeakKeyDict{K}, kk, default)
    return lock(wkh) do
        k = getkey(wkh.ht, kk, secret_table_token)
        k === secret_table_token && return default
        return k.value::K
    end
end

get{K}(wkh::WeakKeyDict{K}, key, default) = lock(() -> get(wkh.ht, key, default), wkh)
get{K}(default::Callable, wkh::WeakKeyDict{K}, key) = lock(() -> get(default, wkh.ht, key), wkh)
get!{K}(wkh::WeakKeyDict{K}, key, default) = lock(() -> get!(wkh.ht, key, default), wkh)
get!{K}(default::Callable, wkh::WeakKeyDict{K}, key) = lock(() -> get!(default, wkh.ht, key), wkh)
pop!{K}(wkh::WeakKeyDict{K}, key) = lock(() -> pop!(wkh.ht, key), wkh)
pop!{K}(wkh::WeakKeyDict{K}, key, default) = lock(() -> pop!(wkh.ht, key, default), wkh)
delete!{K}(wkh::WeakKeyDict{K}, key) = lock(() -> delete!(wkh.ht, key), wkh)
empty!(wkh::WeakKeyDict) = (lock(() -> empty!(wkh.ht)); wkh)
haskey{K}(wkh::WeakKeyDict{K}, key) = lock(() -> haskey(wkh.ht, key), wkh)
getindex{K}(wkh::WeakKeyDict{K}, key) = lock(() -> getindex(wkh.ht, key), wkh)
isempty(wkh::WeakKeyDict) = isempty(wkh.ht)
length(t::WeakKeyDict) = length(t.ht)

function start{K,V}(t::WeakKeyDict{K,V})
    gc_token = Ref{Bool}(false) # no keys will be deleted via finalizers until this token is gc'd
    finalizer(gc_token, function(r)
        if r[]
            r[] = false
            unlock(t.lock)
        end
    end)
    s = lock(t.lock)
    gc_token[] = true
    return (start(t.ht), gc_token)
end
done(t::WeakKeyDict, i) = done(t.ht, i[1])
function next{K,V}(t::WeakKeyDict{K,V}, i)
    gc_token = i[2]
    wkv, i = next(t.ht, i[1])
    kv = Pair{K,V}(wkv[1].value::K, wkv[2])
    return (kv, (i, gc_token))
end

function filter!(f, d::WeakKeyDict)
    for (k, v) in d
        if !f(k, v)
            delete!(d, k)
        end
    end
    return d
end

ext: jl

max_stars_repo_name: habemus-papadum/julia

max_issues_repo_name: habemus-papadum/julia

max_forks_repo_name: habemus-papadum/julia


text:
mutable struct Token
	lexem::String
	line::Int64
	column::Int64
	categ_nom::String #TODO Provavelmente é melhor tirar esse field. Não faz sentido ficar arrastando uma String para cima e para baixo em cada token. Já tem um dicionário com os nomes e que podemos pegar direto
	categ_num::Int64
end
#=
function Token(lexem_::String,	line_::Int64,column_::Int64,categ_nom_::String,categ_num_::Int64)
	Token(lexem_,line_,column_,categ_nom_,categ_nom_,categ_num_)
end
=#

#This is not working
#Todo, research the reason for that
function Base.show(tkn::Token)
	lex = tkn.lexem
	col = tkn.column
	nom = tkn.categ_nom
	num = tkn.categ_num
	println("\(\"$lex\",$col,$nom,$num\)")
end

mutable struct Production
	lexem::String
	subprods
	enum::Int
end

function Production(subprods_,enum_)
	prd = Production("",subprods_,enum_)
end

function Production(subprods_)
	Production(subprods_,-1)
end

Element = Union{Token,Production}

#Lembrar que Element é a união de Token e Production. A definição destes tipos estão em data_structures.jl

function getLexem(enum::Int)
	grammar[enum].lexem
end

function printToken(tkn::Token)
	@sprintf("              [%04d, %04d] (%04d,%10s){%s}",tkn.line,   tkn.column,   tkn.categ_num,   tkn.categ_nom,   tkn.lexem)
end

function prodToString(prod::Production)
	output = ""

	output = prod.lexem*" -> "

	for i=1:length(prod.subprods)

		for elem in prod.subprods[i]
			if typeof(elem) == Symbol
				output = output*string(elem)
			else
        if Int(elem) == Int(EPSILON)
  		    output = output*lowercase(string(" "))
        else
          output = output*lowercase(string(elem))
        end
			end
			output = output*" "
		end

		if i != length(prod.subprods)
			output = output*" | "
		end
	end
	return output*". \n"
end

max_stars_repo_name: NaelsonDouglas/namelesscompiler

max_issues_repo_name: NaelsonDouglas/namelesscompiler

max_forks_repo_name: NaelsonDouglas/namelesscompiler


text:
# This file is a part of Julia. License is MIT: http://julialang.org/license

function test_all_combos()
    for T in (Dates.Date,Dates.DateTime)
        f1 = T(2014); l1 = T(2013,12,31)
        f2 = T(2014); l2 = T(2014)
        f3 = T(-2000); l3 = T(2000)
        f4 = typemin(T); l4 = typemax(T)

        for P in subtypes(Dates.DatePeriod)
            for pos_step in (P(1),P(2),P(50),P(2048),P(10000))
                # empty range
                dr = f1:pos_step:l1
                @test length(dr) == 0
                @test isempty(dr)
                @test first(dr) == f1
                @test last(dr) < f1
                @test length([i for i in dr]) == 0
                @test_throws ArgumentError minimum(dr)
                @test_throws ArgumentError maximum(dr)
                @test_throws BoundsError dr[1]
                @test findin(dr,dr) == Int64[]
                @test [dr;] == T[]
                @test isempty(reverse(dr))
                @test length(reverse(dr)) == 0
                @test first(reverse(dr)) < f1
                @test last(reverse(dr)) >= f1
                @test issorted(dr)
                @test sortperm(dr) == 1:1:0
                @test !(f1 in dr)
                @test !(l1 in dr)
                @test !(f1-pos_step in dr)
                @test !(l1+pos_step in dr)

                for (f,l) in ((f2,l2),(f3,l3),(f4,l4))
                    dr = f:pos_step:l
                    len = length(dr)
                    @test len > 0
                    @test typeof(len) <: Int64
                    @test !isempty(dr)
                    @test first(dr) == f
                    @test last(dr) <= l
                    @test minimum(dr) == first(dr)
                    @test maximum(dr) == last(dr)
                    @test dr[1] == f
                    @test dr[end] <= l
                    @test next(dr,start(dr)) == (first(dr),1)

                    if len < 10000
                        dr1 = [i for i in dr]
                        @test length(dr1) == len
                        @test findin(dr,dr) == [1:len;]
                        @test length([dr;]) == len
                    end
                    @test !isempty(reverse(dr))
                    @test length(reverse(dr)) == len
                    @test last(reverse(dr)) == f
                    @test issorted(dr)
                    @test f in dr

                end
            end
            for neg_step in (P(-1),P(-2),P(-50),P(-2048),P(-10000))
                # empty range
                dr = l1:neg_step:f1
                @test length(dr) == 0
                @test isempty(dr)
                @test first(dr) == l1
                @test last(dr) > l1
                @test length([i for i in dr]) == 0
                @test_throws ArgumentError minimum(dr)
                @test_throws ArgumentError maximum(dr)
                @test_throws BoundsError dr[1]
                @test findin(dr,dr) == Int64[]
                @test [dr;] == T[]
                @test isempty(reverse(dr))
                @test length(reverse(dr)) == 0
                @test first(reverse(dr)) > l1
                @test last(reverse(dr)) <= l1
                @test issorted(dr)
                @test sortperm(dr) == 1:1:0
                @test !(l1 in dr)
                @test !(l1 in dr)
                @test !(l1-neg_step in dr)
                @test !(l1+neg_step in dr)

                for (f,l) in ((f2,l2),(f3,l3),(f4,l4))
                    dr = l:neg_step:f
                    len = length(dr)
                    @test len > 0
                    @test typeof(len) <: Int64
                    @test !isempty(dr)
                    @test first(dr) == l
                    @test last(dr) >= f
                    @test minimum(dr) == last(dr)
                    @test maximum(dr) == first(dr)
                    @test dr[1] == l
                    @test dr[end] >= f
                    @test next(dr,start(dr)) == (first(dr),1)

                    if len < 10000
                        dr1 = [i for i in dr]
                        @test length(dr1) == len
                        @test findin(dr,dr) == [1:len;]
                        @test length([dr;]) == len
                    end
                    @test !isempty(reverse(dr))
                    @test length(reverse(dr)) == len
                    @test issorted(dr) == (len <= 1)
                    @test l in dr
                end
            end
        end
        if T == Dates.DateTime
            for P in subtypes(Dates.TimePeriod)
                for pos_step in (P(1),P(2),P(50),P(2048),P(10000))
                    # empty range
                    dr = f1:pos_step:l1
                    @test length(dr) == 0
                    @test isempty(dr)
                    @test first(dr) == f1
                    @test last(dr) < f1
                    @test length([i for i in dr]) == 0
                    @test_throws ArgumentError minimum(dr)
                    @test_throws ArgumentError maximum(dr)
                    @test_throws BoundsError dr[1]
                    @test findin(dr,dr) == Int64[]
                    @test [dr;] == T[]
                    @test isempty(reverse(dr))
                    @test length(reverse(dr)) == 0
                    @test first(reverse(dr)) < f1
                    @test last(reverse(dr)) >= f1
                    @test issorted(dr)
                    @test sortperm(dr) == 1:1:0
                    @test !(f1 in dr)
                    @test !(l1 in dr)
                    @test !(f1-pos_step in dr)
                    @test !(l1+pos_step in dr)

                    for (f,l) in ((f2,l2),(f3,l3),(f4,l4))
                        dr = f:pos_step:l
                        len = length(dr)
                        @test len > 0
                        @test typeof(len) <: Int64
                        @test !isempty(dr)
                        @test first(dr) == f
                        @test last(dr) <= l
                        @test minimum(dr) == first(dr)
                        @test maximum(dr) == last(dr)
                        @test dr[1] == f
                        @test dr[end] <= l
                        @test next(dr,start(dr)) == (first(dr),1)

                        if len < 10000
                            dr1 = [i for i in dr]
                            @test length(dr1) == len
                            @test findin(dr,dr) == [1:len;]
                            @test length([dr;]) == len
                        end
                        @test !isempty(reverse(dr))
                        @test length(reverse(dr)) == len
                        @test last(reverse(dr)) == f
                        @test issorted(dr)
                        @test f in dr

                    end
                end
                for neg_step in (P(-1),P(-2),P(-50),P(-2048),P(-10000))
                    # empty range
                    dr = l1:neg_step:f1
                    @test length(dr) == 0
                    @test isempty(dr)
                    @test first(dr) == l1
                    @test last(dr) > l1
                    @test length([i for i in dr]) == 0
                    @test_throws ArgumentError minimum(dr)
                    @test_throws ArgumentError maximum(dr)
                    @test_throws BoundsError dr[1]
                    @test findin(dr,dr) == Int64[]
                    @test [dr;] == T[]
                    @test isempty(reverse(dr))
                    @test length(reverse(dr)) == 0
                    @test first(reverse(dr)) > l1
                    @test last(reverse(dr)) <= l1
                    @test issorted(dr)
                    @test sortperm(dr) == 1:1:0
                    @test !(l1 in dr)
                    @test !(l1 in dr)
                    @test !(l1-neg_step in dr)
                    @test !(l1+neg_step in dr)

                    for (f,l) in ((f2,l2),(f3,l3),(f4,l4))
                        dr = l:neg_step:f
                        len = length(dr)
                        @test len > 0
                        @test typeof(len) <: Int64
                        @test !isempty(dr)
                        @test first(dr) == l
                        @test last(dr) >= f
                        @test minimum(dr) == last(dr)
                        @test maximum(dr) == first(dr)
                        @test dr[1] == l
                        @test dr[end] >= f
                        @test next(dr,start(dr)) == (first(dr),1)

                        if len < 10000
                            dr1 = [i for i in dr]
                            @test length(dr1) == len
                            @test findin(dr,dr) == [1:len;]
                            @test length([dr;]) == len
                        end
                        @test !isempty(reverse(dr))
                        @test length(reverse(dr)) == len
                        @test last(reverse(dr)) >= l
                        @test issorted(dr) == (len <= 1)
                        @test l in dr

                    end
                end
            end
        end
    end
end
test_all_combos()

# All the range representations we want to test
# Date ranges
dr  = Dates.DateTime(2013,1,1):Dates.DateTime(2013,2,1)
dr1 = Dates.DateTime(2013,1,1):Dates.DateTime(2013,1,1)
dr2 = Dates.DateTime(2013,1,1):Dates.DateTime(2012,2,1) # empty range
dr3 = Dates.DateTime(2013,1,1):Dates.Day(-1):Dates.DateTime(2012) # negative step
# Big ranges
dr4 = Dates.DateTime(0):Dates.DateTime(20000,1,1)
dr5 = Dates.DateTime(0):Dates.DateTime(200000,1,1)
dr6 = Dates.DateTime(0):Dates.DateTime(2000000,1,1)
dr7 = Dates.DateTime(0):Dates.DateTime(20000000,1,1)
dr8 = Dates.DateTime(0):Dates.DateTime(200000000,1,1)
dr9 = typemin(Dates.DateTime):typemax(Dates.DateTime)
# Non-default steps
dr10 = typemax(Dates.DateTime):Dates.Day(-1):typemin(Dates.DateTime)
dr11 = typemin(Dates.DateTime):Dates.Week(1):typemax(Dates.DateTime)

dr12 = typemin(Dates.DateTime):Dates.Month(1):typemax(Dates.DateTime)
dr13 = typemin(Dates.DateTime):Dates.Year(1):typemax(Dates.DateTime)

dr14 = typemin(Dates.DateTime):Dates.Week(10):typemax(Dates.DateTime)
dr15 = typemin(Dates.DateTime):Dates.Month(100):typemax(Dates.DateTime)
dr16 = typemin(Dates.DateTime):Dates.Year(1000):typemax(Dates.DateTime)
dr17 = typemax(Dates.DateTime):Dates.Week(-10000):typemin(Dates.DateTime)
dr18 = typemax(Dates.DateTime):Dates.Month(-100000):typemin(Dates.DateTime)
dr19 = typemax(Dates.DateTime):Dates.Year(-1000000):typemin(Dates.DateTime)
dr20 = typemin(Dates.DateTime):Dates.Day(2):typemax(Dates.DateTime)

drs = Any[dr,dr1,dr2,dr3,dr4,dr5,dr6,dr7,dr8,dr9,dr10,
          dr11,dr12,dr13,dr14,dr15,dr16,dr17,dr18,dr19,dr20]
drs2 = map(x->Dates.Date(first(x)):step(x):Dates.Date(last(x)),drs)

@test map(length,drs) == map(x->size(x)[1],drs)
@test map(length,drs) == map(x->length(Dates.Date(first(x)):step(x):Dates.Date(last(x))),drs)
@test map(length,drs) == map(x->length(reverse(x)),drs)
@test all(x->findin(x,x)==[1:length(x);],drs[1:4])
@test isempty(dr2)
@test all(x->reverse(x) == range(last(x), -step(x), length(x)),drs)
@test all(x->minimum(x) == (step(x) < zero(step(x)) ? last(x) : first(x)),drs[4:end])
@test all(x->maximum(x) == (step(x) < zero(step(x)) ? first(x) : last(x)),drs[4:end])
@test all(drs[1:3]) do dd
    for (i,d) in enumerate(dd)
        @test d == (first(dd) + Dates.Day(i-1))
    end
    true
end
@test_throws MethodError dr + 1
a = Dates.DateTime(2013,1,1)
b = Dates.DateTime(2013,2,1)
@test map!(x->x+Dates.Day(1),Array{Dates.DateTime}(32),dr) == [(a+Dates.Day(1)):(b+Dates.Day(1));]
@test map(x->x+Dates.Day(1),dr) == [(a+Dates.Day(1)):(b+Dates.Day(1));]

@test map(x->a in x,drs[1:4]) == [true,true,false,true]
@test a in dr
@test b in dr
@test Dates.DateTime(2013,1,3) in dr
@test Dates.DateTime(2013,1,15) in dr
@test Dates.DateTime(2013,1,26) in dr
@test !(Dates.DateTime(2012,1,1) in dr)

@test all(x->sort(x) == (step(x) < zero(step(x)) ? reverse(x) : x),drs)
@test all(x->step(x) < zero(step(x)) ? issorted(reverse(x)) : issorted(x),drs)

@test length(b:Dates.Day(-1):a) == 32
@test length(b:a) == 0
@test length(b:Dates.Day(1):a) == 0
@test length(a:Dates.Day(2):b) == 16
@test last(a:Dates.Day(2):b) == Dates.DateTime(2013,1,31)
@test length(a:Dates.Day(7):b) == 5
@test last(a:Dates.Day(7):b) == Dates.DateTime(2013,1,29)
@test length(a:Dates.Day(32):b) == 1
@test last(a:Dates.Day(32):b) == Dates.DateTime(2013,1,1)
@test (a:b)[1] == Dates.DateTime(2013,1,1)
@test (a:b)[2] == Dates.DateTime(2013,1,2)
@test (a:b)[7] == Dates.DateTime(2013,1,7)
@test (a:b)[end] == b
@test first(a:Dates.DateTime(20000,1,1)) == a
@test first(a:Dates.DateTime(200000,1,1)) == a
@test first(a:Dates.DateTime(2000000,1,1)) == a
@test first(a:Dates.DateTime(20000000,1,1)) == a
@test first(a:Dates.DateTime(200000000,1,1)) == a
@test first(a:typemax(Dates.DateTime)) == a
@test first(typemin(Dates.DateTime):typemax(Dates.DateTime)) == typemin(Dates.DateTime)

# Date ranges
dr  = Dates.Date(2013,1,1):Dates.Date(2013,2,1)
dr1 = Dates.Date(2013,1,1):Dates.Date(2013,1,1)
dr2 = Dates.Date(2013,1,1):Dates.Date(2012,2,1) # empty range
dr3 = Dates.Date(2013,1,1):Dates.Day(-1):Dates.Date(2012,1,1) # negative step
# Big ranges
dr4 = Dates.Date(0):Dates.Date(20000,1,1)
dr5 = Dates.Date(0):Dates.Date(200000,1,1)
dr6 = Dates.Date(0):Dates.Date(2000000,1,1)
dr7 = Dates.Date(0):Dates.Date(20000000,1,1)
dr8 = Dates.Date(0):Dates.Date(200000000,1,1)
dr9 = typemin(Dates.Date):typemax(Dates.Date)
# Non-default steps
dr10 = typemax(Dates.Date):Dates.Day(-1):typemin(Dates.Date)
dr11 = typemin(Dates.Date):Dates.Week(1):typemax(Dates.Date)
dr12 = typemin(Dates.Date):Dates.Month(1):typemax(Dates.Date)
dr13 = typemin(Dates.Date):Dates.Year(1):typemax(Dates.Date)
dr14 = typemin(Dates.Date):Dates.Week(10):typemax(Dates.Date)
dr15 = typemin(Dates.Date):Dates.Month(100):typemax(Dates.Date)
dr16 = typemin(Dates.Date):Dates.Year(1000):typemax(Dates.Date)
dr17 = typemax(Dates.Date):Dates.Week(-10000):typemin(Dates.Date)
dr18 = typemax(Dates.Date):Dates.Month(-100000):typemin(Dates.Date)
dr19 = typemax(Dates.Date):Dates.Year(-1000000):typemin(Dates.Date)
dr20 = typemin(Dates.Date):Dates.Day(2):typemax(Dates.Date)

drs = Any[dr,dr1,dr2,dr3,dr4,dr5,dr6,dr7,dr8,dr9,dr10,
          dr11,dr12,dr13,dr14,dr15,dr16,dr17,dr18,dr19,dr20]

@test map(length,drs) == map(x->size(x)[1],drs)
@test all(x->findin(x,x) == [1:length(x);], drs[1:4])
@test isempty(dr2)
@test all(x->reverse(x) == last(x):-step(x):first(x),drs)
@test all(x->minimum(x) == (step(x) < zero(step(x)) ? last(x) : first(x)),drs[4:end])
@test all(x->maximum(x) == (step(x) < zero(step(x)) ? first(x) : last(x)),drs[4:end])
@test all(drs[1:3]) do dd
    for (i,d) in enumerate(dd)
        @test d == (first(dd) + Dates.Day(i-1))
    end
    true
end
@test_throws MethodError dr + 1
a = Dates.Date(2013,1,1)
b = Dates.Date(2013,2,1)
@test map!(x->x+Dates.Day(1),Array{Dates.Date}(32),dr) == [(a+Dates.Day(1)):(b+Dates.Day(1));]
@test map(x->x+Dates.Day(1),dr) == [(a+Dates.Day(1)):(b+Dates.Day(1));]

@test map(x->a in x,drs[1:4]) == [true,true,false,true]
@test a in dr
@test b in dr
@test Dates.Date(2013,1,3) in dr
@test Dates.Date(2013,1,15) in dr
@test Dates.Date(2013,1,26) in dr
@test !(Dates.Date(2012,1,1) in dr)

@test all(x->sort(x) == (step(x) < zero(step(x)) ? reverse(x) : x),drs)
@test all(x->step(x) < zero(step(x)) ? issorted(reverse(x)) : issorted(x),drs)

@test length(b:Dates.Day(-1):a) == 32
@test length(b:a) == 0
@test length(b:Dates.Day(1):a) == 0
@test length(a:Dates.Day(2):b) == 16
@test last(a:Dates.Day(2):b) == Dates.Date(2013,1,31)
@test length(a:Dates.Day(7):b) == 5
@test last(a:Dates.Day(7):b) == Dates.Date(2013,1,29)
@test length(a:Dates.Day(32):b) == 1
@test last(a:Dates.Day(32):b) == Dates.Date(2013,1,1)
@test (a:b)[1] == Dates.Date(2013,1,1)
@test (a:b)[2] == Dates.Date(2013,1,2)
@test (a:b)[7] == Dates.Date(2013,1,7)
@test (a:b)[end] == b
@test first(a:Dates.Date(20000,1,1)) == a
@test first(a:Dates.Date(200000,1,1)) == a
@test first(a:Dates.Date(2000000,1,1)) == a
@test first(a:Dates.Date(20000000,1,1)) == a
@test first(a:Dates.Date(200000000,1,1)) == a
@test first(a:typemax(Dates.Date)) == a
@test first(typemin(Dates.Date):typemax(Dates.Date)) == typemin(Dates.Date)

# Non-default step sizes
@test length(typemin(Dates.Date):Dates.Week(1):typemax(Dates.Date)) == 26351950414948059
# Big Month/Year ranges
@test length(typemin(Dates.Date):Dates.Month(1):typemax(Dates.Date)) == 6060531933867600
@test length(typemin(Dates.Date):Dates.Year(1):typemax(Dates.Date)) == 505044327822300
@test length(typemin(Dates.DateTime):Dates.Month(1):typemax(Dates.DateTime)) == 3507324288
@test length(typemin(Dates.DateTime):Dates.Year(1):typemax(Dates.DateTime)) == 292277024

@test length(typemin(Dates.DateTime):Dates.Week(1):typemax(Dates.DateTime)) == 15250284420
@test length(typemin(Dates.DateTime):Dates.Day(1):typemax(Dates.DateTime)) == 106751990938
@test length(typemin(Dates.DateTime):Dates.Hour(1):typemax(Dates.DateTime)) == 2562047782512
@test length(typemin(Dates.DateTime):Dates.Minute(1):typemax(Dates.DateTime)) == 153722866950720
@test length(typemin(Dates.DateTime):Dates.Second(1):typemax(Dates.DateTime)) == 9223372017043200
@test length(typemin(DateTime):Dates.Millisecond(1):typemax(DateTime)) == 9223372017043199001

c = Dates.Date(2013,6,1)
@test length(a:Dates.Month(1):c) == 6
@test [a:Dates.Month(1):c;] == [a + Dates.Month(1)*i for i in 0:5]
@test [a:Dates.Month(2):Dates.Date(2013,1,2);] == [a]
@test [c:Dates.Month(-1):a;] == reverse([a:Dates.Month(1):c;])

@test length(range(Date(2000),366)) == 366
function testlengths(n)
    a = Dates.Date(2000)
    for i = 1:n
        @test length(range(a,i)) == i
    end
    return a+Dates.Day(n)
end
testlengths(100000)

# Custom definition to override default step of DateTime ranges
@test typeof(step(Dates.DateTime(2000):Dates.DateTime(2001))) == Dates.Day

a = Dates.Date(2013,1,1)
b = Dates.Date(2013,2,1)
d = Dates.Date(2020,1,1)
@test length(a:Dates.Year(1):d) == 8
@test first(a:Dates.Year(1):d) == a
@test last(a:Dates.Year(1):d) == d
@test length(a:Dates.Month(12):d) == 8
@test first(a:Dates.Month(12):d) == a
@test last(a:Dates.Month(12):d) == d
@test length(a:Dates.Week(52):d) == 8
@test first(a:Dates.Week(52):d) == a
@test last(a:Dates.Week(52):d) == Dates.Date(2019,12,24)
@test length(a:Dates.Day(365):d) == 8
@test first(a:Dates.Day(365):d) == a
@test last(a:Dates.Day(365):d) == Dates.Date(2019,12,31)

a = Dates.Date(2013,1,1)
b = Dates.Date(2013,2,1)
@test length(a:Dates.Year(1):Dates.Date(2020,2,1)) == 8
@test length(a:Dates.Year(1):Dates.Date(2020,6,1)) == 8
@test length(a:Dates.Year(1):Dates.Date(2020,11,1)) == 8
@test length(a:Dates.Year(1):Dates.Date(2020,12,31)) == 8
@test length(a:Dates.Year(1):Dates.Date(2021,1,1)) == 9
@test length(Dates.Date(2000):Dates.Year(-10):Dates.Date(1900)) == 11
@test length(Dates.Date(2000,6,23):Dates.Year(-10):Dates.Date(1900,2,28)) == 11
@test length(Dates.Date(2000,1,1):Dates.Year(1):Dates.Date(2000,2,1)) == 1

function testyearranges(n)
    a = b = Dates.Date(0)
    for i = 1:n
        @test length(a:Dates.Year(1):b) == i
        b += Dates.Year(1)
    end
end
testyearranges(100000)

function testmonthranges(n)
    a = Dates.Date(1985,12,5)
    b = Dates.Date(1986,12,27)
    c = Dates.DateTime(1985,12,5)
    d = Dates.DateTime(1986,12,27)
    for i = 1:n
        @test length(a:Dates.Month(1):b) == 13
        @test length(a:Dates.Year(1):b) == 2
        @test length(c:Dates.Month(1):d) == 13
        @test length(c:Dates.Year(1):d) == 2
        a += Dates.Day(1)
        b += Dates.Day(1)
    end
    return b
end
testmonthranges(10000)

function testmonthranges2(n)
    a = b = Dates.Date(2000)
    for i = 1:n
        @test length(a:Dates.Month(1):b) == i
        b += Dates.Month(1)
    end
    return b
end
testmonthranges2(100000)

@test length(Dates.Year(1):Dates.Year(10)) == 10
@test length(Dates.Year(10):Dates.Year(-1):Dates.Year(1)) == 10
@test length(Dates.Year(10):Dates.Year(-2):Dates.Year(1)) == 5
@test_throws OverflowError length(typemin(Dates.Year):typemax(Dates.Year))
@test_throws MethodError Dates.Date(0):Dates.DateTime(2000)
@test_throws MethodError Dates.Date(0):Dates.Year(10)
@test length(range(Dates.Date(2000),366)) == 366
@test last(range(Dates.Date(2000),366)) == Dates.Date(2000,12,31)
@test last(range(Dates.Date(2001),365)) == Dates.Date(2001,12,31)
@test last(range(Dates.Date(2000),367)) == last(range(Dates.Date(2000),Dates.Month(12),2)) == last(range(Dates.Date(2000),Dates.Year(1),2))
@test last(range(Dates.DateTime(2000),Dates.Day(366),2)) == last(range(Dates.DateTime(2000),Dates.Hour(8784),2))

# Issue 5
lastdaysofmonth = [Dates.Date(2014,i,Dates.daysinmonth(2014,i)) for i=1:12]
@test [Date(2014,1,31):Dates.Month(1):Date(2015);] == lastdaysofmonth

# Range addition/subtraction:
let d = Dates.Day(1)
    @test (Dates.Date(2000):d:Dates.Date(2001))+d == (Dates.Date(2000)+d:d:Dates.Date(2001)+d)
    @test (Dates.Date(2000):d:Dates.Date(2001))-d == (Dates.Date(2000)-d:d:Dates.Date(2001)-d)
end


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

name = "Lz4"
version = v"1.9.2"

# Collection of sources required to build Lz4
sources = [
    ArchiveSource("https://github.com/lz4/lz4/archive/v$(version).tar.gz",
                  "658ba6191fa44c92280d4aa2c271b0f4fbc0e34d249578dd05e50e76d0e5efcc")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/lz4-*/
make -j${nproc} CFLAGS="-O3 -fPIC"
make install
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()

# The products that we will ensure are always built
products = [
    LibraryProduct(["liblz4", "msys-lz4"], :liblz4),
    ExecutableProduct("lz4", :lz4),
    ExecutableProduct("lz4c", :lz4c),
    ExecutableProduct("lz4cat", :lz4cat),
    ExecutableProduct("unlz4", :unlz4),
]

# Dependencies that must be installed before this package can be built
dependencies = [
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)

max_stars_repo_name: PallHaraldsson/Yggdrasil

max_issues_repo_name: PallHaraldsson/Yggdrasil

max_forks_repo_name: PallHaraldsson/Yggdrasil


text:
import Maps
using Test

@testset "earth globe" begin
    scene = (Maps.globe())
end
@testset "mars globe" begin
    display(Maps.globe(Maps.mars_img()))
end

@testset "usa small" begin
    display(Maps.usa(0.001))
end
@testset "usa default" begin
    display(Maps.usa())
end


text:
#Following Hamilton(1994)
#TODO: Implement for omega =/= Identity

#data: lines are different dates, columns are different variables!

function loglike(PI,data)
    T = size(data,1)
    n = size(data,2)
    if(size(PI,1) != n)
        @info "Dimensions do not match"
        return 99999999
    end
    bloc1 = -(T*n)/2*log(2*pi)
    aux1 = data[2,:] - PI'*data[1,:]
    sum_like = aux1'*aux1
    for j in 2:(T-1)
        aux1 = data[j+1,:] - PI'*data[j,:]
        sum_like = sum_like + aux1'*aux1
    end
    bloc3 = -1/2*sum_like
end

max_stars_repo_name: danmrc/DSGE-HMC

max_issues_repo_name: danmrc/DSGE-HMC

max_forks_repo_name: danmrc/DSGE-HMC


text:
function triangular_window(n)
    if iseven(n)
        W_f = range(0, stop = n/2 - 1)
        W_r = range(n/2, stop = n - 1)

        W_f = W_f/(n/2)
        W_r = -(W_r/(n/2)) .+ 2

        return vcat(W_f, W_r)
    else

    end
end

function hamming_window(n)

end

function hanning_window(n)

    W = range(0, stop=n-1)
    W = W .* 2 * pi / n
    W = -0.5 * broadcast(cos, W) .+ 0.5

    return W
end

function window(type, n)
    if type == "triangle"
        return triangular_window(n)
    elseif type == "hamming"
        return hamming_window(n)
    elseif type == "hanning"
        return hanning_window(n)
    end
end


text:
"""
    Nilplexification{T <: Number} <: Plexification{T}

A nilplexification as a pair.
"""
struct Nilplexification{T <: Number} <: Plexification{T}
    l::T
    r::T
end

function (==)(x::Nilplexification, y::Nilplexification)
    x.l == y.l && x.r == y.r
end

function real(z::Nilplexification)
    real(z.l)
end

function zero(::Type{Nilplexification{T}}) where T <: Number
    Nilplexification{T}(zero(T), zero(T))
end

function zero(::Nilplexification{T}) where T <: Number
    zero(Nilplexification{T})
end

function one(::Type{Nilplexification{T}}) where T <: Number
    Nilplexification{T}(one(T), zero(T))
end

function one(::Nilplexification{T}) where T <: Number
    one(Nilplexification{T})
end

function (-)(z::Nilplexification)
    Nilplexification(-(z.l), -(z.r))
end

function (+)(x::Nilplexification{T}, y::Nilplexification{T}) where T <: Number
    Nilplexification{T}(x.l + y.l, x.r + y.r)
end

function (+)(a::T, z::Nilplexification{T}) where T <: Number
    Nilplexification{T}(a + z.l, z.r)
end

function (+)(z::Nilplexification{T}, a::T) where T <: Number
    Nilplexification{T}(z.l + a, z.r)
end

function (+)(a::Real, z::Nilplexification)
    Nilplexification(a + z.l, z.r)
end

function (+)(z::Nilplexification, a::Real)
    Nilplexification(z.l + a, z.r)
end

function (-)(x::Nilplexification{T}, y::Nilplexification{T}) where T <: Number
    Nilplexification{T}(x.l - y.l, x.r - y.r)
end

function (-)(a::T, z::Nilplexification{T}) where T <: Number
    Nilplexification{T}(a - z.l, -(z.r))
end

function (-)(z::Nilplexification{T}, a::T) where T <: Number
    Nilplexification{T}(z.l - a, z.r)
end

function (-)(a::Real, z::Nilplexification)
    Nilplexification(a - z.l, -(z.r))
end

function (-)(z::Nilplexification, a::Real)
    Nilplexification(z.l - a, z.r)
end

function (*)(x::Nilplexification{T}, y::Nilplexification{T}) where T <: Number
    Nilplexification{T}(
        (x.l * y.l),
        (x.l * y.r) + (x.r * y.l)
    )
end

function (*)(a::T, z::Nilplexification{T}) where T <: Number
    Nilplexification{T}(a * z.l, a * z.r)
end

function (*)(z::Nilplexification{T}, a::T) where T <: Number
    Nilplexification{T}(z.l * a , z.r * a)
end

function (*)(a::Real, z::Nilplexification)
    Nilplexification(a * z.l, a * z.r)
end

function (*)(z::Nilplexification, a::Real)
    Nilplexification(z.l * a, z.r * a)
end

function (/)(z::Nilplexification, a::Real)
    if iszero(a)
        error(ZeroDenominator)
    end

    Nilplexification(z.l / a, z.r / a)
end

function (\)(a::Real, z::Nilplexification)
    if iszero(a)
        error(ZeroDenominator)
    end

    Nilplexification(a \ z.l, a \ z.r)
end


text:
using HypothesisTests
# ------------------------------------------------------------------------------------------------ #
#                        Plot inference (consider changing to series recipe)                       #
# ------------------------------------------------------------------------------------------------ #
# This one takes a time series and moves all the way through to esimation, plotting relevant stuff
# Plots best in pyplot()
@userplot ParameterEstimate
@recipe function f(P::ParameterEstimate; cluster=false, tswindows=(length(P.args[1].timeseries) > 10000), normalisef=false, textcolor=:black, featurecolor=cgrad(:RdYlBu_11, 7, categorical = true))
    I = P.args[1]
    legend --> false
    #link := :x
    grid --> false
    layout --> @layout [
        x
        F
        P
    ]
    size --> (800, 500)
    left_margin --> 10Plots.mm
    right_margin --> 25Plots.mm

    windowCentres = round.(I.windowCentres)
# ------------------------------------------ Time series ----------------------------------------- #
    t = NonstationaryProcesses.timeDims(I.timeseries)
    # ! Doesnt work with overlapping windows
    if tswindows
        @series begin
            seriestype := :tswindows
            subplot := 1
            yguide --> "Time Series"
            xguide := ""
            framestyle := :box
            N --> size(I.windowedTimeseries, 1) #Int(round(mean((collect(I.windowEdges[2:end]) .- collect(I.windowEdges[1:end-1])))))
            yaxis --> nothing
            xaxis --> nothing
            top_margin --> 3Plots.mm
            ymax = round(max(I.timeseries...),  sigdigits=3)
            ymin = round(min(I.timeseries...),  sigdigits=3)
            annotations := [(max(t...)*1.01, ymin, text("$ymin", textcolor, :left, 8)),
            (max(t...)*1.01, ymax, text("$ymax", textcolor, :left, 8))]
            xlims := extrema(t)
            (t, I.timeseries)
        end
    else
        @series begin
            seriestype := :path
            subplot := 1
            yguide --> "Time Series"
            xguide := ""
            framestyle := :box
            yaxis --> nothing
            xaxis --> nothing
            top_margin --> 3Plots.mm
            seriescolor := :black
            ymax = max(I.timeseries...)
            ymin = min(I.timeseries...)
            ymax -= 0.05*(ymax-ymin)
            ymin += 0.05*(ymax-ymin)
            ymax = round(ymax,  sigdigits=3)
            ymin = round(ymin,  sigdigits=3)
            annotations:= [(max(t...)*1.01, ymin, text("$ymin",  textcolor, :left, 8)),
            (max(t...)*1.01, ymax, text("$ymax", textcolor, :left, 8))]
            xlims := extrema(t)
            x := t
            y := I.timeseries
        end
    end

# ------------------------------------------- Features ------------------------------------------- #
    # Need to edit the plot attributes of this subplot in the last series of this recipe
    F = I.F̂
    if cluster
        #D = StatsBase.corspearman(F')
        #idxs = clusterDistances(D, linkageMetric=:average, branchOrder=:optimal)
        idxs = clusterPairwise(F, CorrDist(), linkageMetric=:average, branchOrder=:optimal, dim=1)
        clusterF = F[idxs, :]
    else
        ρ = (mapslices(x -> corspearman(x, I.parameters[Int.(windowCentres)]), F, dims=2))
        idxs = sortperm(ρ[:], rev=true)
        clusterF = F[idxs, :]
    end
    if normalisef
        clusterF = sigmoidNormalise(clusterF)
    else
        clusterF = normalise(clusterF, centre, 2)
    end
    @series begin
        seriestype := :heatmap
        subplot := 2
        seriescolor := featurecolor
        clim = max(abs.(extrema(clusterF))...)
        clims := (-clim, clim)
        try
            println("The clustered features are:\n")
            display.(Catch22.featureDims(clusterF))
        catch
            @warn "Could not display clustered features, probably because the feature matrix is not a FeatureMatrix"
        end
        #clusterReorder(F, CorrDist(), linkageMetric=:average, branchOrder=:optimal, dim=1)
        (x, y, X) = (NonstationaryProcesses.timeDims(I.timeseries)[Int.(windowCentres)], 1:size(clusterF, 1), clusterF)
    end

# ------------------------------------------ Parameters ------------------------------------------ #

    @series begin
        seriestype := :path
        subplot := 3
        yaxis := nothing
        seriescolor := :black
        xlims := extrema(t)
        (x, y) = (t, I.parameters)
    end
    pmax = round(max(I.parameters...), sigdigits=3)
    pmin = round(min(I.parameters...), sigdigits=3)
    inset_subplots := (3, bbox(0,0,1,1))
    @series begin
        seriestype := :scatter
        seriescolor := :black
        xguide --> "Time"
        yguide --> "Parameters"
        framestyle := :box
        yaxis := nothing
        xaxis := nothing
        background_color_inside := nothing
        background_color_subplot := nothing
        p = I.estimates
        if StatsBase.corspearman(p, I.parameters[Int.(windowCentres)]) < 0
            @warn "It looks like the estimated parameters are the negative of the true parameters. This is not unexpected, so flipping for visualisation."
            p = -p
        end
        ymax = max(p...)
        ymin = min(p...)
        ymax += 0.05*(ymax-ymin)
        ymin -= 0.05*(ymax-ymin)
        ylims := (ymin, ymax)
        ymax -= 0.1*(ymax-ymin)
        ymin += 0.1*(ymax-ymin)
        xs = length(p)*1.01
        ρₚ = round(corspearman(I.parameters[Int.(windowCentres)], I.estimates); sigdigits=3)
        annotations:= [(xs, ymin, text("$pmin", textcolor, :left, 8)),
                        (xs, ymax, text("$pmax", textcolor, :left, 8)),
                        (xs, (ymin+ymax)/2, text("ρ = $ρₚ", textcolor, :left, 11))]
        xlims := (0, length(p)) # These go in centres of windows

        (x, y) = (0.5:1:length(p)-0.5, p)
    end

# -------------------------------- Add windows to the feature plot ------------------------------- #
    @series begin
        seriescolor := :black
        seriestype := :vline
        subplot := 2
        framestyle := :box
        colorbar --> nothing
        ymax = length(ρ)+0.5
        ymin = 0.5
        ymax -= 0.05*(ymax-ymin)
        ymin += 0.05*(ymax-ymin)
        if cluster == false
            notnani = ρ[.!isnan.(ρ)]
            ρmin = round(min(notnani...), sigdigits=3)
            ρmax = round(max(notnani...), sigdigits=3)
            annotations:= [(max(NonstationaryProcesses.timeDims(I.timeseries)...)*1.01, ymax, text("ρ = $ρmin", textcolor, :left, 8)),
                        (max(NonstationaryProcesses.timeDims(I.timeseries)...)*1.01,  ymin, text("ρ = $ρmax", textcolor, :left, 8))]
        end
        yaxis := nothing
        xaxis := nothing
        yflip := true
        yguide --> "Features"
        framestyle := :box
        #xlims := extrema(dims(I.timeseries, Ti).val)
        ylims := (0.5, length(idxs)+0.5)
        if length(I.windowedTimeseries) <= length(I.timeseries) # i.e. no overlap
            x = NonstationaryProcesses.timeDims(I.timeseries)[I.windowEdges]
        else
            x = [NaN]
        end
    end
end

# ------------------------------------------------------------------------------------------------ #
#                                        Baseline Comparison                                       #
# ------------------------------------------------------------------------------------------------ #

@userplot BaselineComparison
@recipe function f(P::BaselineComparison; features=catch24, parameters=1, var=1, tswindows=(length(timeseries(P.args[1])) > 10000), orthonormalise=false)
    S = P.args[1]
    Fₕ = P.args[2]
    Fₗ = P.args[3]

    baselines = [
        "Standardised"
        "Low dim. baseline"
        "High dim. baseline"
        "Interval baseline"
    ]

    if orthonormalise == :orthonormalise || (orthonormalise isa Bool && orthonormalise)
        # Orthogonalise and then scale
        𝑜 = orthogonaliseto(Fₕ, principalcomponents)
        I_a = [
            infer(S, var; parameters, features, baseline=standardbaseline(), normalisation=𝑜), # No baseline
            infer(S, var; parameters, features, baseline=lowbaseline(𝑜(Fₗ)), normalisation=𝑜), # Low
            infer(S, var; parameters, features, baseline=highbaseline(𝑜(Fₕ)), normalisation=𝑜), # High
            infer(S, var; parameters, features, baseline=intervalbaseline(𝑜(Fₗ), 𝑜(Fₕ)), normalisation=𝑜)  # Both
        ]
    elseif orthonormalise == :orthogonalise
        I_a = [
            infer(S, var; parameters, features, baseline=orthogonaliseto(standardbaseline()(Fₕ)), normalisation=standardbaseline()), # No baseline
            infer(S, var; parameters, features, baseline=orthogonaliseto(lowbaseline(Fₗ)(Fₕ)), normalisation=lowbaseline(Fₗ)), # Low
            infer(S, var; parameters, features, baseline=orthogonaliseto(highbaseline(Fₕ)(Fₕ)), normalisation=highbaseline(Fₕ)), # High
            infer(S, var; parameters, features, baseline=orthogonaliseto(intervalbaseline(Fₗ, Fₕ)(Fₕ)), normalisation=intervalbaseline(Fₗ, Fₕ))  # Both
        ]
    elseif orthonormalise == :ranksum_orthogonalise
        # ! Not done ------------------------------->
        𝑜 = orthogonaliseto(Fₕ, principalcomponents)
        F̂ₕ, F̂ₗ = 𝑜.((Fₕ, Fₗ))
        p = zeros(size(F̂ₕ, 1))
        for i = 1:size(F̂ₕ, 1)
            if all(F̂ₗ[i, :] .== F̂ₗ[i, 1]) # The low baseline is constant, so use a one-sample t-test
                p[i] = pvalue(OneSampleTTest(F̂ₗ[i, :], F̂ₕ[i, :]))
            else
                p[i] = pvalue(MannWhitneyUTest(F̂ₗ[i, :], F̂ₕ[i, :]))
            end
        end
        display(histogram(Fₕ))
        show(p)

        I_a = [
            infer(S, var; parameters, features, baseline=orthogonaliseto(standardbaseline()(Fₕ)), normalisation=standardbaseline()), # No baseline
            infer(S, var; parameters, features, baseline=orthogonaliseto(lowbaseline(Fₗ)(Fₕ)), normalisation=lowbaseline(Fₗ)), # Low
            infer(S, var; parameters, features, baseline=orthogonaliseto(highbaseline(Fₕ)(Fₕ)), normalisation=highbaseline(Fₕ)), # High
            infer(S, var; parameters, features, baseline=orthogonaliseto(intervalbaseline(Fₗ, Fₕ)(Fₕ)), normalisation=intervalbaseline(Fₗ, Fₕ))  # Both
        ]
    elseif orthonormalise == :truncate3
        # ! Not done ------------------------------->
        𝑜 = orthogonaliseto(Fₕ, principalcomponents)
        F̂ₕ, F̂ₗ = 𝑜.((Fₕ, Fₗ))

        idxs = partialsortperm(vec(StatsBase.std(F̂ₕ, dims=2)), 1:3, rev=true)

        F̂ₕ = F̂ₕ[idxs, :]
        F̂ₗ = F̂ₗ[idxs, :]

        I_a = [
            infer(S, var; parameters, features, baseline=standardbaseline()∘(X -> X[idxs, :]), normalisation=orthogonaliseto(Fₕ), filter=identity), # No baseline
            infer(S, var; parameters, features, baseline=lowbaseline(F̂ₗ)∘(X -> X[idxs, :]), normalisation=orthogonaliseto(Fₕ), filter=identity), # Low
            infer(S, var; parameters, features, baseline=highbaseline(F̂ₕ)∘(X -> X[idxs, :]), normalisation=orthogonaliseto(Fₕ), filter=identity), # High
            infer(S, var; parameters, features, baseline=intervalbaseline(F̂ₗ, F̂ₕ)∘(X -> X[idxs, :]), normalisation=orthogonaliseto(Fₕ), filter=identity)  # Both
        ]
    elseif orthonormalise == :totalcovariance
        function projectedtotalcovariance(𝑏::Function)
            M = principalcomponents(Array(𝑏(Fₕ)))
            𝑜 = orthogonaliseto(𝑏(Fₕ), principalcomponents)
            Σₕ² = StatsBase.cov(𝑏(Fₕ), dims=2)
            T = Array(sum(abs.(Σₕ²), dims=2))
            T′ = projection(M)'*Diagonal(T[:])*projection(M) # Don't want to subtract means, just want the rotation
            # Will want to rethink this formula, since we are now ignoring the off-diagonal terms.
            #T′ = sqrt.(diag(T′))
            g = X -> FeatureMatrix(inv(T′)*Array(X), getnames(X))
            return g∘𝑜
        end
        I_a = [
            infer(S, var; parameters, features, baseline=projectedtotalcovariance(standardbaseline()), normalisation=standardbaseline(), filter=identity), # No baseline
            infer(S, var; parameters, features, baseline=projectedtotalcovariance(lowbaseline(Fₗ)), normalisation=lowbaseline(Fₗ), filter=identity), # Low
            infer(S, var; parameters, features, baseline=projectedtotalcovariance(highbaseline(Fₕ)), normalisation=highbaseline(Fₕ), filter=identity), # High
            infer(S, var; parameters, features, baseline=projectedtotalcovariance(intervalbaseline(Fₗ, Fₕ)), normalisation=intervalbaseline(Fₗ, Fₕ), filter=identity)  # Both
        ]
    elseif orthonormalise == :dependencyscaling
        #! This should be identical to :totalcovariance
        function dependencyscaling(𝑏, Fₕ)
            Fₕ′ = 𝑏(Fₕ)
            Σₕ² = StatsBase.cov(Array(Fₕ′), dims=2)
            𝑜 = orthogonaliseto(Fₕ′, principalcomponents)
            𝐧 = sum(abs.(Array(Σₕ²)), dims=2)
            N⁻¹ = FeatureMatrix(inv(sqrt(Diagonal(𝐧[:]))), getnames(Fₕ′))
            return F -> FeatureMatrix(𝑜(N⁻¹*𝑏(F)), getnames(F))
        end
        I_a = [
            infer(S, var; parameters, features, baseline=dependencyscaling(standardbaseline(), Fₕ)), # No baseline
            infer(S, var; parameters, features, baseline=dependencyscaling(lowbaseline(Fₗ), Fₕ)), # Low
            infer(S, var; parameters, features, baseline=dependencyscaling(highbaseline(Fₕ), Fₕ)), # High
            infer(S, var; parameters, features, baseline=dependencyscaling(intervalbaseline(Fₗ, Fₕ), Fₕ))  # Both
        ]
    elseif orthonormalise == :dependencyscalingnorotation
        #! This should be identical to :dependencyscaling
        function dependencyscalingnorotation(𝑏, Fₕ)
            Fₕ′ = 𝑏(Fₕ)
            Σₕ² = StatsBase.cov(Array(Fₕ′), dims=2)
            𝑜 = orthogonaliseto(Fₕ′, principalcomponents)
            𝐧 = sum(abs.(Array(Σₕ²)), dims=2)
            N⁻¹ = FeatureMatrix(inv(sqrt(Diagonal(𝐧[:]))), getnames(Fₕ′))
            return F -> FeatureMatrix(N⁻¹*𝑏(F), getnames(F))
        end
        I_a = [
            infer(S, var; parameters, features, baseline=dependencyscalingnorotation(standardbaseline(), Fₕ)), # No baseline
            infer(S, var; parameters, features, baseline=dependencyscalingnorotation(lowbaseline(Fₗ), Fₕ)), # Low
            infer(S, var; parameters, features, baseline=dependencyscalingnorotation(highbaseline(Fₕ), Fₕ)), # High
            infer(S, var; parameters, features, baseline=dependencyscalingnorotation(intervalbaseline(Fₗ, Fₕ), Fₕ))  # Both
        ]
    elseif orthonormalise == :whiten
        function whitento(𝑏, Fₕ)
            Fₕ′ = 𝑏(Fₕ)
            𝑜 = orthogonaliseto(Fₕ′, principalcomponents)
            𝐧 = sum(abs.(Array(Σₕ²)), dims=2)
            N⁻¹ = FeatureMatrix(inv(sqrt(Diagonal(𝐧[:]))), getnames(Fₕ′))
            return F -> FeatureMatrix(N⁻¹*𝑏(F), getnames(F))
        end
        I_a = [
            infer(S, var; parameters, features, baseline=dependencyscalingnorotation(standardbaseline(), Fₕ)), # No baseline
            infer(S, var; parameters, features, baseline=dependencyscalingnorotation(lowbaseline(Fₗ), Fₕ)), # Low
            infer(S, var; parameters, features, baseline=dependencyscalingnorotation(highbaseline(Fₕ), Fₕ)), # High
            infer(S, var; parameters, features, baseline=dependencyscalingnorotation(intervalbaseline(Fₗ, Fₕ), Fₕ))  # Both
        ]
    elseif orthonormalise == :errororthonormalise
            # Orthogonalise and then scale, but using the error interval for the high and zero dim scaling
            𝑜 = orthogonaliseto(Fₕ, principalcomponents)
            I_a = [
                infer(S, var; parameters, features, baseline=standardbaseline(), normalisation=𝑜), # No baseline
                infer(S, var; parameters, features, baseline=lowbaseline(𝑜(Fₗ)), normalisation=𝑜), # Low
                infer(S, var; parameters, features, baseline=highbaseline(𝑜(Fₕ)), normalisation=𝑜), # High
                infer(S, var; parameters, features, baseline=errorintervalbaseline(𝑜(Fₗ), 𝑜(Fₕ)), normalisation=𝑜)  # Both
            ]
    else
        I_a = [
            infer(S, var; parameters, features, baseline=standardbaseline()), # No baseline
            infer(S, var; parameters, features, baseline=lowbaseline(Fₗ)), # Low
            infer(S, var; parameters, features, baseline=highbaseline(Fₕ)), # High
            infer(S, var; parameters, features, baseline=intervalbaseline(Fₗ, Fₕ))  # Both
        ]
    end
    cluster=false
    normalisef=false
    legend --> false
    #link := :x
    grid --> false
    layout --> @layout [
        x{0.2h}
        [a; b] [c; d]
        [d; e] [f; g]
    ]
    size --> (1000, 1000)
    left_margin --> 20Plots.mm
    right_margin --> 20Plots.mm

    # Do a quick inference for quick access to time series
    I = infer(S, var; parameters, features, baseline=identity, normalisation=identity)

    windowCentres = round.((I.windowEdges[1:end-1] + I.windowEdges[2:end])./2)
# ------------------------------------------ Time series ----------------------------------------- #
    t = NonstationaryProcesses.timeDims(I.timeseries)
    if tswindows
        @series begin
            seriestype := :tswindows
            subplot := 1
            # yguide --> "Time Series"
            xguide := ""
            framestyle := :box
            N --> Int(round(mean((collect(I.windowEdges[2:end]) .- collect(I.windowEdges[1:end-1])))))
            yaxis --> nothing
            xaxis --> nothing
            top_margin --> 3Plots.mm
            ymax = round(max(I.timeseries...),  sigdigits=3)
            ymin = round(min(I.timeseries...),  sigdigits=3)
            annotations := [(max(t...)*1.01, ymin, text("$ymin", :black, :left, 8)),
            (max(t...)*1.01, ymax, text("$ymax", :black, :left, 8))]
            xlims := extrema(t)
            (t, I.timeseries)
        end
    else
        @series begin
            seriestype := :path
            subplot := 1
            # yguide --> "Time Series"
            xguide := ""
            framestyle := :box
            yaxis --> nothing
            xaxis --> nothing
            top_margin --> 3Plots.mm
            seriescolor := :black
            ymax = max(I.timeseries...)
            ymin = min(I.timeseries...)
            ymax -= 0.05*(ymax-ymin)
            ymin += 0.05*(ymax-ymin)
            ymax = round(ymax,  sigdigits=3)
            ymin = round(ymin,  sigdigits=3)
            annotations:= [(max(t...)*1.01, ymin, text("$ymin", :black, :left, 8)),
            (max(t...)*1.01, ymax, text("$ymax", :black, :left, 8))]
            xlims := extrema(t)
            x := t
            y := I.timeseries
        end
    end

# ------------------------------------------- Features ------------------------------------------- #
    bb = [1, 5, 3, 7]
    bbb = [2, 6, 4, 8]
    bbbb = [9, 10, 11, 12]
    inset_subplots := [(x+1, bbox(0,0,1,1)) for x ∈ bbb]
    for b ∈ 1:4
        I = I_a[b]
        F = I.F̂
        if cluster
            #D = StatsBase.corspearman(F')
            #idxs = clusterDistances(D, linkageMetric=:average, branchOrder=:optimal)
            idxs = clusterPairwise(F, CorrDist(), linkageMetric=:average, branchOrder=:optimal, dim=1)
            clusterF = F[idxs, :]
        else
            ρ = (mapslices(x -> corspearman(x, I.parameters[Int.(windowCentres)]), F, dims=2))
            idxs = sortperm(ρ[:], rev=true)
            clusterF = F[idxs, :]
        end
        if normalisef
            clusterF = sigmoidNormalise(clusterF)
        else
            clusterF = normalise(clusterF, centre, 2)
        end
        @series begin
            seriestype := :heatmap
            framestyle := :box
            title := baselines[b]
            colorbar --> nothing
            ymax = length(ρ)+0.5
            ymin = 0.5
            ymax -= 0.05*(ymax-ymin)
            ymin += 0.05*(ymax-ymin)
            if !cluster
                ρmin = round(min(ρ...), sigdigits=3)
                ρmax = round(max(ρ...), sigdigits=3)
                annotations:= [(max(NonstationaryProcesses.timeDims(I.timeseries)...)*1.01, ymax, text("ρ = $ρmin", :black, :left, 8)),
                            (max(NonstationaryProcesses.timeDims(I.timeseries)...)*1.01,  ymin, text("ρ = $ρmax", :black, :left, 8))]
            end
            yaxis := nothing
            xaxis := nothing
            yflip := true
            # if b == 1
            #     yguide := "Features"
            # end
            framestyle := :box
            #xlims := extrema(dims(I.timeseries, Ti).val)
            ylims := (0.5, length(idxs)+0.5)
            subplot := bb[b]+1
            seriescolor := cgrad(:RdYlBu_11, 7, categorical = true)
            clim = max(abs.(extrema(clusterF))...)
            clims := (-clim, clim)
            println("The clustered features are:")
            display.(Catch22.featureDims(clusterF))
            print("\n")
            #clusterReorder(F, CorrDist(), linkageMetric=:average, branchOrder=:optimal, dim=1)
            (x, y, X) = (NonstationaryProcesses.timeDims(I.timeseries)[Int.(windowCentres)], 1:size(clusterF, 1), clusterF)
        end

        @series begin
            seriestype := :path
            subplot := bbb[b]+1
            yaxis := nothing
            seriescolor := :black
            xlims := extrema(t)
            (x, y) = (t, I.parameters)
        end
        pmax = round(max(I.parameters...), sigdigits=3)
        pmin = round(min(I.parameters...), sigdigits=3)
        @series begin
            seriestype := :scatter
            seriescolor := :black
            # xguide --> "Time"
            subplot := bbbb[b]+1
            framestyle := :box
            yaxis := nothing
            xaxis := nothing
            background_color_inside := nothing
            background_color_subplot := nothing
            p = I.estimates
            if StatsBase.corspearman(p, I.parameters[Int.(windowCentres)]) < 0
                @warn "It looks like the estimated parameters are the negative of the true parameters. This is not unexpected, so flipping for visualisation."
                p = -p
            end
            ymax = max(p...)
            ymin = min(p...)
            ymax += 0.05*(ymax-ymin)
            ymin -= 0.05*(ymax-ymin)
            ylims := (ymin, ymax)
            ymax -= 0.1*(ymax-ymin)
            ymin += 0.1*(ymax-ymin)
            xs = length(p)*1.01

            ρₚ = round(corspearman(I.parameters[Int.(windowCentres)], I.estimates); sigdigits=3)
            markercolor := cgrad([:crimson, :forestgreen], LinRange(0, 1, 256))[round(Int, abs(ρₚ)*255)+1]
            markerstrokewidth := 0.0
            annotations:= [(xs, ymin, text("$pmin", :black, :left, 8)),
            (xs, ymax, text("$pmax", :black, :left, 8)),
            (xs, (ymin+ymax)/2, text("ρ = $ρₚ", :black, :left, 8))]
            # if bbb[b] < 5
            #     yguide := "Parameters"
            # end
            xlims := (0, length(p)) # These go in centres of windows

            (x, y) = (0.5:1:length(p)-0.5, p)
        end
    end
end


text:
using GuidedProposals, DiffusionDefinition, ObservationSchemes
using OrdinaryDiffEq, StaticArrays
using ForwardDiff, Random
using Test
const DD = DiffusionDefinition
const OBS = ObservationSchemes
const GP = GuidedProposals

@testset "GuidedProposals.jl" begin
    Random.seed!(10)
    # Write your own tests here.
    @load_diffusion LotkaVolterraAux

    function DD.B!(save_to, t, P::LotkaVolterraAux)
        save_to[1,1] = 0.0
        save_to[1,2] = -P.β * P.γ/P.δ
        save_to[2,1] = P.α * P.δ/P.β
        save_to[2,2] = 0.0
    end

    function DD.β!(save_to, t, P::LotkaVolterraAux)
        save_to[1] = P.γ*P.α/P.δ
        save_to[2] = -P.α*P.γ/P.β
    end

    function DD.σ!(save_to, t, P::LotkaVolterraAux)
        save_to[1,1] = P.σ1
        save_to[1,2] = 0.0
        save_to[2,1] = 0.0
        save_to[2,2] = P.σ2
    end

    function DD.a!(save_to, t, P::LotkaVolterraAux)
        save_to[1,1] = P.σ1^2
        save_to[1,2] = 0.0
        save_to[2,1] = 0.0
        save_to[2,2] = P.σ2^2
    end

    Base.eltype(::LotkaVolterraAux{T}) where T = T

    P = LotkaVolterraAux(
        2.0/3.0, 4.0/3.0, 1.0, 1.0, 0.2, 0.2, 0.0, 0.0, nothing
    )

    function build_params(mode, obs, Σ; t0=0)
        params_intv1 = (
            tt = (t0+0.0):0.01:(t0+1.0),
            P_aux = P,
            P_target = LotkaVolterraAux,
            obs = OBS.LinearGsnObs(t0+1.0, obs; Σ=Σ),
            solver_choice=(
                solver=Tsit5(),
                ode_type=:HFc,
                convert_to_HFc=false,
                mode=mode,
                gradients=false,
                eltype=Float64,
            )
        )
    end

    gp2_inplace = GuidProp(
        build_params(:inplace, [1.0, 2.0], [1.0 0.0; 0.0 1.0]; t0=0.0)...
    )
    gp1_inplace = GuidProp(
        build_params(:inplace, [2.0, 3.0], [1.0 0.0; 0.0 1.0]; t0=1.0)...,
        next_guided_prop=gp2_inplace
    )

    gp1_inplace_recomputed = deepcopy(gp1_inplace)
    gp2_inplace_recomputed = deepcopy(gp2_inplace)

    recompute_guiding_term!(gp2_inplace_recomputed, nothing)
    recompute_guiding_term!(gp1_inplace_recomputed, gp2_inplace_recomputed)

    gp2_static = GuidProp(
        build_params(:outofplace, (@SVector [1.0, 2.0]), SDiagonal(1.0, 1.0); t0=0.0)...
    )
    gp1_static = GuidProp(
        build_params(:outofplace, (@SVector [2.0, 3.0]), SDiagonal(1.0, 1.0); t0=1.0)...,
        next_guided_prop=gp2_static
    )

    gp1_static_recomputed = deepcopy(gp1_static)
    gp2_static_recomputed = deepcopy(gp2_static)

    recompute_guiding_term!(gp2_static, nothing)
    recompute_guiding_term!(gp1_static, gp2_static)

    @testset "computation of H,F,c" begin
        @testset "recomputation inplace" for i in 1:101
            @test H(gp1_inplace_recomputed, i) == H(gp1_inplace, i)
            @test F(gp1_inplace_recomputed, i) == F(gp1_inplace, i)
            @test c(gp1_inplace_recomputed, i) == c(gp1_inplace, i)
            @test H(gp2_inplace_recomputed, i) == H(gp2_inplace, i)
            @test F(gp2_inplace_recomputed, i) == F(gp2_inplace, i)
            @test c(gp2_inplace_recomputed, i) == c(gp2_inplace, i)
        end

        @testset "recomputation outofplace" for i in 1:101
            @test H(gp1_static_recomputed, i) == H(gp1_static, i)
            @test F(gp1_static_recomputed, i) == F(gp1_static, i)
            @test c(gp1_static_recomputed, i) == c(gp1_static, i)
            @test H(gp2_static_recomputed, i) == H(gp2_static, i)
            @test F(gp2_static_recomputed, i) == F(gp2_static, i)
            @test c(gp2_static_recomputed, i) == c(gp2_static, i)
        end

        @testset "inplace vs outofplace" for i in 1:101
            @test all(
                [
                    H(gp1_static, i)[k,l] ≈ H(gp1_inplace, i)[k,l]
                    for k in 1:2 for l in 1:2
                ]
            )
            @test all(
                [
                    F(gp1_static, i)[k] ≈ F(gp1_inplace, i)[k]
                    for k in 1:2
                ]
            )
            @test c(gp1_static, i) ≈ c(gp1_inplace, i)

            @test all(
                [
                    H(gp2_static, i)[k,l] ≈ H(gp2_inplace, i)[k,l]
                    for k in 1:2 for l in 1:2
                ]
            )
            @test all(
                [
                    F(gp2_static, i)[k] ≈ F(gp2_inplace, i)[k]
                    for k in 1:2
                ]
            )
            @test c(gp2_static, i) ≈ c(gp2_inplace, i)
        end
    end

    N = 2
    tt = reverse(gp2_static.guiding_term_solver.saved_values.t)
    WW = trajectory(tt, SVector{N,Float64})
    wr = Wiener()
    rand!(wr, WW)

    XX = trajectory(tt, SVector{N,Float64})
    x0 = @SVector [1.0, 2.0]
    DD.solve!(XX, WW, gp2_static, x0)

    #[TODO move to DiffusionDefinition.jl]
    #@inline DD.constdiff(P::LotkaVolterraAux) = true

    loglikhd(gp2_static, XX)
    loglikhd_obs(gp2_static, x0)

    function foo(θ)
        params_intv2 = (
            tt = 1.0:0.01:2.0,
            P_target = LotkaVolterraAux(θ..., 0.0,0.0, nothing),
            P_aux_type = LotkaVolterraAux,
            obs = OBS.LinearGsnObs(2.0, (@SVector [2.0, 3.0]); Σ=SDiagonal(1.0, 1.0)),
            solver_choice=(
                solver=Tsit5(),
                ode_type=:HFc,
                convert_to_HFc=false,
                mode=:outofplace,
                gradients=true,
                eltype=Float64,
            )
        )

        gp2 = GuidProp(params_intv2...)
        recompute_guiding_term!(gp2, nothing)

        sum(gp2.guiding_term_solver.HFc0)
    end

    θinit = [2.0/3.0, 4.0/3.0, 1.0, 1.0, 0.2, 0.2]
    grad = ForwardDiff.gradient(foo, θinit)

    out_at_θ = foo(θinit)
    ϵ = 0.01
    out_mod = [
        foo(θinit .+ [ϵ, 0.0, 0.0, 0.0, 0.0, 0.0]),
        foo(θinit .+ [0.0, ϵ, 0.0, 0.0, 0.0, 0.0]),
        foo(θinit .+ [0.0, 0.0, ϵ, 0.0, 0.0, 0.0]),
        foo(θinit .+ [0.0, 0.0, 0.0, ϵ, 0.0, 0.0]),
        foo(θinit .+ [0.0, 0.0, 0.0, 0.0, ϵ, 0.0]),
        foo(θinit .+ [0.0, 0.0, 0.0, 0.0, 0.0, ϵ]),
    ]
    @testset "automatic differentiation" for i in 1:6
        @test abs( (out_mod[i] - out_at_θ)/ϵ - grad[i] ) < 0.1
    end
end

@testset "bffg.jl" begin
    @load_diffusion LotkaVolterra
    @load_diffusion LotkaVolterraAux

    θ = [2.0/3.0, 4.0/3.0, 1.0, 1.0, 0.2, 0.2]
    x0 = @SVector [0.5, 1.0]
    recording_params = (
        tt = [1.0, 2.0, 3.0],
        observs = [(@SVector [1.0, 2.0]), (@SVector [2.0, 3.0]), (@SVector [1.5, 2.5])],
        P = LotkaVolterra(θ...),
        t0 = 0.0,
        x0_prior = KnownStartingPt(x0),
    )
    recording = build_recording(
        LinearGsnObs, recording_params...;
        Σ = SDiagonal(1.0, 1.0),
    )

    tts = [0.0:0.01:1.0, 1.0:0.01:2.0, 2.0:0.01:3.0]
    guid_props = build_guid_prop(LotkaVolterraAux, recording, tts)

    XX = [Trajectory(collect(tts[i]), zeros(SVector{2,Float64}, length(tts[i]))) for i in 1:3]
    WW = [Trajectory(collect(tts[i]), zeros(SVector{2,Float64}, length(tts[i]))) for i in 1:3]
    forward_guide!(guid_props, WW, XX, x0; Wnr=Wiener())
end


text:
export prunefiles, upload_par, read_resp, yyyyjjj2date, date2yyyyjjj, nancorr
export s3_get_autocorr, XML_download, indexpath, scedcpath, size_check, update_resp_t!
export sync_resp, get_gaps, scedc_stream, mseed_stream, seisio_stream
export fast_mad, fast_mad2d

function prunefiles(filelist::AbstractArray; minfraction = 0.25, maxfraction = 2., minsize=20000)
    if length(filelist) == 0
	    return []
    end

    files = size_check(filelist,minfraction=minfraction,maxfraction=maxfraction, minsize=minsize)

    # get individual stations
    stations = unique([replace(basename(f)[1:7],"_"=>"") for f in files])
    infiles = []
    for jj in eachindex(stations)
	    ind = findall(occursin.(stations[jj],files))
        if length(ind) != 3
	        continue
        end
        push!(infiles,files[ind])
    end
	return infiles
end

function size_check(filelist::AbstractArray; minfraction = 0.25, maxfraction = 2., minsize=20000)
	files = deepcopy(filelist)
    fsizes = [filesize(f) for f in files]

    # check for minimum and maximum sizes relative to median
    ind1 = findall((fsizes .< median(fsizes) * minfraction) .| (fsizes .> median(fsizes) * maxfraction))
    ind2 = findall(fsizes .< minsize)
    deleteat!(files,unique([ind1;ind2]))
    return files
end

function yyyyjjj2date(yearday::String)
    @assert occursin(r"[1-2][0-9][0-9][0-9][0-3][0-9][0-9]",yearday)
    yint = parse(Int,yearday[1:4])
    dint = parse(Int,yearday[5:end])
    @assert dint <= 366 "Input day must be less than or equal to 366"
    return DateTime(yint) + Day(dint-1)
end

function date2yyyyjjj(d::TimeType)
    return "$(year(d))_$(lpad(dayofyear(d),3,"0"))"
end

function upload_par(aws::AWSConfig,output_bucket::String,s3file::String,ec2file::String)
    println("Uploading file $ec2file")
    s3_put(aws,output_bucket,s3file,read(ec2file))
end
upload_par(a...) = upload_par(global_aws_config(region="us-west-2"),a...)

function read_resp(file::String,XMLDIR::String)
    s = yyyyjjj2date(file[end-9:end-3])
	t = s + Day(1)
	s = Dates.format(s, "yyyy-mm-dd HH:MM:SS")
	t = Dates.format(t, "yyyy-mm-dd HH:MM:SS")
	net = basename(file)[1:2]
	sta = split(basename(file),"_")[1][3:end]
	instpath = joinpath(XMLDIR,net * '_' * sta * ".xml" )
    return read_meta("sxml",instpath,s=s,t=t)
end

function XML_download(aws,XMLDIR)
    if !isdir(XMLDIR)
        mkpath(XMLDIR)
    end
    req = collect(s3_list_objects(aws,"scedc-pds","FDSNstationXML/CI/"))
    xmlin = [r["Key"] for r in req]
    xmlout = joinpath.(XMLDIR,basename.(xmlin))
    for ii = 1:length(xmlin)
        s3_get_file(aws,"scedc-pds",xmlin[ii],xmlout[ii])
    end
    return nothing
end
XML_download(XMLDIR) = XML_download(global_aws_config(region="us-west-2"),XMLDIR)

function indexpath(d::Date)
    days = (d - Date(Year(d))).value + 1
    n = ndigits(days)
	jstr = ('0' ^ (3 - n)) * string(days)
	ystr = string(Year(d).value)
    outstring = "continuous_waveforms/index/csv/year="
    outstring *= ystr * "/year_doy="
    outstring *= ystr * '_' * jstr
    outstring *= "/$(ystr)_$(jstr)_waveform_index.csv"
    return outstring
end

"""
  scedcpath(filename)
Convert filename to scedc-pds path.
"""
function scedcpath(filename::String)
    year = filename[14:17]
    day = filename[18:20]
    return "continuous_waveforms/" * year * '/' * year * '_' * day * '/' * filename
end

"""
  update_resp_t!(S)

Add time matrices for instrument response stored in SeisData
"""
function update_resp_t!(S::SeisData)
    for ii = 1:S.n
        S.t[ii] = [1 S.misc[ii]["startDate"];0 S.misc[ii]["endDate"]]
    end
    return nothing
end

"""
  sync_resp(S,s,t)

Prune SeisData such that response are within statrttime `s`
"""
function sync_resp(S::SeisData,s::Int64,t::Int64)
    todelete = []
    for ii = 1:S.n
        if S.t[ii][1,2] > t
            append!(todelete,ii)
        elseif S.t[ii][2,2] < s
            append!(todelete,ii)
        end
    end
    ind = setdiff(1:S.n,todelete)
    return S[ind]
end

function get_gaps(S::SeisData)
    ngaps = zeros(Int,S.n)
    for ii = 1:S.n
        ngaps[ii] = size(S.t[ii],1) - 2
    end
    return ngaps
end

function nancorr(d::DateTime, fs::Real, maxlag::Real)
    C = CorrData()
    C.t = [d2u(d)]
    C.corr = zeros(Float32,convert(Int,2 * fs * maxlag) + 1,1)
    C.corr .= NaN
    return C
end

function s3_get_autocorr(aws::AWSConfig,bucket::String,path::String)
    s = IOBuffer(s3_get(aws,bucket,path))
    seekstart(s)
    return deserialize(s)
end

function mseed_stream(
    aws::AWSConfig,
    bucket::String,
    mseedfiles::AbstractArray,
)
    S = SeisData()
	for ii = 1:length(mseedfiles)
		S += SCEDC.s3_get_seed(
            aws,
			bucket,
			mseedfiles[ii],
			false,
			false,
			false,
			false,
			false,
			false,
			false,
			false,
			false,
			0,
		)
	end
    return S
end
scedc_stream(mseedfiles::AbstractArray) = mseed_stream(global_aws_config(), "scedc-pds",mseedfiles)

function seisio_stream(
    aws::AWSConfig,
    bucket::String,
    files;
    v=0,
)

    A = []
    sbuf  = Array{UInt8, 1}(undef, 65535)
    chans = Int64[]
    ver   = SeisIO.vSeisIO
    L     = zero(Int64)
    if isa(files, String)
        files = [files]
    end

    for path in files
        io  = IOBuffer(s3_get(aws, bucket, path))

        # All SeisIO files begin with "SEISIO"
        if SeisIO.fastread(io, 6) != UInt8[0x53, 0x45, 0x49, 0x53, 0x49, 0x4f]
            @warn string("Skipped ", path, ": not a SeisIO file!")
            close(io)
        end

        ver = SeisIO.fastread(io, Float32)
        L   = SeisIO.fastread(io, Int64)
        C   = read!(io, Array{UInt32,1}(undef, L))
        B   = read!(io, Array{UInt64,1}(undef, L))

        # DND -- faster to avoid seek
        (v > 0) && println("Reading ", L, " objects from ", f)
        (v > 1) && println("C = ", C)
        for n = 1:L
            (v > 1) && println("Reading object with code ", repr(getindex(C, n)), " (", n, "/", L, ")")
            R = SeisIO.read_rec(io, ver, getindex(C, n), getindex(B, n == L ? n : n+1))
            push!(A, R)
            (v > 1) && println("Read ", typeof(getindex(A, n)), " object (", n, "/", L, ")")
        end

        close(io)
    end
    if size(A,1) == 1
        return A[1]
    else
        return SeisData(A...)
    end
end

"""
    fast_mad(A)
Approximate Median Absolute Deviation of array `A`.
MAD = median(|Xi- median(A)|)
"""
function fast_mad(A::AbstractArray,B::Int=1000)
    return median_approx(abs.(A .- median_approx(A,B)),B)
end

function fast_mad2d(A::AbstractArray,B::Int=1000)
    T = eltype(A)
    N = size(A,2)
    mads = zeros(T,1,N)
    for ii in 1:N
        mads[ii] = fast_mad(A[:,ii],B)
    end
    return mads
end

function median_bins(A::AbstractArray, B)
    T = eltype(A)
    N = length(A)
    μ = mean(A)
    σ = std(A)
    minval = μ - σ
    maxval = μ + σ

    leftbin = 1
    bins = zeros(T,B)
    binwidth = 2 * σ / B

    for ii in 1:N
        if A[ii] <= minval
            leftbin += 1
        elseif A[ii] < maxval
            cur = clamp(ceil(Int,(A[ii] - minval) / binwidth),1,B)
            bins[cur] += 1
        end
    end
    return μ, σ, leftbin, bins
end

function median_approx(A::AbstractArray,B)
    μ, σ, leftbin, bins = median_bins(A, B)
    NA = length(A)
    mid = (NA + 1) / 2
    count = leftbin
    lastii = length(bins)
    for (ii, bincount) in enumerate(bins)
        count += bincount
        if count >= mid
            lastii = ii
            break
        end
    end

    binwidth = 2 * σ / B
    med = μ - σ + binwidth * (lastii + 0.5)
    return med
end


text:
using Flux, Test, Random, Statistics, Documenter
using Random

Random.seed!(0)

@testset "Flux" begin

@info "Testing Basics"

include("utils.jl")
include("onehot.jl")
include("optimise.jl")
include("data.jl")

@info "Testing Layers"

include("layers/basic.jl")
include("layers/normalisation.jl")
include("layers/stateless.jl")
include("layers/conv.jl")

if Flux.use_cuda[]
  include("cuda/cuda.jl")
else
  @warn "CUDA unavailable, not testing GPU support"
end

if VERSION >= v"1.2"
  doctest(Flux)
end

end


text:
list_test_str = split(
"[1,2]
[[1,2],3]
[9,[8,7]]
[[1,9],[8,5]]
[[[[1,2],[3,4]],[[5,6],[7,8]]],9]
[[[9,[3,8]],[[0,9],6]],[[[3,7],[4,9]],3]]
[[[[1,3],[5,3]],[[1,3],[8,7]]],[[[4,9],[6,9]],[[8,2],[7,3]]]]",
'\n'
)

list_str = let input = @__DIR__() * "/day18_input.txt"
    isfile(input) ? readlines(input) : list_test_str
end

# Test function

function testit(name, result, check::Function)
    if check(result)
        @info "$name successful, with result $result"
    else
        @warn "$name failed, with result $result"
    end
end

# Part 1

function encode(s::Int, l)
    return [[l, s]]
end

function encode(s::Vector, l)
    return reduce(vcat, encode.(s, l+1))
end

function reduce_code(code)
    reduced = deepcopy(code)
    while any(>(4), getindex.(reduced, 1)) || any(≥(10), getindex.(reduced, 2))
        if any(>(4), getindex.(reduced, 1))
            n = findfirst(getindex.(reduced, 1) .> 4)
            level, data = reduced[n]
            if n == 1
                reduced[n] = [level-1, 0]
                reduced[n+2][2] = last(reduced[n+2]) + last(reduced[n+1])
                deleteat!(reduced, n+1)
            elseif n == length(reduced) - 1
                reduced[n-1][2] = last(reduced[n-1]) + data
                reduced[n] = [level-1, 0]
                deleteat!(reduced, n+1)
            else
                reduced[n-1][2] = last(reduced[n-1]) + data
                reduced[n] = [level-1, 0]
                reduced[n+2][2] = last(reduced[n+2]) + last(reduced[n+1])
                deleteat!(reduced, n+1)
            end
        else
            n = findfirst(getindex.(reduced, 2) .≥ 10)
            level, data = reduced[n]
            reduced[n] = [level+1, div(data, 2)]
            insert!(reduced, n+1, [level+1, div(data+1, 2)])
        end
    end
    return reduced
end

function magnitude(reduced)
    redmag = deepcopy(reduced)
    lv = 4
    while lv ≥ 1
        n = 1
        while n ≤ length(redmag)
            if n < length(redmag) && all(==(lv), first.(redmag[n:n+1]))
                redmag[n] = [lv - 1, 3 * last(redmag[n]) + 2 * last(redmag[n+1])]
                deleteat!(redmag, n+1)
            end
            n += 1
        end
        lv -= 1
    end
    return last(first(redmag))
end

function part1(list)
    sn = eval.(Meta.parse.(list))
    reduced = encode(sn[begin], 0)
    for s in sn[begin+1:end]
        reduced = [[a+1, b] for (a, b) in reduced]
        scode = encode(s, 1)
        reduced = reduce_code(vcat(reduced, scode))
    end
    return reduced, magnitude(reduced)
end

testit("Test Part 1", part1(split("[1,1]\n[2,2]\n[3,3]\n[4,4]", '\n')), ==(part1("[[[[1,1],[2,2]],[3,3]],[4,4]]")))
testit("Test Part 1", part1(split("[1,1]
[2,2]
[3,3]
[4,4]", '\n')), ==(part1("[[[[1,1],[2,2]],[3,3]],[4,4]]")))
testit("Test Part 1", part1(split("[1,1]\n[2,2]\n[3,3]\n[4,4]\n[5,5]", '\n')), ==(part1("[[[[3,0],[5,3]],[4,4]],[5,5]]")))
testit("Test Part 1", part1(split("[1,1]\n[2,2]\n[3,3]\n[4,4]\n[5,5]\n[6,6]", '\n')), ==(part1("[[[[5,0],[7,4]],[5,5]],[6,6]]")))
testit("Test Part 1", part1(split("[[[0,[4,5]],[0,0]],[[[4,5],[2,6]],[9,5]]]
[7,[[[3,7],[4,3]],[[6,3],[8,8]]]]", '\n')), ==(part1("[[[[4,0],[5,4]],[[7,7],[6,0]]],[[8,[7,7]],[[7,9],[5,0]]]]")))
testit("Test Part 1", part1(split("[[[0,[4,5]],[0,0]],[[[4,5],[2,6]],[9,5]]]
[7,[[[3,7],[4,3]],[[6,3],[8,8]]]]
[[2,[[0,8],[3,4]]],[[[6,7],1],[7,[1,6]]]]
[[[[2,4],7],[6,[0,5]]],[[[6,8],[2,8]],[[2,1],[4,5]]]]
[7,[5,[[3,8],[1,4]]]]
[[2,[2,2]],[8,[8,1]]]
[2,9]
[1,[[[9,3],9],[[9,0],[0,7]]]]
[[[5,[7,4]],7],1]
[[[[4,2],2],6],[8,7]]", '\n')), ==(part1("[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]")))

testit("Test Part 1", part1("[[1,2],[[3,4],5]]")[2], ==(143))
testit("Test Part 1", part1("[[[[0,7],4],[[7,8],[6,0]]],[8,1]]")[2], ==(1384))
testit("Test Part 1", part1("[[[[1,1],[2,2]],[3,3]],[4,4]]")[2], ==(445))
testit("Test Part 1", part1("[[[[3,0],[5,3]],[4,4]],[5,5]]")[2], ==(791))
testit("Test Part 1", part1("[[[[5,0],[7,4]],[5,5]],[6,6]]")[2], ==(1137))
testit("Test Part 1", part1("[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]")[2], ==(3488))

testit("Test Part 1", part1(split("[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]
[[[5,[2,8]],4],[5,[[9,9],0]]]
[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]
[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]
[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]]
[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]]
[[[[5,4],[7,7]],8],[[8,3],8]]
[[9,3],[[9,9],[6,[4,9]]]]
[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]
[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]", '\n'))[2], ==(4140))

testit("Challenge Part 1", part1(list_str)[2], ==(3411))

# Part 2

function part2(list)
    sn = eval.(Meta.parse.(list))
    mag = 0
    k = length(sn)
    for k1 in 1:k, k2 in 1:k
        if k1 ≠ k2
            c1 = encode(sn[k1], 1)
            c2 = encode(sn[k2], 1)
            reduced = reduce_code(vcat(c1, c2))
            mag = max(mag, magnitude(reduced))
        end
    end
    return mag
end

testit("Test Part 2", part2(split("[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]
[[[5,[2,8]],4],[5,[[9,9],0]]]
[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]
[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]
[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]]
[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]]
[[[[5,4],[7,7]],8],[[8,3],8]]
[[9,3],[[9,9],[6,[4,9]]]]
[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]
[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]", '\n')), ==(3993))

testit("Challenge Part 2", part2(list_str), ==(4680))

max_stars_repo_name: rmsrosa/adventofcode

max_issues_repo_name: rmsrosa/adventofcode

max_forks_repo_name: rmsrosa/adventofcode


text:
test_gage(GeometricCenter,
    Array[[1.111, 0, 0]],
    [1.111, 0, 0],
    "test 1 for array of arrays")


text:
using DynamicalBilliards

using Documenter, PyPlot, DocumenterMarkdown

ioff()
makedocs(modules=[DynamicalBilliards], doctest=false, root = @__DIR__, format = DocumenterMarkdown.Markdown())
close("all")

if !Sys.iswindows()
    deploydocs(
        deps   = Deps.pip("mkdocs==0.17.5", "mkdocs-material==2.9.4",
        "python-markdown-math", "pygments", "pymdown-extensions"),
        repo   = "github.com/JuliaDynamics/DynamicalBilliards.jl.git",
        target = "site",
        make = () -> run(`mkdocs build`)
    )
end


text:
using DecisionMakingPolicies
using Test

import Zygote: gradient
import Distributions: Normal, MvNormal

@testset "Stateless Normal Tests" begin
    num_actions = 1
    T = Float32
    p = StatelessNormal(T, num_actions)
    @test eltype(p.μ) == T
    @test eltype(p.σ) == T
    @test size(p.μ) == (num_actions,)
    @test size(p.σ) == (num_actions,)
    d = p()
    a = T(1.0)
    logp1 = logpdf(d, a)
    @test typeof(d) <: Normal{T}
    @test typeof(logp1) == T

    num_actions = 2
    p = StatelessNormal(T, num_actions)
    @test typeof(p()) <: MvNormal

    a = rand(p())
    @test eltype(a) == T
    @test size(a) == (2,)
    a = Array{T,1}([1.0, 0.0])
    d = p()
    logp1 = logpdf(d, a)
    logp2 = logpdf(p, a)
    @test typeof(logp2) == T
    @test_broken typeof(logp2) == typeof(logp1)
    @test isapprox(logp1, logp2)
    g = (μ=zero(p.μ), σ=zero(p.σ))
    gauto1 = gradient(p->logpdf(p(),a),p)[1]
    gauto2 = gradient(p->logpdf(p,a),p)[1]

    @test_broken eltype(gauto1.μ) == eltype(gauto2.σ)
    @test_broken eltype(gauto1.σ) == eltype(gauto2.σ)
    @test eltype(gauto2.μ) == eltype(p.μ)
    @test eltype(gauto2.σ) == eltype(p.σ)
    @test all(isapprox.(gauto1.μ, gauto2.μ))
    @test all(isapprox.(gauto1.σ, gauto2.σ))

    logp3 = grad_logpdf!(g, p, a)
    @test typeof(logp3) == T
    @test logp3 == logp2
    @test all(isapprox.(g[1], gauto1[1]))
    @test all(isapprox.(g[2], gauto1[2]))
    g2 = (μ=Array{T,1}([1.0, 0.0]), σ=Array{T,1}([0.0, -1.0]))

    @test all(isapprox.(g.μ, g2.μ))
    @test all(isapprox.(g.σ, g2.σ))

    A = zeros(T,2)
    A2 = zeros(T,(2,2))
    logp4 = sample_with_trace!(g, A, p)
    @test all(.!isapprox.(A, 0.0))
    @test all(isapprox.(g[1], A))
    @test all(isapprox.(g[2], A.^2 .- 1))

    sample_with_trace!(g, view(A2,:,1), p)
    @test all(.!isapprox.(A2[:,1], 0.0))
    @test all(isapprox.(A2[:,2], 0.0))
    a1 = A2[:,1]
    sample_with_trace!(g, view(A2,:, 2), p)
    @test all(isapprox.(A2[:, 1], a1))
    @test all(.!isapprox.(A2[:,2], 0.0))
end

@testset "Stateless Normal Buffer Tests" begin
    num_actions = 2
    T = Float32
    p = StatelessNormal(T, num_actions)
    buff = NormalBuffer(p)
    @test eltype(buff.μ) == T
    @test eltype(buff.action) == T
    @test eltype(buff.ψ.μ) == T
    @test eltype(buff.ψ.σ) == T
    @test size(buff.μ) == (num_actions,)
    @test size(buff.action) == (num_actions,)
    @test size(buff.ψ.σ) == (num_actions,)
    @test size(buff.ψ.μ) == (num_actions,)
    d = p(buff)
    @test eltype(d.μ) == T
    a = Array{T,1}([1.0, 0.0])
    logp1 = logpdf!(buff, p, a)
    @test typeof(logp1) == T

    g = (μ=similar(p.μ), σ=zero(p.σ))
    gauto1 = gradient(p->logpdf(p,a),p)[1]
    logp3 = grad_logpdf!(buff, p, a)
    @test typeof(logp3) == T
    @test logp3 == logp1
    @test all(isapprox.(buff.ψ.μ, gauto1.μ))
    @test all(isapprox.(buff.ψ.σ, gauto1.σ))
    g2 = (Array{T,1}([1.0, 0.0]), Array{T,1}([0.0, -1.0]))

    @test all(isapprox.(buff.ψ.μ, g2[1]))
    @test all(isapprox.(buff.ψ.σ, g2[2]))

    logp4 = sample_with_trace!(buff, p)
    @test typeof(logp4) == T
    @test all(.!isapprox.(buff.action, 0.0))
    @test all(isapprox.(buff.ψ.μ, buff.action))
    @test all(isapprox.(buff.ψ.σ, buff.action.^2 .- 1))
end

@testset "Linear Normal Tests" begin
    num_actions = 1
    num_features = 3
    T = Float32
    p = LinearNormal(T, num_features, num_actions)
    s = Array{T, 1}([0.0, 1.0, 2.0])

    @test eltype(p.W) == T
    @test eltype(p.σ) == T
    @test size(p.W) == (num_features, num_actions)
    @test size(p.σ) == (num_actions,)
    @test typeof(p(s)) <: Normal

    num_actions = 2
    p = LinearNormal(T, num_features, num_actions)
    @test typeof(p(s)) <: MvNormal

    a = rand(p(s))
    @test eltype(a) == T
    @test size(a) == (2,)
    a = Array{T,1}([1.0, 0.0])

    logp1 = logpdf(p(s), a)
    logp2 = logpdf(p, s, a)

    @test typeof(logp2) == T
    @test_broken typeof(logp2) == typeof(logp1)
    @test isapprox(logp1, logp2)
    g = (W=similar(p.W), σ=similar(p.σ))
    gauto1 = gradient(p->logpdf(p(s),a),p)[1]
    gauto2 = gradient(p->logpdf(p,s,a),p)[1]

    @test_broken eltype(gauto1.W) == eltype(gauto2.W)
    @test_broken eltype(gauto1.σ) == eltype(gauto2.σ)
    @test eltype(gauto2.W) == eltype(p.W)
    @test eltype(gauto2.σ) == eltype(p.σ)
    @test all(isapprox.(gauto1.W, gauto2.W))
    @test all(isapprox.(gauto1.σ, gauto2.σ))

    logp3 = grad_logpdf!(g, p, s, a)
    @test typeof(logp3) == T
    @test logp3 == logp2
    @test all(isapprox.(g.W, gauto1.W))
    @test all(isapprox.(g.σ, gauto1.σ))
    g2 = (Array{T,2}([0.0 0.0; 1.0 0.0; 2.0 0.0]), Array{T,1}([0.0, -1.0]))

    @test all(isapprox.(g.W, g2[1]))
    @test all(isapprox.(g.σ, g2[2]))

    A = zeros(T,2)
    A2 = zeros(T,(2,2))
    logp4 = sample_with_trace!(g, A, p, s)
    @test all(.!isapprox.(A, 0.0))
    @test all(isapprox.(g.W, s * A'))
    @test all(isapprox.(g.σ, A.^2 .- 1))

    sample_with_trace!(g, view(A2,:,1), p, s)
    @test all(.!isapprox.(A2[:,1], 0.0))
    @test all(isapprox.(A2[:,2], 0.0))
    a1 = A2[:,1]
    sample_with_trace!(g, view(A2,:, 2), p, s)
    @test all(isapprox.(A2[:, 1], a1))
    @test all(.!isapprox.(A2[:,2], 0.0))
end

@testset "Linear Normal Buffer Tests" begin
    num_actions = 2
    num_features = 3
    T = Float32
    p = LinearNormal(T, num_features, num_actions)
    s = Array{T, 1}([0.0, 1.0, 2.0])
    buff = NormalBuffer(p)
    @test eltype(buff.μ) == T
    @test eltype(buff.action) == T
    @test eltype(buff.ψ.W) == T
    @test eltype(buff.ψ.σ) == T
    @test size(buff.μ) == (num_actions,)
    @test size(buff.action) == (num_actions,)
    @test size(buff.ψ.W) == size(p.W)
    @test size(buff.ψ.σ) == (num_actions,)
    d = p(buff, s)
    @test eltype(d.μ) == T
    a = Array{T,1}([1.0, 0.0])
    logp1 = logpdf!(buff, p, s, a)
    println(logpdf(d, a))
    @test typeof(logp1) == T
    @test logp1 == logpdf(p, s, a)

    gauto1 = gradient(p->logpdf(p,s,a),p)[1]

    logp3 = grad_logpdf!(buff, p, s, a)
    @test typeof(logp3) == T
    @test logp3 == logp1
    @test all(isapprox.(buff.ψ.W, gauto1.W))
    @test all(isapprox.(buff.ψ.σ, gauto1.σ))
    g2 = (Array{T,2}([0.0 0.0; 1.0 0.0; 2.0 0.0]), Array{T,1}([0.0, -1.0]))

    @test all(isapprox.(buff.ψ.W, g2[1]))
    @test all(isapprox.(buff.ψ.σ, g2[2]))

    logp4 = sample_with_trace!(buff, p, s)
    @test typeof(logp4) == T
    @test all(.!isapprox.(buff.action, 0.0))
    @test all(isapprox.(buff.ψ[1], s * buff.action'))
    @test all(isapprox.(buff.ψ[2], buff.action.^2 .- 1))
end


text:
# SPDX-License-Identifier: X11
# 2020-09-13 (Live)
# Product Max (200pt)

a,b,c,d = parse.(Int, split(readline()))
println(maximum([a * c, a * d, b * c, b * d]))

max_stars_repo_name: jthvai/competitive-programming

max_issues_repo_name: jthvai/competitive-programming

max_forks_repo_name: jthvai/competitive-programming


text:
module AbstractGPs

using Distributions
using FillArrays
using LinearAlgebra
using PDMats: AbstractPDMat, ScalMat
using Reexport
@reexport using KernelFunctions
using Random
using Statistics
using StatsBase
using RecipesBase
using IrrationalConstants: log2π

using KernelFunctions: ColVecs, RowVecs

using ChainRulesCore: ChainRulesCore

export GP,
    rand!,
    mean,
    cov,
    var,
    std,
    mean_and_cov,
    mean_and_var,
    marginals,
    logpdf,
    elbo,
    dtc,
    posterior,
    VFE,
    DTC,
    update_posterior,
    LatentGP,
    ColVecs,
    RowVecs

# Various bits of utility functionality.
include("util/common_covmat_ops.jl")

# AbstractGP interface.
include("abstract_gp.jl")

# FiniteGP object that describes the projection of a GP at points x.
include("finite_gp_projection.jl")

# Basic GP object, e.g. to define the prior.
include("mean_function.jl")
include("base_gp.jl")

# Efficient exact posterior GP implementation.
include("exact_gpr_posterior.jl")

# Approximate sparse GP inference for Gaussian likelihood.
include("sparse_approximations.jl")

# LatentGP and LatentFiniteGP objects to accommodate GPs with non-Gaussian likelihoods.
include("latent_gp.jl")

# Plotting utilities.
include("util/plotting.jl")

# Testing utilities.
include("util/TestUtils.jl")

# Deprecations.
include("deprecations.jl")

end # module

max_stars_repo_name: JuliaGaussianProcesses/AbstractGP

max_issues_repo_name: JuliaGaussianProcesses/AbstractGP

max_forks_repo_name: JuliaGaussianProcesses/AbstractGP


text:
using BasicBSpline
using IntervalSets
using LinearAlgebra
using Test
using Random

@testset "BasicBSpline.jl" begin
    include("test_Knots.jl")
    include("test_BSplineSpace.jl")
    include("test_FastBSplineSpace.jl")
    include("test_BSplineBasis.jl")
    include("test_BSplineManifold.jl")
    include("test_Integral.jl")
    include("test_Fitting.jl")
    include("test_compatibility.jl")
end