text:
RpcApi.SimpleOrganism[RpcApi.SimpleOrganism(0x000000000000751c,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_3(var_2::Int16=-475)
            local var_8::Bool = false
            return var_2
        end
        local var_1::Int8 = 118
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        var_1 = var_1 * var_1
        Creature.eatUp(c,o,Int(var_1))
        if var_1 !== var_1
            Creature.stepUp(o)
            Creature.stepLeft(o)
        end
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,448073,0x00000043,Dict{Int16,Int16}(),[186,156],16),RpcApi.SimpleOrganism(0x000000000000719f,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_9(var_7::Int8=116,var_8::Int16=-6418)
            return var_7
        end
        local var_1::Int8 = 118
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            local var_6::Int8 = 0
            local var_5::Int64 = 5157083918494790572
            Creature.stepDown(o)
            Creature.stepUp(o)
        end
        Creature.stepDown(o)
        Creature.eatRight(c,o,Int(var_1))
        Creature.stepUp(o)
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        var_1 = var_1 + var_1
        Creature.stepDown(o)
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,361396,0x00000059,Dict{Int16,Int16}(),[34,92],23),RpcApi.SimpleOrganism(0x0000000000007369,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_9(var_7::Int16=36,var_8::Bool=true)
            return var_7
        end
        function func_6(var_5::Int16=32298)
            var_5 = if haskey(o.mem,var_5)
                    o.mem[var_5]
                else
                    var_5
                end
            return var_5
        end
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.stepDown(o)
        Creature.eatUp(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
        end
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,359680,0x0000004c,Dict{Int16,Int16}(),[242,165],15),RpcApi.SimpleOrganism(0x00000000000070c7,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_6(var_5::Bool=false)
            local var_7::Int16 = -16358
            Creature.stepRight(o)
            return var_5
        end
        function func_3(var_2::Int16=-475)
            return var_2
        end
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,313387,0x0000003e,Dict{Int16,Int16}(),[257,147],10),RpcApi.SimpleOrganism(0x000000000000731d,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_9(var_7::Int16=2352,var_8::Int64=9133158049229628223)
            Creature.stepUp(o)
            return var_7
        end
        local var_1::Int8 = 118
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepDown(o)
        end
        return true
    end),[110,300,98,0,1,1,1],22,1000,1,310972,0x00000059,Dict{Int16,Int16}(),[14,177],8),RpcApi.SimpleOrganism(0x0000000000006d17,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_12(var_11::Int8=82)
            Creature.eatRight(c,o,Int(var_11))
            return var_11
        end
        function func_3(var_2::Int16=-475)
            local var_10::Int8 = 26
            Creature.eatUp(c,o,Int(var_10))
            return var_2
        end
        local var_1::Int8 = 118
        function func_9(var_7::Int8=26,var_8::Int8=56)
            return var_7
        end
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        if var_1 !== var_1
            Creature.stepLeft(o)
        end
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
        end
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,300078,0x00000046,Dict{Int16,Int16}(),[192,154],15),RpcApi.SimpleOrganism(0x00000000000067df,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_1::Int8 = 118
        function func_4(var_2::String="MNzqi667",var_3::Int16=-8895)
            return var_2
        end
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepLeft(o)
        end
        Creature.stepDown(o)
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            local var_12::String = "toXGxplE"
        end
        Creature.eatDown(c,o,Int(var_1))
        Creature.stepLeft(o)
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,286071,0x0000004d,Dict{Int16,Int16}(),[9,144],12),RpcApi.SimpleOrganism(0x0000000000006fd8,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_1::Int8 = 118
        Creature.eatRight(c,o,Int(var_1))
        Creature.stepRight(o)
        Creature.eatLeft(c,o,Int(var_1))
        Creature.stepDown(o)
        Creature.eatLeft(c,o,Int(var_1))
        Creature.stepRight(o)
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,419,1,248467,0x00000028,Dict{Int16,Int16}(),[248,39],9),RpcApi.SimpleOrganism(0x000000000000761b,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_3(var_2::Int16=-475)
            local var_8::Bool = false
            return var_2
        end
        local var_1::Int8 = 118
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        var_1 = var_1 * var_1
        Creature.eatUp(c,o,Int(var_1))
        if var_1 !== var_1
            Creature.stepLeft(o)
        end
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,245342,0x00000045,Dict{Int16,Int16}(),[186,156],15),RpcApi.SimpleOrganism(0x0000000000006550,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_1::Int8 = 118
        function func_9(var_7::Int8=26,var_8::Int8=56)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_7
        end
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.stepDown(o)
        Creature.eatDown(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,242142,0x00000045,Dict{Int16,Int16}(),[192,115],9),RpcApi.SimpleOrganism(0x0000000000007252,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_14(var_13::Int8=-76)
            return var_13
        end
        function func_8(var_6::Int16=8879,var_7::Int8=-29)
            local var_11::String = "wNNAU2Ib"
            var_7 = var_7 / var_7
            return var_6
        end
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.stepLeft(o)
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            local var_9::Int8 = 49
            local var_5::Int64 = -8273336838347865267
            Creature.stepLeft(o)
        end
        Creature.eatLeft(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,616,1,240481,0x00000055,Dict{Int16,Int16}(),[249,23],21),RpcApi.SimpleOrganism(0x0000000000007368,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_5(var_4::Int8=-70)
            for i::Int8 = 1:div(var_4,_LOOP_STEPS_DIVIDER)
            end
            Creature.stepUp(o)
            return var_4
        end
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
        end
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
        end
        Creature.eatDown(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,232592,0x00000049,Dict{Int16,Int16}(),[88,177],10),RpcApi.SimpleOrganism(0x0000000000006f20,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_12(var_11::Int8=82)
            local var_13::Int16 = 7012
            return var_11
        end
        function func_3(var_2::Int16=-475)
            local var_10::Int8 = 26
            var_2 = var_2 - var_2
            return var_2
        end
        local var_1::Int8 = 118
        function func_9(var_7::Int8=26,var_8::Int8=56)
            var_7 = var_8 - var_8
            return var_7
        end
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        if var_1 !== var_1
            Creature.stepLeft(o)
            Creature.stepLeft(o)
        end
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepDown(o)
        end
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,231148,0x00000048,Dict{Int16,Int16}(),[193,154],18),RpcApi.SimpleOrganism(0x000000000000764a,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_1::Int8 = 118
        local var_9::Int8 = -112
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepLeft(o)
        end
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,229688,0x00000047,Dict{Int16,Int16}(),[157,50],10),RpcApi.SimpleOrganism(0x0000000000006a19,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_7::Bool = false
        function func_3(var_2::Int16=-475)
            return var_2
        end
        local var_1::Int8 = 118
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        if var_1 !== var_1
            Creature.stepLeft(o)
        end
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,214471,0x00000040,Dict{Int16,Int16}(),[181,153],12),RpcApi.SimpleOrganism(0x00000000000066dc,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_1::Int8 = 118
        function func_4(var_2::String="MNzqi667",var_3::Int16=-8895)
            var_2 = var_2[1:if length(var_2) > length(var_2)
                            0
                        else
                            length(var_2) - length(var_2)
                        end]
            return var_2
        end
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,0,210587,0x00000000,Dict{Int16,Int16}(),[260,64],7),RpcApi.SimpleOrganism(0x0000000000007424,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_6::Int8 = -122
        function func_3(var_2::Int16=-475)
            if var_2 >= var_2
                Creature.stepLeft(o)
            end
            var_2 = if haskey(o.mem,var_2)
                    o.mem[var_2]
                else
                    var_2
                end
            return var_2
        end
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        var_6 = var_6 - var_1
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,209594,0x0000004b,Dict{Int16,Int16}(),[239,161],12),RpcApi.SimpleOrganism(0x0000000000007681,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_8::Int16 = -30821
        function func_3(var_2::String="coZMo3wf")
            if var_2 !== var_2
                Creature.stepRight(o)
            end
            return var_2
        end
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepRight(o)
        end
        Creature.eatRight(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,574,1,205829,0x00000051,Dict{Int16,Int16}(),[135,21],12),RpcApi.SimpleOrganism(0x0000000000006d1b,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepRight(o)
        return true
    end),[110,300,98,0,1,1,1],0,802,1,198970,0x00000054,Dict{Int16,Int16}(),[175,106],12),RpcApi.SimpleOrganism(0x00000000000076ff,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_10(var_8::String="MvDdYyK4",var_9::Int16=19954)
            return var_8
        end
        local var_1::Int8 = 118
        function func_4(var_2::String="MNzqi667",var_3::Int16=-8895)
            Creature.stepLeft(o)
            var_2 = var_2 * var_2
            Creature.stepDown(o)
            return var_2
        end
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepRight(o)
            Creature.stepUp(o)
        end
        Creature.stepDown(o)
        var_1 = var_1 + var_1
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            local var_12::String = "toXGxplE"
            Creature.stepRight(o)
        end
        Creature.stepLeft(o)
        Creature.eatLeft(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,195196,0x0000005e,Dict{Int16,Int16}(),[24,141],21),RpcApi.SimpleOrganism(0x000000000000722c,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_9::Int16 = -11877
        function func_8(var_6::Int16=8879,var_7::Int8=-29)
            Creature.stepRight(o)
            return var_6
        end
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        var_9 = if haskey(o.mem,var_9)
                o.mem[var_9]
            else
                var_9
            end
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.stepLeft(o)
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepLeft(o)
        end
        Creature.stepUp(o)
        Creature.stepUp(o)
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,193942,0x00000059,Dict{Int16,Int16}(),[53,192],18),RpcApi.SimpleOrganism(0x0000000000006898,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_8::Int16 = -30821
        function func_3(var_2::String="coZMo3wf")
            return var_2
        end
        local var_1::Int8 = 118
        function func_6(var_5::String="SYGCsvm3")
            return var_5
        end
        Creature.eatDown(c,o,Int(var_1))
        var_8 = if haskey(o.mem,var_8)
                o.mem[var_8]
            else
                var_8
            end
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepRight(o)
        end
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,574,1,189085,0x00000051,Dict{Int16,Int16}(),[133,21],12),RpcApi.SimpleOrganism(0x0000000000006b0e,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_16::Int16 = -20204
        function func_10(var_8::String="MvDdYyK4",var_9::Int16=19954)
            Creature.stepLeft(o)
            return var_8
        end
        local var_1::Int8 = 118
        function func_4(var_2::String="MNzqi667",var_3::Int16=-8895)
            Creature.stepRight(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepDown(o)
            return var_2
        end
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.stepUp(o)
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepUp(o)
        end
        Creature.eatLeft(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            local var_12::String = "toXGxplE"
            Creature.stepRight(o)
        end
        Creature.stepLeft(o)
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,185584,0x0000005c,Dict{Int16,Int16}(),[14,177],21),RpcApi.SimpleOrganism(0x0000000000007263,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_3(var_2::Int16=-475)
            return var_2
        end
        local var_1::Int8 = 118
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        if var_1 !== var_1
            Creature.stepLeft(o)
            Creature.stepLeft(o)
        end
        Creature.stepRight(o)
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,185209,0x00000040,Dict{Int16,Int16}(),[177,3],11),RpcApi.SimpleOrganism(0x0000000000006e9c,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_6::String = "ZyhtgXbe"
        function func_5(var_4::Int8=-70)
            return var_4
        end
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
        end
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepRight(o)
            Creature.stepUp(o)
        end
        return true
    end),[110,300,98,0,1,1,1],4,1000,1,184485,0x0000004c,Dict{Int16,Int16}(),[84,177],10),RpcApi.SimpleOrganism(0x0000000000007510,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_9(var_7::Int16=36,var_8::Bool=true)
            return var_7
        end
        function func_6(var_5::Int16=32298)
            o.mem[var_5] = var_5
            return var_5
        end
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.stepLeft(o)
        Creature.eatUp(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepRight(o)
        end
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,184333,0x0000004c,Dict{Int16,Int16}(),[173,95],16),RpcApi.SimpleOrganism(0x0000000000006971,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_5(var_4::Int8=-70)
            for i::Int8 = 1:div(var_4,_LOOP_STEPS_DIVIDER)
                Creature.stepRight(o)
            end
            var_4 = var_4 - var_4
            return var_4
        end
        local var_1::Int8 = 118
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
        end
        Creature.eatLeft(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,178272,0x0000004d,Dict{Int16,Int16}(),[85,177],10),RpcApi.SimpleOrganism(0x00000000000073f8,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_3(var_2::Int16=-475)
            return var_2
        end
        local var_1::Int8 = 118
        function func_9(var_7::Int8=26,var_8::Int8=56)
            Creature.stepLeft(o)
            Creature.stepUp(o)
            return var_7
        end
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatLeft(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,177927,0x00000043,Dict{Int16,Int16}(),[193,154],10),RpcApi.SimpleOrganism(0x0000000000007612,:(function (c::Config.ConfigData,o::Creature.Organism)
        function func_6(var_5::Bool=false)
            local var_7::Int16 = -16358
            Creature.stepRight(o)
            return var_5
        end
        function func_3(var_2::Int16=-475)
            return var_2
        end
        local var_1::Int8 = 118
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatRight(c,o,Int(var_1))
        Creature.stepLeft(o)
        Creature.eatRight(c,o,Int(var_1))
        Creature.eatDown(c,o,Int(var_1))
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,175925,0x0000003f,Dict{Int16,Int16}(),[258,147],11),RpcApi.SimpleOrganism(0x0000000000007497,:(function (c::Config.ConfigData,o::Creature.Organism)
        local var_9::Int64 = 695849987980146412
        local var_6::String = "TKDkiukK"
        function func_5(var_4::Int16=-30639)
            return var_4
        end
        Creature.eatDown(c,o,Int(var_1))
        Creature.eatUp(c,o,Int(var_1))
        var_6 = var_6[1:if length(var_6) > length(var_6)
                        0
                    else
                        length(var_6) - length(var_6)
                    end]
        var_6 = var_6[1:if length(var_6) > length(var_6) > 0
                        0
                    else
                        div(length(var_6),length(var_6))
                    end]
        var_9 = var_9 / var_9
        Creature.stepDown(o)
        Creature.eatRight(c,o,Int(var_1))
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepRight(o)
        end
        return true
    end),[110,300,98,0,1,1,1],0,1000,1,173295,0x00000054,Dict{Int16,Int16}(),[137,181],12)]

max_stars_repo_name: tmptrash/jevo

max_issues_repo_name: tmptrash/jevo

max_forks_repo_name: tmptrash/jevo


text:
# #############################################################################
# #############################################################################
#I/O methods

#This file contains functions for recording and reading the results of computations.

#   resultsdir = getresultsdir(simulation_params_hash::AbstractString,bnd::Boundary,idx::RefractiveIndex,resultsroot::AbstractString=".")
#   Returns the path <resultsdir> (as a subdirectory of <resultsroot>) to the uniquely assigned directory location for storing results of the simulation with parameters represented by the hash <simulation_params_hash>, for the cavity with boundary <bnd> and index distribution <idx>. Makes nonexisting directories via mkdir() whenever appropriate.

#   writeresults(resultsdir::AbstractString,resultid::Int64, label::AbstractString,data::Array)
#   writeresults(resultsdir::AbstractString,resultid::Int64, [label1::AbstractString,data1::Union{Integer,AbstractFloat},[label2::AbstractString,data2::Union{Integer,AbstractFloat},[...]]])
#   Writes the results corresponding to the <resultid>th computation of a specified simulation run, into files at the directory location <resultsdir> (as a subdirectory of <resultsroot>). For each label-data pair (<label>,<data>) in the variable argument list, the data are stored in appropriate formats (csv files) depending on their type, and systematically associated with their corresponding labels for later retrieval.
#   If multiple label-data argument pairs are present, either the data must all be of Integer or AbstractFloat types, so that they can be combined into a single file and identified by their position in the order. This is meant to reduce the clutter of multiple result files with only a single value stored in each. In other words, each call to writeresults should correspond to 1 result file (or directory for 3D and higher arrays).

#   data = readresults(resultsdir::AbstractString,resultid::Int64,label::AbstractString, T::Type=Float64)
#   Extracts the recorded data <data> associated to the label <label> for the <resultid>th computation of a specified simulation run, and stored in the directory <resultsdir>. If <data> is of type Number, attempts to reinterpret it as the type <T>.

# #############################################################################
# #############################################################################
#Initiate

#Dependencies
#require("util.jl")
#require("boundary.jl")
#require("refractive_index.jl")

# #############################################################################
# #############################################################################
#Results directory structure

#The result files are organized into directories first by cavity type (Boundary-RefractiveIndex constructor pairs), then by the specific parameters, then finally the actual control file that is executed to run the computations.

#Get cavity-specific directory
#Results directory is one more level deeper, separated by specific control file
function getcavitydir(bnd::Boundary,idx::RefractiveIndex,resultsroot::AbstractString=".")
    #Get cavity constructor names
    cavitytype::AbstractString = @sprintf("%s_%s",
                                          replace("$(typeof(bnd))",r"^CavChaos\.",""),
                                          replace("$(typeof(idx))",r"^CavChaos\.",""))
    #Get hash of specific cavity with parameters
    cavityhash = dec2base64(hash(bnd,hash(idx)))
    #Return path to cavity directory
    return joinpath(resultsroot,"results",cavitytype,"cav"*cavityhash)
end

#Get run-specific directory
function getresultsdir(run_params_hash::UInt64,bnd::Boundary,idx::RefractiveIndex,resultsroot::AbstractString=".";makedir::Bool=true)
    return joinpath(getcavitydir(bnd,idx,resultsroot),"run"*dec2base64(run_params_hash))
end

# #############################################################################
# #############################################################################
#Result file naming conventions

#Combine labels for multiple (nonarray) data in a single file
function combinelabels(labels...)
    return join(labels,"_")::AbstractString
end

#Split combined label into array of labels
function splitlabel(combinedlabel::AbstractString)
    return split(combinedlabel,'_')
end

#Get datafile filename from label (without extension)
#The resultid is included at the start of the filename if it is nonzero
function getresultfname(resultid::Int64,label::AbstractString)
    return (resultid == 0) ? label : @sprintf("%06d_%s",resultid,label)
end

#Extract the result id and labels from a datafile filename
function splitresultfname(fname::AbstractString)
    noextfname::AbstractString = splitext(fname)[1]
    #Check if datafile filename has a resultid at the start
    if ismatch(Regex("^\\d{6}_"),fname)
        return parse(noextfname[1:6]), splitlabel(noextfname[8:end])
    else
        return 0, splitlabel(noextfname)
    end
end

#Check if datafile filename has a given label
#Return (resultid,dataindex) pair, where dataindex is an indicator that is
#-1 if label was not found, 0 if label refers to data in whole file,
#and the actual index of the data otherwise
function checkfnameforlabel(fname::AbstractString,label::AbstractString)
    resultid::Int64,labels::Array{AbstractString,1} = splitresultfname(fname)
    index::Int64 = findfirst(labels,label)
    dataindex::Int64 = (index == 0) ? -1 : (length(labels) == 1) ? 0 : index
    return resultid, dataindex
end

# #############################################################################
# #############################################################################
#Result file I/O

#Write results for array data, with specified associated labels
#Data labels should not include '_' or '.', since these are used as separators of multiple data
function writeresults{T,N}(resultsdir::AbstractString,resultid::Int64,label::AbstractString,data::Array{T,N})
    if N <= 2
        #1D and 2D case
        #single csv file suffices for 1D or 2D arrays
        resultfile::AbstractString = joinpath(resultsdir,getresultfname(resultid,label)*".dat")
        writecsv(resultfile,data)
    else
        #3D and above case
        #need multiple files so store them in a directory
        resultdir::AbstractString = joinpath(resultsdir,getresultfname(resultid,label))
        mkdir(resultdir)
        datasizeN::Int64 = size(data,N)
        numberofdigits::Int64 = floor(log10(datasizeN))+1
        newdims = size(data)[1:end-1]
        for i=1:datasizeN
            #Recursively write results for each slice of data along the last dimension
            writeresults(resultdir,resultid,
                         #page labelling order will be opposite of dimension order
                         label*"."*dec(i,numberofdigits),
                         #the slice reshaped to (N-1)-dimensions
                         reshape(slicedim(data,N,i),newdims))
        end
    end
end

#Combine multiple single numerical data in a single file
function writeresults(resultsdir::AbstractString,resultid::Int64,args...)
    if !isempty(args)
        #Check arguments
        if isodd(length(args)); error("Argument list must contain label and data pairs."); end
        if !all(x -> typeof(x) <: Integer || typeof(x) <: AbstractFloat,
                args[2:2:end])
            error("Data types not suitable for recording in csv format. Only Integers and AbstractFloats accepted.")
        end
        #Write data
        writeresults(resultsdir,resultid,combinelabels(args[1:2:end]...),[args[2:2:end]...])
    end
end

#Read results
function readresults(resultsdir::AbstractString,resultid::Int64,label::AbstractString,T::Type=Float64)
    #First try simple data directory (for large dimensional arrays)
    resultdir::AbstractString = joinpath(resultsdir,getresultfname(resultid,label))
    if isdir(resultdir)
        #an N-dimensional array with N>2
        return readNdimcsv(resultdir,T)
    end

    #Otherwise try simple data file (for non-arrays or arrays of dimension < 3)
    if isfile(resultdir*".dat")
        #Matches exactly
        return readcsv(resultdir*".dat",T)
    end

    #Otherwise search for label in combined data files
    #Search for matches in list of files/directories
    for fname in readdir(resultsdir)
        resultid::Int64,dataindex::Int64 = checkfnameforlabel(fname,label)
        if dataindex > 0
            #found a file with multiple combined results,
            #one of which is the given label
            resultfile::AbstractString = joinpath(resultsdir,fname)
            if isfile(resultfile)
                entry = readcsv(resultfile)[dataindex]
                if typeof(entry) <: Number
                    return convert(T,entry)
                else
                    return entry
                end
            end
        end
    end

    #Otherwise throw an error
    error("The data associated to the label $label cannot be found for run ID $resultid in $resultsdir.")
end

#>> Read an N-dimensional array with N>2 from a directory
function readNdimcsv(resultpath::AbstractString,T::Type=Float64)
    if isfile(resultpath)
        return readcsv(resultpath,T)
    elseif isdir(resultpath)
        resultpartpaths::Array{AbstractString,1} = [joinpath(resultpath,fn) for fn in readdir(resultpath)]
        if isempty(resultpartpaths)
            #Return empty 2D array
            return Array(T,0,0)
        end
        #Get array of subarrays
        resultparts::Array = map(readNdimcsv,resultpartpaths,fill(T,length(resultpartpaths)))
        sizes = map(size,resultparts)
        #Check that all sizes match
        if all(sizes .== sizes[1])
            #Concatenate on next dimension
            return cat(ndims(resultparts[1])+1,resultparts...)
        else
            #size mismatch
            error("Size mismatch in subarrays when reading N-dimensional array from $resultpath.")
        end
    end
end

# #############################################################################
# #############################################################################
#Result collection

#Get list of resultids with a specific result recorded
function collectresultids(resultsdir::AbstractString,label::AbstractString)
    return map(first,
               filter(p -> p[2] != -1,
                      map(fn -> checkfnameforlabel(fn,label),
                          readdir(resultsdir))))
end

ext: jl


text:
function main()
    println(join(["OK"], " "))
    exit(sys, 1)
end

main()


text:
using QDXML

const DEFAULT_API_SERVER = "https://api.eveonline.com/"
const SINGULARITY_API_SERVER = "https://api.testeveonline.com/"

type Character
    id::Int
    name::AbstractString
    apikey
    apiVcode
    apiServer
    cache::Dict{AbstractString, Tuple{DateTime, Any}}
end

function getCharacters(key, vCode, apiserver=DEFAULT_API_SERVER)
    empty_char = Character(0, "", key, vCode, DEFAULT_API_SERVER, Dict())
    r = apiget(empty_char, "account/Characters")
    [Character(parse(Int, c.attrs["characterID"]), c.attrs["name"], key, vCode, apiserver, Dict()) for c in r["row", :]]
end

# example endpoint char/SkillQueue ?
function apiget(character::Character, endpoint)
    if endpoint in keys(character.cache) && character.cache[endpoint][1] > now(Dates.UTC)
        x = character.cache[endpoint][2]
    else
        query = Dict("keyID" => character.apikey, "vCode" => character.apiVcode)
        if character.id ≠ 0
            query["characterID"] = character.id
        end
        r = eget("$DEFAULT_API_SERVER$endpoint.xml.aspx", query = query)
        x = XML(r)
    end

    # TODO: what if there is no cachedUntil
    # TODO: plus a few seconds
    cachetime = DateTime(x["cachedUntil"].elems[1], "y-m-d H:M:S")
    character.cache[endpoint] = (cachetime, x)

    x
end

# TODO: what is a sane type? should this return it as a string?
balance(character::Character, parsetype=Float64) = parse(parsetype, apiget(character, "char/AccountBalance")["key"].attrs["balance"])


text:
# =========================================================================== #
# Test
# =========================================================================== #

function test_triangular_solve_upper()

    U = [
        4.0     2       7   9;
        0       12      2   8;
        0       0       1   10;
        0       0       0   6
    ]
    b = [10.0,  2,  5,  6]

    x_row = linalg.triangular_solve_upper_rowwise(U, b)
    x_col = linalg.triangular_solve_upper_colwise(U, b)
    x_theo = U \ b
    println( "x rowwise: $(x_row)" )
    println( "x colwise: $(x_col)" )
    println( "x_theo rowwise: $(x_theo)" )
    println( "residuum norm x rowwise:  $(norm( U * x_row - b )) " )
    println( "residuum norm x colwise:  $(norm( U * x_col - b )) " )
    println( "residuum norm x_theo:  $(norm( U * x_theo - b )) ")
end

function test_triangular_solve_lower()

    L = [
        6.0     0   0   0
        10      1   0   0;
        8       2   12  0;
        9       7   2   4;
    ]

    b = [10.0,  2,  5,  6]

    x_row = linalg.triangular_solve_lower_rowwise(L, b)
    x_col = linalg.triangular_solve_lower_colwise(L, b)
    x_theo = L \ b
    println( "x rowwise: $(x_row)" )
    println( "x colwise: $(x_col)" )
    println( "x_theo rowwise: $(x_theo)" )
    println( "residuum norm x rowwise:  $(norm( L * x_row - b )) " )
    println( "residuum norm x colwise:  $(norm( L * x_col - b )) " )
    println( "residuum norm x_theo:  $(norm( L * x_theo - b )) ")
end

# =========================================================================== #
# Benchmark
# =========================================================================== #

function benchmark_trisolve_default_upper(U, b)
    b = @benchmark $U \ $b

    println("=== benchmark_trisolve_default ===")
    show(
            stdout,
            MIME("text/plain"),
            b )
    println("\n\n")
end

function benchmark_trisolve_rowwise_upper(U, b)
    b = @benchmark linalg.triangular_solve_upper_rowwise($U, $b)

    println("=== benchmark_trisolve_rowwise ===")
    show(
            stdout,
            MIME("text/plain"),
            b )
    println("\n\n")
end

function benchmark_trisolve_colwise_upper(U, b)
    b = @benchmark linalg.triangular_solve_upper_colwise($U, $b)

    println("=== benchmark_trisolve_colwise ===")
    show(
            stdout,
            MIME("text/plain"),
            b )
    println("\n\n")
end

function benchmark_trisolve_upper()
    N = 30_000
    U = UpperTriangular( rand(N, N) )
    b = rand(N)

    benchmark_trisolve_default_upper(U, b)
    benchmark_trisolve_colwise_upper(U, b)
    benchmark_trisolve_rowwise_upper(U, b)

end

function benchmark_trisolve_default_lower(U, b)
    b = @benchmark $U \ $b

    println("=== benchmark_trisolve_default ===")
    show(
            stdout,
            MIME("text/plain"),
            b )
    println("\n\n")
end

function benchmark_trisolve_rowwise_lower(U, b)
    b = @benchmark linalg.triangular_solve_lower_rowwise($U, $b)

    println("=== benchmark_trisolve_rowwise ===")
    show(
            stdout,
            MIME("text/plain"),
            b )
    println("\n\n")
end

function benchmark_trisolve_colwise_lower(U, b)
    b = @benchmark linalg.triangular_solve_lower_colwise($U, $b)

    println("=== benchmark_trisolve_colwise ===")
    show(
            stdout,
            MIME("text/plain"),
            b )
    println("\n\n")
end

function benchmark_trisolve_lower()
    N = 30_000
    U = LowerTriangular( rand(N, N) )
    b = rand(N)

    benchmark_trisolve_default_lower(U, b)
    benchmark_trisolve_colwise_lower(U, b)
    benchmark_trisolve_rowwise_lower(U, b)

end

max_stars_repo_name: HomoModelicus/julia

max_issues_repo_name: HomoModelicus/julia

max_forks_repo_name: HomoModelicus/julia


text:
import Base.==
# do not fall back to === for edges
==(x::T, y::T) where T <: Edge = x == y
==(x::DirectedEdge, y::DirectedEdge) = keep(x, Dst) == keep(y, Dst) && keep(x, Src) == keep(y, Src)
function ==(x::UndirectedEdge, y::UndirectedEdge)
    (keep(x, Src) == keep(y, Src) && keep(x, Dst) == keep(y, Dst)) ||
    (keep(x, Src) == keep(y, Dst) && keep(x, Dst) == keep(y, Src))
end
==(x::ModifiedEdge, y::ModifiedEdge) = keep(x, Edge) == keep(y, Edge) && x.modifiers == y.modifiers

# there is no special compare method for SimpleNode, since Symbols are not mutable
==(x::ModifyingNode, y::ModifyingNode) = keep(x, Node) == keep(y, Node) && x.modifiers == y.modifiers
==(x::ModifiedNode, y::ModifiedNode) = keep(x, Node) == keep(y, Node) && x.modifiers == y.modifiers

==(x::VecOrMat{T}, y::VecOrMat{T}) where T <: Modifier = issetequal(x, y)

# compare arrows
==(x::T, y::T) where T <: Arrow = x.edges == y.edges && x.lhs == y.lhs && x.rhs == y.rhs

# required for sorting
import Base.isless
isless(x::AbstractNode, y::AbstractNode) = isless(id(x), id(y))

import Base.hash
hash(x::T, h::UInt) where {T <: UndirectedEdge} = hash(T, hash(sort([x.src, x.dst]), h))
hash(x::T, h::UInt) where {T <: ModifiedEdge} = hash(T, hash(x.edge, hash(x.modifiers, h)))


text:
using JSONRPC
using Logging: current_logger, with_logger
using Sockets
using Test
using Test: TestLogger

struct NonSerializable end

function start_test_server(server, serializer)
    dispatcher = Dict(
        "add1" => ((x,),) -> x + 1,
        "nonserializable" => _ -> NonSerializable(),
    )
    @async JSONRPC.serve(dispatcher, server, serializer)
end

function with_test_server(f, serializer = JSONRPC.NDJSON)
    mktempdir() do dir
        listenable = joinpath(dir, "jsonrpc.socket")
        server = listen(listenable)
        logger = TestLogger()
        # logger = current_logger()
        with_logger(logger) do
            task = start_test_server(server, serializer)
            try
                f(listenable, serializer, logger)
            finally
                close(server)
                wait(task)
            end
        end
    end
end

function waittrue(f)
    for _ in 1:100
        f() && return true
        sleep(0.01)
    end
    return false
end

@testset begin
    with_test_server() do listenable, serializer, logger
        io = connect(listenable)
        client = JSONRPC.client(io, serializer)

        @test client.add1(2) == 3

        err = nothing
        @test try
            client.add1(nothing)
        catch err
            err
        end isa JSONRPC.Error
        @test err.code == Int(JSONRPC.MethodException)

        @testset "serialization error on server" begin
            err = nothing
            @test try
                Some(client.nonserializable())
            catch err
                err
            end isa JSONRPC.Error
            @test err.code == Int(JSONRPC.SerializationError)
            @test client.add1(2) == 3  # recoverable
        end

        #=
        @testset "serialization error on client" begin
            write(io, """{"broken": "json"]\n""")
            @test client.add1(2) == 3  # recoverable
        end
        =#

        serializer.serialize(io, Dict("broken" => "request"))
        if logger isa TestLogger
            @test waittrue() do
                any(l.message == "Response with unknown ID" for l in logger.logs)
            end
        else
            @info "It's OK to see `Error: Response with unknown ID` here."
            sleep(0.1)
        end

        @test client.add1(2) == 3  # broken request is recoverable
    end
end

@testset "sending response to closed connection (`jsonprintln`)" begin
    with_test_server()  do listenable, serializer, logger
        io = connect(listenable)
        client = JSONRPC.client(io, serializer)

        # Make sure it's working
        @test client.add1(2) == 3

        # Test that trying to send response to closed connection does
        # not throw:
        serializer.serialize(io, Dict("broken" => "request"))
        if logger isa TestLogger
            @test waittrue() do
                any(l.message == "Response with unknown ID" for l in logger.logs)
            end
        else
            @info "It's OK to see `Error: Response with unknown ID` here."
            sleep(0.1)
        end
    end
end


text:
# ## Bar plot
# ### Vertical Bar Plot

#md # ![FILE_NAME.png](images/FILE_NAME.png)

# https://jp.mathworks.com/matlabcentral/fileexchange/35271-matlab-plot-gallery-vertical-bar-plot?focused=6793087&tab=example

using StatsPlots

measles = [38556, 24472, 14556, 18060, 19549, 8122, 28541, 7880, 3283, 4135, 7953, 1884]
mumps = [20178, 23536, 34561, 37395, 36072, 32237, 18597, 9408, 6005, 6268, 8963, 13882]
chickenPox = [37140, 32169, 37533, 39103, 33244, 23269, 16737, 5411, 3435, 6052, 12825, 23332]

ticklabel = string.(collect('A':'L'))
groupedbar([measles mumps chickenPox], bar_position = :dodge, bar_width=0.7, xticks=(1:12, ticklabel))


text:
export solve

function print_header(io::IO)
    println("it  primal obj    dual obj           mu        delta        alpha   it. time")
end

function print_it(io::IO, it, primobj, dualobj, mu, delta, alpha, time)
    @printf("%2i  % .3e  % .3e   % .3e    % .6f   % .3e   %f\n", it, primobj, dualobj, mu, delta, alpha, time)
end

"""
    solve(pb::SDCOContext{T}, z0::PointPrimalDual)

    Strictly feasible IP method for positive orthant and SDP cone, with NT scaling.
    z0 is the strictly feasible starting point.
"""
function solve(pb::SDCOContext{T}, z0::PointPrimalDual) where T<:Number
    z = deepcopy(z0)

    outlev = pb.options[:opt_outlev]

    ## Centering section
    θ = 1/3
    τ = 0.99
    ω = 1e-4

    cur_mu = mu(z)
    cur_delta = delta(pb, z)
    it = 0
    α = -1
    d = NesterovToddstep(pb, z, 0.)

    (outlev > 0) && print_header(stdout)
    (outlev > 0) && print_it(stdout, it, -1, -1, cur_mu, cur_delta, -1, α)

    if (cur_delta > θ)
        (outlev > 0) && println("Getting to central path...")
    end

    while (cur_delta > θ) && (it < 20)
        t1 = time()
        α = NTcentering_it!(pb, τ, ω, z, cur_mu, cur_delta)

        cur_mu = mu(z)
        cur_delta = delta(pb, z)

        it += 1
        (outlev > 0) && print_it(stdout, it, -1, -1, cur_mu, cur_delta, α, time() - t1)
    end

    ## Path following section
    (outlev > 0) && println("Following central path...")
    ε = pb.options[:opt_ε]
    maxit = pb.options[:opt_maxit]
    alphacorr = 0.999

    nc = get_nc(z.x)
    # K = ceil((1 + sqrt(1+ 13*nc/2)) * log10(mu(z) / epsilon))
    # @show K

    cur_μ = mu(z)

    # K = log(ε / cur_μ) / log(1 + 4 / (13*nc) * (1 - sqrt(1+13*nc/2)))
    # @show K

    while (it < maxit) && (cur_μ > ε)
        t1 = time()

        res = α, cur_μ = NTpredcorr_it!(pb, alphacorr, cur_μ, cur_delta, z, d)

        it+=1

        cur_μ = mu(z)
        cur_delta = delta(pb, z)
        (outlev > 0) && print_it(stdout, it, get_primobj(pb, z), get_dualobj(pb, z), cur_μ, cur_delta, α, time() - t1)
    end

    (outlev > 0) && println("Final duality gap: ", get_primobj(pb, z) - get_dualobj(pb, z))
    (outlev > 0) && println("Final mu         : ", mu(z))

    return z
end

function NTcentering_it!(pb, τ, ω, z, cur_mu, cur_delta)
    mu_z = cur_mu
    dc = NesterovToddstep(pb, z, mu_z)

    if cur_delta < sqrt( (2*τ^2) / (1+2*τ^2) )
        α = 1
    else
        i = 0
        α = 2^(-i)

        while phi_mu(z + α*dc, mu_z) > (phi_mu(z, mu_z) - 4*ω*mu_z*α*delta(pb, z)^2)
            i += 1
            α = (1/2)^(i)

            (i > 100) && error("i = $i...")
        end
    end

    add!(z, α * dc)

    return α
end

# function symmetrize!(z)
#     for i in 1:length(z.x.mats)
#         z.x.mats[i] = (z.x.mats[i] + transpose(z.x.mats[i]))/2
#     end
#
#     for i in 1:length(z.s.mats)
#         z.s.mats[i] = (z.s.mats[i] + transpose(z.s.mats[i]))/2
#     end
# end

function NTpredcorr_it!(pb, alphacorr, cur_mu, cur_delta, z, d)
    # centering step
    mu_z = mu(z)
    NesterovToddstep!(pb, z, mu_z, d)

    # zc = z + dc
    add!(z, d)
    mu_zc = mu(z)

    # affine step
    NesterovToddstep!(pb, z, 0., d)

    α = NT_getalpha(pb, z, d)

    (pb.options[:opt_outlev] > 1) && printstyled("mu(z) - mu(zc) : ", abs(mu_z - mu_zc), "\n", color=:red)

    alphacorr = min(α, 0.99999)

    add!(z, alphacorr*d)
    mu_za = mu(z)

    (pb.options[:opt_outlev] > 1) && printstyled("mu(z+) / mu(zc) - (1 - alpha): ", abs(mu_za / mu_zc - (1-α)), "\n", color=:red)

    return α, mu_za
end


text:
@userplot CornerPlot

@recipe function f(cp::CornerPlot; compact=false, maxvariables=30, histpct = 0.1)
    mat = cp.args[1]
    @assert typeof(mat) <: AbstractMatrix
    N = size(mat,2)
    if N > maxvariables
        error("Requested to plot $N variables in $(N^2) subplots!  Likely, the first input needs transposing, otherwise increase maxvariables.")
    end

    # k is the number of rows/columns to hide
    k = compact ? 1 : 0

    # n is the total number of rows/columns.  hists always shown
    n = N + 1 - k

    labs = pop!(d, :label, ["x$i" for i=1:N])
    if labs!=[""] && length(labs)!=N
        error("Number of labels not identical to number of datasets")
    end

    # build a grid layout, where the histogram sizes are a fixed percentage, and we
    scatterpcts = ones(n-1) * (1-histpct) / (n-1)
    g = grid(n, n, widths = vcat(scatterpcts, histpct), heights = vcat(histpct, scatterpcts))
    spidx = 1
    indices = zeros(Int,n,n)
    for i=1:n, j=1:n
        isblank = (i==1 && j==n) || (compact && i>1 && j<n && j>=i)
        g[i,j].attr[:blank] = isblank
        if !isblank
            indices[i,j] = spidx
            spidx += 1
        end
    end
    layout := g

    # some defaults
    legend    := false
    foreground_color_border := nothing
    margin    --> 1mm
    titlefont --> font(11)
    fillcolor --> :black
    linecolor --> :black
    grid      --> true
    ticks     := nothing
    formatter := v->""
    link      := :both

    # figure out good defaults for scatter plot dots:
    pltarea = 1 / (2n)
    nsamples = size(mat,1)
    markersize  --> clamp(pltarea * 1000 / sqrt(nsamples), 1,     10)
    markeralpha --> clamp(pltarea * 100 / nsamples^0.42,   0.005, 0.4)

    # histograms in the right column
    for i=1:N
        compact && i == 1 && continue
        @series begin
            orientation := :h
            seriestype  := :histogram
            subplot     := indices[i+1-k,n]
            grid        := false
            view(mat,:,i)
        end
    end

    # histograms in the top row
    for j=1:N
        compact && j == N && continue
        @series begin
            seriestype  := :histogram
            subplot     := indices[1,j]
            grid        := false
            view(mat,:,j)
        end
    end

    # scatters
    for i=1:N
        vi = view(mat,:,i)
        for j = 1:N
            # only the lower triangle
            if compact && i <= j
                continue
            end

            vj = view(mat,:,j)
            @series begin
                ticks := :auto
                if i == N
                    xformatter := :auto
                    xguide := cycle(labs, j)
                end
                if j == 1
                    yformatter := :auto
                    yguide := cycle(labs, i)
                end
                seriestype := :scatter
                subplot := indices[i+1-k, j]
                smooth := true
                markerstrokewidth --> 0
                vj, vi
            end
        end
        # end
    end
end


text:
#small function for creating a tuple of numerical params (like grid)
function define_NumParam(a_n, Δ, g, a_min,ϵ)
  @assert a_n > 10
  @assert g > 0.0
  @assert Δ > 0.0
    a_grid = zeros(a_n)
    a_grid[1]=a_min+ϵ
    for i in 2:a_n
       a_grid[i] = a_grid[i-1]+Δ*(1.0+g)^(i-1)
    end
    return(a_n, a_grid, a_min)
end

#function for AR process discretization, basing on the QuantEcon routines
function DiscretizeAR(ρ, σ, n, method)
    #n:number of states
    #\rho , \sigma : values for
    @assert n > 0
    @assert σ > 0.0
    @assert ρ >= 0.0
    @assert ρ < 1.0

    σ= σ*(1-ρ^2)^(1/2)
    if(method == "R")
        MC = rouwenhorst(n, ρ, σ)
    else
        MC = tauchen(n, ρ, σ)
    end
    return(P = MC.p, ϵ = exp.(MC.state_values))
end

#FIX: somehow the Smolyak package does not work on my machine, due to some name spaces mismatch, thus I wirite simply fix for this
#(it reduced to changing a few names), I know that it is not the best solution, but for now it works...

function smolyak_inverse_interpolation_matrix_1(nodes::Union{Array{T,1},Array{T,2}},multi_index::Array{S,2}) where {T<:AbstractFloat,S<:Integer}

    interpolation_matrix = zeros(size(nodes,1),size(nodes,1))

    unique_multi_index = sort(unique(multi_index))
    unique_orders      = m_i(unique_multi_index).-1

    # Below we do the following things:

    #   Generate the polynomial terms for each order
    #   Generate the unique polynomial terms introduced at each higher order
    #   Combine the polynomial terms to construct the first row of the interpolation matrix
    #   Iterate over the nodes, doing the above three steps at each iteration, to compute all rows of the interpolation matrix

    for k = 1:size(nodes,1)

      # Construct the base polynomials

      base_polynomials = Array{Array{T,2}}(undef,length(unique_orders))
      for i = 1:length(unique_orders)
        base_polynomials[i] = SmolyakApprox.chebyshev_polynomial(unique_orders[i],nodes[k,:])
      end

      # Compute the unique polynomial terms from the base polynomials

      unique_base_polynomials = Array{Array{T,2}}(undef,length(unique_orders))
      for i = length(unique_orders):-1:2
        unique_base_polynomials[i] = base_polynomials[i][:,size(base_polynomials[i-1],2)+1:end]
      end
      unique_base_polynomials[1] = base_polynomials[1]

      # Construct the first row of the interplation matrix

      new_polynomials = unique_base_polynomials[multi_index[1,1]][1,:]
      for i = 2:size(multi_index,2)
        new_polynomials = kron(new_polynomials,unique_base_polynomials[multi_index[1,i]][i,:])
      end

      polynomials = copy(new_polynomials)

      # Iterate over nodes, doing the above three steps at each iteration

      for j = 2:size(multi_index,1)
        new_polynomials = unique_base_polynomials[multi_index[j,1]][1,:]
        for i = 2:size(multi_index,2)
          new_polynomials = kron(new_polynomials,unique_base_polynomials[multi_index[j,i]][i,:])
        end
        polynomials = [polynomials; new_polynomials]
      end

      interpolation_matrix[k,:] = polynomials[:]

    end

    inverse_interpolation_matrix = inv(interpolation_matrix)

    return inverse_interpolation_matrix

  end

  function smolyak_inverse_interpolation_matrix_1(nodes::Union{Array{T,1},Array{T,2}},multi_index::Array{S,2},domain::Union{Array{T,1},Array{T,2}}) where {T<:AbstractFloat,S<:Integer}

    # Normalize nodes to the [-1.0 1.0] interval

    nodes = copy(nodes)
    for i = 1:size(nodes,1)
      for j = 1:size(domain,2)
        if domain[1,j] == domain[2,j]
          nodes[i,j] = (domain[1,j]+domain[2,j])/2
        else
          nodes[i,j] = 2*(nodes[i,j]-domain[2,j])/(domain[1,j]-domain[2,j])-one(T)
        end
      end
    end

    inverse_interpolation_matrix = smolyak_inverse_interpolation_matrix_1(nodes,multi_index)

    return inverse_interpolation_matrix

  end


text:
module ObjectiveFunction

using DifferentialEquations
using LinearAlgebra

export data_shooting, single_shooting, tikhonov

"""
Tikhonov Regularization
"""
function tikhonov(lambda::T, phi::Vector{T}, phi_ref::Vector{T},
                  w::Vector{T})::T where T
    res = zero(T)
    @simd for i in 1:length(phi)
        @inbounds res += abs2((phi[i]-phi_ref[i])*w[i])
    end
    res *= lambda
    return res
end
function tikhonov(lambda::T, phi::Vector{D}, phi_ref::Vector{T},
                  w::Vector{T})::D where T where D
    res = zero(D)
    @simd for i in 1:length(phi)
        @inbounds res += abs2((phi[i]-phi_ref[i])*w[i])
    end
    res *= lambda
    return res
end

"""
Sum of Squared Errors
"""
function sse(a::Vector{Vector{T}},b::Vector{Vector{T}})::T where T<:AbstractFloat
    sum = zero(T)

    if length(a) != length(b) || length(a[1]) != length(b[1])
        return Inf64
    end

    @simd for i in 1:length(a)
        for j in 1:length(a[1])
            @inbounds sum += abs2(a[i][j]-b[i][j])
        end
    end
    return sum
end
function sse(a::Vector,b::Vector)
    T = promote_type(eltype(a[1]),eltype(b[1]))
    sum = zero(T)

    if length(a) != length(b) || length(a[1]) != length(b[1])
        return Inf64
    end

    for i in 1:length(a)
        for j in 1:length(a[1])
            @inbounds sum += abs2(a[i][j]-b[i][j])
        end
    end
    return sum
end

"""
phi: Parameters to be optimized. Can be comprized of rate constants.
data: Observed data, used for calculating the residuals.
time_array: Time intervals in which the data has been colected.
f: DE that describes the phenomena.
"""
function data_shooting(phi::Vector{T},
                        data::Vector,
                        time_array::AbstractArray,
                        f::Function)::T where T

    num_samples = length(data)
    num_state_vars = length(data[1])

    estimated = zeros(T,num_state_vars)
    sum_error = zero(T)
    f_0 = zeros(T,num_state_vars)
    f_1 = zeros(T,num_state_vars)
    delta_t = zero(eltype(time_array))

    @inbounds for i in 1:num_samples-1
        delta_t = time_array[i+1] - time_array[i]

        x_0 = data[i]
        x_1 = data[i+1]

        f(f_0, x_0, phi, 0)
        f(f_1, x_1, phi, 0)

        for j in 1:num_state_vars
            estimated[j] = x_0[j] + 0.5*delta_t*(f_0[j]+f_1[j])
            sum_error += abs2(estimated[j]-data[i+1][j])
        end
    end
    return sum_error
end

function single_shooting(phi::Vector{T},
                        data::Vector,
                        t::AbstractArray,
                        f::Function)::T where T
    ini_cond = convert.(eltype(phi),data[1])
    tspan = (t[1], t[end])

    prob = ODEProblem(f, ini_cond, tspan, phi,
                      isoutofdomain=(u,p,t) -> any(x -> (x < 0), p))
    osol  = solve(prob, AutoVern7(Rodas5()), saveat=t)

    return sse(data,osol.u)
end

"""
params: Parameters to be optimized. Can be comprized of rate constants and initial values.
data: Observed data, used for calculating the residuals.
time_array: Time intervals in which the data has been colected.
f: DE that describes the phenomena.
"""
function data_shooting_exp(params::Array{<:AbstractFloat,1},
                        data::Array{<:AbstractFloat},
                        time_array::StepRangeLen,
                        f::Function;
                        unknown_vars::Array{<:Float64,1}=[],
                        differential_vars::Array{<:Float64,1}=[])::Array{<:AbstractFloat,1}

    num_state_vars, num_samples = size(data)

    phi = params[1:length(params)-length(unknown_vars)]

    # If the initial values of some states are not known
    if unknown_vars != []
        known_vars = collect(1:num_state_vars+length(unknown_vars))
        setdiff!(known_vars,unknown_vars)

        num_state_vars += length(unknown_vars)
        estimated = zeros(
                        promote_type(
                            eltype(phi),eltype(data)
                        ),
                        num_state_vars,num_samples
                    )

        # Initial conditions are stored at x_dot_num's first column
        i = 1
        for k in known_vars
            estimated[k,1] = data[i,1]
            i+=1
        end
        i = 1
        for k in unknown_vars
            estimated[k,1] = params[length(params)-length(unknown_vars)+i]
            i+=1
        end

        # Numerical method
        tspan = (time_array[1], time_array[end])

        ini_cond = estimated[:,1]

        oprob = ODEProblem(f, ini_cond, tspan, phi)
        osol  = solve(oprob, Rodas5(), saveat=time_array)
        partial_estimate = reduce(hcat, osol.u)

        # Now make an array comprised of all the states:
        # the ones calculated by the numerical method above
        # and the known ones, from the data
        partial_data = Array{Float64}(undef,0,length(time_array))
        i = 1
        j = 1

        state_vars = collect(1:num_state_vars)
        for k in state_vars
            if k in known_vars
                partial_data = vcat(partial_data,(data[i,:]'))
                i+=1
            else
                partial_data = vcat(partial_data,(partial_estimate[j,:]'))
                j+=1
            end
        end
        data = partial_data
        # TODO
        # Try to avoid so much array transpositions

    else
        estimated = zeros(
                        promote_type(
                            eltype(phi),eltype(data)
                        ),
                        num_state_vars,num_samples
                    )
        # Initial conditions are stored at x_dot_num's first column
        estimated[:,1] = data[:,1]
    end

    @inbounds for i in 1:num_samples-1
        delta_t = time_array[i+1] - time_array[i]

        x_0 = data[:, i]
        x_1 = data[:, i+1]

        f_0 = zeros(num_state_vars)
        f(f_0, x_0, phi, 0)
        f_1 = zeros(num_state_vars)
        f(f_1, x_1, phi, 0)

        if differential_vars != []
            x_est = zeros(num_state_vars)
            x_est[differential_vars] .= x_0[differential_vars] +
                                            (1/2)*delta_t*(
                                                f_0[differential_vars]+
                                                f_1[differential_vars]
                                            )
            x_est[.~differential_vars] .= f_1[.~differential_vars]
        else
            x_est = x_0 + (1/2)*delta_t*(f_0+f_1)
        end

        estimated[:, i+1] = x_est
    end

    states_to_filter = []
    if unknown_vars != []
        states_to_filter = map(x -> if x in unknown_vars false else true end, state_vars)
    elseif differential_vars != []
        states_to_filter = .~differential_vars
    end

    # TODO
    # Fix weighting
    if states_to_filter != []
        data = data[states_to_filter,:]
        estimated = estimated[states_to_filter,:]
        weight = abs2(1/findmax(data)[1])
        residuals = weight .* (data-estimated)
    else
        weight = abs2(1/findmax(data)[1])
        residuals = weight .* (data-estimated)
    end
    #=>
    if findmin(estimated)[1] < 0
        for i in 1:length(residuals)
            residuals[i] = 10^10
        end
    end
    <=#
    return residuals
end

function single_shooting_exp(params::Array{<:AbstractFloat},
                        data::Array{<:AbstractFloat},
                        t::StepRangeLen,
                        f::Function;
                        unknown_vars::Array{<:AbstractFloat} = [],
                        return_estimated::Bool=false)::Array{<:AbstractFloat}

    num_state_vars, num_samples = size(data)
    state_vars = collect(1:num_state_vars)
    # Check whether all state variables are known
    if unknown_vars == []
        known_vars = 1:num_state_vars
        # If there are no unknown states, then there are no initial condition
        # values to be optimized among the "params". This way, "params"
        # stores only to the rate constants to be found.
        ini_cond = data[:,1]
        phi = params
    else
        ini_cond = data[:,1]
        for (idx,val) in zip(unknown_vars,params)
            insert!(ini_cond, idx, val)
        end

        num_state_vars += length(unknown_vars)
        known_vars = collect(1:num_state_vars)
        setdiff!(known_vars,unknown_vars)
        phi = params[1:length(params)-length(unknown_vars)]
    end

    tspan = (t[1], t[end])
    oprob = ODEProblem(f, ini_cond, tspan, phi)
    osol  = solve(oprob, Rodas5(), saveat=t, save_idxs=known_vars)
    estimated = reduce(hcat, osol.u)

    if return_estimated
        return estimated
    end

    # TODO
    # Fix weighting

    weight = abs2(1/findmax(data)[1])
    residuals = weight .* (data-estimated)

    return residuals
end

function soft_l1(z::T)::T where T<:Number
    sz = (2 * ((1 + z)^0.5 - 1))
end

function huber(z::T)::T where T<:Number
    M = 1.35
    if z < M
        return abs2(z)
    else
        return 2.0*M*abs(z) - M^2
    end
end

end

max_stars_repo_name: atgmello/DEParamEst

max_issues_repo_name: atgmello/DEParamEst

max_forks_repo_name: atgmello/DEParamEst


text:
@testset "848.shifting-letters.jl" begin
    @test shifting_letters("abc", [3, 5, 9]) == "rpl"
end


text:
using RvSpectMLBase
using Test

@testset "RvSpectMLBase.jl" begin
    include("types/types.jl")
    include("util/util.jl")
#=
    include("util.jl")
    include("chunk_of_spectrum.jl")
    include("theoretical_instrument.jl")
    include("spectra.jl")
    include("chunk_list.jl")
    #include("spectra_timeseries.jl")    # TODO: Add tests
    #include("spectra_timeseries_common_wavelengths.jl")  # TODO: Add tests
=#
end

max_stars_repo_name: RvSpectML/RvSpectMLTemplate

max_issues_repo_name: RvSpectML/RvSpectMLTemplate

max_forks_repo_name: RvSpectML/RvSpectMLTemplate


text:
# Test that the maximum sphere radius is correctly calculated

@testset "Maximum sphere radius" begin
@testset "fcc" begin
    @test MkCell.score_sphere(fcc1*cellfcc)   ≈ 0.7905694150420949
    @test MkCell.score_sphere(fcc4*cellfcc)   ≈ 0.8660254037844386
    @test MkCell.score_sphere(fcc7*cellfcc)   ≈ 1.118033988749895
    @test MkCell.score_sphere(fcc13*cellfcc)  ≈ 1.50
    @test MkCell.score_sphere(fcc23*cellfcc)  ≈ 1.7677669529663689
    @test MkCell.score_sphere(fcc26*cellfcc)  ≈ 1.7320508075688772
    @test MkCell.score_sphere(fcc32*cellfcc)  ≈ 1.7320508075688772
    @test MkCell.score_sphere(fcc38*cellfcc)  ≈ 1.8708286933869707
    @test MkCell.score_sphere(fcc50*cellfcc)  ≈ 2.1213203435596424
    @test MkCell.score_sphere(fcc70*cellfcc)  ≈ 2.4238399287081647
    @test MkCell.score_sphere(fcc92*cellfcc)  ≈ 2.5495097567963922
    @test MkCell.score_sphere(fcc96*cellfcc)  ≈ 2.500
    @test MkCell.score_sphere(fcc100*cellfcc) ≈ 2.692582403567252
    @test MkCell.score_sphere(fcc108*cellfcc) ≈ 2.598076211353316
end;
@testset "cubic" begin
    @test MkCell.score_sphere(cubic1*cellcubic)   ≈ 0.8660254037844386
    @test MkCell.score_sphere(cubic3*cellcubic)   ≈ 1.50
    @test MkCell.score_sphere(cubic7*cellcubic)   ≈ 2.0615528128088303
    @test MkCell.score_sphere(cubic8*cellcubic)   ≈ 1.7320508075688772
    @test MkCell.score_sphere(cubic13*cellcubic)  ≈ 2.29128784747792
    @test MkCell.score_sphere(cubic14*cellcubic)  ≈ 2.23606797749979
    @test MkCell.score_sphere(cubic24*cellcubic)  ≈ 2.50
    @test MkCell.score_sphere(cubic27*cellcubic)  ≈ 2.598076211353316
    @test MkCell.score_sphere(cubic33*cellcubic)  ≈ 2.8722813232690143
    @test MkCell.score_sphere(cubic38*cellcubic)  ≈ 3.2015621187164243
    @test MkCell.score_sphere(cubic52*cellcubic)  ≈ 3.24037034920393
    @test MkCell.score_sphere(cubic56*cellcubic)  ≈ 3.500
    @test MkCell.score_sphere(cubic64*cellcubic)  ≈ 3.4641016151377544
    @test MkCell.score_sphere(cubic73*cellcubic)  ≈ 3.905124837953327
    @test MkCell.score_sphere(cubic76*cellcubic)  ≈ 3.7416573867739413
    @test MkCell.score_sphere(cubic93*cellcubic)  ≈ 4.06201920231798
    @test MkCell.score_sphere(cubic100*cellcubic) ≈ 4.031128874149275
end;
@testset "bcc" begin
    @test MkCell.score_sphere(bcc1*cellbcc)   ≈ 0.82915619758885
    @test MkCell.score_sphere(bcc2*cellbcc)   ≈ 0.8660254037844386
    @test MkCell.score_sphere(bcc6*cellbcc)   ≈ 1.479019945774904
    @test MkCell.score_sphere(bcc9*cellbcc)   ≈ 1.479019945774904
    @test MkCell.score_sphere(bcc16*cellbcc)  ≈ 1.7320508075688772
    @test MkCell.score_sphere(bcc21*cellbcc)  ≈ 2.0615528128088303
    @test MkCell.score_sphere(bcc25*cellbcc)  ≈ 2.277608394786075
    @test MkCell.score_sphere(bcc28*cellbcc)  ≈ 2.23606797749979
    @test MkCell.score_sphere(bcc35*cellbcc)  ≈ 2.277608394786075
    @test MkCell.score_sphere(bcc48*cellbcc)  ≈ 2.50
    @test MkCell.score_sphere(bcc53*cellbcc)  ≈ 2.8613807855648994
    @test MkCell.score_sphere(bcc54*cellbcc)  ≈ 2.598076211353316
    @test MkCell.score_sphere(bcc65*cellbcc)  ≈ 3.031088913245535
    @test MkCell.score_sphere(bcc84*cellbcc)  ≈ 3.112474899497183
    @test MkCell.score_sphere(bcc91*cellbcc)  ≈ 3.112474899497183
    @test MkCell.score_sphere(bcc103*cellbcc) ≈ 3.344772040064913
    @test MkCell.score_sphere(bcc107*cellbcc) ≈ 3.418698582794336
    @test MkCell.score_sphere(bcc112*cellbcc) ≈ 3.418698582794336
    @test MkCell.score_sphere(bcc128*cellbcc) ≈ 3.4641016151377544
end;
@testset "hcp" begin
    @test MkCell.score_sphere(hcp1*cellhcp)   ≈ 0.6679616056830413
    @test MkCell.score_sphere(hcp3*cellhcp)   ≈ 0.9584314616427545
    @test MkCell.score_sphere(hcp6*cellhcp)   ≈ 1.074616185745714
    @test MkCell.score_sphere(hcp8*cellhcp)   ≈ 1.1224
    @test MkCell.score_sphere(hcp11*cellhcp)  ≈ 1.3650740590409982
    @test MkCell.score_sphere(hcp14*cellhcp)  ≈ 1.4759311049864985
    @test MkCell.score_sphere(hcp16*cellhcp)  ≈ 1.4490121692610682
    @test MkCell.score_sphere(hcp21*cellhcp)  ≈ 1.5538924372898746
    @test MkCell.score_sphere(hcp27*cellhcp)  ≈ 1.7448417081978145
    @test MkCell.score_sphere(hcp37*cellhcp)  ≈ 1.8962138873731165
    @test MkCell.score_sphere(hcp39*cellhcp)  ≈ 1.9775167626765309
    @test MkCell.score_sphere(hcp42*cellhcp)  ≈ 2.0169395793297
    @test MkCell.score_sphere(hcp53*cellhcp)  ≈ 2.167472294325043
    @test MkCell.score_sphere(hcp62*cellhcp)  ≈ 2.2968099877874093
    @test MkCell.score_sphere(hcp65*cellhcp)  ≈ 2.3420716783793503
    @test MkCell.score_sphere(hcp69*cellhcp)  ≈ 2.2968099877874093
    @test MkCell.score_sphere(hcp76*cellhcp)  ≈ 2.3974474509360992
    @test MkCell.score_sphere(hcp80*cellhcp)  ≈ 2.3974474509360992
    @test MkCell.score_sphere(hcp88*cellhcp)  ≈ 2.440843687470926
    @test MkCell.score_sphere(hcp90*cellhcp)  ≈ 2.446214087115026
    @test MkCell.score_sphere(hcp100*cellhcp) ≈ 2.5666337461092237
end;
end;


text:
push!(LOAD_PATH,"../src/")

using Documenter, RLCore

makedocs(
    sitename="RLCore",
    modules = [RLCore],
    format = Documenter.HTML(prettyurls = false),
    pages = [
        "Home"=>"index.md",
        "Manual" => Any[
             "Environments" => "manual/environment.md"
             # "Agents" => "docs/agents.md"
             # "Learning" => "docs/learning.md"
             # "Feature Creators" => "docs/feature_creators.md"
             ],
         "Documentation" => Any[
             "Environments" => "docs/environments.md"
             "Agents" => "docs/agents.md"
             "GVF" => "docs/gvf.md"
             # "Learning" => "docs/learning.md"
             "Feature Constructor" => "docs/feature_creators.md"
             ]
    ]
)

deploydocs(
    repo = "github.com/mkschleg/RLCore.jl.git",
    devbranch = "master"
)


text:
# Tabix Overlap Iterator
# ======================

struct TabixOverlapIterator{T}
    reader::T
    interval::Interval
end

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

function Base.IteratorSize(::Type{TabixOverlapIterator{T}}) where T
    return Base.SizeUnknown()
end

mutable struct TabixOverlapIteratorState{T}
    chunks::Vector{Indexes.Chunk}
    chunkid::Int
    done::Bool
    record::T
end

function Base.iterate(iter::TabixOverlapIterator)
    @assert iter.reader.index !== nothing
    # TODO: Use a method that resets the reading position.
    buffer = BioCore.IO.stream(iter.reader)
    iter.reader.state = BioCore.Ragel.State(1, BufferedStreams.BufferedInputStream(buffer.source))
    state = TabixOverlapIteratorState(
        Indexes.overlapchunks(iter.reader.index, iter.interval),
        0,
        false,
        eltype(iter)())

    return iterate(iter, state)
end

function done(iter::TabixOverlapIterator, state)
    buffer = BioCore.IO.stream(iter.reader)
    source = buffer.source
    if state.chunkid == 0
        if isempty(state.chunks)
            return true
        end
        state.chunkid += 1
        seek(source, state.chunks[state.chunkid].start)
    end
    while state.chunkid ≤ lastindex(state.chunks)
        chunk = state.chunks[state.chunkid]
        # The `virtualoffset(source)` is not synchronized with the current
        # reading position because data are buffered in `buffer` for parsing
        # text. So we need to check not only `virtualoffset` but also
        # `nb_available`, which returns the current buffered data size.
        while bytesavailable(buffer) > 0 || BGZFStreams.virtualoffset(source) < chunk.stop
            read!(iter.reader, state.record)
            c = icmp(state.record, iter.interval)
            if c == 0  # overlapping
                return false
            elseif c > 0
                # no more overlapping records in this chunk
                break
            end
        end
        state.chunkid += 1
        if state.chunkid ≤ lastindex(state.chunks)
            seek(source, state.chunks[state.chunkid].start)
        end
    end
    # no more overlapping records
    return true
end

function Base.iterate(iter::TabixOverlapIterator, state)
    if done(iter, state)
        return nothing
    else
        return copy(state.record), state
    end
end

function icmp(record, interval)
    c = cmp(BioCore.seqname(record), interval.seqname)
    if c < 0 || (c == 0 && BioCore.rightposition(record) < interval.first)
        return -1
    elseif c > 0 || (c == 0 && BioCore.leftposition(record) > interval.last)
        return +1
    else
        return 0
    end
end


text:
"""
`@byrow!(d, x)`

Apply the expression `x` row by row in `d` (to modify `d` in place). Symbols refer to fields of the row.
In this context, `_` refers to the whole row. To use actual symbols, escape them with `^`, as in `^(:a)`.
Use `cols(c)` to refer to field `c` where `c` is a variable that evaluates to a symbol. `c` must be available in
the scope where the macro is called.

## Examples

```jldoctest byrow
julia> t = table((a = [1,2,3], b = ["x","y","z"]));

julia> @byrow! t :b = :b*string(:a)
Table with 3 rows, 2 columns:
a  b
───────
1  "x1"
2  "y2"
3  "z3"

julia> @byrow! t begin
       :a = :a*2
       :b = "x"^:a
       end
Table with 3 rows, 2 columns:
a  b
───────────
2  "xx"
4  "xxxx"
6  "xxxxxx"
```
"""
macro byrow!(args...)
    esc(byrow_helper(args...))
end

function byrow_helper(args...)
    d = gensym()
    iter = gensym()
    function_call = parse_function_call(d, last(args), replace_iterator, iter)
    expr = quote
        for $iter in 1:length($d)
            $function_call
        end
        $d
    end
    func = Expr(:(->), d, expr)
    Expr(:call, :(JuliaDBMeta._pipe_chunks), func, args[1:end-1]...)
end

replace_iterator(d, x, iter) = Expr(:ref, Expr(:call, :getfield, :(JuliaDBMeta.columns($d)), x), iter)
replace_iterator(d, iter) = Expr(:ref, d, iter)


text:
# Copyright (c) 2017: Miles Lubin and contributors
# Copyright (c) 2017: Google Inc.
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.

"""
    SOCtoRSOCBridge{T,F,G} <: Bridges.Constraint.AbstractBridge

`SOCtoRSOCBridge` implements the following reformulation:

  * ``||x||_2 \\le t`` into ``2uv \\ge ||w||_2^2``, with the substitution rules
    ``t = \\frac{u}{\\sqrt 2} + \\frac{v}{\\sqrt 2}``,
    ``x = (\\frac{u}{\\sqrt 2} - \\frac{v}{\\sqrt 2}, w)``.

## Assumptions

  * `SOCtoRSOCBridge` assumes that ``|x| \\ge 1``.

## Source node

`SOCtoRSOCBridge` supports:

  * `G` in [`MOI.SecondOrderCone`](@ref)

## Target node

`SOCtoRSOCBridge` creates:

  * `F` in [`MOI.RotatedSecondOrderCone`](@ref)
"""
struct SOCtoRSOCBridge{T,F,G} <:
       SetMapBridge{T,MOI.RotatedSecondOrderCone,MOI.SecondOrderCone,F,G}
    constraint::MOI.ConstraintIndex{F,MOI.RotatedSecondOrderCone}
end

const SOCR{T,OT<:MOI.ModelLike} = SingleBridgeOptimizer{SOCtoRSOCBridge{T},OT}

function concrete_bridge_type(
    ::Type{<:SOCtoRSOCBridge{T}},
    G::Type{<:MOI.AbstractVectorFunction},
    ::Type{MOI.SecondOrderCone},
) where {T}
    S = MOI.Utilities.promote_operation(/, T, MOI.Utilities.scalar_type(G), T)
    Y = MOI.Utilities.promote_operation(-, T, S, S)
    Z = MOI.Utilities.promote_operation(+, T, S, S)
    F = MOI.Utilities.promote_operation(vcat, T, Z, Y, G)
    return SOCtoRSOCBridge{T,F,G}
end

function MOI.Bridges.map_set(
    ::Type{<:SOCtoRSOCBridge},
    set::MOI.SecondOrderCone,
)
    if MOI.dimension(set) == 1
        error(
            "Unable to reformulate a `SecondOrderCone` into a " *
            "`RotatedSecondOrderCone` because the dimension of `1` is too " *
            "small",
        )
    end
    return MOI.RotatedSecondOrderCone(MOI.dimension(set))
end

function MOI.Bridges.inverse_map_set(
    ::Type{<:SOCtoRSOCBridge},
    set::MOI.RotatedSecondOrderCone,
)
    return MOI.SecondOrderCone(MOI.dimension(set))
end

function MOI.Bridges.map_function(::Type{<:SOCtoRSOCBridge{T}}, func) where {T}
    scalars = MOI.Utilities.eachscalar(func)
    t, u, x = scalars[1], scalars[2], scalars[3:end]
    ts = MOI.Utilities.operate!(/, T, t, sqrt(T(2)))
    us = MOI.Utilities.operate!(/, T, u, sqrt(T(2)))
    return MOI.Utilities.operate(vcat, T, ts + us, ts - us, x)
end

# The map is an involution
function MOI.Bridges.inverse_map_function(BT::Type{<:SOCtoRSOCBridge}, func)
    return MOI.Bridges.map_function(BT, func)
end

# The map is symmetric
function MOI.Bridges.adjoint_map_function(BT::Type{<:SOCtoRSOCBridge}, func)
    return MOI.Bridges.map_function(BT, func)
end

# The map is a symmetric involution
function MOI.Bridges.inverse_adjoint_map_function(
    BT::Type{<:SOCtoRSOCBridge},
    func,
)
    return MOI.Bridges.map_function(BT, func)
end


text:
module Diffusion

import MPI
using ImplicitGlobalGrid
using CairoMakie

@views interior(A) = A[2:end-1,2:end-1]

@views north(A) = A[1:end-2,2:end-1]
@views south(A) = A[3:end,  2:end-1]
@views east(A)  = A[2:end-1,1:end-2]
@views west(A)  = A[2:end-1,3:end]

function diffusion(T, timesteps, comm)
    nx, ny = size(T)
    me, dims = init_global_grid(nx, ny, 1; init_MPI=!MPI.Initialized(), comm=comm, reorder=0)  # Initialize the implicit global grid

    if me == 0
        nx_v = (nx-2)*dims[1]
        ny_v = (ny-2)*dims[2]
        T_v  = zeros(nx_v, ny_v)
    else
        T_v  = nothing
    end
    gather!(Array(interior(T)), T_v)

    if me == 0
        node = Node(T_v)
        fig = heatmap(node, colorrange = (0.0, 2.0))
        video = VideoStream(fig, framerate=3)
    end

    for t in 1:timesteps
        interior(T) .-= interior(T) .- ((north(T) .+ south(T) .+ east(T) .+ west(T)) ./ 4.0)
        update_halo!(T)

        if t % 2 == 0
            gather!(Array(interior(T)), T_v)
            if me == 0
                node[] = T_v
                recordframe!(video)
            end
        end
    end
    if me == 0
        save("diffusion.mp4", video)
    end
end

Base.@ccallable function julia_diffusion(T_ptr::Ptr{Float64}, timesteps::Cint, nx::Cint, ny::Cint, comm_c::MPI.MPI_Comm)::Cint
    try
        comm = MPI.Comm_dup(MPI.Comm(comm_c))
        T    = unsafe_wrap(Array, T_ptr, (Int64(nx), Int64(ny)), own=false)
        diffusion(T, timesteps, comm)
    catch
        Base.invokelatest(Base.display_error, Base.catch_stack())
        return 1
    end
    return 0
end

end # module

max_stars_repo_name: JuliaLabs/CallingJuliaFromCWithMPI

max_issues_repo_name: JuliaLabs/CallingJuliaFromCWithMPI

max_forks_repo_name: JuliaLabs/CallingJuliaFromCWithMPI


text:
push!(LOAD_PATH, ".")
push!(LOAD_PATH, "../Genetic Algorithm")

using GeneticAlgorithm
using RealIndividual
using FitFuns
using Fitness
using Plots

function evalLine(line::String)
  evaluated_line = map(x -> eval(Meta.parse(x)), split(line))
  unpacked_line = Tuple(foldl((x, y) -> y isa Tuple ? push!(x, y...) : push!(x, y), evaluated_line; init=[]))
  return Tuple(unpacked_line)
end

function readArgs(filename::String)
  open(filename, "r") do file
    opt_algo, it, log = evalLine(readline(file))
    ind_args = evalLine(readline(file))
    fit_fun, pop_size, elite_size = evalLine(readline(file))
    init_args = evalLine(readline(file))
    sel_args = evalLine(readline(file))
    cross_args = evalLine(readline(file))
    mut_args = evalLine(readline(file))
    return opt_algo, it, log, ind_args, fit_fun, pop_size, elite_size, init_args, sel_args, cross_args, mut_args
  end
end

function main(args)
  opt_alg, it, log, ind_args, fit_fun, pop_size, elite_size, init_args, sel_args, cross_args, mut_args = readArgs("FitFuns/$(args[1])")
  ga = GeneticAlgorithm.GeneticAlgorithmType(ind_args, fit_fun, pop_size, elite_size;
                                            init_args = init_args,
                                            sel_args = sel_args,
                                            cross_args = cross_args,
                                            mut_args = mut_args)
  gr()
  if opt_alg == "SINGLE"
    best_fit, mean_fit = GeneticAlgorithm.evolveSO!(ga, it, log)
    plot(1:it, [best_fit, mean_fit], xlims=(1, it), label=["Best" "Mean"], xlabel="Generation", ylabel="Fitness", legend=:bottomright)
  elseif opt_alg == "MULTI"
    best_solutions = GeneticAlgorithm.evolveMO!(ga, it, log)
    scatter([x .* Fitness.getDirection(fit_fun) for x in getindex.(best_solutions, 2)], label=["Frontier"], markersize=1)
  end
  savefig("FitFuns/$(args[1])_fitness.png")
end

main(ARGS)

max_stars_repo_name: Markhyz/Portfolio-Optimization

max_issues_repo_name: Markhyz/Portfolio-Optimization

max_forks_repo_name: Markhyz/Portfolio-Optimization


text:
# linreg.jl
#
# File with methods related to linear regression.
#
# Author: John Duchi (jduchi@stanford.edu)

# (A, b, x) = GenerateLinearRegressionData(m, n; condition_number, noise)
#
# Generates data for a linear regression problem
function GenerateLinearRegressionData(mm::Int64, nn::Int64;
                                      condition_number::Float64 = 1.0,
                                      noise::Float64 = 0.0)
  A = randn(mm, nn);
  x = randn(nn);
  if (condition_number > 1)
    D = LinRange(1, condition_number, nn);
    A = A * Diagonal(D);
  end
  b = A * x + noise * randn(mm);
  return (A, b, x);
end

# o = LinearRegressionObj(A::Matrix{Float64}, b::Vector{Float64},
#                         x::Vector{Float64})
#
# Computes and returns linear regression objective (mean squared error).
function LinearRegressionObj(A::Matrix{Float64}, b::Vector{Float64},
                             x::Vector{Float64})
  margins = A * x - b;
  return mean(margins.^2) / 2;
end

# x = ProximalUpdateLinreg(a::Vector{Float64}, b::Float64,
#                              x_init::Vector, stepsize::Float64)
#
# Sets x to minimize
#
#  .5 * (a' * x - b)^2 + norm(x - x_init)^2 / (2 * stepsize)
#
# Returns the minimizing x.
function ProximalUpdateLinreg(a::Vector{Float64}, b::Float64,
                              x_init::Vector, stepsize::Float64)
  # Replace this code to return the correct update.
  return x_init;
end

# x = SGUpdateLinreg(a::Vector{Float64}, b::Float64,
#                    x_init::Vector, stepsize::Float64)
#
# Sets x to minimize the linear approximation to the standard squared
# loss for linear regression, or, if g is the gradient of the loss
#
#   F(x; (a, b)) = .5 * (a' * x - b)^2
#
# at the point x_init, updates
#
#   x = x_init - stepsize * g;
function SGUpdateLinreg(a::Vector{Float64}, b::Float64,
                        x_init::Vector, stepsize::Float64)
  # Replace this code to return the correct update.
  return x_init;
end

# x = TruncatedUpdateLinreg(a::Vector{Float64}, b::Float64,
#                              x_init::Vector, stepsize::Float64)
#
# Let F(x; (a, b)) = .5 * (a' * x - b)^2. Sets x to minimize the
# positive approximation to F at x_init, that is, for
#
#  F_lin(x) = (F(x_init) + F'(x_init) * (x - x_init))_+
#
# sets x to minimize
#
#  F_lin + norm(x - x_init)^2 / (2 * stepsize).
#
# Returns the minimizing x.
function TruncatedUpdateLinreg(a::Vector{Float64}, b::Float64,
                               x_init::Vector, stepsize::Float64)
  # Replace this code to return the correct update.
  return x_init;
end

max_stars_repo_path: Machine Learning Summer School 2019 (London, UK)/tutorials/optimization/linreg.jl


text:
# ---
# title: 1172. Dinner Plate Stacks
# id: problem1172
# author: Tian Jun
# date: 2020-10-31
# difficulty: Hard
# categories: Design
# link: <https://leetcode.com/problems/dinner-plate-stacks/description/>
# hidden: true
# ---
#
# You have an infinite number of stacks arranged in a row and numbered (left to
# right) from 0, each of the stacks has the same maximum `capacity`.
#
# Implement the `DinnerPlates` class:
#
#   * `DinnerPlates(int capacity)` Initializes the object with the maximum `capacity` of the stacks.
#   * `void push(int val)` Pushes the given positive integer `val` into the leftmost stack with size less than `capacity`.
#   * `int pop()` Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns `-1` if all stacks are empty.
#   * `int popAtStack(int index)` Returns the value at the top of the stack with the given `index` and removes it from that stack, and returns -1 if the stack with that given `index` is empty.
#
# **Example:**
#
#
#
#     Input:
#     ["DinnerPlates","push","push","push","push","push","popAtStack","push","push","popAtStack","popAtStack","pop","pop","pop","pop","pop"]
#     [[2],[1],[2],[3],[4],[5],[0],[20],[21],[0],[2],[],[],[],[],[]]
#     Output:
#     [null,null,null,null,null,null,2,null,null,20,21,5,4,3,1,-1]
#
#     Explanation:
#     DinnerPlates D = DinnerPlates(2);  // Initialize with capacity = 2
#     D.push(1);
#     D.push(2);
#     D.push(3);
#     D.push(4);
#     D.push(5);         // The stacks are now:  2  4
#                                                1  3  5
#                                                ﹈ ﹈ ﹈
#     D.popAtStack(0);   // Returns 2.  The stacks are now:     4
#                                                            1  3  5
#                                                            ﹈ ﹈ ﹈
#     D.push(20);        // The stacks are now: 20  4
#                                                1  3  5
#                                                ﹈ ﹈ ﹈
#     D.push(21);        // The stacks are now: 20  4 21
#                                                1  3  5
#                                                ﹈ ﹈ ﹈
#     D.popAtStack(0);   // Returns 20.  The stacks are now:     4 21
#                                                             1  3  5
#                                                             ﹈ ﹈ ﹈
#     D.popAtStack(2);   // Returns 21.  The stacks are now:     4
#                                                             1  3  5
#                                                             ﹈ ﹈ ﹈
#     D.pop()            // Returns 5.  The stacks are now:      4
#                                                             1  3
#                                                             ﹈ ﹈
#     D.pop()            // Returns 4.  The stacks are now:   1  3
#                                                             ﹈ ﹈
#     D.pop()            // Returns 3.  The stacks are now:   1
#                                                             ﹈
#     D.pop()            // Returns 1.  There are no stacks.
#     D.pop()            // Returns -1.  There are still no stacks.
#
#
#
#
# **Constraints:**
#
#   * `1 <= capacity <= 20000`
#   * `1 <= val <= 20000`
#   * `0 <= index <= 100000`
#   * At most `200000` calls will be made to `push`, `pop`, and `popAtStack`.
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end