text:
#########################################################################################################################################
######### bsplinebaisfuns.jl contains all basic functionality in order to compute univariate B-splines and their derivative. ############
#########################################################################################################################################
#
# Functions:
# 		dimsplinespace()       -  compute the dimension of the univariate splinespace
#       grevillepoints()       -  compute the Greville Absiscae of the univariate splinespace
#		onebasisfuneval()      -  evaluate a single basisfunction at a single or a vector of points
#		bsplinebasiseval()     -  evaluate univariate B-pline basisfunction at a point using the Cox-DeBoor algorithm
#		dersbsplinebasisfuns() -  evaluate univariate B-spline basisfunctions and its derivatives at a single point or a vector of points using the Cox-DeBoor algorithm
#		dersbasisfunsinterpolationmatrix()  -  compute the collocation matrices of the space of univariate B-splines up to its nth order derivatives evaluated at a set of points
#
#########################################################################################################################################
#
# File part of the Julia IsoGeometric Analysis toolbox
# R.R.Hiemstra
# 14-09-2015
#
#########################################################################################################################################

# compute the dimension of the spline space defined by degree 'p' and knotsvector 'kts'
dimsplinespace(p::Integer,kts::Vector{Float64}) = length(kts)-p-1
# input:
#    p   :: Int             - polynomial degree
#    kts :: Vector{Float64} - knotvector
# output:
#    n   :: Int             - dimension of the splinespace

# compute the Greville Absiscae of the spline space defined by degree 'p' and knotvector 'kts'
grevillepoints(p::Integer,kts::Array{Float64,1}) = [sum(kts[j+1:j+p]) / p for j in 1:length(kts)-p-1]
# input:
#    p   :: Int             - polynomial degree
#    kts :: Vector{Float64} - knotvector
# output:
#    y   :: Vector{Float64} - vector with Greville Absiscae

# compute value of a single B-spline basis-function of degree 'p' with local knotvector 'knots' evaluated at point 'u'
function onebasisfuneval(p::Integer,kts::Vector{Float64},u::Float64)
# input:
#    p     :: Int             - polynomial degree
#    knots :: Vector{Float64} - knotvector
#    u     :: Float64         - evaluation point
#
# Output:
#    b     :: Float64         - basisfunction defined by degree 'p' and local knotvector 'knots' evaluated at point 'u'

    # initialize
    funs = zeros(Float64,p+1)

    if u<kts[1] || u > kts[p+2]
      funs = 0.0
    elseif sum(u.==kts)==p+1
    	funs = 1.0
    else
      # initialise zeroth degree basisfunction
      for j in 1:p+1
        funs[j] = 0.0
        if (u>=kts[j] && u<kts[j+1])
          funs[j] = 1.0
        end
      end

      # compute triangular table
      for k in 1:p
        if funs[1]==0.0
          saved = 0.0
        else
          saved = ((u-kts[1])*funs[1]) / (kts[k+1]-kts[1])
        end

        for j in 1:p+1-k
          ktsleft  = kts[j+1]
          ktsright = kts[j+k+1]

          if funs[j+1]==0.0
            funs[j] = saved
            saved = 0.0
          else
            temp = funs[j+1] / (ktsright - ktsleft)
            funs[j] = saved + (ktsright - u) * temp
            saved = (u - ktsleft) * temp
          end
        end
      end
    end
  return funs[1]
end

# compute value of a single B-spline basis-function of degree 'p' with local knotvector 'knots' evaluated at points 'u'
onebasisfuneval(p::Integer,kts::Vector{Float64},u::Vector{Float64}) = Float64[onebasisfuneval(p,kts,u[i]) for i in 1:length(u)]
# input:
#    p     :: Int             - polynomial degree
#    knots :: Vector{Float64} - knotvector
#    u     :: Vector{Float64} - vector with evaluation points
#
# Output:
#    b     :: Vector{Float64} - basisfunction defined by degree 'p' and local knotvector 'knots' evaluated at points 'u'

# Compute triangular table of the nonvanishing b-spline basisfunctions up to degree 'p' at the site 'u' and their corresponding support
function bsplinebasiseval(p::Integer, knots::Vector{Float64}, span::Integer, u::Float64)
# input:
#    p     :: Int             - polynomial degree
#    kts   :: Vector{Float64} - knotvector
#    span  :: Int             - index of point u in knotvector
#    u     :: Float64         - evaluation point
# output:
#    Nu    :: Matrix{Float64} - Triangular table of basis functions - Nu[:,k] denotes the kth order basis
#    supp  :: Matrix{Float64} - Triangular table of the support of the basis functions - supp[:,k] denotes the support of the kth order basis

    # initialize
    supp = zeros(Float64,p+1,p+1); supp[1,1] = knots[span+1] - knots[span]
    funs = zeros(Float64,p+1,p+1); funs[1,1] = 1

    # Calculate truncated table of pth basis functions
    for i in 1:p
        for j in 1:i

            # determine support
            supp[j,i+1] = knots[span+j] - knots[span-1+j-i]
            supp[j+1,i+1] = knots[span+j+1] - knots[span+j-i]

            # determine factor of affine map
            alfa = (u - knots[span+j-i]) / supp[j,i]

            # calculate basis function as multi affine map
            funs[j,i+1]   = funs[j,i+1]   + (1-alfa) * funs[j,i]
            funs[j+1,i+1] = funs[j+1,i+1] +    alfa  * funs[j,i]
        end
    end
    return funs, supp
end

# Compute triangular table of the nonvanishing b-spline basisfunctions up to degree 'p' at the site 'u' and their corresponding support
bsplinebasiseval(p::Integer,kts::Vector{Float64},u::Float64) = bsplinebasiseval(p,kts,findspan(p,kts,u),u)
# input:
#    p     :: Int             - polynomial degree
#    knots :: Vector{Float64} - knotvector
#    u     :: Float64         - evaluation point
#
# output:
#    Nu    :: Matrix{Float64} - Triangular table of basis functions - Nu[:,k] denotes the kth order basis
#    supp  :: Matrix{Float64} - Triangular table of the support of the basis functions - supp[:,k] denotes the support of the
#                               kth order basis

