text:
"""
`module  JAC.TestFrames`
    ... a submodel of JAC that contains all methods for testing individual methods, modules, ....
"""
module TestFrames

    using Printf, JLD, JAC, ..AngularMomentum, ..Basics, ..Continuum, ..Defaults, ..ManyElectron, ..Nuclear, ..Radial, ..TableStrings

    export testDummy

    function testCompareFiles(fold::String, fnew::String, sa::String, noLines::Int64)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        # Compare the test computations with previous results
        oldLines = readlines(fold)
        newLines = readlines(fnew)
        iold = 0;  for i=1:length(oldLines)   line = oldLines[i];   if  occursin(sa, line)  iold = i;   break   end   end
        inew = 0;  for i=1:length(newLines)   line = newLines[i];   if  occursin(sa, line)  inew = i;   break   end   end
        if  iold == 0   ||   inew == 0    success = false
            if printTest   println(iostream, "Tries to compare two inappropriate files fold = $(fold); fnew =$(fnew) on string $sa  ($iold, $inew)")  end
            return( success )
        end
        #
        ii = inew + 1
        for  i = iold+2:iold+noLines
        ii = ii + 1
        if   length(oldLines[i]) < 5    continue    end
        if   oldLines[i] != newLines[ii]    success = false
            if  printTest  println(iostream, "    *** Old::  " * oldLines[i])
                            println(iostream, "    *** New::  " * newLines[ii])
            end
        end
        end

        return( success )
    end

    function testPrint(sa::String, success::Bool)
        printTest, iostream = Defaults.getDefaults("test flag/stream")
        ok(succ) =  succ ? "[OK]" : "[Fail]"
        sb = sa * TableStrings.hBlank(110);   sb = sb[1:100] * ok(success);    println(iostream, sb)
        return( nothing )
    end

    """
    `TestFrames.testEvaluation_Wigner_3j_specialValues(; short::Bool=true)`
        ... tests on special values for the Wigner 3j symbols.
    """
    function testEvaluation_Wigner_3j_specialValues(; short::Bool=true)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        w3j = RacahAlgebra.selectW3j(2);                    println(">> w3j-original     = $w3j")
        wa  = RacahAlgebra.symmetricForms(w3j)
        wb  = RacahAlgebra.evaluate(wa[1], special=true);   println(">> wb-special value  = $wb")
        wc  = RacahAlgebra.evaluate(wa[2], special=true);   println(">> wc-special value  = $wc")
        if  wb != wc
            success = false
            if printTest   info(iostream, "$w3j:   $wb != $wc")   end
        end

        testPrint("testEvaluation_Wigner_3j_specialValues()::", success)
        return(success)
    end

    """
    `TestFrames.testEvaluation_Wigner_6j_specialValues(; short::Bool=true)`
        ... tests on special values for the Wigner 6j symbols.
    """
    function testEvaluation_Wigner_6j_specialValues(; short::Bool=true)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        w6j = RacahAlgebra.selectW6j(2);                    println(">> w6j-original      = $w6j")
        wa  = RacahAlgebra.symmetricForms(w6j)
        wb  = RacahAlgebra.evaluate(wa[1], special=true);   println(">> wb-special value  = $wb")
        wc  = RacahAlgebra.evaluate(wa[2], special=true);   println(">> wc-special value  = $wc")
        if  wb != wc
            success = false
            if printTest   info(iostream, "$w6j:   $wb != $wc")   end
        end

        testPrint("testEvaluation_Wigner_6j_specialValues()::", success)
        return(success)
    end

    """
    `TestFrames.testEvaluation_Wigner_9j_specialValues(; short::Bool=true)`
        ... tests on special values for the Wigner 9j symbols.
    """
    function testEvaluation_Wigner_9j_specialValues(; short::Bool=true)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        w9j = RacahAlgebra.selectW9j(2);                     println(">> w9j-original     = $w9j")
        wa  = RacahAlgebra.symmetricForms(w9j)
        wb  = RacahAlgebra.evaluate(wa[5],  special=true);   println(">> wb-special value = $wb")
        wc  = RacahAlgebra.evaluate(wa[11], special=true);   println(">> wc-special value = $wc")
        if  wb != wc
            success = false
            if printTest   info(iostream, "$w9j:   $wb != $wc")   end
        end

        testPrint("testEvaluation_Wigner_9j_specialValues()::", success)
        return(success)
    end

    """
    `TestFrames.testEvaluation_sumRulesForOneWnj(; short::Bool=true)`
        ... tests on special values for the Wigner 3-j symbols.
    """
    function testEvaluation_sumRulesForOneWnj(; short::Bool=true)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        rex = RacahAlgebra.selectRacahExpression(1);         println(">> rex-original  = $rex")
        wa  = RacahAlgebra.evaluate(rex);                    println(">> rex-evaluated = $wa")
        if  wa == nothing
            success = false
            if printTest   info(iostream, "No simplification found for $rex")   end
        end

        rex = RacahAlgebra.selectRacahExpression(2);         println(">> rex-original  = $rex")
        wa  = RacahAlgebra.evaluate(rex);                    println(">> rex-evaluated = $wa")
        if  wa == nothing
            success = false
            if printTest   info(iostream, "No simplification found for $rex")   end
        end

        rex = RacahAlgebra.selectRacahExpression(3);         println(">> rex-original  = $rex")
        wa  = RacahAlgebra.evaluate(rex);                    println(">> rex-evaluated = $wa")
        if  wa == nothing
            success = false
            if printTest   info(iostream, "No simplification found for $rex")   end
        end

        rex = RacahAlgebra.selectRacahExpression(4);         println(">> rex-original  = $rex")
        wa  = RacahAlgebra.evaluate(rex);                    println(">> rex-evaluated = $wa")
        if  wa == nothing
            success = false
            if printTest   info(iostream, "No simplification found for $rex")   end
        end

        rex = RacahAlgebra.selectRacahExpression(5);         println(">> rex-original  = $rex")
        wa  = RacahAlgebra.evaluate(rex);                    println(">> rex-evaluated = $wa")
        if  wa == nothing
            success = false
            if printTest   info(iostream, "No simplification found for $rex")   end
        end

        testPrint("testEvaluation_sumRulesForOneWnj()::", success)
        return(success)
    end

    """
    `TestFrames.testEvaluation_sumRulesForTwoWnj(; short::Bool=true)`
        ... tests on special values for the Wigner 3-j symbols.
    """
    function testEvaluation_sumRulesForTwoWnj(; short::Bool=true)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        rex = RacahAlgebra.selectRacahExpression(6);         println(">> rex-original  = $rex")
        wa  = RacahAlgebra.evaluate(rex);                    println(">> rex-evaluated = $wa")
        if  wa == nothing
            success = false
            if printTest   info(iostream, "No simplification found for $rex")   end
        end

        rex = RacahAlgebra.selectRacahExpression(7);         println(">> rex-original  = $rex")
        wa  = RacahAlgebra.evaluate(rex);                    println(">> rex-evaluated = $wa")
        if  wa == nothing
            success = false
            if printTest   info(iostream, "No simplification found for $rex")   end
        end

        rex = RacahAlgebra.selectRacahExpression(8);         println(">> rex-original  = $rex")
        wa  = RacahAlgebra.evaluate(rex);                    println(">> rex-evaluated = $wa")
        if  wa == nothing
            success = false
            if printTest   info(iostream, "No simplification found for $rex")   end
        end

        testPrint("testEvaluation_sumRulesForTwoWnj()::", success)
        return(success)
    end

    """
    `Basics.testMethod_integrate_ongrid(; short::Bool=true)`  ... tests the integration on grid.
    """
    function testMethod_integrate_ongrid(; short::Bool=true)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        # Test the integration on the grid for an analytical function
        grid = Radial.Grid(Radial.Grid(false), rnt=2.0e-10, h=5.0e-3, NoPoints=9000)
        function f1(r)
            A = 10^5;    gamma = 3;    a = 300
            return( A * r^gamma * exp(-a * r^2) )
        end
        exact1 = 5/9

        integrand = Vector{Float64}(size(grid.r, 1))
        for i = 1:size(grid.r, 1)
            integrand[i] = f1(grid.r[i])
        end
        integrand = integrand .* grid.rp[1:size(integrand, 1)]   # adopt to the form of Grasp92

        integral  = Basic.integrate("function: on radial grid, Newton-Cotes", integrand, grid)
        err = abs(integral - exact1)
        if  abs(err) > 1.0e-12
            success = false
            if printTest   info(iostream, "... Newton-Cotes:  I = $integral,  Err = $err")  end
        end

        integral  = Basic.integrate("function: on radial grid, Simpson rule", integrand, grid)
        err = abs(integral - exact1)
        if  abs(err) > 1.0e-12
            success = false
            if printTest   info(iostream, "... Simpson rule:  I = $integral,  Err = $err")  end
        end

        integral  = Basic.integrate("function: on radial grid, trapez rule", integrand, grid)
        err = abs(integral - exact1)
        if  abs(err) > 1.0e-12
            success = false
            if printTest   info(iostream, "... trapez rule:  I = $integral,  Err = $err")  end
        end

        println(iostream, "Warning(testMethod_integrate_ongrid): test of integration with Grasp orbitals has been set silent.")
        #=
        # Test the integration with orbital functions from Grasp92
        grid = Radial.Grid(true)

        orbitals1 = Basics.readOrbitalFileGrasp92("../test/approved/Ne-0+-scf.exp.out", grid)
        orbitals2 = Basics.readOrbitalFileGrasp92("../test/approved/Ne-1+-scf.exp.out", grid)

        for i = 1:size(orbitals1, 1)
            for j = 1:size(orbitals2, 1)
                orb1      = orbitals1[i];   orb2 = orbitals2[j]
                if   orb1.subshell.kappa != orb2.subshell.kappa    break   end

                mtp       = min(size(orb1.P, 1), size(orb2.P, 1))
                integrand = ( orb1.P[1:mtp] .* orb2.P[1:mtp] + orb1.Q[1:mtp] .* orb2.Q[1:mtp] ) .* grid.rp[1:mtp]

                integrala = Basic.integrate("function: on radial grid, Newton-Cotes", integrand, grid)^2
                integralb = Basic.integrate("function: on radial grid, Simpson rule", integrand, grid)^2
                integralc = Basic.integrate("function: on radial grid, trapez rule",  integrand, grid)^2

                info(iostream, "<$(string(orb1.subshell)) | $(string(orb2.subshell))> = $integrala, $integralb, $integralc")
            end
        end  =#

        testPrint("testMethod_integrate_ongrid()::", success)
        return(success)
    end

    """
    `TestFrames.testMethod_Wigner_3j(; short::Bool=true)`  ... tests on Wigner 3j symbols.
    """
    function testMethod_Wigner_3j(; short::Bool=true)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        # Wigner_3j(1,2,1,0,0,0) = 0.36514837167011074230
        a = c = AngularJ64(1);    b = AngularJ64(2);    ma = mb = mc = AngularM64(0)
        wa = AngularMomentum.Wigner_3j(a,b,c,ma,mb,mc)
        if  abs(wa - 0.36514837167011074230) > 1.0e-12
            success = false
            if printTest   info(iostream, "Wigner_3j(1,2,1,0,0,0) = 0.36514837167011074230 ... but obtains value = $wa")   end
        end

        # Wigner_3j(3,6,3,0,0,0) = 0.182482967150452976281
        a = c = AngularJ64(3);    b = AngularJ64(6);    ma = mb = mc = AngularM64(0)
        wa = AngularMomentum.Wigner_3j(a,b,c,ma,mb,mc)
        if  abs(wa - 0.18248296715045297628) > 1.0e-12
            success = false
            if printTest   info(iostream, "Wigner_3j(3,6,3,0,0,0) = 0.182482967150452976281 ... but obtains value = $wa")   end
        end

        # Wigner_3j(1/2,1,1/2,1/2,0,-1/2) = 0.40824829046386301637
        a = c = AngularJ64(1//2);    b = AngularJ64(1);    ma =  AngularM64(1//2);   mb =  AngularM64(0);    mc = AngularM64(-1//2)
        wa = AngularMomentum.Wigner_3j(a,b,c,ma,mb,mc)
        if  abs(wa - 0.40824829046386301637) > 1.0e-12
            success = false
            if printTest   info(iostream, "Wigner_3j(1/2,1,1/2,1/2,0,-1/2) = 0.40824829046386301637 ... but obtains value = $wa")  end
        end

        testPrint("testMethod_Wigner_3j()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_AlphaVariation(; short::Bool=true)`  ... tests on module AlphaVariation.
    """
    function testModule_AlphaVariation(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-AlphaVariation-new.sum")
        printstyled("\n\nTest the module  AlphaVariation  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=Radial.Grid(true),
                                nuclearModel=Nuclear.Model(26.),
                                configs=[Configuration("[Ne] 3s^2 3p^5"), Configuration("[Ne] 3s 3p^6")],
                                propertySettings = [ AlphaVariation.Settings(true, true, LevelSelection() )] )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-AlphaVariation-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-AlphaVariation-new.sum"), "Alpha variation parameters:", 1)
        testPrint("testModule_AlphaVariation()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_AutoIonization(; short::Bool=true)`  ... tests on module AutoIonization.
    """
    function testModule_AutoIonization(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-AutoIonization-new.sum")
        printstyled("\n\nTest the module  AutoIonization  ... \n", color=:cyan)
        ### Make the tests
        grid = Radial.Grid(Radial.Grid(false), rnt = 2.0e-5, h = 5.0e-2, hp = 1.5e-2, rbox = 9.5)
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=grid, nuclearModel=Nuclear.Model(36.),
                                initialConfigs=[Configuration("1s^2 2s^2 2p"), Configuration("1s 2s^2 2p^2")],
                                finalConfigs  =[Configuration("1s^2 2s^2"), Configuration("1s^2 2p^2")],
                                processSettings = AutoIonization.Settings(true, true, LineSelection(true, indexPairs=[(3,1), (4,1), (5,1), (6,1)]),
                                                                          0., 1.0e6, 2, CoulombInteraction()) )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-AutoIonization-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-AutoIonization-new.sum"), "Auger rates and intrinsic", 5)
        testPrint("testModule_AutoIonization()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_Cascade_StepwiseDecay(; short::Bool=true)`  ... tests on module Cascade.
    """
    function testModule_Cascade_StepwiseDecay(; short::Bool=true)
        Defaults.setDefaults("method: continuum, asymptotic Coulomb")    ## setDefaults("method: continuum, Galerkin")
        Defaults.setDefaults("method: normalization, pure sine")         ## setDefaults("method: normalization, pure Coulomb")
        Defaults.setDefaults("print summary: open", "test-Cascade-StepwiseDecay-new.sum")
        printstyled("\n\nTest the module  Cascade for the StepwiseDecayScheme ... \n", color=:cyan)
        ### Make the tests
        name = "Cascade after neon 1s --> 3p excitation"
        grid = Radial.Grid(Radial.Grid(false), rnt = 2.0e-5, h = 5.0e-2, hp = 1.5e-2, rbox = 9.5)
        wa   = Cascade.Computation(Cascade.Computation(); name=name, nuclearModel=Nuclear.Model(10.), grid=grid, approach=Cascade.AverageSCA(),
                                   scheme=Cascade.StepwiseDecayScheme([Auger(), Radiative()], 1, Dict{Int64,Float64}(), 0, Shell[], Shell[]),
                                   initialConfigs=[Configuration("1s^1 2s^2 2p^6 3p")] )
        println(wa)
        wb = perform(wa; output=true)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-Cascade-StepwiseDecay-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-Cascade-StepwiseDecay-new.sum"), "Steps that are defined for the curren", 15)
        testPrint("testModule_Cascade-StepwiseDecay()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_Cascade_PhotonIonization(; short::Bool=true)`  ... tests on module Cascade.
    """
    function testModule_Cascade_PhotonIonization(; short::Bool=true)
        Defaults.setDefaults("method: continuum, asymptotic Coulomb")    ## setDefaults("method: continuum, Galerkin")
        Defaults.setDefaults("method: normalization, pure sine")         ## setDefaults("method: normalization, pure Coulomb")
        Defaults.setDefaults("print summary: open", "test-Cascade-PhotonIonization-new.sum")
        printstyled("\n\nTest the module  Cascade for the PhotonIonizationScheme ... \n", color=:cyan)
        ### Make the tests
        name = "Photoionization of Si- "
        grid = Radial.Grid(Radial.Grid(false); rnt = 3.0e-6, h = 2.0e-2, hp = 3.0e-2, rbox = 11.0)
        wa   = Cascade.Computation(Cascade.Computation(); name=name, nuclearModel=Nuclear.Model(10.), grid=grid, approach=Cascade.AverageSCA(),
                                   scheme=Cascade.PhotonIonizationScheme([Photo()], 1, [5.0]),
                                   initialConfigs=[Configuration("1s^2 2s^2 2p^5")] )
        wb = perform(wa; output=true)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-Cascade-PhotonIonization-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-Cascade-PhotonIonization-new.sum"), "Total photoionization cross sections for", 15)
        testPrint("testModule_Cascade-PhotonIonization()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_Cascade_PhotonExcitation(; short::Bool=true)`  ... tests on module Cascade.
    """
    function testModule_Cascade_PhotonExcitation(; short::Bool=true)
        Defaults.setDefaults("method: continuum, asymptotic Coulomb")    ## setDefaults("method: continuum, Galerkin")
        Defaults.setDefaults("method: normalization, pure sine")         ## setDefaults("method: normalization, pure Coulomb")
        Defaults.setDefaults("print summary: open", "test-Cascade-PhotonExcitation-new.sum")
        printstyled("\n\nTest the module  Cascade for the PhotonExcitationScheme ... \n", color=:cyan)
        ### Make the tests
        grid = Radial.Grid(Radial.Grid(false); rnt = 3.0e-6, h = 2.0e-2, hp = 3.0e-2, rbox = 11.0)
        name = "Photoabsorption calculations for Ne^+ for energies = [1, 4] a.u."
        wa   = Cascade.Computation(Cascade.Computation(); name=name, nuclearModel=Nuclear.Model(10.), grid=grid, approach=Cascade.AverageSCA(),
                                   scheme=Cascade.PhotonExcitationScheme([PhotoExc()], [E1], 0.5, 4.0, 1, [Shell("2s"), Shell("2p")],
                                                                         [Shell("2s"), Shell("2p"), Shell("3p"), Shell("4p"), Shell("5p")]),
                                                                         initialConfigs=[Configuration("1s^2 2s^2 2p^5")] )
        wb = perform(wa; output=true)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-Cascade-PhotonExcitation-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-Cascade-PhotonExcitation-new.sum"), "Steps that are defined for the", 15)
        testPrint("testModule_Cascade-PhotonExcitation()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_Cascade_Simulation(; short::Bool=true)`  ... tests on module Cascade.
    """
    function testModule_Cascade_Simulation(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-Cascade-Simulation-new.sum")
        printstyled("\n\nTest the module  Cascade for Simulations ... \n", color=:cyan)
        ### Make the tests
        datafile = joinpath(@__DIR__, "..", "test", "approved", "test-Cascade-StepwiseDecay-data.jld")
        data = [JLD.load(datafile)]
        name = "Simulation of the neon 1s^-1 3p decay"

        wc   = Cascade.Simulation(Cascade.Simulation(), name=name, property=Cascade.IonDistribution(),
                                  settings=Cascade.SimulationSettings(0., 0., 0., 0., 0., [(1, 2.0), (2, 1.0), (3, 0.5)]), computationData=data )
        wd = perform(wc; output=true)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-Cascade-Simulation-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-Cascade-Simulation-new.sum"), "(Final) Ion distribution for", 7)
        testPrint("testModule_Cascade-Simulation()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_CoulombExcitation(; short::Bool=true)`  ... tests on module CoulombExcitation.
    """
    function testModule_CoulombExcitation(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-CoulombExcitation-new.sum")
        printstyled("\n\nTest the module  CoulombExcitation  ... \n", color=:cyan)
        ### Make the tests
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        printTest, iostream = Defaults.getDefaults("test flag/stream")
        println(iostream, "Make the comparison with approved data for ... test-CoulombExcitation-new.sum")
        success = true
        ## success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-AutoIonization-approved.sum"),
        ##                             joinpath(@__DIR__, "..", "test", "test-AutoIonization-new.sum"), "AutoIonization rates and intrinsic angular parameters:", 25)
        testPrint("testModule_CoulombExcitation()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_DecayYield(; short::Bool=true)`  ... tests on module DecayYield.
    """
    function testModule_DecayYield(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-DecayYield-new.sum")
        printstyled("\n\nTest the module  DecayYield  ... \n", color=:cyan)
        ### Make the tests
        grid = Radial.Grid(Radial.Grid(false), rnt = 2.0e-5, h = 5.0e-2, hp = 2.0e-2, rbox=10.0)
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=grid, nuclearModel=Nuclear.Model(12.),
                                configs=[Configuration("1s 2s^2 2p^6")],
                                propertySettings = [ DecayYield.Settings("SCA", true, LevelSelection() )] )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-DecayYield-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-DecayYield-new.sum"), "Fluorescence and Auger", 4)
        testPrint("testModule_DecayYield()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_Dielectronic(; short::Bool=true)`  ... tests on module Dielectronic.
    """
    function testModule_Dielectronic(; short::Bool=true)     Defaults.setDefaults("print summary: open", "test-Dielectronic-new.sum")
        printstyled("\n\nTest the module  Dielectronic  ... \n", color=:cyan)
        ### Make the tests
        grid = Radial.Grid(Radial.Grid(false), rnt = 2.0e-5, h = 5.0e-2, hp = 2.0e-2, rbox = 7.0)
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=grid,
                                nuclearModel=Nuclear.Model(26.),
                                initialConfigs=[Configuration("1s^2 2s"), Configuration("1s^2 2p")],
                                intermediateConfigs=[Configuration("1s 2s^2 2p"), Configuration("1s 2s 2p^2") ],
                                finalConfigs  =[Configuration("1s^2 2s^2"), Configuration("1s^2 2s 2p") ],
                                processSettings=Dielectronic.Settings([E1, M1], [UseCoulomb, UseBabushkin], false, false,
                                                                      PathwaySelection(true, indexTriples=[(1,1,0)]), 0., 0., 0., Float64[], CoulombInteraction() )
)
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-Dielectronic-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-Dielectronic-new.sum"),
                                "Partial (Auger) capture", 10)
        testPrint("testModule_Dielectronic()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_Einstein(; short::Bool=true)`  ... tests on module Einstein.
    """
    function testModule_Einstein(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-Einstein-new.sum")
        printstyled("\n\nTest the module  Einstein  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=Radial.Grid(true), nuclearModel=Nuclear.Model(36.),
                                configs=[Configuration("1s 2s^2"), Configuration("1s 2s 2p"), Configuration("1s 2p^2")],
                                propertySettings = [ Einstein.Settings([E1, M1, E2, M2], true,
                                                     LineSelection(true, indexPairs=[(5,0), (7,0), (10,0), (11,0), (12,0), (13,0), (14,0)]), 0., 0., 10000. )] )

        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-Einstein-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-Einstein-new.sum"), "Einstein coefficients, t", 100)
        testPrint("testModule_Einstein()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_FormFactor(; short::Bool=true)`  ... tests on module FormFactor.
    """
    function testModule_FormFactor(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-FormFactor-new.sum")
        printstyled("\n\nTest the module  FormFactor  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=Radial.Grid(true), nuclearModel=Nuclear.Model(26.),
                                configs=[Configuration("[Ne] 3s^2 3p^5"), Configuration("[Ne] 3s 3p^6")],
                                propertySettings = [ FormFactor.Settings([0.1], true, LevelSelection() )] )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-FormFactor-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-FormFactor-new.sum"), "Standard and modifi", 6)
        testPrint("testModule_FormFactor()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_Hfs(; short::Bool=true)`  ... tests on module Hfs.
    """
    function testModule_Hfs(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-Hfs-b-new.sum")
        printstyled("\n\nTest the module  Hfs  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=Radial.Grid(true),
                                nuclearModel=Nuclear.Model(26., "Fermi", 58., 3.81, AngularJ64(5//2), 1.0, 1.0),
                                configs=[Configuration("[Ne] 3s^2 3p^5"), Configuration("[Ne] 3s 3p^6")],
                                propertySettings = [ Hfs.Settings(true, true, true, true, true, true, LevelSelection() )] )

        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        println("aaa  ")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-Hfs-b-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-Hfs-b-new.sum"), "Level        J^P           Energy", 20)
        println("bbb  success = $success")
        testPrint("testModule_Hfs()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_IsotopeShift(; short::Bool=true)`  ... tests on module IsotopeShift.
    """
    function testModule_IsotopeShift(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-IsotopeShift-new.sum")
        printstyled("\n\nTest the module  IsotopeShift  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=Radial.Grid(true),
                                nuclearModel=Nuclear.Model(26.),
                                configs=[Configuration("[Ne] 3s^2 3p^5"), Configuration("[Ne] 3s 3p^6")],
                                propertySettings = [ IsotopeShift.Settings(true, true, true, false, true, 0.0, LevelSelection())] )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-IsotopeShift-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-IsotopeShift-new.sum"), "IsotopeShift parameters and amplitudes:", 15)
        testPrint("testModule_IsotopeShift()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_LandeZeeman(; short::Bool=true)`  ... tests on module LandeZeeman.
    """
    function testModule_LandeZeeman(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-LandeZeeman-new.sum")
        printstyled("\n\nTest the module  LandeZeeman  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=Radial.Grid(true),
                                nuclearModel=Nuclear.Model(26., "Fermi", 58., 3.75, AngularJ64(5//2), 1.0, 2.0),
                                configs=[Configuration("[Ne] 3s^2 3p^5"), Configuration("[Ne] 3s 3p^6")],
                                propertySettings = [ LandeZeeman.Settings(true, true, true, true, 0., true, LevelSelection() )] )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-LandeZeeman-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-LandeZeeman-new.sum"), "Lande g_J factors and Zeeman amplitudes:", 30)
        testPrint("testModule_LandeZeeman()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_MultiPhotonDeExcitation(; short::Bool=true)`  ... tests on module MultiPhotonDeExcitation.
    """
    function testModule_MultiPhotonDeExcitation(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-MultiPhotonDeExcitation-new.sum")
        printstyled("\n\nTest the module  MultiPhotonDeExcitation  ... \n", color=:cyan)
        ### Make the tests
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        printTest, iostream = Defaults.getDefaults("test flag/stream")
        println(iostream, "Make the comparison with approved data for ... test-MultiPhotonDeExcitation-new.sum")
        success = true
        ## success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-MultiPhotonDeExcitation-approved.sum"),
        ##                             joinpath(@__DIR__, "..", "test", "test-MultiPhotonDeExcitation-new.sum"), "xxx", 100)
        testPrint("testModule_MultiPhotonDeExcitation()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_MultipoleMoment(; short::Bool=true)`  ... tests on module MultipoleMoment.
    """
    function testModule_MultipoleMoment(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-MultipoleMoment-new.sum")
        ### Make the tests
        printstyled("\n\nTest the module  MultipoleMoment  ... \n", color=:cyan)
        grid = Radial.Grid(true)
        wa = Atomic.Computation(Atomic.Computation(),
                                name="xx",  nuclearModel=Nuclear.Model(26.), grid=grid,
                                configs=[Configuration("1s 2s^2"), Configuration("1s 2s 2p"), Configuration("1s 2p^2")], printout=true )

        wxa  = perform(wa; output=true)
        wma  = wxa["multiplet:"]

        flow = 6;    fup = 8;   ilow = 1;   iup = 3
        println("\n\nDipole amplitudes:\n")
        for  finalLevel in wma.levels
            for  initialLevel in wma.levels
                if  flow <= finalLevel.index <= fup   &&    ilow <= initialLevel.index <= iup
                    MultipoleMoment.dipoleAmplitude(finalLevel, initialLevel, grid; display=true)
                end
            end
        end
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-MultipoleMoment-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-MultipoleMoment-new.sum"), "Dipole amplitude", 2)
        testPrint("testModule_MultipoleMoment()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_MultipolePolarizibility(; short::Bool=true)`  ... tests on module MultipolePolarizibility.
    """
    function testModule_MultipolePolarizibility(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-MultipolePolarizibility-new.sum")
        printstyled("\n\nTest the module  MultipolePolarizibility  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=Radial.Grid(true),
                                nuclearModel=Nuclear.Model(26.),
                                configs=[Configuration("[Ne] 3s^2 3p^5"), Configuration("[Ne] 3s 3p^6")],
                                propertySettings = [ MultipolePolarizibility.Settings(EmMultipole[], 0, 0, Float64[], false, LevelSelection() )] )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-MultipolePolarizibility-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-MultipolePolarizibility-new.sum"),
                                "Multipole polarizibilities and amplitudes:", 5)
        testPrint("testModule_MultipolePolarizibility()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_ParityNonConservation(; short::Bool=true)`  ... tests on module ParityNonconservation.
    """
    function testModule_ParityNonConservation(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-ParityNonConservation-new.sum")
        printstyled("\n\nTest the module  ParityNonConservation  ... \n", color=:cyan)
        ### Make the tests
        grid = Defaults.getDefaults("standard grid")
        wa = Atomic.Computation(Atomic.Computation(), name="xx",  nuclearModel=Nuclear.Model(26.),
                                grid=grid,
                                configs=[Configuration("1s 2s^2"), Configuration("1s 2s 2p"), Configuration("1s 2p^2")] )

        wxa  = perform(wa; output=true)
        wma  = wxa["multiplet:"]

        nModel = Nuclear.Model(26.);    flow = 6;    fup = 8;   ilow = 1;   iup = 3

        println("\n\nWeak-charge and Schiff-moment amplitudes:\n")
        for  finalLevel in wma.levels
            for  initialLevel in wma.levels
                if  flow <= finalLevel.index <= fup   &&    ilow <= initialLevel.index <= iup
                    ParityNonConservation.weakChargeAmplitude(finalLevel, initialLevel, nModel, grid; display=true)
                    ParityNonConservation.schiffMomentAmplitude(finalLevel, initialLevel, nModel, grid; display=true)
                end
            end
        end
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-ParityNonConservation-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-ParityNonConservation-new.sum"), "weak-charge amplitude", 12)
        testPrint("testModule_ParityNonConservation()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_PlasmaShift(; short::Bool=true)`  ... tests on module PlasmaShift.
    """
    function testModule_PlasmaShift(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-PlasmaShift-new.sum")
        printstyled("\n\nTest the module  PlasmaShift  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=Radial.Grid(true),
                                nuclearModel=Nuclear.Model(26.),
                                configs=[Configuration("[Ne] 3s^2 3p^5"), Configuration("[Ne] 3s 3p^6")],
                                propertySettings = [ PlasmaShift.Settings()] )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-PlasmaShift-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-PlasmaShift-new.sum"), "Plasma screening", 3)
        testPrint("testModule_PlasmaShift()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_PhotoExcitation(; short::Bool=true)`  ... tests on module PhotoExcitation.
    """
    function testModule_PhotoExcitation(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-PhotoExcitation-new.sum")
        printstyled("\n\nTest the module  PhotoExcitation  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=Radial.Grid(true),
                                nuclearModel=Nuclear.Model(36.),
                                initialConfigs=[Configuration("1s 2s^2"), Configuration("1s 2s 2p"), Configuration("1s 2p^2")],
                                finalConfigs  =[Configuration("1s 2s^2"), Configuration("1s 2s 2p"), Configuration("1s 2p^2")],
                                processSettings=PhotoExcitation.Settings([E1, M1], [UseCoulomb, UseBabushkin], true, true, true, true,
                                                                         LineSelection(), 0., 0., 1.0e6, Basics.ExpStokes(0., 0., 0.) ) )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-PhotoExcitation-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-PhotoExcitation-new.sum"),
                                "Photoexcitation cross sections for (completely)", 200)
        testPrint("testModule_PhotoExcitation()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_PhotoExcitationAutoion(; short::Bool=true)`  ... tests on module PhotoExcitationAutoion.
    """
    function testModule_PhotoExcitationAutoion(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-PhotoExcitationAutoion-new.sum")
        printstyled("\n\nTest the module  PhotoExcitationAutoion  ... \n", color=:cyan)
        ### Make the tests
        grid = Radial.Grid(Radial.Grid(false), rnt = 2.0e-5, h = 5.0e-2, hp = 1.5e-2, NoPoints = 600)
        wa = Atomic.Computation("xx",  Nuclear.Model(26.); grid=grid,
                                initialConfigs=[Configuration("1s^2 2s"), Configuration("1s^2 2p")],
                                intermediateConfigs=[Configuration("1s 2s^2"), Configuration("1s 2p^2")],
                                finalConfigs=[Configuration("1s^2")],
                                processSettings=PhotoExcitationAutoion.Settings([E1, M1], [UseCoulomb, UseBabushkin], true,
                                                                                PathwaySelection(true, indexTriples=[(1,1,1)]), 2 ) )

    wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        printTest, iostream = Defaults.getDefaults("test flag/stream")
        println(iostream, "Make the comparison with approved data for ... test-PhotoExcitationAutoion-new.sum")
        success = true
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-PhotoExcitationAutoion-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-PhotoExcitationAutoion-new.sum"), "xxx", 10)
        testPrint("testModule_PhotoExcitationAutoion()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_PhotoExcitationFluores(; short::Bool=true)`  ... tests on module PhotoExcitationFluores.
    """
    function testModule_PhotoExcitationFluores(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-PhotoExcitationFluores-new.sum")
        printstyled("\n\nTest the module  PhotoExcitationFluores  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation("xx",  Nuclear.Model(26.),
                                initialConfigs=[Configuration("1s^2 2s"), Configuration("1s^2 2p")],
                                intermediateConfigs=[Configuration("1s 2s^2 2p"), Configuration("1s 2s 2p^2") ],
                                finalConfigs  =[Configuration("1s^2 2s^2"), Configuration("1s^2 2s 2p") ],
                                processSettings=PhotoExcitationFluores.Settings([E1, M1], [UseCoulomb, UseBabushkin], true,
                                                     PathwaySelection(true, indexTriples=[(1,1,1)]) )  )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        printTest, iostream = Defaults.getDefaults("test flag/stream")
        println(iostream, "Make the comparison with approved data for ... test-PhotoExcitationFluores-new.sum")
        success = true
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-PhotoExcitationFluores-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-PhotoExcitationFluores-new.sum"),  "xxx", 10)
        testPrint("testModule_PhotoExcitationFluores()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_PhotoIonization(; short::Bool=true)`  ... tests on module PhotoIonization.
    """
    function testModule_PhotoIonization(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-PhotoIonization-new.sum")
        printstyled("\n\nTest the module  PhotoIonization  ... \n", color=:cyan)
        ### Make the tests
        grid = Radial.Grid(Radial.Grid(false), rnt = 2.0e-5, h = 5.0e-2, hp = 2.0e-2, rbox = 10.0)
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=grid, nuclearModel=Nuclear.Model(36.),
                                initialConfigs=[Configuration("1s^2 2s^2 2p^6")],
                                finalConfigs  =[Configuration("1s^2 2s^2 2p^5"), Configuration("1s^2 2s 2p^6") ],
                                processSettings=PhotoIonization.Settings([E1, M1], [UseCoulomb, UseBabushkin], [3000., 4000.], false, true, true, true,
                                                                         LineSelection(true, indexPairs=[(1,1), (1,2)]), ExpStokes(1., 0., 0.)) )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-PhotoIonization-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-PhotoIonization-new.sum"), "Total photoionization c", 3)
        testPrint("testModule_PhotoIonization()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_PhotoRecombination(; short::Bool=true)`  ... tests on module PhotoRecombination.
    """
    function testModule_PhotoRecombination(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-PhotoRecombination-new.sum")
        printstyled("\n\nTest the module  PhotoRecombination  ... \n", color=:cyan)
        ### Make the tests
        grid = Radial.Grid(Radial.Grid(true), rnt = 2.0e-5,h = 5.0e-2, hp = 1.0e-2, rbox = 6.5)
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=grid, nuclearModel=Nuclear.Model(12.),
                                initialConfigs=[Configuration("1s^2")],
                                finalConfigs  =[Configuration("1s^2 2s"), Configuration("1s^2 3s"), Configuration("1s^2 3p"), Configuration("1s^2 3d")],
                                processSettings=PhotoRecombination.Settings([E1, M1], [JAC.UseCoulomb, JAC.UseBabushkin], [10.],
                                                     [2.18, 21.8, 218.0], false, false, false, true, LineSelection() ) )
        wb = perform(wa)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-PhotoRecombination-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-PhotoRecombination-new.sum"), "Photorecombination cross sections", 10)
        testPrint("testModule_PhotoRecombination()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_PhotoEmission(; short::Bool=true)`  ... tests on module PhotoEmission.
    """
    function testModule_PhotoEmission(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-PhotoEmission-new.sum")
        printstyled("\n\nTest the module  PhotoEmission  ... \n", color=:cyan)
        ### Make the tests
        wa = Atomic.Computation(Atomic.Computation(), name="xx", grid=Radial.Grid(true), nuclearModel=Nuclear.Model(36.),
                                initialConfigs=[Configuration("1s 2s^2"), Configuration("1s 2s 2p"), Configuration("1s 2p^2")],
                                finalConfigs  =[Configuration("1s 2s^2"), Configuration("1s 2s 2p"), Configuration("1s 2p^2")],
                                processSettings=PhotoEmission.Settings([E1, M1, E2, M2], [UseCoulomb, UseBabushkin], true, true, CorePolarization(),
                                    LineSelection(true, indexPairs=[(5,0), (7,0), (10,0), (11,0), (12,0), (13,0), (14,0), (15,0), (16,0)]), 0., 0., 10000. ) )
        ##x streamDummy = open(pwd() * "/runtests.dummy", "w")
        ##x redirect_stdout(streamDummy) do
        wb = perform(wa)
        ##x end
        ##x close(streamDummy)
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-PhotoEmission-approved.sum"),
                                    joinpath(@__DIR__, "..", "test", "test-PhotoEmission-new.sum"), "Einstein coefficients, t", 100)
        testPrint("testModule_PhotoEmission()::", success)
        return(success)
    end

    """
    `TestFrames.testModule_RayleighCompton(; short::Bool=true)`  ... tests on module RayleighCompton.
    """
    function testModule_RayleighCompton(; short::Bool=true)
        Defaults.setDefaults("print summary: open", "test-RayleighCompton-new.sum")
        printstyled("\n\nTest the module  RayleighCompton  ... \n", color=:cyan)
        ### Make the tests
        ###
        Defaults.setDefaults("print summary: close", "")
        # Make the comparison with approved data
        printTest, iostream = Defaults.getDefaults("test flag/stream")
        println(iostream, "Make the comparison with approved data for ... test-RayleighCompton-new.sum")
        success = true
        ## success = testCompareFiles( joinpath(@__DIR__, "..", "test", "approved", "test-RayleighCompton-approved.sum"),
        ##                             joinpath(@__DIR__, "..", "test", "test-RayleighCompton-new.sum"), "xxx", 100)
        testPrint("testModule_RayleighCompton()::", success)
        return(success)
    end

    """
    `TestFrames.testRepresentation_MeanFieldBasis_CiExpansion(; short::Bool=true)`  ... tests on the representation .
    """
    function testRepresentation_MeanFieldBasis_CiExpansion(; short::Bool=true)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        name        = "Oxygen 1s^2 2s^2 2p^4 ground configuration"
        refConfigs  = [Configuration("[He] 2s^2 2p^4")]
        mfSettings  = MeanFieldSettings()
        #
        wa          = Representation(name, Nuclear.Model(8.), Radial.Grid(true), refConfigs, MeanFieldBasis(mfSettings) )
        wb = generate(wa, output=true)
        #
        orbitals    = wb["mean-field basis"].orbitals
        ciSettings  = CiSettings(CoulombInteraction(), LevelSelection() )
        from        = [Shell("2s")]
        #
        frozen      = [Shell("1s")]
        to          = [Shell("2s"), Shell("2p")]
        excitations = RasStep()
        #             RasStep(RasStep(), seFrom=from, seTo=deepcopy(to), deFrom=from, deTo=deepcopy(to), frozen=deepcopy(frozen))
        #
        wc          = Representation(name, Nuclear.Model(8.), Radial.Grid(true), refConfigs,
                                     CiExpansion(orbitals, excitations, ciSettings) )
        println("wc = $wc")
        wd = generate(wc, output=true)

        if  abs(orbitals[Subshell("1s_1/2")].energy + 18.705283) > 1.0e-3
            success = false
            if printTest   @info(iostream, "orbital energy $(orbitals[Subshell("1s_1/2")].energy) != -18.705283")     end
            @info(iostream, "orbital energy $(orbitals[Subshell("1s_1/2")].energy) != -18.705283")
        end
        if  abs(wd["CI multiplet"].levels[1].energy + 74.840309)  > 1.0e-2
            success = false
            if printTest   @info(iostream, "levels[1].energy $(wd["CI multiplet"].levels[1].energy) != -74.840309")   end
            @info(iostream, "levels[1].energy $(wd["CI multiplet"].levels[1].energy) != -74.840309")
        end

        testPrint("testRepresentation_MeanFieldBasis_CiExpansion()::", success)
        return(success)
    end

    """
    `TestFrames.testRepresentation_RasExpansion(; short::Bool=true)`  ... tests on the representation .
    """
    function testRepresentation_RasExpansion(; short::Bool=true)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        name        = "Beryllium 1s^2 2s^2 ^1S_0 ground state"
        refConfigs  = [Configuration("[He] 2s^2")]
        rasSettings = RasSettings([1], 24, 1.0e-6, CoulombInteraction(), LevelSelection(true, indices=[1,2,3]) )
        from        = [Shell("2s")]
        #
        frozen      = [Shell("1s")]
        to          = [Shell("2s"), Shell("2p")]
        step1       = RasStep(RasStep(), seFrom=from, seTo=deepcopy(to), deFrom=from, deTo=deepcopy(to), frozen=deepcopy(frozen))
        #
        append!(frozen, [Shell("2s"), Shell("2p")])
        append!(to,     [Shell("3s"), Shell("3p"), Shell("3d")])
        step2       = RasStep(step1; seTo=deepcopy(to), deTo=deepcopy(to), frozen=deepcopy(frozen))
        #
        append!(frozen, [Shell("3s"), Shell("3p"), Shell("3d")])
        append!(to,     [Shell("4s"), Shell("4p"), Shell("4d"), Shell("4f")])
        step3       = RasStep(step2, seTo=deepcopy(to), deTo=deepcopy(to), frozen=deepcopy(frozen))
        #
        wa          = Representation(name, Nuclear.Model(4.), Radial.Grid(true), refConfigs,
                                     RasExpansion([LevelSymmetry(0, Basics.plus)], 4, [step1, step2, step3], rasSettings) )
        wb = generate(wa, output=true)
        if  abs(wb["step3"].levels[1].energy + 14.61679117)  > 1.0e-3
            success = false
            if printTest   info(iostream, "levels[1].energy $(wd["CI multiplet"].levels[1].energy) != -14.61679117")   end
        end

        testPrint("testRepresentation_RasExpansion()::", success)
        return(success)
    end

    """
    `TestFrames.testRepresentation_GreenExpansion(; short::Bool=true)`  ... tests on the representation .
    """
    function testRepresentation_GreenExpansion(; short::Bool=true)
        success = true
        printTest, iostream = Defaults.getDefaults("test flag/stream")

        name          = "Lithium 1s^2 2s ground configuration"
        refConfigs    = [Configuration("[He] 2s")]
        greenSettings = GreenSettings(5, [0, 1, 2], 0.01, true, LevelSelection() )
        #
        wa          = Representation(name, Nuclear.Model(8.), Radial.Grid(true), refConfigs,
                                     ## GreenExpansion( AtomicState.SingleCSFwithoutCI(), Basics.DeExciteSingleElectron(),
                                     ## GreenExpansion( AtomicState.CoreSpaceCI(), Basics.DeExciteSingleElectron(),
                                        GreenExpansion( AtomicState.DampedSpaceCI(), Basics.DeExciteSingleElectron(),
                                                        [LevelSymmetry(1//2, Basics.plus), LevelSymmetry(3//2, Basics.plus)], 3, greenSettings) )
        wb = generate(wa, output=true)

        if  abs(wb["Green channels"][1].gMultiplet.levels[1].energy + 64.080705)  > 1.0e-3
            success = false
            if printTest   info(iostream, "gMultiplet.levels[1].energy $(wb["Green channels"][1].gMultiplet.levels[1].energy) != -64.080705")   end
        end

        testPrint("testRepresentation_GreenExpansion()::", success)
        return(success)
    end

end # module


text:
#=――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
    NOTE
    This file provides utilities for managing (possibly poorly-formatted)
    English text. The intent is not to implement a parser of English, since NLP
    is well beyond the scope of this library, but rather to capture common
    cases.
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――=#

module Text

export sentences

abstract type Sentence end

struct TextSentence <: Sentence
    data::String
end

Base.show(io::IO, sentence::TextSentence) = print(io, sentence.data)

"""
An iterable over the `Sentence`s contained within a block of text. The
iteration over this iterable is guaranteed to be pure and so can be done an
arbitrary number of times.
"""
struct Sentences{T}
    text::T
end

Base.IteratorSize(::Sentences) = Base.SizeUnknown()
Base.iterate(itr::Sentences, ::Nothing) = nothing
function Base.iterate(itr::Sentences, state::Some...)
    buffer = Char[]
    text = itr.text
    next = iterate(text, map(something, state)...)
    while next !== nothing
        c, st = next
        if !isempty(buffer) || !isspace(c)
            push!(buffer, c)
        end
        if c == '.' || c == '!' || c == '?'
            return TextSentence(join(buffer)), Some(st)
        end
        next = iterate(text, st)
    end
    if !isempty(buffer)
        TextSentence(join(buffer)), nothing
    else
        nothing
    end
end

"""
    sentences(text::AbstractString)

Return an iterable over the `Sentence`s contained within `text`. Sentences are
identified naïvely; that is, every full stop, exclamation mark, or question
mark is considered to delimit a sentence. This is of course prone to error, as
some full stops are used for abbreviations and not for delimiting sentences.

```jldoctest
julia> using EnglishText

julia> for s in sentences("Hi! Iterate over sentences. OK?")
           println(s)
       end
Hi!
Iterate over sentences.
OK?
```
"""
sentences(text::AbstractString) = Sentences(text)

end  # module Text

import .Text: sentences
export sentences

ext: jl


text:
export MJD, J2000, J1950,
    SECONDS_PER_MINUTE, SECONDS_PER_HOUR, SECONDS_PER_DAY, SECONDS_PER_YEAR, SECONDS_PER_CENTURY,
    MINUTES_PER_HOUR, MINUTES_PER_DAY, MINUTES_PER_YEAR, MINUTES_PER_CENTURY,
    HOURS_PER_DAY, HOURS_PER_YEAR, HOURS_PER_CENTURY,
    DAYS_PER_YEAR, DAYS_PER_CENTURY,
    YEARS_PER_CENTURY,
    OFFSET_TT_TAI, MOD_JD_77, ELG, fairhd, DAYS_PER_MILLENNIUM, TDB0, ELB, JD_MAX, JD_MIN

const MJD = 2400000.5
const J2000 = Dates.datetime2julian(DateTime(2000, 1, 1, 12, 0, 0))
const J1950 = Dates.datetime2julian(DateTime(1950, 1, 1, 12, 0, 0))

const SECONDS_PER_MINUTE   = 60.0
const SECONDS_PER_HOUR     = 60.0 * 60.0
const SECONDS_PER_DAY      = 60.0 * 60.0 * 24.0
const SECONDS_PER_YEAR     = 60.0 * 60.0 * 24.0 * 365.25
const SECONDS_PER_CENTURY  = 60.0 * 60.0 * 24.0 * 365.25 * 100.0

const MINUTES_PER_HOUR     = 60.0
const MINUTES_PER_DAY      = 60.0 * 24.0
const MINUTES_PER_YEAR     = 60.0 * 24.0 * 365.25
const MINUTES_PER_CENTURY  = 60.0 * 24.0 * 365.25 * 100.0

const HOURS_PER_DAY        = 24.0
const HOURS_PER_YEAR       = 24.0 * 365.25
const HOURS_PER_CENTURY    = 24.0 * 365.25 * 100.0

const DAYS_PER_YEAR        = 365.25
const DAYS_PER_CENTURY     = 365.25 * 100.0

const YEARS_PER_CENTURY    = 100.0

const OFFSET_TT_TAI = 32.184

const MOD_JD_77 = 43144.0
const ELG = 6.969290134e-10
const DAYS_PER_MILLENNIUM = 365250.0

const TDB0 = -6.55e-5
const ELB = 1.550519768e-8

const JD_MIN = -68569.5
const JD_MAX = 1e9

include("fairhd.jl")


text:
@testset "test gaussian likelihood" begin
  # Set random seed for reproducibility.
  Random.seed!(123)

  # Number of observations.
  N = 50000

  # Predictors. Required to be two-dimensional.
  X = rand(N, 1) * 2

  # True function.
  f(x::Real) = 3 * exp(-0.5 * x) * sin(6 * x)

  # True observation error.
  sigma_true = 0.1

  # Responses with random noise. Expected to be univariate.
  Y = f.(X[:, 1]) + randn(N) * sigma_true

  # Initialize model.
  num_inducing_points = 10  # number of inducing points
  model = HSVGP.SVGP_obj(X, Y, num_inducing_points)

  # Fit model.
  opt_trace, p_traces = HSVGP.fit_svgp!(model, n_iters=20000, batch_size=20);

  # Locations at which to precit.
  Xnew = hcat(range(0, step=0.05, stop=2))

  # True predictions (without noise).
  Ynew_true = f.(Xnew[:, 1])

  # Get posterior predictive means and SDs.
  predY, predSD = HSVGP.pred_vgp(Xnew, model)

  # Get observation error.
  err_sigma = exp(model.params.log_sigma[1])

  # Assert that the predictions are close to the truth.
  @test rmse(predY, Ynew_true) < 0.15

  # Assert that the observation error term is close to the truth.
  @test abs(err_sigma - sigma_true) < 0.05
end

max_stars_repo_name: ayanbiswas/PRISM

max_issues_repo_name: ayanbiswas/PRISM

max_forks_repo_name: ayanbiswas/PRISM


text:
"""
    divergence(f)
"""
divergence(f) = tr(gradient(f))

function symmetric_gradient end

"""
    symmetric_gradient(f)
"""
symmetric_gradient(f) = symmetic_part(gradient(f))

"""
    const ε = symmetric_gradient

Alias for the symmetric gradient
"""
const ε = symmetric_gradient

"""
    curl(f)
"""
curl(f) = grad2curl(gradient(f))

"""
    grad2curl(∇f)
"""
function grad2curl(f)
  @abstractmethod
end

function laplacian end

"""
    const Δ = laplacian

Alias for the `laplacian` function
"""
const Δ = laplacian

"""
    laplacian(f)
"""
function laplacian(f)
  g = gradient(f)
  h = gradient(g)
  tr(h)
end

"""
    ∇*f

Equivalent to

    divergence(f)
"""
(*)(::typeof(∇),f) = divergence(f)

"""
    outer(∇,f)

Equivalent to

    gradient(f)
"""
outer(::typeof(∇),f) = gradient(f)

"""
    outer(f,∇)

Equivalent to

    transpose(gradient(f))
"""
outer(f,::typeof(∇)) = transpose(gradient(f))

"""
    cross(∇,f)

Equivalent to

    curl(f)
"""
cross(::typeof(∇),f) = curl(f)

# Helpers

grad2curl(f::Field) = apply_kernel_to_field(bcast(_curl_kernel),f)

grad2curl(f::AbstractArray{<:Field}) = apply_to_field_array(bcast(_curl_kernel),f)

function _curl_kernel(∇u::TensorValue{2})
  ∇u[1,2] - ∇u[2,1]
end

function _curl_kernel(∇u::TensorValue{3})
  c1 = ∇u[2,3] - ∇u[3,2]
  c2 = ∇u[3,1] - ∇u[1,3]
  c3 = ∇u[1,2] - ∇u[2,1]
  VectorValue(c1,c2,c3)
end


text:
# Libraries
using DataFrames, Dates, FileIO, JLD;
using Contour, DecisionTree, Random, StableRNGs;
using PGFPlotsX, LaTeXStrings;
using MessyTimeSeries, MessyTimeSeriesOptim, Statistics;

overall_mse  = Matrix{Float64}(undef, 5, 2);
model_prefix = "VAR";

# BJK specific options
t0 = 52;
adj_bjk = true;

for i=1:2

    f1 = load("./$(model_prefix)_output/realised_error.jld");

    if i == 1
        realised_errors = f1["weighted_errors"];
    else
        realised_errors = f1["weighted_errors_excl_recessions"];
    end

    for j=1:5

        # Raw output
        if j <= 3
            err_type = j;
        else
            err_type = j-1;
        end

        if err_type != 3
            f2 = load("./$(model_prefix)_output/err_type_$(err_type).jld");
        else
            f2 = load("./$(model_prefix)_output/3_$(10+(j-3)*10)pct/err_type_$(err_type).jld");
        end

        expected_errors = f2["errors"];

        if err_type == 3
            if adj_bjk
                if j==3
                    bjk_sample = block_jackknife(f2["selection_sample"], 0.1);
                else
                    bjk_sample = block_jackknife(f2["selection_sample"], 0.2);
                end

                T_validation = size(bjk_sample, 2)-t0;
                missings_after_t0 = [sum(sum(ismissing.(bjk_sample[:, t0+1:end, i]), dims=1) .== size(bjk_sample, 1)) for i=1:size(bjk_sample, 3)];
                expected_errors .*= mean(T_validation ./ (T_validation .- missings_after_t0));
            end
        end

        # Compute metrics
        overall_mse[j,i] = mean((realised_errors .- expected_errors).^2);
    end
end

println(DataFrame(round.(overall_mse ./ overall_mse[2,:]', digits=2), Symbol.(["all periods", "all periods excl. recessions"])));


text:
using POMDPGym, POMDPs, Test

mdp = LavaWorldMDP(lava = [GWPos(1,1), GWPos(2,2), GWPos(3,3)], goal=GWPos(4,4))
actions(mdp)
@test length(actions(mdp)) == 4
@test mdp.gridworld.rewards[GWPos(1,1)] == -1
@test mdp.gridworld.rewards[GWPos(2,2)] == -1
@test mdp.gridworld.rewards[GWPos(3,3)] == -1
@test mdp.gridworld.rewards[GWPos(4,4)] == 1
@test GWPos(4,4) in mdp.gridworld.terminate_from
@test GWPos(1,1) in mdp.gridworld.terminate_from
@test GWPos(2,2) in mdp.gridworld.terminate_from
@test GWPos(3,3) in mdp.gridworld.terminate_from

s = rand(initialstate(mdp))
svec = convert_s(AbstractArray, s, mdp)
@test size(svec) == (7,5,3,1)

s, r = gen(mdp, s, :up)
c = render(mdp, s)

max_forks_repo_name: ancorso/POMDPGym


text:
using ThreeJS
import ThreeJS
using Compat

function ConvertToTuple(p,t)
    points = Array(Tuple{Float64,Float64,Float64},size(p,2))
    for i in 1:size(p,2)
        points[i] = tuple(p[:,i]...)
    end

    faces = Array(Tuple{Int64,Int64,Int64},size(t,2))
    for i in 1:size(t,2)
        faces[i] = tuple(t[:,i]...)
    end

    return points,faces
end

function elipspar(p)
    elpar = (0,0,0)
    try
        elpar = ellipsoid_parameters(p)
    catch
        elpar = (0.,0.,0.)
    end

    return [round(i,2) for i in elpar]
end

function main(window)

    push!(window.assets,("ThreeJS","threejs"))
    push!(window.assets,"widgets")

    convert(Int,round(3.6))

    geom(frame) = geometry(ConvertToTuple(memory[frame][2],memory[frame][3])...)

    ff = Signal(1)
    #ThreeJS.title(2,"Viewer for time dependant calculation"),
    vbox(
                  #"Viewer for time dependant calculation $fname",
         hbox(
            vbox(
                 #"data",
                 hbox("frame",slider(1:size(memory,1)) >>> ff),
                 ),
             ),
         vskip(2em),

         map(ff) do ff
         vbox(
              """
              Time is $(try round(memory[ff][1],2) catch NaN end);
              Volume is $(try round(volume(memory[ff][2],memory[ff][3]),4) catch NaN end);
              Elipsoid parameters $(try [round(i,2) for i in FitEllipsoid(memory[ff][2])] catch NaN end)
             """,
          outerdiv() <<
          (
           initscene() <<
           [
         ### Pozikridis veids ka attlot meshu
            #ThreeJS.mesh(0.0, 0.0, 0.0) << [ geom(ff), material(Dict(:color=>"red",:kind=>"phong")) ],
            ThreeJS.mesh(0.0, 0.0, 0.0) << [ geom(ff), material(Dict(:color=>"red",:kind=>"lambert")) ],
            #ThreeJS.mesh(0.0, 0.0, 0.0) << [ geom(ff), material(Dict(:kind=>"basic",:color=>"black",:wireframe=>true,:wireframeLinewidth=>2)) ], # :wireframe=>true ],
            pointlight(0.,10.,10.),
             #ambientlight(0x404040),
#            pointlight(0.,-10.,0.),
 #           pointlight(0.,0.,10.),
#             pointlight(0.,0.,-10.),
            camera(10.0, 0., 0.),
           ]
          )
          )

         end
    )

end


text: using DataFrames, FixedEffectModels, Random


text:
using Gurobi

function print_help()
    println("""
    Usage
        perf.jl [arg] [name]

    [arg]
        --new       Begin a new benchmark comparison
        --compare   Run another benchmark and compare to existing

    [name]          A name for the benchmark test

    Examples
        git checkout master
        julia perf.jl --new master
        git checkout approach_1
        julia perf.jl --new approach_1
        git checkout approach_2
        julia perf.jl --compare master
        julia perf.jl --compare approach_1
    """)
end

if length(ARGS) != 2
    print_help()
else
    const Benchmarks = Gurobi.MOI.Benchmarks
    const GUROBI_ENV = Gurobi.Env()
    const suite = Benchmarks.suite() do
        Gurobi.Optimizer(GUROBI_ENV, OutputFlag = 0)
    end
    if ARGS[1] == "--new"
        Benchmarks.create_baseline(
            suite, ARGS[2]; directory = @__DIR__, verbose = true
        )
    elseif ARGS[1] == "--compare"
        Benchmarks.compare_against_baseline(
            suite, ARGS[2]; directory = @__DIR__, verbose = true
        )
    else
        print_help()
    end
end


text:
module Scores

using Niancat.Users
using Niancat.Persistence
using Niancat.Gameface
using Niancat.Formatters
import Niancat.Gameface: score!
using SQLite

const UserScore = Tuple{User, Float32}

struct Scoreboard
    scores::Vector{UserScore}
end

function Gameface.score!(persistence::GamePersistence, user::User, score::Score)
    sql = """
        INSERT OR IGNORE INTO scores
            (game_instance_id, user_id, round, score_key, points)
        VALUES
            (?, ?, ?, ?, ?);
    """

    DBInterface.execute(persistence.db, sql, (score.gameinstanceid, user.databaseid, score.round, score.key, score.value))
end

function builduser(row)
    teamdatabaseid = row[:team_id]
    teamname = row[:team_name]
    teamicon = row[:icon]
    team = Team(teamdatabaseid, teamname, teamicon)

    userdatabaseid = row[:user_id]
    displayname = row[:display_name]
    teamuserid = row[:team_user_id]

    User(userdatabaseid, teamuserid, displayname, team)
end

function getscoreboard(persistence::GamePersistence, instanceid::Int, round::String) :: Scoreboard

    sql = """
        SELECT
            scores.user_id,
            SUM(scores.points) AS score,
            users.team_user_id,
            users.display_name,
            teams.team_id,
            teams.team_name,
            teams.icon
        FROM scores
            JOIN teams ON users.team_id = teams.team_id
            JOIN users ON users.user_id = scores.user_id
        WHERE scores.game_instance_id = ?
          AND scores.round = ?
        GROUP BY scores.user_id;
    """
    results = DBInterface.execute(persistence.db, sql, (instanceid, round))

    scores = UserScore[(builduser(row), row[:score]) for row in results]

    Scoreboard(scores)
end

function userscore(scoreboard::Scoreboard, user::User) :: Float32
    d = Dict{User, Float32}(
        u => s
        for (u, s) in scoreboard.scores
    )
    d[user]
end

hasuser(scoreboard::Scoreboard, user::User) :: Bool = any(((u, _s), ) -> u == user, scoreboard.scores)

struct Solutionboard
    solutions::Dict{String, Vector{User}}

    Solutionboard() = new(Dict{String, Vector{String}}())
end

function getsolutionboard(persistence::GamePersistence, instanceid::Int, round::String) :: Solutionboard
    board = Solutionboard()

    # Fetch all possible solutions
    wordssql = """
        SELECT event_data
        FROM gameevents
        WHERE game_instance_id = ? AND round = ? AND event_type = ?;
    """
    wordsparams = (instanceid, round, Gameface.GameEvent_Solution)
    wordsresults = DBInterface.execute(persistence.db, wordssql, wordsparams)
    allsolutions = [row[:event_data] for row in wordsresults]

    # Fetch all user solutions
    sql = """
        SELECT userevents.user_id, userevents.event_data, users.team_user_id, users.display_name, teams.team_id, teams.team_name, teams.icon
        FROM userevents
        JOIN users ON users.user_id = userevents.user_id
        JOIN teams ON users.team_id = teams.team_id
        WHERE userevents.game_instance_id = ? AND userevents.round = ? AND userevents.event_type = ?;
    """
    params = (instanceid, round, Gameface.UserEvent_Solution)
    usersolutionresults = DBInterface.execute(persistence.db, sql, params)
    usersolutions = [(builduser(row), row[:event_data]) for row in usersolutionresults]

    # TODO Nicer implementation
    for word in allsolutions
        board.solutions[word] = User[]
    end

    for (user, word) in usersolutions
        push!(board.solutions[word], user)
    end

    board
end

##
## Notifications
##

struct SolutionboardNotification <: GameNotification
    instanceid::Int
    round::String
end

struct ScoreboardNotification <: GameNotification
    instanceid::Int
    round::String
end

##
## Formatting
##

function formatsolution(word::String, users::Vector{User}) :: String
    usertext = join(["$(u)" for u in users], ",")
    # TODO This should technically be done in the language module.
    wordtext = uppercase(word)
    "*$(wordtext)*: $(usertext)"
end

function Formatters.format(::SlackFormatter, board::Solutionboard) :: String
    solutions = [
        formatsolution(word, users)
        for (word, users) in board.solutions
    ]
    headers = ["*Lösningar*"]
    join(vcat(headers, solutions), "\n")
end

function Formatters.format(::SlackFormatter, board::Scoreboard) :: String
    userscoreformat = (user, score) -> "$(user): $(score)"
    scorestexts = [userscoreformat(user, score) for (user, score) in board.scores]
    headers = ["*Poäng:*"]
    join(vcat(headers, scorestexts), "\n")
end

##
## Export
##

export Scoreboard, getscoreboard, record!, Score, UserScore, userscore, hasuser, getsolutionboard
export SolutionboardNotification, ScoreboardNotification

end


text:
using HDF5

import Particles.PoissonSolverPBSplines

function _name(h5::H5DataStore)
    name = HDF5.name(h5)
    name = name[findlast(isequal('/'), name)+1:end]
end

function _create_group(h5::H5DataStore, name)
    if haskey(h5, name)
        g = h5[name]
    else
        g = create_group(h5, name)
    end
    return g
end

function save_projections(fpath::String, k, kₑ, Ψ, Ψₑ, Πₑ, P₀) where {T}
    h5open(fpath, "w") do file
        g = _create_parameter_group(file)
        g["k"] = k
        g["k_e"] = kₑ

        f = create_group(file, "projections")
        f["Psi"] = Ψ
        f["Psi_e"] = Ψₑ
        f["Pi_e"] = Πₑ

        h = create_group(file, "initial_condition")
        h["x_0"] = P₀.x
        h["v_0"] = P₀.v
        h["w"] = P₀.w
    end
end

function save_tests(fpath::String, Rtest, Rrm, Ψ)
    h5open(fpath, "w") do file
        s = create_group(file, "tests")
        s["X_test"] = Rtest.X
        s["V_test"] = Rtest.V
        s["Phi_test"] = Rtest.Φ
        s["X_rm"] = Ψ * Rrm.Zₓ
        s["V_rm"] = Ψ * Rrm.Zᵥ
        s["Phi_rm"] = Rrm.Φ
    end
end

"""
save sampling parameters
"""
function save_sampling_parameters(fpath::AbstractString, sampling_params::NamedTuple)
    h5open(fpath, "r+") do file
        g = _create_parameter_group(file)
        g["κ"]  = sampling_params.κ
        g["ε"]  = sampling_params.ε
        g["a"]  = sampling_params.a
        g["v₀"] = sampling_params.v₀
        g["σ"]  = sampling_params.σ
        g["χ"]  = sampling_params.χ
    end
end

function read_sampling_parameters(fpath::AbstractString)
    h5open(fpath, "r") do file
        (
            κ = read(file["parameters/κ"]),
            ε = read(file["parameters/ε"]),
            a = read(file["parameters/a"]),
            v₀= read(file["parameters/v₀"]),
            σ = read(file["parameters/σ"]),
            χ = read(file["parameters/χ"]),
        )
    end
end

"""
save testing parameters
"""
function save_testing_parameters(fpath::AbstractString, μₜ::Matrix)
    h5open(fpath, "r+") do file
        g = _create_parameter_group(file)
        g["mu_test"] = μₜ
    end
end

"""
save spline solver parameters
"""
function h5save(fpath::String, P::PoissonSolverPBSplines)
    h5open(fpath, "r+") do file
        attributes(file)["p"] = P.p
    end
end

function Particles.PoissonSolverPBSplines(fpath::String)
    h5open(fpath, "r") do file
        p = read(attributes(file)["p"])
        n = read(attributes(file)["nh"])
        κ = read(file["parameters/κ"])
        PoissonSolverPBSplines(p, n, 2π/κ)
    end
end

"""
save training data
"""
function h5save(fpath::String, TS::TrainingSet, IP::VPIntegratorParameters, poisson::PoissonSolverPBSplines, pspace::ParameterSpace, sampling_params::NamedTuple)
    # create file and save snapshots
    h5open(fpath, "w") do file
    end

    h5save(fpath, TS)
    h5save(fpath, pspace)
    h5save(fpath, poisson)
    h5save(fpath, IP)
    save_sampling_parameters(fpath, sampling_params)
end

"""
save projection data
"""
function h5save(fpath::String, IP::IntegratorParameters, P::PoissonSolverPBSplines{T}, sampling_params::NamedTuple, μtrain::Matrix{T}, k, kₑ, Ψ, Ψₑ, Πₑ, P₀) where {T}
    # create file and save projections
    save_projections(fpath, k, kₑ, Ψ, Ψₑ, Πₑ, P₀)
    h5save(fpath, P)
    h5save(fpath, IP)
    save_sampling_parameters(fpath, sampling_params)
    save_training_parameters(fpath, μtrain)
end

"""
save testing data
"""
function h5save(fpath::String, IP::IntegratorParameters, P::PoissonSolverPBSplines{T}, sampling_params::NamedTuple, μtrain::Matrix{T}, μtest::Matrix{T}, Rtest, Rrm, Ψ) where {T}
    # create file and save test data
    save_tests(fpath, Rtest, Rrm, Ψ)
    h5save(fpath, P)
    h5save(fpath, IP)
    save_sampling_parameters(fpath, sampling_params)
    save_training_parameters(fpath, μtrain)
    save_testing_parameters(fpath, μtest)
end

function h5save(data, fpath::String, args...; mode="r+", kwargs...)
    h5open(fpath, mode) do file
        h5save(data, file, args...; kwargs...)
    end
end

function h5load(T::Type, fpath::AbstractString, args...; mode="r", kwargs...)
    h5open(fpath, mode) do file
        h5load(T, file, args...; kwargs...)
    end
end


text:
#
# This file is part of module
#   ModiaMedia (ModiaMedia/src/ModiaMedia.jl)
#

"""
    data = SimpleMediumData(;cp_const=nothing, cv_const=nothing, d_const=nothing, eta_const=nothing,
                             lambda_const=nothing, a_const=nothing, T0=nothing, MM_const=nothing)

Generate a `SimpleMediumData` object containing the data
for a SimpleMedium medium.
"""
mutable struct SimpleMediumData
    cp_const::Float64       # "Constant specific heat capacity at constant pressure";
    cv_const::Float64       # "Constant specific heat capacity at constant volume";
    d_const::Float64        # "Constant density";
    eta_const::Float64      # "Constant dynamic viscosity";
    lambda_const::Float64   # "Constant thermal conductivity";
    a_const::Float64        # "Constant velocity of sound";
    T_min::Float64          # Minimum temperature valid for medium model
    T_max::Float64          # Maximum temperature valid for medium model
    T0::Float64             # "Zero enthalpy temperature";
    MM_const                # "Molar mass";

    SimpleMediumData(;cp_const=nothing, cv_const=nothing, d_const=nothing, eta_const=nothing,
                      lambda_const=nothing, a_const=nothing, T_min=nothing, T_max=nothing,
                      T0=nothing, MM_const=nothing) =
         new(cp_const, cv_const, d_const, eta_const, lambda_const, a_const, T_min, T_max, T0, MM_const)
end

"""
    medium = SimpleMedium(; mediumName     = nothing,
                            reference_p    = 101325,
                            reference_T    = 298.15,
                            p_default      = 101325,
                            T_default      = 293.15,
                            fluidConstants = nothing,
                            data           = nothing)

Generate a `SimpleMedium <: PureSubstance` medium object.
"""
struct SimpleMedium <: PureSubstance
    infos::FluidInfos
    fluidConstants::SVector{1,BasicFluidConstants}
    fluidLimits::FluidLimits
    data::SimpleMediumData

    function SimpleMedium(; mediumName=nothing,
                            reference_p=101325,
                            reference_T=298.15,
                            p_default=101325,
                            T_default=293.15,
                            fluidConstants=nothing,
                            data=nothing)

        infos = FluidInfos(mediumName           = mediumName,
                           substanceNames       = [mediumName],
                           extraPropertiesNames = fill("",0),
                           ThermoStates         = IndependentVariables_pT,
                           baseProperties       = :BaseProperties_SimpleMedium,
                           singleState          = true,
                           reducedX             = true,
                           fixedX               = false,
                           reference_p          = reference_p,
                           reference_T          = reference_T,
                           reference_X          = fill(1.0,1),
                           p_default            = p_default,
                           T_default            = T_default,
                           h_default            = specificEnthalpy(data, ThermodynamicState_pT(p_default,T_default)))

        fluidLimits = FluidLimits(TMIN = data.T_min,
                                  TMAX = data.T_max,
                                  HMIN = specificEnthalpy(data, ThermodynamicState_pT(p_default,data.T_min)),
                                  HMAX = specificEnthalpy(data, ThermodynamicState_pT(p_default,data.T_max)))

        new(infos, fill(fluidConstants,1), fluidLimits, data)
    end
end

setState_pTX(m::SimpleMedium,p,T,X) = ThermodynamicState_pT(p,T)
setState_phX(m::SimpleMedium,p,h,X) = ThermodynamicState_pT(p,m.data.T0+h/m.data.cp_const)
setState_psX(m::SimpleMedium,p,s,X) = ThermodynamicState_pT(p,exp(s/m.data.cp_const + log(m.infos.reference_T)))
setState_dTX(m::SimpleMedium,d,T,X) = error("From setState_dTX: Pressure cannot be computed from temperature and density for the incompressible fluid $(m.infos.mediumName)!")

specificEnthalpy(data::SimpleMediumData, state::ThermodynamicState_pT)::Float64 = data.cp_const*(state.T - data.T0)
pressure(               m::SimpleMedium, state::ThermodynamicState_pT)::Float64 = state.p
temperature(            m::SimpleMedium, state::ThermodynamicState_pT)::Float64 = state.T
density(                m::SimpleMedium, state::ThermodynamicState_pT)::Float64 = m.data.d_const
specificEnthalpy(       m::SimpleMedium, state::ThermodynamicState_pT)::Float64 = specificEnthalpy(m.data,state)
specificInternalEnergy( m::SimpleMedium, state::ThermodynamicState_pT)::Float64 = m.data.cv_const*(state.T - m.data.T0)
specificHeatCapacityCp( m::SimpleMedium, state::ThermodynamicState_pT)::Float64 = m.data.cp_const

### Functions for mass and energy balance

density(      m::SimpleMedium)::Float64 = m.data.d_const
density_der_1(m::SimpleMedium)::Float64 = 0.0

specificInternalEnergy_T(      m::SimpleMedium,T)::Float64 = m.data.cv_const*(T - m.data.T0)
specificInternalEnergy_T_der_1(m::SimpleMedium,T)::Float64 = 0.0
specificInternalEnergy_T_der_2(m::SimpleMedium,T)::Float64 = m.data.cv_const

function standardCharacteristics(m::SimpleMedium)::Dict{AbstractString,Any}
    p = m.infos.reference_p
    T = collect( range(m.fluidLimits.TMIN, stop=m.fluidLimits.TMAX, length=101) )
    h = zeros(length(T))

    for i in 1:length(T)
        h[i] = specificEnthalpy(m, setState_pT(m,p,T[i]))
    end

    mediumDict = Dict{AbstractString,Any}()
    mediumDict["T"] = uconvert.(u"°C", T*1u"K")
    mediumDict["h"] = h*U"J/kg"

    return mediumDict
end

function standardPlot(m::SimpleMedium; figure=1)
    mediumDict = standardCharacteristics(m)
    ModiaMath.plot(mediumDict, "h", xAxis="T", heading=m.infos.mediumName, figure=figure)
end


text:
using  Languages, TextAnalysis, Flux, PyPlot, Statistics, MLDataUtils, Embeddings, MLLabelUtils
using Flux: logitcrossentropy, normalise, onecold, onehotbatch
using Parameters: @with_kw
using BSON: @save,@load

@with_kw mutable struct Args
    lr::Float64 = 0.05 # learning rate
    τ::Int = 110 # max iterations
    path::String = "data/short-amazon-reviews.txt" # path to data
    max_length::Int = 4 # Max length of the doc to be considered
end

#Function to return the index of the word in the embedding (returns 0 if the word is not found)
function vec_idx(s,vocab)
    i=findfirst(x -> x==s, vocab)
    i==nothing ? i=0 : i
end

#This function provides the GloVe word vector of the given word.
function wvec(s,embeddings,vocab)
    return embeddings[:, vec_idx(s,vocab)]
end

# Padding the corpus wrt the longest document
function pad_corpus(c, pad_size, word_dict)
    M = []
    for doc in 1:length(c)
        tks = tokens(c[doc])
        if length(tks) >= pad_size
            tk_indexes = [tk_idx(w,word_dict) for w in tks[1:pad_size]]
        end
        if length(tks) < pad_size
            tk_indexes = zeros(Int64,pad_size - length(tks))
            tk_indexes = vcat(tk_indexes, [tk_idx(w,word_dict) for w in tks])
        end
        doc == 1 ? M = tk_indexes' : M = vcat(M, tk_indexes')
    end
    return M
end

# function to return the index of the word in the word dictionary
tk_idx(s,word_dict) = haskey(word_dict, s) ? i = word_dict[s] : i=0

function load_embeddings()
    embtable = Embeddings.load_embeddings(GloVe{:en},1) # or load_embeddings(FastText_Text) or ...
    embeddings = embtable.embeddings
    vocab = embtable.vocab
    return vocab,embeddings
end

function get_processed_data(args)
    f = open(args.path)
    doc_array = readlines(f)

    labels, texts = [], []
    for doc in doc_array
        content = split(doc)
        push!(labels,content[1])
        push!(texts,join(content[2:end]," "))
    end

    # pushing the text from the files to the string documents
    docs = []
    for i in 1:length(texts)
        push!(docs, StringDocument(texts[i]))
    end

    # building a Corpus
    corpus = Corpus(docs)

    # updating the lexicon and creating the word dict
    update_lexicon!(corpus)
    doc_term_matrix = DocumentTermMatrix(corpus)
    word_dict = doc_term_matrix.column_indices
    # splitting words in the document
    word_docs = map(s -> split(s,r"[,. ]",keepempty = false),texts)
    # pad size is the number of words in the maximum word document

    # Can set a fixed length or the max doc length
    # pad_size = maximum(length(word_docs[i]) for i in 1:length(texts))
    pad_size = args.max_length

    # padding the docs
    padded_docs = pad_corpus(corpus, pad_size,word_dict)
    # forming the data with the labels
    X = padded_docs'

    (X_train, y_train), (X_test, y_test) = splitobs((X, labels); at = 0.67)

    klasses = sort(unique(labels))
    y_train = Flux.onehotbatch(y_train,klasses)
    y_test = Flux.onehotbatch(y_test,klasses)
    train_data = [(X_train, y_train)]
    test_data = [(X_test, y_test)]

    return train_data, test_data, doc_term_matrix, klasses
end

# Accuracy Function
accuracy(x, y, model) = mean(onecold(model(x)) .== onecold(y))

# Function to build confusion matrix
function confusion_matrix(X, y, model)
    ŷ = onehotbatch(onecold(model(X)), 1:2)
    y * transpose(ŷ)
end

function train(; kws...)
    # Initialize hyperparameter arguments
    args = Args(; kws...)

    #Loading processed data
    train_data, test_data, doc_term_matrix, klasses = get_processed_data(args)
    word_dict = doc_term_matrix.column_indices
    X_train, y_train = train_data[1]

    # loading the embeddings
    embedding_vocab, embeddings = load_embeddings()
    max_features,em_vocab_size = size(embeddings)

    # Building Flux Embeddings
    N = size(X_train,2)  #Number of documents
    # features per word to learn, depends on the size of the corpus, larger corpus will probably need a higher dimension
    # number of words in the vocabulary, should always be higher than the maximum index in our dictionary.
    vocab_size = maximum(word_dict)[2] + 1

    # Embedding layer for Flux model
    # glorot_normal returns an Array of size dims containing random variables taken from a normal distribution with mean 0 and standard deviation (2 / sum(dims)).
    embedding_matrix = Flux.glorot_normal(max_features, vocab_size)

    # Creating the embedding matrix
    for term in doc_term_matrix.terms
        if vec_idx(term,embedding_vocab)!= 0
            embedding_matrix[:,word_dict[term] + 1] = wvec(term,embeddings,embedding_vocab)
        end
    end

    m = Chain((x) -> (embedding_matrix * Flux.onehotbatch(reshape(x, args.max_length*size(x,2)), 0:vocab_size - 1),size(x,2)),
          (arg) -> (reshape(arg[1], max_features, args.max_length, arg[2]),arg[2]),
          (arg) -> (sum(arg[1], dims = 2),arg[2]),
          (arg) -> reshape(arg[1], max_features, arg[2]),
        LSTM(max_features,100),
        Dense(100,50),
        Dense(50, size(klasses,1), σ)
         )

    # Defining loss function to be used in training
    # For numerical stability, we use here logitcrossentropy
    loss(x, y) = sum(Flux.logitcrossentropy(m(x), y))

    # Training
    # Gradient descent optimiser with learning rate `args.lr`
    optimiser = Descent(args.lr)

    println("Starting training.")
    loss_h = []
    accuracy_train = []

    for epoch in 1:args.τ
        Flux.train!(loss, Flux.params(m), train_data, optimiser)

        println(loss(X_train, y_train), " ", accuracy(X_train, y_train, m))
        push!(loss_h, loss(X_train, y_train))
        push!(accuracy_train, accuracy(X_train, y_train, m))
    end

    print(Flux.onecold(m(X_train)), accuracy(X_train, y_train, m))

    return m, test_data
end

function test(model, test)
    # Testing model performance on test data
    X_test, y_test = test[1]
    accuracy_score = accuracy(X_test, y_test, model)

    println("\nAccuracy: $accuracy_score")

    # Sanity check.
    # @assert accuracy_score > 0.6

    println("\nConfusion Matrix:\n")
    display(confusion_matrix(X_test, y_test, model))
end

max_stars_repo_name: akaysh/Rango

max_issues_repo_name: akaysh/Rango

max_forks_repo_name: akaysh/Rango


text:
@testset "Space Tests" begin

@testset "Default physical weights" begin
    x, y = hemispheric_means(B)
    @test timemean(x) != dropagg(mean, x, Time)
    d1 = timemean(x) - timemean(y)
    @test abs(d1) < 0.01
    d2 = dropagg(mean, x, Time) - dropagg(mean, y, Time)
    @test d2 < -0.1
    x = B[:, :, 1]
    @test zonalmean(latmean(x)) ≈ latmean(zonalmean(x)) ≈ spacemean(x)
    @test spacemean(x) - mean(x) > 50
    @test all(y -> abs(y) < 1e-8, spacemean(A))
end

@testset "Spatial weighting" begin
    W = zero(A)
    W[Lon(5)] .= 1.0
    res = spaceagg(mean, A, W)
    @test all(res .≈ latmean(A)[Lon(5)])
    @test dims(A, Time) == dims(res, Time)
    res = spaceagg(std, A, W)
    @test all(x -> x>0, res)

    W = zeros(length(lons), length(lats))
    W[5, :] .= 1.0
    W = ClimArray(W, dims(A, (Lon, Lat)))
    res = spaceagg(mean, A, W)
    @test all(res .≈ latmean(A)[Lon(5)])
    @test dims(A, Time) == dims(res, Time)
end

@testset "Insolation/Hemispheres" begin
    @test !any(x -> x < 0, B)
    x = timemean(B)
    x, y = hemispheric_functions(zonalmean(x))
    # @test x isa ClimArray
    x[Lat(1)] == y[Lat(1)]
    for j in 2:size(x, Lat)
        @test x[j] < x[j-1]
        @test y[j] < y[j-1]
    end
end

@testset "tropics/extratropics" begin
    tropics, extratropics = tropics_extratropics(B)
    tlats = dims(tropics, Lat).val
    elats = dims(extratropics, Lat).val
    @test all(l -> -30 ≤ l ≤ 30, tlats)
    @test all(l -> abs(l) ≥ 30, elats)
    @test hasdim(tropics, Ti)

    tmean = spacemean(timemean(tropics))
    emean = spacemean(timemean(extratropics))
    amean = spacemean(timemean(B))
    @test amean ≈ (emean + tmean)/2 rtol = 5

    # Test for keyword options for latitude bounds
    tropics, extratropics = tropics_extratropics(B, lower_lat=20, higher_lat=78)
    tlats = dims(tropics, Lat).val
    elats = dims(extratropics, Lat).val
    @test all(l -> -20 ≤ l ≤ 20, tlats)
    @test all(l -> abs(l) ≥ 20, elats)
    @test maximum(abs.(elats)) <= 78
    @test hasdim(tropics, Ti) # probably redundant, already tested

end

end # Space Tests


text:
using Base.Filesystem

 import .Base:
     IOError, _UVError, _sizeof_uv_fs, check_open, close, eof, eventloop, fd, isopen,
     bytesavailable, position, read, read!, readavailable, seek, seekend, show,
     skip, stat, unsafe_read, unsafe_write, write, transcode, uv_error,
     rawhandle, OS_HANDLE, INVALID_OS_HANDLE, windowserror

# We can see the [`mtime`](@ref) has been modified by `touch`.
function futime1(f::File, atime::Float64, mtime::Float64)
            check_open(f)
             req = Libc.malloc(_sizeof_uv_fs)
            err = ccall(:uv_fs_futime, Int32,
                        (Ptr{Cvoid}, Ptr{Cvoid}, OS_HANDLE, Float64, Float64, Ptr{Cvoid}),
                        C_NULL, req, f.handle, atime, mtime, C_NULL)
                Libc.free(req)
            uv_error("futime", err)
            return f
         end

function Filesystem.touch(path::AbstractString,newtime::Float64)
        f = Filesystem.open(path, JL_O_WRONLY | JL_O_CREAT, 0o0666)
        # f = open(path, "r")
        try
                if Sys.isunix()
                    tv_sec =trunc(Int,newtime)
                    tv_usec=trunc(  Int ,(newtime- tv_sec )*1000000 )
                    tv=[tv_sec,tv_usec,tv_sec,tv_usec]
                    # println(  timevals[0], timevals[1])
                    ret = ccall(:futimes, Cint, (Cint, Ptr{Cvoid}), fd(f), tv)
                    systemerror(:futimes, ret != 0, extrainfo=path)
                else
                        t = newtime #time()
                        # println( typeof( t ))
                        Filesystem.futime(f,t,t)
                end
        finally
           close(f)
        end
end

function touchfile( srcfile::String,tgrfile::String)
        newtime = mtime(srcfile)
        # println("$s1,$s2,$(s2-s1)")

        # newtime =s1
        touch(tgrfile,newtime)
        # s2=mtime(tgrfile)
end
function TestMain()
            srcfile ="LICENSE.md"
            tgrfile="test.tgr"

            cp(srcfile,tgrfile,force=true)
            s1=mtime( srcfile)
            s2=mtime(tgrfile)
            println("$s1,$s2,$(s2-s1)")

            newtime =s1
            touch(tgrfile,newtime::Float64)
            s2=mtime(tgrfile)
            println(":::: $s1,$s2,$(s2-s1)")
end

# TestMain()

# #include <sys/time.h>
# #include <stdio.h>

# int
# main(void)
# {
# int i;
# struct timeval tv;

# for(i = 0; i < 4; i++){
#      gettimeofday(&tv, NULL);
#      printf("%d\t%d\n", tv.tv_usec, tv.tv_sec);
#      sleep(1);
# }

# return 0;
# }