# compute the nonvanishing B-spline basis-functions of degree 'p' and its '1,2,...,nout-1'th order derivatives at the site 'u'
function dersbsplinebasisfuns(p::Degree, kts::KnotVector, i::Int, u::Float64, nout::Int)
# input:
#    p     :: Int             - polynomial degree
#    kts   :: Vector{Float64} - knotvector
#    i     :: Int             - index of point u in knotvector
#    u     :: Float64         - evaluation point
#    nout  :: Int             - number of outputs
# Output:
#    ders  :: Matrix{Float64} - [B(u); B'(u); B''(u) ... ] where B(u) denote the vector of B-spline basis functions evaluated
#                               at u

    # initialize
    n = dimsplinespace(p,kts)

    # compute triangular table of basis functions
    ndu   = zeros(Float64,p+1,p+1)
    left  = zeros(Float64,p+1)
    right = zeros(Float64,p+1)
    ndu[1,1] = 1
    for j in 1:p
        left[j+1]  = u - kts[i+1-j]
        right[j+1] = kts[i+j] - u
        saved = 0.0

        for r in 0:j-1
            # lower trinagle
            ndu[j+1,r+1] = right[r+2]+ left[j-r+1]
            temp = ndu[r+1,j] / ndu[j+1,r+1]

            # upper triangle
            ndu[r+1,j+1] = saved + right[r+2] * temp;
            saved = left[j-r+1]*temp;
        end
        ndu[j+1,j+1] = saved;
    end

    # load the basisfunctions
    ders = zeros(Float64,nout,p+1)
    ders[1,:] = ndu[:,end]'

    # This section computes the derivatives
    a = zeros(nout,p+1)
    r = 0
    for r in 0:p
        s1=0; s2=1; a[1,1] = 1

        # loop to compute kth derivative
        for k in 1:nout-1
            d=0
            rk=r-k; pk = p-k
            if (r >= k)
                a[s2+1,1] = a[s1+1,1] / ndu[pk+2,rk+1]
                d = a[s2+1,1] * ndu[rk+1,pk+1]
            end

            if (rk >= -1)
                j1 = 1
            else
                j1 = -rk
            end

            if (r-1 <= pk)
                j2 = k-1
            else
                j2 = p-r
            end

            for j in j1:j2
                a[s2+1,j+1] = (a[s1+1,j+1] - a[s1+1,j]) / ndu[pk+2,rk+j+1]
                d = d + a[s2+1,j+1] * ndu[rk+j+1,pk+1]
            end

            if (r <= pk)
                a[s2+1,k+1] = - a[s1+1,k] / ndu[pk+2,r+1]
                d = d + a[s2+1,k+1] * ndu[r+1,pk+1]
            end
            ders[k+1,r+1] = d
            j = s1; s1 = s2; s2 = j
        end
    end

    # multiply by the correct factors
    r = p
    for k in 1:nout-1
        for j=0:p
            ders[k+1,j+1] = ders[k+1,j+1] * r
        end
        r = r*(p-k);
    end

    return ders
end

# compute B-spline basis-functions of degree 'p' and its '1,2,...,nout-1'th order derivatives at the site 'u'
dersbsplinebasisfuns(p::Degree,kts::KnotVector,u::Float64,nout::Int) = dersbsplinebasisfuns(p, kts, findspan(p,kts,u), u, nout)
# input:
#    p     :: Int             - polynomial degree
#    kts   :: Vector{Float64} - knotvector
#    u     :: Float64         - evaluation point
#    nout  :: Int             - number of outputs
# Output:
#    ders  :: Matrix{Float64} - [B(u); B'(u); B''(u) ... ] where B(u) denote the vector of B-spline basis functions evaluated
#                               at u

# compute B-spline basis-functions of degree 'p' and its '1,2,...,nout-1'th order derivatives at the vector of sites 'u'
function dersbsplinebasisfuns(p::Int, kts::Vector{Float64}, span::Vector{Int64}, u::Vector{Float64}, nout::Int)
# input:
#    p     :: Int             - polynomial degree
#    kts   :: Vector{Float64} - knotvector
#    span  :: Vector{Int}     - vector knot-span-index of points u in knotvector
#    u     :: Vector{Float64} - vector with evaluation points
#    nout  :: Int             - number of outputs
# Output:
#    ders  :: Vector{Matrix{Float64}} - [B(u); B'(u); B''(u) ... ] where B(u) denote the vector of B-spline basis functions
#                                       evaluated at the vector of sites u

    # dimension Spline space and number of collocation points
    n = dimsplinespace(p,kts)
    m = length(u)

    # allocate space for matrices
    Nu = [zeros(Float64,m,p+1) for k in 1:nout]

    for i in 1:m
        ders = dersbsplinebasisfuns(p, kts, span[i], u[i], nout)
        [Nu[k][i,:] = ders[k,:] for k in 1:nout]
    end
    return Nu
end

# compute B-spline basis-functions of degree 'p' and its '1,2,...,nout-1'th order derivatives at the vector of sites 'u'
dersbsplinebasisfuns(p::Int, kts::Vector{Float64}, u::Vector{Float64}, nout::Int) = dersbsplinebasisfuns(p, kts, findspan(p,kts,u), u, nout)
# input:
#    p     :: Int             - polynomial degree
#    kts   :: Vector{Float64} - knotvector
#    u     :: Vector{Float64} - vector with evaluation points
#    nout  :: Int             - number of outputs
# Output:
#    ders  :: Vector{Matrix{Float64}} - [B(u); B'(u); B''(u) ... ] where B(u) denote the vector of B-spline basis functions
#                                       evaluated at the vector of sites u

# compute the collocation matrix and the matrices with 1st, 2nd,..., derivatives for the space of B-splines at a set of collocation points
function dersbsplinebasisfunsinterpolationmatrix(p::Int, kts::Vector{Float64}, u::Vector{Float64}, nout::Int)
# input:
#    p     :: Int             - polynomial degree
#    kts   :: Vector{Float64} - knotvector
#    u     :: Vector{Float64} - vector with evaluation points
#    nout  :: Int             - number of outputs
# Output:
#    ders  :: Vector{Matrix{Float64}} - [B(u); B'(u); B''(u) ... ] where B(u) denotes the vector of B-spline basis functions
#                                       evaluated at the vector of sites u

    # initialize
    n = dimsplinespace(p,kts)
    m = length(u)

    # find span and compute basis functions and derivatives
    span = findspan(p, kts, u)
    Nu = dersbsplinebasisfuns(p, kts, span, u, nout)

    # indices sparse matrix format
    I = repmat(collect(1:m)',p+1,1)
    J = Int64[span[i]-p-1+j for j in 1:p+1, i in 1:m]

    # return matrixes
    return [sparse(I[:],J[:],Nu[k]'[:],m,n) for k in 1:nout]
end

max_stars_repo_name: hiemstar/iga-demos

max_issues_repo_name: hiemstar/iga-demos

max_forks_repo_name: hiemstar/iga-demos


text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: forecastquery
using AWS.Compat
using AWS.UUIDs

"""
    query_forecast(filters, forecast_arn)
    query_forecast(filters, forecast_arn, params::Dict{String,<:Any})

Retrieves a forecast for a single item, filtered by the supplied criteria. The criteria is
a key-value pair. The key is either item_id (or the equivalent non-timestamp, non-target
field) from the TARGET_TIME_SERIES dataset, or one of the forecast dimensions specified as
part of the FeaturizationConfig object. By default, QueryForecast returns the complete date
range for the filtered forecast. You can request a specific date range. To get the full
forecast, use the CreateForecastExportJob operation.  The forecasts generated by Amazon
Forecast are in the same timezone as the dataset that was used to create the predictor.

# Arguments
- `filters`: The filtering criteria to apply when retrieving the forecast. For example, to
  get the forecast for client_21 in the electricity usage dataset, specify the following:
  {\"item_id\" : \"client_21\"}  To get the full forecast, use the CreateForecastExportJob
  operation.
- `forecast_arn`: The Amazon Resource Name (ARN) of the forecast to query.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"EndDate"`: The end date for the forecast. Specify the date using this format:
  yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T20:00:00.
- `"NextToken"`: If the result of the previous request was truncated, the response includes
  a NextToken. To retrieve the next set of results, use the token in the next request. Tokens
  expire after 24 hours.
- `"StartDate"`: The start date for the forecast. Specify the date using this format:
  yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T08:00:00.
"""
query_forecast(Filters, ForecastArn; aws_config::AbstractAWSConfig=global_aws_config()) = forecastquery("QueryForecast", Dict{String, Any}("Filters"=>Filters, "ForecastArn"=>ForecastArn); aws_config=aws_config)
query_forecast(Filters, ForecastArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = forecastquery("QueryForecast", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Filters"=>Filters, "ForecastArn"=>ForecastArn), params)); aws_config=aws_config)

ext: jl


text:
import Base: @deprecate

# Deprecated in v0.6

@deprecate fits_get_col_repeat(f::FITSFile, colnum::Integer) fits_get_coltype(f, colnum)[2, 3]

@deprecate fits_read_col{T}(f::FITSFile, ::Type{T}, colnum::Integer, firstrow::Integer, firstelem::Integer, data::Array{T}) fits_read_col(f, colnum, firstrow, firstelem, data)

@deprecate fits_write_col{T}(f::FITSFile, ::Type{T}, colnum::Integer, firstrow::Integer, firstelem::Integer, data::Array{T}) fits_write_col(f, colnum, firstrow, firstelem, data)


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct IoK8sApimachineryPkgVersionInfo <: SwaggerModel
    buildDate::Any # spec type: Union{ Nothing, String } # spec name: buildDate
    compiler::Any # spec type: Union{ Nothing, String } # spec name: compiler
    gitCommit::Any # spec type: Union{ Nothing, String } # spec name: gitCommit
    gitTreeState::Any # spec type: Union{ Nothing, String } # spec name: gitTreeState
    gitVersion::Any # spec type: Union{ Nothing, String } # spec name: gitVersion
    goVersion::Any # spec type: Union{ Nothing, String } # spec name: goVersion
    major::Any # spec type: Union{ Nothing, String } # spec name: major
    minor::Any # spec type: Union{ Nothing, String } # spec name: minor
    platform::Any # spec type: Union{ Nothing, String } # spec name: platform

    function IoK8sApimachineryPkgVersionInfo(;buildDate=nothing, compiler=nothing, gitCommit=nothing, gitTreeState=nothing, gitVersion=nothing, goVersion=nothing, major=nothing, minor=nothing, platform=nothing)
        o = new()
        validate_property(IoK8sApimachineryPkgVersionInfo, Symbol("buildDate"), buildDate)
        setfield!(o, Symbol("buildDate"), buildDate)
        validate_property(IoK8sApimachineryPkgVersionInfo, Symbol("compiler"), compiler)
        setfield!(o, Symbol("compiler"), compiler)
        validate_property(IoK8sApimachineryPkgVersionInfo, Symbol("gitCommit"), gitCommit)
        setfield!(o, Symbol("gitCommit"), gitCommit)
        validate_property(IoK8sApimachineryPkgVersionInfo, Symbol("gitTreeState"), gitTreeState)
        setfield!(o, Symbol("gitTreeState"), gitTreeState)
        validate_property(IoK8sApimachineryPkgVersionInfo, Symbol("gitVersion"), gitVersion)
        setfield!(o, Symbol("gitVersion"), gitVersion)
        validate_property(IoK8sApimachineryPkgVersionInfo, Symbol("goVersion"), goVersion)
        setfield!(o, Symbol("goVersion"), goVersion)
        validate_property(IoK8sApimachineryPkgVersionInfo, Symbol("major"), major)
        setfield!(o, Symbol("major"), major)
        validate_property(IoK8sApimachineryPkgVersionInfo, Symbol("minor"), minor)
        setfield!(o, Symbol("minor"), minor)
        validate_property(IoK8sApimachineryPkgVersionInfo, Symbol("platform"), platform)
        setfield!(o, Symbol("platform"), platform)
        o
    end
end # type IoK8sApimachineryPkgVersionInfo

const _property_map_IoK8sApimachineryPkgVersionInfo = Dict{Symbol,Symbol}(Symbol("buildDate")=>Symbol("buildDate"), Symbol("compiler")=>Symbol("compiler"), Symbol("gitCommit")=>Symbol("gitCommit"), Symbol("gitTreeState")=>Symbol("gitTreeState"), Symbol("gitVersion")=>Symbol("gitVersion"), Symbol("goVersion")=>Symbol("goVersion"), Symbol("major")=>Symbol("major"), Symbol("minor")=>Symbol("minor"), Symbol("platform")=>Symbol("platform"))
const _property_types_IoK8sApimachineryPkgVersionInfo = Dict{Symbol,String}(Symbol("buildDate")=>"String", Symbol("compiler")=>"String", Symbol("gitCommit")=>"String", Symbol("gitTreeState")=>"String", Symbol("gitVersion")=>"String", Symbol("goVersion")=>"String", Symbol("major")=>"String", Symbol("minor")=>"String", Symbol("platform")=>"String")
Base.propertynames(::Type{ IoK8sApimachineryPkgVersionInfo }) = collect(keys(_property_map_IoK8sApimachineryPkgVersionInfo))
Swagger.property_type(::Type{ IoK8sApimachineryPkgVersionInfo }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_IoK8sApimachineryPkgVersionInfo[name]))}
Swagger.field_name(::Type{ IoK8sApimachineryPkgVersionInfo }, property_name::Symbol) =  _property_map_IoK8sApimachineryPkgVersionInfo[property_name]

function check_required(o::IoK8sApimachineryPkgVersionInfo)
    (getproperty(o, Symbol("buildDate")) === nothing) && (return false)
    (getproperty(o, Symbol("compiler")) === nothing) && (return false)
    (getproperty(o, Symbol("gitCommit")) === nothing) && (return false)
    (getproperty(o, Symbol("gitTreeState")) === nothing) && (return false)
    (getproperty(o, Symbol("gitVersion")) === nothing) && (return false)
    (getproperty(o, Symbol("goVersion")) === nothing) && (return false)
    (getproperty(o, Symbol("major")) === nothing) && (return false)
    (getproperty(o, Symbol("minor")) === nothing) && (return false)
    (getproperty(o, Symbol("platform")) === nothing) && (return false)
    true
end

function validate_property(::Type{ IoK8sApimachineryPkgVersionInfo }, name::Symbol, val)
end


text:
@testset "flow" begin

    # Test construction and dims.
    @test_throws AssertionError InverseNormalisingFlow(DiagonalStandardNormal(1), [DiagAffine(zeros(5), zeros(5))])
    @test_throws AssertionError InverseNormalisingFlow(DiagonalStandardNormal(2), [DiagAffine(0.0, 0.0)])
    @test dim(InverseNormalisingFlow(DiagonalStandardNormal(1), [DiagAffine(0.0, 0.0)])) == 1
    @test dim(InverseNormalisingFlow(DiagonalStandardNormal(1), [DiagAffine([0.0], [0.0])])) == 1

    # Test params.
    let rng = MersenneTwister(123456)
        a = DiagAffine(identity_init, rng, 5)
        p = Planar(identity_init, rng, 5)
        flow = InverseNormalisingFlow(DiagStdNormal(5), [a, p])
        @test length(params(flow)) == 5
        @test params(flow) == vcat(params(a), params(p))
    end

    # Test the mechanics of constructing an INF from an initialiser.
    let rng = MersenneTwister(123456), D = 3, ctors = __transforms
        for (init, inplace_init!) in [(naive_init, naive_init!),
                                     (identity_init, identity_init!)]
            θ = fill!(Vector{Float64}(nparams(INF, D, ctors)), NaN)
            θ = inplace_init!(θ, InverseNormalisingFlow, rng, D, ctors)
            @test all(.!isnan.(θ))
            @test all(.!isinf.(θ))
            @test nparams(INF(DiagStdNormal(D), θ, ctors)) == length(θ)

            @test_throws AssertionError inplace_init!(θ, INF, rng, D + 1, ctors)
            @test_throws TypeError inplace_init!(θ, INF, rng, D, randn(rng, 3))
            @test_throws AssertionError inplace_init!(θ, INF, rng, D, [INF, INF, INF])

            @test length(init(INF, rng, D, ctors)) == length(θ)
            @test nparams(INF(init, rng, D, ctors)) == length(θ)

            @test dim(INF(DiagStdNormal(D), θ, ctors)) == dim(INF(init, rng, D, ctors))
        end
    end

    # Test basics of log probability computations are consistent with the construction.
    let
        flow = InverseNormalisingFlow(DiagonalStandardNormal(1), [DiagAffine(0.0, 0.0)])
        @test logpdf(flow, [0.0]) == logpdf(DiagonalStandardNormal(1), [0.0])
        @test logpdf(flow, [1.0]) == logpdf(DiagonalStandardNormal(1), [1.0])

        p0, a = DiagonalStandardNormal(1), DiagAffine(0.0, 1.0)
        flow, y = InverseNormalisingFlow(p0, [a]), [1.0]
        z = apply(a, y)
        @test logpdf(flow, y) == logpdf(p0, z) + logdetJ(a, y)

        p0, a1, a2 = DiagonalStandardNormal(1), DiagAffine(0.0, 1.0), DiagAffine(3.0, 2.0)
        flow, y = InverseNormalisingFlow(p0, [a1, a2]), [1.0]
        z1, z2 = apply(a1, y), apply(a2, apply(a1, y))
        @test logpdf(flow, y) == logdetJ(a2, z1) + logdetJ(a1, y) + logpdf(p0, z2)
    end

    # Test the mechanics of `rand` for InverseNormalisingFlows.
    let rng = MersenneTwister(123456), N = 10, D = 2
        p0 = DiagonalStandardNormal(D)
        a = DiagAffine(ones(D), 1.5 * ones(D))
        flow = InverseNormalisingFlow(p0, [a, a])
        @test size(rand(rng, flow, N)) == (D, N)
    end

    # Test that each single-layer flow integrates to 1 in 1-dimension.
    for Transform in __transforms
        let rng = MersenneTwister(123456)
            p0 = DiagonalStandardNormal(1)
            flow = InverseNormalisingFlow(p0, [Transform(naive_init, rng, 1)])
            @test abs(quadgk(y->exp(logpdf(flow, [y])), -10, 10)[1] - 1) < 1e-6
        end
    end

    # Test that we approximately recover a random transform given sufficiently many sampled.
    let rng = MersenneTwister(123456), N = 10000
        for D = [1, 5]

            # Construct an INF and sample from it N times.
            p0 = DiagonalStandardNormal(D)
            θ = randn(rng, 2D)
            a = DiagAffine(θ[1:D], θ[D+1:2D])
            y = rand(rng, InverseNormalisingFlow(p0, [a]), N)

            # Constuct objective function, perform ML inference, and test θ is recovered.
            function obj(θ)
                p0 = DiagonalStandardNormal(D)
                transforms = [DiagAffine(θ[1:D], θ[D+1:2D])]
                return -logpdf(InverseNormalisingFlow(p0, transforms), y)
            end
            ∇obj = ∇(obj)
            g!(storage, θ) = (storage .= ∇obj(θ)[1]; storage)
            @test maximum(abs.(optimize(obj, g!, θ).minimizer .- θ)) < 1e-1
        end
    end
end


text:
"""
Tests the forward modelling function `calculate_response` against a range of
models. For model information, see "./test-models/README.md". A comparison
of the expected output and calculated output for each model is plotted and saved
into "./test-models/generated-plots".
"""
module TestCalcResponse
using Base.Test
using MT1D
using Utils
using Gadfly

fs = logspace(-4, 4, 100)
cd("./test-models") do
    model_files = filter(s -> ismatch(r"\.model$", s), readdir())

    map(model_files) do fname
        model = readdlm(fname)
        expected_response = readdlm("$fname.response")

        ρ, Φ = calc_response(model, fs)
        p = plot_response(expected_response, [ρ Φ], model, fs)
        draw(SVG("./generated-plots/$fname.svg", 1140px, 800px), p)

        @test_approx_eq expected_response[:,1] ρ
        @test_approx_eq expected_response[:,2] Φ
    end
end

end


text:
function perimetr!(r::Robot)

to_West = to_side!(r,West)
to_Sud = to_side!(r,Sud)

    for side in (Nord,Ost,Sud,West)
        putmarkers!(r,side)
    end

to_side!(r,Nord,to_Sud)
to_side!(r,Ost,to_West)

end
#Робот ставит маркеры по периметру

function to_side!(r::Robot,side::HorizonSide)
    num_steps=0
    while isborder(r,side) == false
        move!(r,side)
        num_steps+=1
    end
    return num_steps
end
#на выходе получаем кол-во шагов по прямой до границы

function to_side!(r::Robot,side::HorizonSide,num_steps::Int)
    for _ in (1:num_steps)
        move!(r,side)
    end
end
#используем кол-во шагов,чтобы вернуться в исходную точку

function putmarkers!(r::Robot, side::HorizonSide)
    while isborder(r,side)==false
        move!(r,side)
        putmarker!(r)
    end
end
#ставим маркеры по линии до границы(в начале маркера нет)

max_stars_repo_name: ilya-design/mirea-progs

max_issues_repo_name: ilya-design/mirea-progs

max_forks_repo_name: ilya-design/mirea-progs


text:
function safeName(input::AbstractString)
    chars = ["/", "\\", "\"", "?", "<", ">", "*", ":","\'", "|"]
    output = input
    for mchar in chars
        output = replace(output,mchar=>"_")
    end
    if output[1] == '.'
        output = replace(output,"."=>"_",count=1)
    end
    len = length(output)
    if len > 240
        output = output[len - 240, len]
    end
    return output
end

function logprint(Arg...; log = LOGGING_TO_FILE, path = BUILD_INFORMATION_PATH)
    if log
        if !isdir(BUILD_INFORMATION_PATH)
            mkpath(BUILD_INFORMATION_PATH)
        end
        io = open(joinpath(path,BUILD_LOG_FILE_NAME),"a")
        for component in Arg
            print(io,component)
        end
        close(io)
    end
    for component in Arg
        print(component)
    end
    flush(stdout)
end

logprintln(Args...;log = LOGGING_TO_FILE , path = BUILD_INFORMATION_PATH) = logprint(Args...,'\n';log=log , path = path)

function julia_version_compatibility_check()
    logprintln("== Checking Julia version...")
    if VERSION < v"1.2.0"
        logprintln("ERROR: Incompatible Julia version: At least julia 1.2.0 is required")
    else
        logprintln("    <> Julia VERSION $(VERSION) is enaugh.")
    end
    return nothing
end

"""
making or use the build directory and append the new date and time to that.
"""
function Saving_the_build_information(path,type)
    logprintln("== Saving the build information...")
    mkpath(path)
    Build_Spec_File = open(joinpath(path,BUILD_TIME_FILE_NAME), "a")
    if type == :start
        write(Build_Spec_File, "Started at: $(repr(Dates.now()))\n",)
    end
    if type == :finish
        write(Build_Spec_File, "  Ended at: $(repr(Dates.now()))\n",)
    end
    close(Build_Spec_File)
    logprintln("    <> Saved build time at: $(path)/$(BUILD_TIME_FILE_NAME)")
end

function remove_dir!(path, info="";force = true, recursive = true)
    if !SILENT
        logprintln("Do you confirm removing \"$(path)\": [type \"y\" and Enter to remove or press any other keys to decline]")
        answer = lowercase(readline())
    else
        answer = "y"
    end
    if answer == "y" || answer == "Y"
        if info ==""
            logprintln("Removing $(path)")
        else
            logprintln(info)
        end
        rm(
            path,
            force = force,
            recursive = recursive,
        )
    end
    return nothing
end

function download_a_file(url::AbstractString,target_directory::AbstractString,file_name::AbstractString)
    mkpath(target_directory)
    path = joinpath(target_directory,file_name)
    file_name_and_address = download(url,path)
    return file_name_and_address
end

function handle_files(op,key,target;backup = MAKE_BACKUPS)
    target_directory = joinpath(target)
    downloaded_files_pathes = String[]
    if haskey(op, key)
        for item in op[key]
            url = item["url"]
            logprintln("* downloading $(repr(url))...")
            file_name = safeName(url)
            file_name_and_address = joinpath(target_directory,file_name)
            if isfile(file_name_and_address) && !REFRESH_CONF_FILES
                logprintln("    >> The specified file $(repr(url)) already exists at $(joinpath(target_directory,file_name)). skipping download ...")
                push!(downloaded_files_pathes,file_name_and_address)
            else
                mkpath(target_directory)
                handle_dublicate_file(file_name_and_address)
                try   # =================================== TODO: make it a function
                file_name_and_address = download_a_file(url,target_directory,file_name)
                push!(downloaded_files_pathes,file_name_and_address)
                catch e
                    logprintln(e)
                end
            end
        end
    end
    return downloaded_files_pathes
end

function maketempdir()::String
    dir::String = mktempdir()
    atexit(() -> rm(dir; force = true, recursive = true,))
    return dir
end

function git_clone(url::AbstractString, path::AbstractString)
    if path ==  nothing
        tmp = maketempdir()
    else
        tmp = path
    end
    mkpath(tmp)
    # Base.shred!(LibGit2.CachedCredentials()) do creds
    #     LibGit2.with(
    #         Pkg.GitTools.clone(
    #             url,
    #             tmp;
    #             header = "registry from $(repr(url))",
    #             credentials = creds,
    #             )
    #         ) do repo
    #     end
    # end

    repo = LibGit2.clone(url, tmp)
    return tmp
end

function git_update(path)
    errors = Tuple{String, String}[]
    if isdir(joinpath(path,REPO_PATH_EXTENTION))
        repo = nothing
        try
            repo = LibGit2.GitRepo(path)
            if LibGit2.isdirty(repo)
                push!(errors, (path, "repo is dirty"))
                @goto done
            end
            if !LibGit2.isattached(repo)
                push!(errors,(path, "registry detached"))
                @goto done
            end
            branch = LibGit2.headname(repo)
            try
                GitTools.fetch(repo; refspecs=["+refs/heads/$branch:refs/remotes/origin/$branch"])
            catch e
                push!(errors, (path, "failed to fetch from repo"))
                @goto done
            end
            ff_succeeded = try
                LibGit2.merge!(repo; branch="refs/remotes/origin/$branch", fastforward=true)
            catch e
                e isa LibGit2.GitError && e.code == LibGit2.Error.ENOTFOUND || rethrow()
                push!(errors, (repo.path, "branch origin/$branch not found"))
                @goto done
            end
            if !ff_succeeded
                try LibGit2.rebase!(repo, "origin/$branch")
                catch e
                    e isa LibGit2.GitError || rethrow()
                    push!(errors, (repo.path, "registry failed to rebase on origin/$branch"))
                    @goto done
                end
            end
            @label done
        finally
            if repo isa LibGit2.GitRepo
                close(repo)
            end # end if
        end
    end # end if
    if !isempty(errors) # TODO: Add instructions in case of package failure
        warn_str = "Failed to update the repo."
        @warn warn_str
        logprintln("WARNING: ",warn_str)
    end # end if
    return
end # end function

function handle_a_git_repo(url, path; update = UPDATE_MODE)
    errors = Tuple{String,String}[]
    if isdir(joinpath(path,REPO_PATH_EXTENTION)) && update
        logprintln("    >> repo already exists at: \"",path,"\"")
        logprintln("    >> Trying to update...")

        update_errors = Tuple{String,String}[]
        try
            git_update(path)
        catch e
            logprintln("    >> Error in update...")
            logprintln(e)
            push!(update_errors,(path,"Error in update"))
        end
        if !isempty(update_errors)
            logprintln("    >> Try cloning...")
            logprintln("    >> Macking a backup from old repo...")
            try
                cp(joinpath(path),joinpath(path*"(backup)"))
            catch e
                rm(joinpath(path*"(backup)"),
                recursive = true,
                force = true)
                cp(joinpath(path),joinpath(path*"(backup)"))
            end
            rm(joinpath(path),recursive = true, force = true)
            newclown = Tuple{String,String}[]
            try
                git_clone(url, path)
            catch e
                push!(errors, (url,"Cloning repo faild"))
                logprintln(e)
            end
            if isempty(errors)
                rm(joinpath(path*"(backup)"),
                recursive = true,
                force = true)
            end

        end
        # logprintln("    >> updated successfully.")
    elseif isdir(joinpath(path,REPO_PATH_EXTENTION)) && !update
        logprintln("    >> repo already exists at: \"",path,"\"")
        logprintln("    >> skipping the update...")
    else
        try
            git_clone(url, path)
        catch e
            push!(errors, (url,"Cloning repo faild"))
            logprintln(e)
        end
    end
    if !isempty(errors)
        warn_str = "Faild to clone a repo from: " * url
        @warn warn_str
        logprintln("WARNING: ",warn_str)
        return "failed"
    else
        return "success"
    end
end

function cloning_registeries(op,key,target)
    cloned_registeries_path = String[]
    for registery in op[key]
        url = registery["url"]
        save_at = safeName(url)
        path = joinpath(target,save_at)
        logprintln("* Handling repo: ",repr(url))
        handle_a_git_repo(url,path)
        push!(cloned_registeries_path,path)
    end
    return cloned_registeries_path
end

function save_data(vector::Vector,path::String,name::String)
    mkpath(path)
    file = open(joinpath(path,name),"w")
    writedlm(file,vector)
    close(file)
end

read_vector(file_path) = vec(readdlm(file_path))

function read_meta_data_phase2()
    spr_path = nothing
    spm_path = nothing
    spp_path = nothing
    ko_path = nothing
    rm_path = nothing
    spr_metadata = joinpath(META_DATA_PATH,"CLONED_REGISTERIES_PATH.DATA")
    if isfile(spr_metadata)
        spr_path = read_vector(spr_metadata)
    end
    spm_metadata = joinpath(META_DATA_PATH,"SPMANIFESTS_PATH.DATA")
    if isfile(spm_metadata)
        spm_path = read_vector(spm_metadata)
    end
    spp_metadata = joinpath(META_DATA_PATH,"SPPROJECTS_PATH.DATA")
    if isfile(spp_metadata)
        spp_path = read_vector(spp_metadata)
    end
    keep_online = joinpath(META_DATA_PATH,"KEEPONLINE_PATH.DATA")
    if isfile(keep_online)
        ko_path = read_vector(keep_online)
    end
    remove_from_repo = joinpath(META_DATA_PATH,"REMOVEFROMREPO_PATH.DATA")
    if isfile(remove_from_repo)
        rm_path = read_vector(remove_from_repo)
    end
    return spr_path, spm_path, spp_path, ko_path, rm_path
end

"""
    fetch_packages_names_and_addresses!(packages_names_dict, packages_addresses_dict, spr_path)
To handle the cases whith several Registry input, this function records all the names and addresses
of every package available in the provided registries.
This absolute addresses can be handy in the last step which is coping the packages metadata.
"""
function fetch_packages_names_and_addresses!(packages_names_dict, packages_addresses_dict, spr_path)
    for reg_path in spr_path
        reg_file_name_and_address = joinpath(reg_path,"Registry.toml")
        parsed_registery = Dict{String,Any}()
        try
            parsed_registery = Pkg.TOML.parsefile(reg_file_name_and_address)
        catch e
            logprintln(e)
        end
        for uuid in keys(parsed_registery["packages"])
            push!(packages_names_dict,uuid=>parsed_registery["packages"][uuid]["name"])
            push!(packages_addresses_dict,uuid=>joinpath(reg_path,splitpath(parsed_registery["packages"][uuid]["path"])...))
        end
    end
end

has(x::AbstractString, y) = x == y

has(x::AbstractArray, y) = any(has(i, y) for i in x)

"""
Returns a vector of UUIDs if there are several maches.
"""
function get_uuid(name::String,d::Dict)
    [k for (k,v) in d if has(v, name)]
end

"""
    get_address(input::String, type = :uuid, packages_metadata = packages_metadata)

returns an array of addresses of specified package.
Default input type is `:uuid` if type `:name` specitied,
returns an array of all matches to the input type `:name`

#Example:

```julia_repel
julia> get_address("Example",:name)
```
"""
function get_address(input::String, type = :uuid, packages_metadata = packages_metadata)
    uuid = input
    out = []
    if type == :name
        uuid = get_uuid(input,packages_metadata["names"])
    end
    for id in uuid
        push!(out,packages_metadata["addresses"][id])
    end
    return out
end

"""
Reads a project file (in the format of julia ```Project.toml```)
and returns the UUIDs for packages in that file.
"""
function read_packages_in_projects!(download_list,spp_path)
    for path in spp_path
        push!(download_list,values(Pkg.TOML.parsefile(path)["deps"])...)
    end
    unique!(download_list)
end

"""
Reads a manifest file (in the format of julia ```Manifest.toml```)
and returns the UUIDs for packages in that file.
"""
function read_packages_in_manifests!(download_list,spm_path)
    for path in spm_path
        p = Pkg.TOML.parsefile(path)
        for key in keys(p)
            for i = 1:size(p[key],1)
                push!(download_list,p[key][1]["uuid"])
            end
        end
    end
    unique!(download_list)
end

function read_remove_from_repo_packages(rm_path,packages_metadata = packages_metadata)
    rm_packages = String[]
    rm_packages_uuid = String[]
    for file in rm_path
        rm_packages = push!(Pkg.TOML.parsefile(file)["packages"]["name"])
    end
    unique!(rm_packages)
    for name in rm_packages
        push!(rm_packages_uuid, get_uuid(name,packages_metadata["names"])...)
    end
    unique!(rm_packages_uuid)
end

"""
    is_stdlib(id::String)

returns `true` if the id belongs to any Julia standard library
"""
is_stdlib(id::String) = Pkg.Operations.is_stdlib(UUID(id))

"""
    remove_stdlib_packages!(list)

removes all standard library uuids from the list which must contain a list of packages uuids.
"""
function remove_stdlib_packages!(list)
    deleteat!(list,[is_stdlib(item) for item in list])
end

function remove_keep_online_packages!(list,ko_path,packages_metadata = packages_metadata)
    ko_packages = String[]
    ko_packages_uuid = String[]
    for file in ko_path
        ko_packages = push!(Pkg.TOML.parsefile(file)["packages"]["name"])
    end
    unique!(ko_packages)
    for name in ko_packages
        push!(ko_packages_uuid, get_uuid(name,packages_metadata["names"])...)
    end
    unique!(ko_packages_uuid)
    setdiff!(list,ko_packages_uuid)
end

function get_urls!(urls, dict = packages_metadata["addresses"])
    for id in keys(dict)
        path = joinpath(dict[id],"Package.toml")
        p = Pkg.TOML.parsefile(path)
        if id != p["uuid"]
            logprintln("WARNING: The \"",id,"\" uuid doesn't mach the UUID in the registery metadata.")
        end
        push!(urls,id => p["repo"])
    end
end

function make_download_list!(out::Dict{String,String},list::Array{String},d::Dict)
    for id in list
        push!(out, id => d[id])
    end
end

"""
    remove!(d::Dict,keys::Vector)

Removes keys from dictionary d.

    remove!(a::Array,b::Array)

Removes all members of b from the a
"""
function remove!(d::Dict,keys::Vector)
    for key in keys
        delete!(d,key)
    end
    return d
end

function remove!(a::Array,b::Array)
    setdiff!(a,b)
end

function remove!(d::Dict{String,Dict{String,String}},list::Array{String,1})
    remove!(d["names"],list)
    remove!(d["addresses"],list)
end

function remove!(a::Dict{String,Dict{String,String}},b::Dict{String,Dict{String,String}})
    list = collect(keys(b))
    remove!(a,b)
end

"""
    generate_path(uuid,packages_metadata = packages_metadata,; prefix = PREFIX, repo = REG_DIR)

Creates a path based on the package UUID,name.
path = joinpath(prefix,repo,first capital leter of the name,name,uuid,name*".jl.git")
"""
function generate_path(uuid,packages_metadata = packages_metadata; prefix = PACKAGES_PATH)
    name = packages_metadata["names"][uuid]
    rel_path = joinpath(string(uppercase(name[1])),name,uuid,name*".jl$(REPO_PATH_EXTENTION)")
    path = joinpath(prefix,rel_path)
    return path, rel_path
end

"""
    make_repo(download_list_urls_dict,packages_metadata = packages_metadata)

Gets all packages listed in \"download_list_urls_dict\".
The function will try to update a packages if it finds
an older version. returns the list of packages that could not be cloned.
being unable to update is not considered an error.
"""
function make_repo(download_list_urls_dict,packages_metadata = packages_metadata)
    brokenPackages = Dict{String,String}()
    downloaded_packages_path_dict = Dict{String,String}()
    downloaded_packages_rel_path_dict = Dict{String,String}()
    ll = size(collect(keys(download_list_urls_dict)),1)
    for (i,id) in enumerate(keys(download_list_urls_dict))
        logprintln("* ",i,"/",ll," ",packages_metadata["names"][id],".jl")
        url = download_list_urls_dict[id]
        path, rel_path = generate_path(id,packages_metadata)
        push!(downloaded_packages_path_dict,id => path)
        push!(downloaded_packages_rel_path_dict,id => rel_path)
        println(path)
        mkpath(path)
        result = handle_a_git_repo(url,path)
        if result == "failed"
            push!(brokenPackages,id => url)
            delete!(downloaded_packages_path_dict,id)
            rm(
                path,
                force = true,
                recursive = true,
            )
        end
    end
    return brokenPackages, downloaded_packages_path_dict, downloaded_packages_rel_path_dict
end

"""
    handle_dublicate_file(file, backup = true)

if backup is true,make a copy of the \"file\" with the \"backup_\" prefix and removes the original file. Otherwise removes the file
"""
function handle_dublicate_file(file; backup = MAKE_BACKUPS)
    sp = splitpath(file)
    dest = joinpath(sp[1:end-1]...,"backup_"*sp[end])
    if isfile(file)
        if backup == true
            cp(file,dest,force = true)
            logprintln("    >> creating a backup from: ",file,"\n       to: ",dest)
        end
        rm(file,force = true)
    end
end

"""
    save_broken_packages(d,md = packages_metadata)
gets the dictionary \"d\" and makes two \"TOML\" file. One with the
format of julia \"Project.toml\" file format which can be used as an input
to special projects key in \"configuration.toml\" and one with the acceptable
format for the \"keep_online\" and \"remove_from_repo\" format in the
\"configuration.toml\"

Note: The function keeps one (and only one) backup from previous build if
Clean installation has been set to false.
"""
function save_broken_packages(d,md = packages_metadata)
    mkpath(BUILD_INFORMATION_PATH)
    path = joinpath(BUILD_INFORMATION_PATH,"broken_packages.toml")
    logprintln("== saving broken packages names to: ", path)
    logprintln("   you can feed this file to exclude packages.")
    handle_dublicate_file(path)
    file = open(path,"w")
    println(file,"[packages]\nname = [")
    for id in keys(d)
        println(file,"\t",repr(packages_metadata["names"][id]),",")
    end
    println(file,"]")
    close(file)

    path = joinpath(BUILD_INFORMATION_PATH,"broken_packages_Project.toml")
    logprintln("== saving broken packages names to: ", path)
    logprintln("   This file is in the format of julia \"Project.toml\".")
    handle_dublicate_file(path)
    file = open(path,"w")
    println(file,"[deps]")
    for id in keys(d)
        println(file,packages_metadata["names"][id], " = ",repr(id))
    end
    close(file)
end

function handel_brocken_packages_metadata(broken_packages_dict,packages_metadata)
    if !isempty(broken_packages_dict)
        save_broken_packages(broken_packages_dict,packages_metadata)
    else
        logprintln("== There are no broken packages.")
        logprintln("   >> making backup from the old broken packages lists if there are any.")
        path = joinpath(BUILD_INFORMATION_PATH,"broken_packages.toml")
        handle_dublicate_file(path)
        path = joinpath(BUILD_INFORMATION_PATH,"broken_packages_Project.toml")
        handle_dublicate_file(path)
    end
end

# ======================= PHASE 4 functions ==============================
function copy_package_metadata_to_new_reg(uuid,packages_metadata,new_reg_root_path)
    original_reg_metadata_path = packages_metadata["addresses"][uuid]
    name = packages_metadata["names"][uuid]
    target = joinpath(new_reg_root_path,string(uppercase(name[1])),name) # following julia registry pattern here. I dont know what will happen in case of similarities in the names.
    mkpath(target)
    cp(original_reg_metadata_path,target,force = true)
    return target
end

function change_url_in_package_metadata(package_metadata_root,
        type,
        abs_path_to_package_git,
        rel_path_to_package_git)
    path = joinpath(package_metadata_root,"Package.toml") # following julia registry pattern here. I dont know what will happen in case of similarities in the names.
    if isfile(path)
        p = Pkg.TOML.parsefile(path)
        p["repo"] = get_new_url(type,abs_path_to_package_git,        rel_path_to_package_git)
        rm(path,force = true)
        file = open(path,"w")
        Pkg.TOML.print(file, p)
        close(file)
    else
        logprintln("No Package.toml for this package has been found.")
    end
end

function get_new_url(type,abs_path_to_package_git,rel_path_to_package_git)
    if type == "public_access"
        url = NETWORK_PREFIX
        while url[end] == '/'
            url = url[1:end-1]
        end
        url = url *"/" * PACKAGES_DIR
        for comp in splitpath(rel_path_to_package_git)
            url = url*"/"*comp
        end
    elseif type == "local"
        url = abs_path_to_package_git
    end
    return url
end

function commit_changes(reg_root)
    logprintln("    >> Updating the registry git repo ...")
    logprintln("       *tracking files and staging changes...")

    if !isdir(joinpath(reg_root),".git")
        try
            LibGit2.init(reg_root)
        catch e
            logprintln("WARNING: Unanle to initialize git in the Registry.")
        end
    end

    git_repo = LibGit2.GitRepo(reg_root) # Open a git repository at path.
    LibGit2.add!(git_repo, "Registry.toml",) # Add all the files with paths specified by files to the index idx (or the index of the repo).
    # for i = 'A':'Z'
    #     logprintln("        >> Tracking ",string(i),"/...")
    #     # LibGit2.add!(git_repo, joinpath(reg_root,string(i)))
    #     LibGit2.add!(git_repo,string(i))
    # end
    LibGit2.add!(git_repo,".")
    logprintln("        <> successfully tracked all files and staged all changes")

    logprintln("        * committing...")
    commit_msg = "Automated commit made on $(repr(Dates.now())). $(GIT_COMMIT_INFO)"
    sig = LibGit2.Signature(
        MY_GIT_USER_NAME,
        MY_GIT_USER_EMAIL,
        )
    LibGit2.commit(git_repo,commit_msg;author = sig,committer = sig,) # committing the repo
    all_project_remotes = LibGit2.remotes(git_repo)
    for project_remote in all_project_remotes
        LibGit2.remote_delete(git_repo, project_remote)
    end
    logprintln("    <> successfully committed all changes.")
end

function make_reg_toml(make_repo_for_this_packages,packages_metadata,reg_root,type)
    logprintln("    >> Writing new Registery.toml...")
    path = joinpath(reg_root,"Registry.toml")
    file = open(path,"w")
    println(file,"name = ",repr(MY_REGISTRY_NAME))
    println(file,"uuid = ",repr(MY_REGISTRY_UUID))
    if type == "local"
        println(file,"repo = ",repr(joinpath(reg_root))) # change
    end
    if type == "public_access"
        url = NETWORK_PREFIX
        while url[end] == '/'
            url = url[1:end-1]
        end
        url = url * "/" * NEW_REG_DIR * "/" * PUBLIC_REG_DIR
        println(file,"repo = ",repr(url)) # change
    end
    println(file,"\ndescription = ","\"\"\"\n$(HEADER_MASSAGE) $(MY_INFO)\n\"\"\"\n")
    println(file,"[packages]")
    for (i,id) in enumerate(keys(make_repo_for_this_packages))
        name = packages_metadata["names"][id]
        println(file,id," = { name = ",repr(name),", path = ","\"",string(uppercase(name[1])),"/",name,"\""," }")
    end
    close(file)
end

function make_reg(packages_metadata,
    download_list_urls_dict,
    broken_packages_dict,
    reg_root,
    type,
    downloaded_packages_path_dict,
    downloaded_packages_rel_path_dict)

        if MINIMAL_REG
            make_repo_for_this_packages = download_list_urls_dict
        else
            make_repo_for_this_packages = packages_metadata["names"]
        end

        # ll = size(collect(keys(make_repo_for_this_packages)))

        for (i,id) in enumerate(keys(make_repo_for_this_packages))

            new_metadata_path = copy_package_metadata_to_new_reg(id,packages_metadata,reg_root)

            # logprint(i,"/",ll," ",packages_metadata["names"][id])
            # padding = maximum(sizeof.(collect(values(packages_metadata["names"])))) + 35
            if haskey(download_list_urls_dict,id)
                if haskey(broken_packages_dict,id)
                    # logprintln(lpad(" ==> status: Failed to clone using online repo insted",padding - sizeof(packages_metadata["names"][id]) + 29 - size(digits(i),1)," " ))
                else
                    # logprintln(lpad(" ==> status: Local repo",padding - sizeof(packages_metadata["names"][id]) -1 - size(digits(i),1)," " ))

                    change_url_in_package_metadata(new_metadata_path,type,downloaded_packages_path_dict[id],downloaded_packages_rel_path_dict[id])
                end
            else
                # logprintln(lpad(" ==> status: Online repo",padding - sizeof(packages_metadata["names"][id]) - size(digits(i),1)," "))
            end
        end # end for id in keys

        make_reg_toml(make_repo_for_this_packages,packages_metadata,reg_root,type)
        commit_changes(reg_root)
end


text:
function get_spice()
    root_url = "http://naif.jpl.nasa.gov/pub/naif/toolkit/C/"

    @static if is_linux()
      platform_url = "PC_Linux_GCC_64bit/"
    end

    @static if is_apple()
      platform_url = "MacIntel_OSX_AppleC_64bit/"
    end

    @static if is_windows()
      platform_url = "PC_Windows_VisualC_32bit/"
    end

    pkg_name = "packages/cspice.tar.Z"
    @static if is_windows()
      pkg_name = "packages/cspice.zip"
    end

    @static if !is_windows()
        full_url = root_url * platform_url * pkg_name
        println()
        println(" - Downloading SPICE library:")
        println("   ", full_url)
        print("   This might take a moment...   ")

        cspice_archive = get(full_url)
        println("OK")
        save(cspice_archive, joinpath(install_path, basename(pkg_name)))
    end
    nothing
end

function init_spice()
  get_spice()
  cd(install_path)
  try
    rm("cspice")
    rm("cspice.tar.Z")
  catch
  end
  @static if !is_windows()
    run(`tar -zxf cspice.tar.Z`)
    rm("cspice.tar.Z")
  end
  @static if is_linux()
    compileLinux(install_path)
  end
  @static if is_apple()
    compileOSX(install_path)
  end
  @static if is_windows()
    compileWin(install_path)
  end
end

function compileOSX(path)
  previousDir = pwd()
  cd(joinpath(path, "cspice", "lib"))
  run(`ar -x cspice.a`)
  run(`ar -x csupport.a`)
  objectFiles = get_object_files(".")
  run(`gcc -dynamiclib -lm $objectFiles -o spice.dylib`)
  run(`rm $objectFiles`)
  cd(previousDir)
  nothing
end

function compileLinux(path)
  previousDir = pwd()
  cd(joinpath(path, "cspice", "lib"))
  run(`ar -x cspice.a`)
  run(`ar -x csupport.a`)
  objectFiles = get_object_files(".")
  run(`gcc -shared -fPIC -lm $objectFiles -o spice.so`)
  run(`rm $objectFiles`)
  cd(previousDir)
  nothing
end

function compileWin(path)
  mkdir(joinpath(path, "cspice"))
  mkdir(joinpath(path, "cspice", "lib"))
  cp(joinpath(path, "cspice.dll"), joinpath(path, "cspice", "lib", "spice.dll" ))
  nothing
end

function get_object_files(path)
  objectFiles = AbstractString[]
  for fileName in readdir(path)
    if split(fileName, '.')[end] == "o"
      push!(objectFiles, fileName)
    end
  end
  return objectFiles

end


text:
using HTTP2.Frame
import HTTP2: bytearr

@test decode(IOBuffer(encode(ContinuationFrame(false, 0x51, bytearr("test"))))) == ContinuationFrame(false, 0x51, bytearr("test"))
@test decode(IOBuffer(encode(DataFrame(0x51, false, bytearr("test"))))) == DataFrame(0x51, false, bytearr("test"))
@test decode(IOBuffer(encode(GoawayFrame(0x4f, 0x4, bytearr("test"))))) == GoawayFrame(0x4f, 0x4, bytearr("test"))
@test decode(IOBuffer(encode(HeadersFrame(false, false, true, 0x51, false, 0x50, 0x1, bytearr("test"))))) == HeadersFrame(false, false, true, 0x51, false, 0x50, 0x1, bytearr("test"))
@test decode(IOBuffer(encode(PingFrame(false, bytearr("testtest"))))) == PingFrame(false, bytearr("testtest"))
@test decode(IOBuffer(encode(PriorityFrame(0x51, false, 0x50, 0x2)))) == PriorityFrame(0x51, false, 0x50, 0x2)
@test decode(IOBuffer(encode(PushPromiseFrame(false, 0x51, 0x54, bytearr("test"))))) == PushPromiseFrame(false, 0x51, 0x54, bytearr("test"))
@test decode(IOBuffer(encode(RstStreamFrame(0x51, 0x4)))) == RstStreamFrame(0x51, 0x4)
@test decode(IOBuffer(encode(SettingsFrame(true, nothing)))) == SettingsFrame(true, nothing)
@test decode(IOBuffer(encode(WindowUpdateFrame(0x51, 0x2)))) == WindowUpdateFrame(0x51, 0x2)


text:
# This file is a part of BAT.jl, licensed under the MIT License (MIT).

include("error_log.jl")
include("util_functions.jl")
include("array_utils.jl")
include("convolution_utils.jl")
include("coord_utils.jl")
include("valueshapes_utils.jl")
include("executors.jl")

# Included via @require: "executors_folds.jl")