text:
g(x) = begin
        begin
            while false
            end
            local var"#48#stats" = Base.gc_num()
            local var"#51#compile_elapsedtime" = Base.cumulative_compile_time_ns_before()
            local var"#50#elapsedtime" = Base.time_ns()
            local var"#49#val" = begin
                        sleep(1)
                        sin(x)
                    end
            var"#50#elapsedtime" = Base.time_ns() - var"#50#elapsedtime"
            var"#51#compile_elapsedtime" = Base.cumulative_compile_time_ns_after() - var"#51#compile_elapsedtime"
            local var"#52#diff" = Base.GC_Diff(Base.gc_num(), var"#48#stats")
            Base.time_print(var"#50#elapsedtime", (var"#52#diff").allocd, (var"#52#diff").total_time, Base.gc_alloc_count(var"#52#diff"), var"#51#compile_elapsedtime", true)
            var"#49#val"
        end
    end

max_stars_repo_name: genkuroki/public

max_issues_repo_name: genkuroki/public

max_forks_repo_name: genkuroki/public


text:
importall Bukdu

type PageController <: ApplicationController
end

show(::PageController) = render(View; path="renderers/page.tpl", contents="hello")

Router() do
    get("/:page", PageController, show)
end

using Base.Test
conn = (Router)(get, "/1")
@test 200 == conn.status
@test "
hello
" == conn.resp_body
@test "1" == conn.params["page"]
@test "1" == conn.params[:page]

layout(::Layout, body) = """$body"""
index(c::PageController) = render(View/Layout; path="renderers/page.tpl", contents="hello")

Router() do
    get("/", PageController, index)
end

conn = (Router)(get, "/")
@test 200 == conn.status
@test "
hello
" == conn.resp_body
@test !haskey(conn.params, "page")

logs = []
before(render, View) do
    push!(logs, "before")
end

after(render, View) do
    push!(logs, "after")
end
conn = (Router)(get, "/")
@test ["before", "after"] == logs
empty!(logs)

layout(::Layout, body, c::PageController, kwd) = """layout2 - $body, $c, $(kwd[:path])"""
index2(c::PageController) = render(View, c; path="renderers/page.tpl", contents="hello")
index_with_layout2(c::PageController) = render(View/Layout, c; path="renderers/page.tpl", contents="hello")

Router() do
    get("/index2", PageController, index2)
    get("/index_with_layout2", PageController, index_with_layout2)
end

conn = (Router)(get, "/index2")
@test "
hello
" == conn.resp_body
@test [] == logs
empty!(logs)

before(render, View) do c
    push!(logs, "before $c")
end

after(render, View) do c
    push!(logs, "after $c")
end

conn = (Router)(get, "/index2")
@test "
hello
" == conn.resp_body
@test ["before PageController()","after PageController()"] == logs
empty!(logs)

conn = (Router)(get, "/index_with_layout2")
@test "layout2 -
hello
, PageController(), renderers/page.tpl" == conn.resp_body
@test ["before PageController()","after PageController()"] == logs
empty!(logs)

before(render, View/Layout) do c
    push!(logs, "bl")
end

after(render, View/Layout) do c
    push!(logs, "al")
end

conn = (Router)(get, "/index_with_layout2")
@test "layout2 -
hello
, PageController(), renderers/page.tpl" == conn.resp_body
@test ["bl", "before PageController()","after PageController()", "al"] == logs
empty!(logs)

ext: jl


text:
struct Model{T <: AbstractParam, S <: AbstractFixedParam}
    param::T
    fparam::S
    generate_data::Function
end

function make_models()
    R"source('UM459.R')"
    R"x <- get(load('PSA_MLE.res'))"

    R"x_common <- get_all_models(x, FALSE)"
    R"x_mix <- get_all_models(x, TRUE)"

    @rget x_common
    @rget x_mix

    x_common, x_mix
end

function G1Model(n=200)
    param = Param(n, [-0.15 -0.15 -0.15 -0.15], ## xi
                           [0.75 1.0 0.6 0.15 0.0 0.05], ## beta
                           [-0.01 0.1 -0.01], ## mu
                           [0.6 1.3 0.45], ## S
                           zeros(Float64, 2, 3, 3), ##
                           0.28, ## sigma
                           [1.13], [0.065], [0.9 0.33 1.1])

    C = [1.0 0.41 0.19;
         0.41 1.0 0.49;
         0.19 0.49 1.0]

    param.L[1,:,:] = cholesky!(C).L

    Model(param,
          FixedParam(n, 2, 3, 3, 6, 3, 15.0, reshape(repeat(vcat([0.0, 0.2], 0.5:0.5:14.0), inner=n), n, 30), -1.5, 0.0),
          generate_data)
end

function G2Model_common(n=200)
    param = Param(n, transform_zero_sum(vcat([5.86 -1.11 -0.80 -1.45; 0.0 0.0 0.0 0.0])),
                  [0.71 0.19 0.07 1.05 0.32 0.45 0.08 0.19 0.09;
                   0.71 0.19 0.07 1.05 0.32 0.45 0.08 0.19 0.09], ## beta
                  [0.0 0.1 0.0;
                   0.05 0.13 0.14], ## mu
                  [0.52 1.08 0.30; 2.27 4.72 1.30], ## S
                  zeros(Float64, 2, 3, 3), ##
                  0.28, ## sigma
                  ##[0.9, 1.2], ##[log(2)/8, log(2)/5],
                  [1.2, 0.8], ## shape
                  [0.01, 0.03], ## scale
                  [-0.05 1.10 0.71;
                   -0.05 1.10 0.71])

    C1 = [1.0 0.42 0.15;
          0.42 1.0 0.63;
          0.15 0.63 1.0]

    param.L[1,:,:] = cholesky(C1).L
    param.L[2,:,:] = cholesky(C1).L

    Model(param,
          FixedParam(n, 2, 3, 3, 9, 3, 14.0, reshape(repeat(vcat([0.0, 0.2], 0.5:0.5:14.0), inner=n), n, 30), -1.5, 0.0),
          generate_data)
end

function G3Model_common(n=200)
    param = Param(n,  [-1.71569    0.396632   0.72337    0.417877;
                       0.943128  -0.229865  -0.555035  -0.249195;
                       0.772563  -0.166767  -0.168335  -0.168682], ## xi
                   [0.680831  0.0179264  0.0295299  0.527697  0.216786  0.198365  0.055459  0.0259366  0.0463118;
                    0.680831  0.0179264  0.0295299  0.527697  0.216786  0.198365  0.055459  0.0259366  0.0463118;
                    0.680831  0.0179264  0.0295299  0.527697  0.216786  0.198365  0.055459  0.0259366  0.0463118], ## beta
                   [0.783827   3.39527   1.3682;
                    0.0834099  1.13367  -0.00579376;
                    -0.0223524  1.36281   0.138263], ## mu
                   [0.41662   2.20853   1.44009;
                    0.489405  0.856195  0.142059;
                    0.677583  1.12779   0.255282], ## S
                  zeros(Float64, 3, 3, 3), ##
                  0.2758719120316683, ## sigma
                  [1.2722676092491088, 0.5853348931121277, 1.8478952942493387], ## shape
                  [0.1324342419290664, 0.0026427656627794963, 0.003291411020296823], ## scale
                  [-0.0437378  1.12338  1.06778;
                   -0.0437378  1.12338  1.06778;
                   -0.0437378  1.12338  1.06778]) ## delta

      L1 = [1.0 0.0 0.0;
            -0.283485   0.958977 0.0;
            -0.0586009  0.688782  0.722597]

     L2 = [1.0 0.0 0.0;
           0.349312  0.937007 0.0;
           -0.026874  0.690872  0.722478]

    L3 = [1.0 0.0 0.0;
          0.516247  0.85644 0.0;
          0.078312  0.666531  0.741353]

    param.L[1,:,:] = L1
    param.L[2,:,:] = L2
    param.L[3,:,:] = L3

    Model(param,
          FixedParam(n, 3, 3, 3, 9, 3, 14.74, reshape(repeat(vcat([0.0, 0.2], 0.5:0.5:14.0), inner=n), n, 30), -1.5, 0.0),
          generate_data)
end

function G4Model_common(n=200)
    param = Param(n, [1.05065   -0.272717   -0.597822   -0.30393;
                      0.588372  -0.0421882  -0.0987289  -0.280867;
                      0.342734  -0.141391    0.0141266  -0.0628513;
                      -1.98176    0.456296    0.682425   0.647649], ## xi
                   [0.698363  0.0346776  0.0366413  0.555682  0.327393  0.189299  0.0648854  0.117044  0.0360385;
                    0.698363  0.0346776  0.0366413  0.555682  0.327393  0.189299  0.0648854  0.117044  0.0360385;
                    0.698363  0.0346776  0.0366413  0.555682  0.327393  0.189299  0.0648854  0.117044  0.0360385;
                    0.698363  0.0346776  0.0366413  0.555682  0.327393  0.189299  0.0648854  0.117044  0.0360385], ## beta
                   [0.0847991  1.03647  -0.0311116;
                  -0.162945   1.09494  -0.00677467;
                    0.165787   1.54475   0.202036;
                    0.732935   3.51918   1.54742], ## mu
                  [0.400097  0.775207  0.0983229;
                   0.784702  1.27895   0.286956;
                   0.472082  0.749551  0.155471;
                   0.427116  2.3425    1.4966], ## S
                  zeros(Float64, 4, 3, 3), ##
                  0.2764, ## sigma
                  [0.5481491252817777, 0.5479779849110288, 1.914072045693419, 1.4028548110541126], ## shape
                  [0.0046433585808854615, 0.003836702125103769, 0.008567616582312225, 0.17172971717241955], ## scale
                  [-0.0335354  1.41136  0.766381;
                  -0.0335354  1.41136  0.766381;
                  -0.0335354  1.41136  0.766381;
                   -0.0335354  1.41136  0.766381]) ## delta

    L1 = [1.0 0.0 0.0;
          0.28681  0.957988 0.0;
          -0.16006  0.754256  0.636772]

    L2 = [1.0 0.0 0.0;
          0.551333   0.834285 0.0;
          0.0561526  0.728513  0.682727]

    L3 = [1.0 0.0 0.0;
          0.25514    0.966904 0.0;
          -0.0490336  0.356662  0.932946]

    L4 = [1.0 0.0 0.0;
          -0.29198    0.956424 0.0;
          -0.0816144  0.662468  0.744631]

    param.L[1,:,:] = L1
    param.L[2,:,:] = L2
    param.L[3,:,:] = L3
    param.L[4,:,:] = L4

    Model(param,
          FixedParam(n, 3, 3, 3, 9, 3, 14.74, reshape(repeat(vcat([0.0, 0.2], 0.5:0.5:14.0), inner=n), n, 30), -1.5, 0.0),
          generate_data)
end

function G5Model_common(n=200)
    param = Param(n, transform_zero_sum(vcat([3.85913  -0.252416  -0.21723   -1.01946;
                                              3.26331  -0.686945  -0.190965  -1.8576;
                                              2.74887  -0.664152  -0.982845  -0.358021;
                                              -1.13517   0.853032   0.905174  -0.167422;
                                              0.0 0.0 0.0 0.0])),
                  [0.779325  1.05135    0.341292  0.0664238  -0.00193719   0.0159451;
                   0.171515  0.544798   0.223382  0.0819862  -0.0240127   -0.0398766;
                   0.559038  0.841526   1.7512    0.0646566   0.126851    -0.0518065;
                   0.910531  1.24407    1.00238   0.356472   -0.113962     0.0115417;
                   1.06964   3.18616   -0.977044  1.74197    -2.40273      2.02623], ## beta
                   [0.032456   0.0472063  -0.0119529;
                    -0.207048   0.201388    0.0234077;
                    -0.0634234  0.113967    0.00832463;
                    0.0245966  0.169543    0.0534571;
                    0.0694684  0.470818    0.24703], ## mu
                  [0.35 0.95 0.22; 0.41 1.11 0.26; 0.043 0.12 0.03; 0.58 1.56 0.37; 1.47 3.96 0.93], ## S
                  zeros(Float64, 2, 3, 3), ##
                  0.27657, ## sigma
                  [1.68, 0.8, 1.77, 1.57, 2.2], [0.15 0.05 0.36 0.66], [0.53 -1.32 0.63; 0.53 -1.32 0.63; 0.53 -1.32 0.63; 0.53 -1.32 0.63; 0.53 -1.32 0.63])

         L1 = [1.0        0.0       0.0;
           -0.283485   0.918914  0.0;
           -0.0586009  0.670328  0.679233]

    L2 = [1.0       0.0       0.0;
          0.349312  0.904321  0.0;
          -0.026874  0.657138  0.669897]

    L3 = [1.0       0.0       0.0;
          0.516247  0.828326  0.0;
          0.078312  0.63311   0.702438]

    param.L[1,:,:] = L1
    param.L[2,:,:] = L2
    param.L[3,:,:] = L3
    param.L[4,:,:] = L4

    Model(param,
          FixedParam(n, 2, 3, 3, 6, 3, 15.0, reshape(repeat(vcat([0.0, 0.2], 0.5:0.5:14.0), inner=n), n, 30), -1.5, 0.0),
          generate_data)
end

function G2Model_mix(n=200)
    param = Param(n, transform_zero_sum(vcat([5.82012 -1.30911 -0.308415 -1.09223; 0.0 0.0 0.0 0.0])),
                           [0.71 1.0 0.53 0.1 0.05 -0.02;
                            0.90 1.27 1.42 0.41 0.39 0.14], ## beta
                           [0.0 0.1 0.0;
                            0.05 0.13 0.14], ## mu
                           [0.5 1.0 0.25; 1.5 3.0 0.75], ## S
                           zeros(Float64, 2, 3, 3), ##
                           0.25, ## sigma
                           [1.59, 1.65], [0.19, 0.52], [0.2 -0.15 0.15; 0.2 -0.15 0.15])

    C1 = [1.0 0.43 0.05;
          0.43 1.0 0.60;
          0.05 0.60 1.0]

    param.L[1,:,:] = cholesky(C1).L
    param.L[2,:,:] = cholesky(C1).L

    Model(param,
          FixedParam(n, 2, 3, 3, 6, 3, 15.0, reshape(repeat(vcat([0.0, 0.2], 0.5:0.5:14.0), inner=n), n, 30), -1.5, 0.0),
          generate_data)
end

function G3Model_mix(n=200)
    param = Param(n, transform_zero_sum(vcat([5.58913 -1.24644 -0.346802 -1.04714;
                                              5.01629 -1.89479 0.0111542 -2.12278;
                                              0.0 0.0 0.0 0.0])),
                  [0.772001 1.0691 0.473564 0.0844346 0.0449494 -0.0126505;
                   0.151949 0.273523 0.796271 0.0422973 0.0385719 -0.0586332;
                   0.919505 1.29305 1.46563 0.419051 0.385805 0.129744], ## beta
                  [0.0193879 0.0757485 -0.00638583;
                   -0.210521 0.180814 0.0197556;
                   0.0425674 0.120704 0.143396], ## mu
                  [0.38 0.97 0.26; 0.35 0.89 0.24; 1.12 2.85 0.77], ## S
                  zeros(Float64, 3, 3, 3), ##
                  0.279346, ## sigma
                  [1.6, 1.26, 1.65], [0.2, 0.05, 0.53], [0.184 -0.165 0.127; 0.184 -0.165 0.127; 0.184 -0.165 0.127])

    C1 = [1.0 0.202 -0.059;
          0.202 1.0 0.603;
          -0.059 0.603 1.0]

    param.L[1,:,:] = cholesky(C1).L
    param.L[2,:,:] = cholesky(C1).L
    param.L[3,:,:] = cholesky(C1).L

    Model(param,
          FixedParam(n, 3, 3, 3, 6, 3, 15.0, reshape(repeat(vcat([0.0, 0.2], 0.5:0.5:14.0), inner=n), n, 30), -1.5, 0.0),
          generate_data)
end

function G4Model_mix(n=200)
    param = Param(n, transform_zero_sum(vcat([4.17036 -0.314482 -0.36471 -0.947192;
                                              3.12245 -0.669232 -0.122069 -1.90321;
                                              -1.08051 0.83242 0.907163 -0.150338;
                                              0.0 0.0 0.0 0.0])),
                  [0.75541   1.03187    0.438526  0.0679392   0.00342521   0.0026285;
                   0.158113  0.447918   0.643502  0.3680193   0.520754  -0.0517327;
                   0.910455  1.24207    0.9907    0.54634   -1.25036     0.199782;
                   1.06352   3.14072   -0.872009  1.72911    -2.36841      2.00441], ## beta
                  [0.0174885  0.0740613  -0.0061236;
                   -0.248795   0.161989    0.0174643;
                   0.0432951  0.22873    0.1466806;
                   -0.0283931  0.38582     0.258297], ## mu
                  [0.36 0.94 0.21; 0.41 1.07 0.24; 0.59 1.54 0.35; 1.5 3.92 0.90], ## S
                  zeros(Float64, 4, 3, 3), ##
                  0.27656, ## sigma
                  [sqrt(1.68), sqrt(1.06), sqrt(1.57), sqrt(2.20)],
                  [0.15, 0.05, 0.19, 0.36], [0.55 -1.34 0.64;
                                             0.55 -1.34 0.64;
                                             0.55 -1.34 0.64;
                                             0.55 -1.34 0.64])

    C1 = [ 1.0        0.260983  -0.0176565;
           0.260983   1.0        0.645612;
           -0.0176565  0.645612   1.0]

    param.L[1,:,:] = cholesky(C1).L
    param.L[2,:,:] = cholesky(C1).L
    param.L[3,:,:] = cholesky(C1).L
    param.L[4,:,:] = cholesky(C1).L

    Model(param,
          FixedParam(n, 2, 3, 3, 6, 3, 15.0, reshape(repeat(vcat([0.0, 0.2], 0.5:0.5:14.0), inner=n), n, 30), -1.5, 0.0),
          generate_data)
end

function G5Model_mix(n=200)
    param = Param(n, transform_zero_sum(vcat([3.85913  -0.252416  -0.21723   -1.01946;
                                              3.26331  -0.686945  -0.190965  -1.8576;
                                              2.74887  -0.664152  -0.982845  -0.358021;
                                              -1.13517   0.853032   0.905174  -0.167422;
                                              0.0 0.0 0.0 0.0])),
                  [0.779325  1.05135    0.341292  0.0664238  -0.00193719   0.0159451;
                   0.171515  0.544798   0.223382  0.0819862  -0.0240127   -0.0398766;
                   0.559038  0.841526   1.7512    0.0646566   0.126851    -0.0518065;
                   0.910531  1.24407    1.00238   0.356472   -0.113962     0.0115417;
                   1.06964   3.18616   -0.977044  1.74197    -2.40273      2.02623], ## beta
                   [0.032456   0.0472063  -0.0119529;
                    -0.207048   0.201388    0.0234077;
                    -0.0634234  0.113967    0.00832463;
                    0.0245966  0.169543    0.0534571;
                    0.0694684  0.470818    0.24703], ## mu
                  [0.35 0.95 0.22; 0.41 1.11 0.26; 0.043 0.12 0.03; 0.58 1.56 0.37; 1.47 3.96 0.93], ## S
                  zeros(Float64, 2, 3, 3), ##
                  0.27657, ## sigma
                  [1.68, 0.8, 1.77, 1.57, 2.2], [0.15 0.05 0.36 0.66], [0.53 -1.32 0.63; 0.53 -1.32 0.63; 0.53 -1.32 0.63; 0.53 -1.32 0.63; 0.53 -1.32 0.63])

    C1 = [1.0       0.289117  0.010405;
          0.289117  1.0       0.650236;
          0.010405  0.650236  1.0]

    param.L[1,:,:] = cholesky(C1).L
    param.L[2,:,:] = cholesky(C1).L
    param.L[3,:,:] = cholesky(C1).L
    param.L[4,:,:] = cholesky(C1).L
    param.L[5,:,:] = cholesky(C1).L

    Model(param,
          FixedParam(n, 2, 3, 3, 6, 3, 15.0, reshape(repeat(vcat([0.0, 0.2], 0.5:0.5:14.0), inner=n), n, 30), -1.5, 0.0),
          generate_data)
end

function G2Model_spline(n=200)
    param = ParamSpline(n, [-0.15 -0.15 -0.15 -0.15; 0.15 0.15 0.15 0.15], ## xi
                        [2 2 2 0.2 0.3 0.4;
                         1 1 1 0.1 0.1 0.1], ## beta
                        [0 0.0 0.0;
                         0 1.5 0.95], ## mu
                        sqrt.([0.5 1.3 0.3; 0.1 0.1 0.5]), ## S
                        zeros(Float64, 2, 3, 3), ##
                        0.25, ## sigma
                        log.([1.0 1.2 1.1; 0.8 0.6 0.9]))

    param.L[1,:,:] = [1.0 0.0 0.0;
                      0.5 0.866025 0.0;
                      -0.75 0.583124 0.312197]

    param.L[2,:,:] = [1.0 0.0 0.0;
                      0.5 0.866025 0.0;
                      0.75 -0.282902 0.597885]

    param.spline[1] = SplineHazard.Spline.const_spline(log(2)/8, (0.0, 24.0))
    param.spline[2] = SplineHazard.Spline.const_spline(log(2)/5, (0.0, 24.0))

    Model(param,
          FixedParam(n, 2, 3, 3, 6, 3, 10.0, reshape(repeat([0.0, 0.5, 1.0, 1.5, 2.0:1.0:10.0...], inner=n), n, 13), -1.5, 0.0),
          generate_data)
end

function rj_mix_test(M::Int; chains=1, warmup=Int(floor(M/2)))

    model2 = JLCMWeibull.G2Model_common(200)
    model3 = JLCMWeibull.G3Model_common(200)
    model4 = JLCMWeibull.G4Model_common(400)

    data2 = model2.generate_data(model2.param, model2.fparam)
    data3 = model3.generate_data(model3.param, model3.fparam)
    data4 = model4.generate_data(model4.param, model4.fparam)

    data = JLCMWeibull.merge_data(data2, data3)

    prior = JLCMWeibull.Prior(3, 3, 6, 3)

    x = JLCMWeibull.fit(M, data, model4.param, prior; warmup=warmup, G=3, chains=chains)
    x, data ##, JLCMWeibull.summary(x, data)
end


text:
###############################################################################
#
# Calculate photosynthesis from CO₂ partial pressure
#
###############################################################################
"""
    leaf_photosynthesis!(
                photo_set::AbstractPhotoModelParaSet{FT},
                leaf::Leaf{FT},
                envir::AirLayer{FT},
                mode::PCO₂Mode
    ) where {FT<:AbstractFloat}
    leaf_photosynthesis!(
                photo_set::AbstractPhotoModelParaSet{FT},
                leaf::Leaf{FT},
                envir::AirLayer{FT},
                mode::PCO₂Mode,
                p_i::FT
    ) where {FT<:AbstractFloat}
    leaf_photosynthesis!(
                photo_set::C3ParaSet{FT},
                leaf::Leaf{FT},
                envir::AirLayer{FT},
                mode::GCO₂Mode
    ) where {FT<:AbstractFloat}
    leaf_photosynthesis!(
                photo_set::C4ParaSet{FT},
                leaf::Leaf{FT},
                envir::AirLayer{FT},
                mode::GCO₂Mode
    ) where {FT<:AbstractFloat}
    leaf_photosynthesis!(
                photo_set::AbstractPhotoModelParaSet{FT},
                leaf::Leaf{FT},
                envir::AirLayer{FT},
                mode::GCO₂Mode,
                g_lc::FT
    ) where {FT<:AbstractFloat}

Compute leaf photosynthetic rates, given
- `photo_set` [`AbstractPhotoModelParaSet`](@ref) type parameter set
- `leaf` [`Leaf`](@ref) type struct
- `p_i` Given leaf internal CO₂
- `envir` [`AirLayer`](@ref) type struct
- `g_lc` Given leaf diffusive conductance to CO₂

The C3 photosynthesis model is from Farquhar et al. (1980) "A biochemical model
    of photosynthetic CO₂ assimilation in leaves of C3 species."

The C4 photosynthesis model is adapted from Collatz et al. (1992) "Coupled
    photosynthesis-stomatal conductance model for leaves of C4 plants."
"""
function leaf_photosynthesis!(
            photo_set::AbstractPhotoModelParaSet{FT},
            leaf::Leaf{FT},
            envir::AirLayer{FT},
            mode::PCO₂Mode
) where {FT<:AbstractFloat}
    leaf_temperature_dependence!(photo_set, leaf, envir);
    leaf_ETR!(photo_set, leaf);
    light_limited_rate!(photo_set, leaf);
    rubisco_limited_rate!(photo_set, leaf);
    product_limited_rate!(photo_set, leaf);
    leaf.Ag = min(leaf.Ac, leaf.Aj, leaf.Ap);
    leaf.An = leaf.Ag - leaf.Rd;

    return nothing
end

function leaf_photosynthesis!(
            photo_set::AbstractPhotoModelParaSet{FT},
            leaf::Leaf{FT},
            envir::AirLayer{FT},
            mode::PCO₂Mode,
            p_i::FT
) where {FT<:AbstractFloat}
    leaf.p_i = p_i;
    leaf_photosynthesis!(photo_set, leaf, envir, mode);

    return nothing
end

function leaf_photosynthesis!(
            photo_set::C3ParaSet{FT},
            leaf::Leaf{FT},
            envir::AirLayer{FT},
            mode::GCO₂Mode
) where {FT<:AbstractFloat}
    leaf_temperature_dependence!(photo_set, leaf, envir);
    leaf_ETR!(photo_set, leaf);
    light_limited_rate!(photo_set, leaf, envir);
    rubisco_limited_rate!(photo_set, leaf, envir);
    product_limited_rate!(photo_set, leaf);
    leaf.Ag  = min(leaf.Ac, leaf.Aj, leaf.Ap);
    leaf.An  = leaf.Ag - leaf.Rd;
    leaf.p_i = envir.p_a - leaf.An / leaf.g_lc * envir.p_atm * FT(1e-6);
    leaf.p_s = envir.p_a - leaf.An / leaf.g_bc * envir.p_atm * FT(1e-6);

    return nothing
end

function leaf_photosynthesis!(
            photo_set::C4ParaSet{FT},
            leaf::Leaf{FT},
            envir::AirLayer{FT},
            mode::GCO₂Mode
) where {FT<:AbstractFloat}
    leaf_temperature_dependence!(photo_set, leaf, envir);
    leaf_ETR!(photo_set, leaf);
    light_limited_rate!(photo_set, leaf);
    rubisco_limited_rate!(photo_set, leaf);
    product_limited_rate!(photo_set, leaf, envir);
    leaf.Ag  = min(leaf.Ac, leaf.Aj, leaf.Ap);
    leaf.An  = leaf.Ag - leaf.Rd;
    leaf.p_i = envir.p_a - leaf.An / leaf.g_lc * envir.p_atm * FT(1e-6);
    leaf.p_s = envir.p_a - leaf.An / leaf.g_bc * envir.p_atm * FT(1e-6);

    return nothing
end

function leaf_photosynthesis!(
            photo_set::AbstractPhotoModelParaSet{FT},
            leaf::Leaf{FT},
            envir::AirLayer{FT},
            mode::GCO₂Mode,
            g_lc::FT
) where {FT<:AbstractFloat}
    leaf.g_lc = g_lc;
    leaf_photosynthesis!(photo_set, leaf, envir, mode);

    return nothing
end

max_stars_repo_name: bbuman/Land

max_issues_repo_name: bbuman/Land

max_forks_repo_name: bbuman/Land


text:
###############################################################################
# Damper Force
###############################################################################

function damper_force(joint::Rotational{T}, qa::Quaternion, ϕa::AbstractVector,
        qb::Quaternion, ϕb::AbstractVector,
        timestep;
        unitary::Bool=false) where T
    A = nullspace_mask(joint)
    Aᵀ = zerodimstaticadjoint(A)
    axis_offset = joint.axis_offset
    force = 2 * Aᵀ * A * (vector_rotate(ϕb, inv(axis_offset) * inv(qa) * qb) - vector_rotate(ϕa, inv(axis_offset))) # in offset frame
    unitary && (force *= joint.damper) # Currently assumes same damper constant in all directions
    return force # in the offset frame
end

function damper_force(relative::Symbol, joint::Rotational{T}, qa::Quaternion, ϕa::AbstractVector,
        qb::Quaternion, ϕb::AbstractVector, timestep;
        rotate::Bool=true,
        unitary::Bool=false) where T

    damper = unitary ? 1.0 : joint.damper
    A = nullspace_mask(joint)
    Aᵀ = zerodimstaticadjoint(A)
    axis_offset = joint.axis_offset

    if relative == :parent
        velocity = A * (vector_rotate(ϕb, qa \ qb / axis_offset) - vector_rotate(ϕa, inv(axis_offset))) # in offset frame
        force = 2 * Aᵀ * A * damper * Aᵀ * velocity # currently assumes same damper constant in all directions
        rotate && (force = vector_rotate(force, axis_offset)) # rotate back to frame a
        return [szeros(T, 3); force]
    elseif relative == :child
        velocity = A * (vector_rotate(ϕb, qa \ qb / axis_offset) - vector_rotate(ϕa, inv(axis_offset))) # in offset frame
        force = - 2 * Aᵀ * A * damper * Aᵀ * velocity # currently assumes same damper constant in all directions
        rotate && (force = vector_rotate(force, inv(qb) * qa * axis_offset)) # rotate back to frame b
        return [szeros(T, 3); force]
    end
end

damper_impulses(relative::Symbol, joint::Rotational, pbody::Node, cbody::Node, timestep; unitary::Bool=false) =
    timestep * damper_force(relative, joint, current_configuration(pbody.state)[2], pbody.state.ϕsol[2],
    current_configuration(cbody.state)[2], cbody.state.ϕsol[2], timestep, unitary=unitary)

damper_impulses(relative::Symbol, joint::Rotational{T,3}, pbody::Node, cbody::Node, timestep; unitary::Bool=false) where T = szeros(T, 6)

###############################################################################
# Damper Jacobians
################################################################################

function damper_jacobian_configuration(relative::Symbol, jacobian::Symbol,
        joint::Rotational, pbody::Node, cbody::Node,
        timestep::T; attjac::Bool = true) where T

    A = nullspace_mask(joint)
    Aᵀ = zerodimstaticadjoint(A)
    xa, va, qa, ϕa = current_configuration_velocity(pbody.state)
    xb, vb, qb, ϕb = current_configuration_velocity(cbody.state)
    axis_offset = joint.axis_offset
    X = szeros(T, 3, 3)
    Z = attjac ? szeros(T, 3, 6) : szeros(T, 3, 7)

    force = damper_force(relative, joint, qa, ϕa, qb, ϕb, timestep; rotate = false)[SVector{3,Int}(4,5,6)]

    if relative == :parent
        if jacobian == :parent
            Q = ∂vector_rotate∂p(force, axis_offset) * 2 * joint.damper * Aᵀ * A * ∂vector_rotate∂q(ϕb, qa \ qb / axis_offset) * Rmat(qb * inv(axis_offset)) * Tmat()
            attjac && (Q *= LVᵀmat(qa))
        elseif jacobian == :child
            Q = ∂vector_rotate∂p(force, axis_offset) * 2 * joint.damper * Aᵀ * A * ∂vector_rotate∂q(ϕb, qa \ qb / axis_offset) * Rmat(inv(axis_offset)) * Lmat(inv(qa))
            attjac && (Q *= LVᵀmat(qb))
        end
    elseif relative == :child
        if jacobian == :parent
            Q = ∂vector_rotate∂p(force, inv(qb) * qa * axis_offset) * -2 * joint.damper * Aᵀ * A * ∂vector_rotate∂q(ϕb, qa \ qb / axis_offset) * Rmat(qb * inv(axis_offset)) * Tmat()
            Q += ∂vector_rotate∂q(force, inv(qb) * qa * axis_offset) * Rmat(axis_offset) * Lmat(inv(qb))
            attjac && (Q *= LVᵀmat(qa))
        elseif jacobian == :child
            Q = ∂vector_rotate∂p(force, inv(qb) * qa * axis_offset) * -2 * joint.damper * Aᵀ * A * ∂vector_rotate∂q(ϕb, qa \ qb / axis_offset) * Rmat(inv(axis_offset)) * Lmat(inv(qa))
            Q += ∂vector_rotate∂q(force, inv(qb) * qa * axis_offset) * Rmat(qa * axis_offset) * Tmat()
            attjac && (Q *= LVᵀmat(qb))
        end
    end
    return timestep * [Z; X Q]
end

function damper_jacobian_velocity(relative::Symbol, jacobian::Symbol,
    joint::Rotational, pbody::Node, cbody::Node,
    timestep::T) where T

    A = nullspace_mask(joint)
    Aᵀ = zerodimstaticadjoint(A)
    xa, va, qa, ϕa = current_configuration_velocity(pbody.state)
    xb, vb, qb, ϕb = current_configuration_velocity(cbody.state)
    axis_offset = joint.axis_offset
    V = szeros(T, 3, 3)

    force = damper_force(relative, joint, qa, ϕa, qb, ϕb, timestep; rotate = false)[SVector{3,Int}(4,5,6)]
    if relative == :parent
        if jacobian == :parent
            Ω = ∂vector_rotate∂p(force, axis_offset) * 2 * joint.damper * Aᵀ * A * -1.0 * ∂vector_rotate∂p(ϕa, inv(axis_offset))
        elseif jacobian == :child
            Ω = ∂vector_rotate∂p(force, axis_offset) * 2 * joint.damper * Aᵀ * A * ∂vector_rotate∂p(ϕb, qa \ qb / axis_offset)
        end
    elseif relative == :child
        if jacobian == :parent
            Ω = ∂vector_rotate∂p(force, inv(qb) * qa * axis_offset) * -2 * joint.damper * Aᵀ * A * -1.0 * ∂vector_rotate∂p(ϕa, inv(axis_offset))
        elseif jacobian == :child
            Ω = ∂vector_rotate∂p(force, inv(qb) * qa * axis_offset) * -2 * joint.damper * Aᵀ * A * ∂vector_rotate∂p(ϕb, qa \ qb / axis_offset)
        end
    end
    return timestep * [szeros(T, 3, 6); V Ω]
end

damper_jacobian_configuration(relative::Symbol, jacobian::Symbol, joint::Rotational{T,3}, pbody::Node, cbody::Node, timestep::T; attjac::Bool = true) where T = attjac ? szeros(T, 6, 6) : szeros(T, 6, 7)
damper_jacobian_velocity(relative::Symbol, jacobian::Symbol, joint::Rotational{T,3}, pbody::Node, cbody::Node, timestep::T) where T = szeros(T, 6, 6)


text:
#=
Created on 22/01/2021 10:45:30
Last update: 04/02/2021

@author: Michiel Stock
michielfmstock@gmail.com

The British wizarding world uses Galleons, Sickles, and Knuts as a currency. There are 17 Sickles in a Galleon, and 29 Knuts in a Sickle, meaning there are 493 Knuts to a Galleon. We will make a structure `WizCur` to represent wizarding currency. This structure has three integer-valued fields: `galleons`, `sickles`, and `knuts`. The constructor should always create tidy representations, meaning that, for example, if the number of knuts is 29 or more, it just adds an appropriate number of sickles such that the number knuts is less than 29 (it's magical money). The same applies to the sickles, which can also never exceed 17.

Overload `Base.show` such that Julia prints your currency as, for example, `7G, 2S, 9K`.

Also, overload the function `+` to add two instances of `WizCur` and the `>` and `<` operators to compare two instances of wizarding currency.

The piggy bank with Ron's life savings contains 19 Sickles and 732 Knuts. Harry has 3 Galleons, 1 Sickle, and 7 Knuts pocket change. Who has the most money? How many do they have together?

HINT: you might find `%` and `div` useful here.
=#

# first we define the WizCur structure

struct WizCur
    galleons::Int
    sickles::Int
    knuts::Int
    function WizCur(galleons::Int, sickles::Int, knuts::Int)
        sickles += knuts ÷ 29
        knuts %= 29
        galleons += sickles ÷ 17
        sickles %= 17
        return new(galleons, sickles, knuts)
    end
end

# we make it more "Julia" by removing the need for . notations

galleons(money::WizCur) = money.galleons
sickles(money::WizCur) = money.sickles
knuts(money::WizCur) = money.knuts

# by calculating the total amount of knuts we can easily compare two values

moneyinknuts(money::WizCur) = 29*17galleons(money) + 29sickles(money) + knuts(money)

function Base.show(io::IO, money::WizCur)
    print(io, "$(galleons(money))G, $(sickles(money))S, $(knuts(money))K")
end

# lastly we extend some base functions so that they work with our newly defined structure

Base.isless(m1::WizCur, m2::WizCur) = moneyinknuts(m1) < moneyinknuts(m2)
Base.isgreater(m1::WizCur, m2::WizCur) = moneyinknuts(m1) > moneyinknuts(m2)
Base.isequal(m1::WizCur, m2::WizCur) = moneyinknuts(m1) == moneyinknuts(m2)

Base.:+(m1::WizCur, m2::WizCur) = WizCur(galleons(m1)+galleons(m2),
                                            sickles(m1)+sickles(m2),
                                            knuts(m1)+knuts(m2))

money_ron = WizCur(0, 19, 732)
money_harry = WizCur(3, 1, 7)

dungbomb_fund = money_ron + money_harry


text:
using Stheno: CustomMean, ZeroMean, ConstantMean, EmpiricalMean

@testset "mean" begin

    # Test fallbacks.
    let
        @test_throws ErrorException eachindex(CustomMean(sin))
        @test_throws AssertionError AbstractVector(CustomMean(cos))

        m = randn(5)
        @test AbstractVector(EmpiricalMean(m)) == m
    end

    # Test CustomMean function.
    let
        rng, N, D = MersenneTwister(123456), 11, 2
        X, x = ColsAreObs(randn(rng, D, N)), randn(rng, N)
        foo_mean = x->sum(abs, x)
        f = CustomMean(foo_mean)

        @test f(X[1]) == foo_mean(X[1])

        mean_function_tests(f, x)
        mean_function_tests(f, X)
        mean_function_tests(f, BlockData([x, X]))

        @test isinf(length(f))

        # Check that shorthand for block-wise application of mean function works.
        @test map(f, BlockData([x, X])) isa BlockVector
        @test map(f, BlockData([x, X])) == map(f, BlockData([x, X]))
    end

    # Test ZeroMean.
    let
        rng, P, Q, D = MersenneTwister(123456), 3, 2, 4
        X, x = ColsAreObs(randn(rng, D, P)), randn(rng, P)
        f = ZeroMean{Float64}()

        @test f(randn(rng)) === zero(Float64)
        @test f == ZeroMean{Float32}()

        mean_function_tests(f, x)
        mean_function_tests(f, X)
        mean_function_tests(f, BlockData([x, X]))

        @test isinf(length(f))

        c = ConstantMean(5.0)
        @test f + f === f
        @test f + c == c
        @test c + f == c
        @test f * f === f
        @test f * c === f
        @test c * f === f
    end

    # Test ConstantMean.
    let
        rng, P, Q, D = MersenneTwister(123456), 3, 2, 4
        X, x = ColsAreObs(randn(rng, D, P)), randn(rng, P)
        c = randn(rng)
        f = ConstantMean(c)

        @test ConstantMean(1.0) == ConstantMean(1)
        @test ConstantMean(1.0) ≠ ConstantMean(2)
        @test f(randn(rng)) == c

        mean_function_tests(f, x)
        mean_function_tests(f, X)
        mean_function_tests(f, BlockData([x, X]))

        @test isinf(length(f))
    end

    # Test EmpiricalMean.
    let
        rng, N, D = MersenneTwister(123456), 11, 2
        x = 1:N
        m = randn(rng, N)
        μ = EmpiricalMean(m)

        @test length(μ) == length(m)
        @test eachindex(μ) == eachindex(m)
        @test μ == μ

        mean_function_tests(μ, x)
        mean_function_tests(μ, BlockData([x, x]))

        @test map(μ, :) == map(μ, eachindex(μ))
        @test map(μ, :) == m

    end
end


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

module MacroCalls

export @macrocall

macro macrocall(ex)
    @assert Meta.isexpr(ex, :macrocall)
    ex.head = :call
    for i in 2:length(ex.args)
        ex.args[i] = QuoteNode(ex.args[i])
    end
    insert!(ex.args, 3, __module__)
    return esc(ex)
end

end

max_stars_repo_name: greimel/julia

max_issues_repo_name: greimel/julia

max_forks_repo_name: greimel/julia


text:
lookandsay(input::Integer, iters = 1) = lookandsay!(reverse(digits(input)), iters)
function lookandsay!(input::AbstractVector{Int}, iters = 1)
    result = input
    input = Int[]
    for _ in 1:iters
        input, result = result, input
        while !isempty(input)
            next = popfirst!(input)
            count = 1
            while !isempty(input) && first(input) == next
                popfirst!(input)
                count += 1
            end
            push!(result, reverse(digits(count))..., next)
        end
    end
    join(result)
end

@assert lookandsay(1) == "11"
@assert lookandsay(11) == "21"
@assert lookandsay(1, 2) == "21"
@assert lookandsay(1211) == "111221"
@assert lookandsay(111221) == "312211"
@assert lookandsay(1, 5) == "312211"
@time length(lookandsay(3113322113, 40))
#   0.213305 seconds (3.49 M allocations: 162.478 MiB, 8.26% gc time)
# 329356
@time length(lookandsay(3113322113, 50))
#   3.463646 seconds (49.40 M allocations: 2.089 GiB, 14.32% gc time)
# 4666278

max_stars_repo_name: stellartux/advent-of-code

max_issues_repo_name: stellartux/advent-of-code

max_forks_repo_name: stellartux/advent-of-code


text:
# File: fKurt.jl
# Author:
# Date: 29-June-2020

# EXCESS KURTOSIS
function fKurt(x,flag,f)
# --------------------------------------------------------------------------
# x:     returns
# flag:  0 = sample, 1 = population
# f:     reporting frequency
# m4:    excess kurtosis (sample or population)
# --------------------------------------------------------------------------

    m4 = (kurtosis(x,flag)-3)./f
    return m4
end


text:
"""
$(SIGNATURES)

Given `{{ ... }}` blocks, identify what kind of blocks they are and return a vector
of qualified blocks of type `AbstractBlock`.
"""
function qualify_html_hblocks(blocks::Vector{OCBlock})::Vector{AbstractBlock}

    qb = Vector{AbstractBlock}(undef, length(blocks))

    # TODO improve this (if there are many blocks this would be slow)
    for (i, β) ∈ enumerate(blocks)
        # if block {{ if v }}
        m = match(HBLOCK_IF_PAT, β.ss)
        isnothing(m) || (qb[i] = HIf(β.ss, m.captures[1]); continue)
        # else block {{ else }}
        m = match(HBLOCK_ELSE_PAT, β.ss)
        isnothing(m) || (qb[i] = HElse(β.ss); continue)
        # else if block {{ elseif v }}
        m = match(HBLOCK_ELSEIF_PAT, β.ss)
        isnothing(m) || (qb[i] = HElseIf(β.ss, m.captures[1]); continue)
        # end block {{ end }}
        m = match(HBLOCK_END_PAT, β.ss)
        isnothing(m) || (qb[i] = HEnd(β.ss); continue)
        # ---
        # isdef block
        m = match(HBLOCK_ISDEF_PAT, β.ss)
        isnothing(m) || (qb[i] = HIsDef(β.ss, m.captures[1]); continue)
        # ifndef block
        m = match(HBLOCK_ISNOTDEF_PAT, β.ss)
        isnothing(m) || (qb[i] = HIsNotDef(β.ss, m.captures[1]); continue)
        # ---
        # ispage block
        m = match(HBLOCK_ISPAGE_PAT, β.ss)
        isnothing(m) || (qb[i] = HIsPage(β.ss, split(m.captures[1])); continue)
        # isnotpage block
        m = match(HBLOCK_ISNOTPAGE_PAT, β.ss)
        isnothing(m) || (qb[i] = HIsNotPage(β.ss, split(m.captures[1])); continue)
        # ---
        # function block {{ fname v1 v2 ... }}
        m = match(HBLOCK_FUN_PAT, β.ss)
        isnothing(m) || (qb[i] = HFun(β.ss, m.captures[1], split(m.captures[2])); continue)
        # ---
        # function toc {{toc}}
        m = match(HBLOCK_TOC_PAT, β.ss)
        isnothing(m) || (qb[i] = HFun(β.ss, "toc", String[]); continue)

        throw(HTMLBlockError("I found a HBlock that did not match anything, " *
                             "verify '$(β.ss)'"))
    end
    return qb
end

"""
$(SIGNATURES)

Given qualified blocks `HIf`, `HElse` etc, construct a vector of the conditional blocks which
contain the list of conditions etc. No nesting is allowed at the moment.
"""
function find_html_cblocks(qblocks::Vector{AbstractBlock}
                           )::Tuple{Vector{HCond},Vector{AbstractBlock}}
    # container for the conditional blocks
    cblocks = Vector{HCond}()
    isempty(qblocks) && return cblocks, qblocks
    active_qblocks = ones(Bool, length(qblocks))
    i = 0
    while i < length(qblocks)
        i += 1
        β = qblocks[i]
        (typeof(β) == HIf) || continue

        # look forward until the next `{{ end }}` block
        k = findfirst(cβ -> (typeof(cβ) == HEnd), qblocks[i+1:end])
        if isnothing(k)
            throw(HTMLBlockError("Found an {{if ...}} block but no matching {{end}} block. "))
        end

        n_between = k - 1
        k += i

        initial_cond = β.vname
        secondary_conds = Vector{String}()
        afrom, ato = Vector{Int}(), Vector{Int}()
        push!(afrom, to(β) + 1)

        for bi ∈ 1:n_between
            β = qblocks[i + bi]
            if typeof(β) == HElseIf
                push!(ato,   from(β) - 1)
                push!(afrom, to(β) + 1)
                push!(secondary_conds, β.vname)
            elseif typeof(β) == HElse
                # TODO, should check that there are no other HElseIf etc after
                push!(ato,   from(β) - 1)
                push!(afrom, to(β) + 1)
            end
        end
        stβ, endβ = qblocks[i], qblocks[k]
        hcondss = subs(str(stβ), from(stβ), to(endβ))
        push!(ato, from(endβ) - 1)

        # assemble the actions
        actions = [subs(str(stβ), afrom[i], ato[i]) for i ∈ eachindex(afrom)]
        # form the hcond
        push!(cblocks, HCond(hcondss, initial_cond, secondary_conds, actions))
        active_qblocks[i:k] .= false
        i = k
    end
    return cblocks, qblocks[active_qblocks]
end

"""
$(SIGNATURES)

Given qualified blocks `HIsDef` or `HIsNotDef` build conditional page blocks.
"""
function find_html_cdblocks(qblocks::Vector{AbstractBlock}
                            )::Tuple{Vector{HCondDef},Vector{AbstractBlock}}
    # container for the conditional blocks
    cdblocks = Vector{HCondDef}()
    isempty(qblocks) && return cdblocks, qblocks
    active_qblocks = ones(Bool, length(qblocks))
    i = 0
    while i < length(qblocks)
        i += 1
        β = qblocks[i]
        (typeof(β) ∈ (HIsDef, HIsNotDef)) || continue
        # look forward until next `{{end}} block
        k = findfirst(cβ -> (typeof(cβ) == HEnd), qblocks[i+1:end])
        if isnothing(k)
            throw(HTMLBlockError("Found an {{if(n)def ...}} block but no matching {{end}} block."))
        end
        k += i
        endβ = qblocks[k]
        hcondss = subs(str(β), from(β), to(endβ))
        action = subs(str(β), to(β)+1, from(endβ)-1)
        push!(cdblocks, HCondDef(β, hcondss, action))
        active_qblocks[i:k] .= false
        i = k
    end
    return cdblocks, qblocks[active_qblocks]
end

"""
$(SIGNATURES)

Given qualified blocks `HIsPage` or `HIsNotPage` build conditional page blocks.
"""
function find_html_cpblocks(qblocks::Vector{AbstractBlock}
                            )::Tuple{Vector{HCondPage},Vector{AbstractBlock}}
    # container for the conditional blocks
    cpblocks = Vector{HCondPage}()
    isempty(qblocks) && return cpblocks, qblocks
    active_qblocks = ones(Bool, length(qblocks))
    i = 0
    while i < length(qblocks)
        i += 1
        β = qblocks[i]
        (typeof(β) ∈ (HIsPage, HIsNotPage)) || continue
        # look forward until next `{{end}} block
        k = findfirst(cβ -> (typeof(cβ) == HEnd), qblocks[i+1:end])
        if isnothing(k)
            throw(HTMLBlockError("Found an {{is(not)page ...}} block but no matching {{end}} " *
                                 "block."))
        end
        k += i
        endβ = qblocks[k]
        hcondss = subs(str(β), from(β), to(endβ))
        action = subs(str(β), to(β)+1, from(endβ)-1)
        push!(cpblocks, HCondPage(β, hcondss, action))
        active_qblocks[i:k] .= false
        i = k
    end
    return cpblocks, qblocks[active_qblocks]
end


text:
"From http://www.pserc.cornell.edu/matpower/MATPOWER-manual.pdf Table B-4"
@enum GeneratorCostModel begin
    PIECEWISE_LINEAR = 1
    POLYNOMIAL = 2
end

"Thrown upon detection of user data that is not supported."
struct DataFormatError <: Exception
    msg::String
end

struct InvalidParameter <: Exception
    msg::String
end

PS_MAX_LOG = parse(Int, get(ENV, "PS_MAX_LOG", "50"))


text:
RpcApi.SimpleOrganism(0x0000000000034521,:(function (o::Creature.Organism,)
        local var_161::Int8 = 81
        local var_131::Int16 = 20703
        local var_125::Bool = true
        function func_96(var_95::String="CMsQ6J5t")
            Creature.stepUp(o)
            return var_95
        end
        local var_82::Int16 = -28253
        function func_63(var_62::Int64=-5487471262987408691)
            return var_62
        end
        local var_55::Int64 = 8062249648076403993
        function func_45(var_43::String="D42FzkNp",var_44::String="QVktoUuw")
            return var_43
        end
        local var_34::Int64 = -6982312523886405890
        function func_25(var_24::Int64=5926471544133193903)
            return var_24
        end
        function func_9(var_8::Int8=-18)
            local var_123::Int64 = 2850089338817388517
            local var_85::Int16 = -29091
            local var_76::Int64 = -8364194871863581978
            local var_57::Bool = true
            local var_28::Int64 = -5547387289894786475
            local var_26::String = "zSGt1MST"
            local var_16::Bool = true
            local var_14::Int8 = 115
            local var_13::Int16 = 31438
            Creature.eatDown(o,Int(var_14))
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            o.mem[var_85] = var_13
            if var_28 > var_76
                Creature.stepUp(o)
                Creature.stepUp(o)
            end
            o.mem[var_13] = var_13
            Creature.eatUp(o,Int(var_8))
            var_26 = var_26 * var_26
            Creature.eatLeft(o,Int(var_14))
            Creature.stepLeft(o)
            var_26 = var_26[1:if length(var_26) > length(var_26)
                            0
                        else
                            length(var_26) - length(var_26)
                        end]
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepDown(o)
            Creature.eatLeft(o,Int(var_8))
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_8))
            var_13 = var_13 - var_13
            var_85 = if haskey(o.mem,var_13)
                    o.mem[var_13]
                else
                    var_85
                end
            Creature.eatDown(o,Int(var_14))
            if var_28 !== var_28
                local var_169::Int8 = 65
                Creature.stepUp(o)
            end
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepLeft(o)
            var_76 = var_76 * var_76
            Creature.eatDown(o,Int(var_14))
            o.mem[var_85] = var_85
            Creature.stepDown(o)
            if var_8 !== var_14
                local var_170::String = "jKh2LEpo"
                Creature.stepUp(o)
            end
            Creature.eatRight(o,Int(var_8))
            if var_26 === var_26
                Creature.stepDown(o)
                Creature.stepDown(o)
            end
            Creature.eatRight(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            if var_123 === var_123
                Creature.stepDown(o)
            end
            Creature.stepDown(o)
            Creature.eatLeft(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            var_123 = var_123 + var_76
            Creature.eatUp(o,Int(var_8))
            if var_14 !== var_14
                local var_171::Bool = false
                Creature.stepUp(o)
            end
            if var_16 === var_16
                Creature.stepUp(o)
                Creature.stepRight(o)
                Creature.stepRight(o)
            end
            var_26 = var_26 * var_26
            Creature.eatDown(o,Int(var_14))
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.eatLeft(o,Int(var_8))
            return var_8
        end
        local var_1::Int8 = 59
        function func_135(var_134::Int64=6349986163145892178)
            local var_173::Bool = false
            return var_134
        end
        var_12 = func_9(var_1)
        var_12 = func_9(var_12)
        var_15 = func_9(var_12)
        var_1 = func_9(var_1)
        var_15 = func_9(var_1)
        Creature.stepDown(o)
        var_131 = if haskey(o.mem,var_131)
                o.mem[var_131]
            else
                var_131
            end
        Creature.stepRight(o)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        if var_55 == var_34
            Creature.stepLeft(o)
        end
        var_12 = func_9(var_12)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_12))
        o.mem[var_82] = var_82
        var_34 = var_34 - var_34
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.stepUp(o)
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_15))
        Creature.stepUp(o)
        Creature.stepDown(o)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.stepUp(o)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.stepRight(o)
        Creature.stepUp(o)
        if var_1 != var_1
            local var_160::Int64 = 6104843260668152792
            local var_166::Int64 = -7678350092020504724
            Creature.stepRight(o)
            Creature.stepDown(o)
            var_160 = var_160 * var_160
        end
        Creature.stepUp(o)
        var_131 = var_131 * var_82
        Creature.stepUp(o)
        Creature.eatLeft(o,Int(var_12))
        o.mem[var_82] = var_131
        if var_12 <= var_12
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepDown(o)
        end
        Creature.stepRight(o)
        var_55 = Int(Creature.getEnergy(o,Int(var_82),Int(var_82)))
        Creature.eatDown(o,Int(var_15))
        return true
    end),[100,300,95,0,1,1,1],27,6924,35,1173252,0x00000327,Dict(0=>0,31438=>31438,-28253=>20703,-29091=>31438,-2660=>-29091,20703=>-21217,-5320=>-5320,-572=>-572,1=>1),[141,288],149),RpcApi.SimpleOrganism(0x00000000000342b9,:(function (o::Creature.Organism,)
        local var_131::Int16 = 20703
        local var_125::Bool = true
        function func_96(var_95::String="CMsQ6J5t")
            Creature.stepDown(o)
            Creature.stepRight(o)
            return var_95
        end
        local var_82::Int16 = -28253
        function func_63(var_62::Int64=-5487471262987408691)
            local var_175::Int64 = 2239460045388253167
            Creature.stepUp(o)
            return var_62
        end
        local var_55::Int64 = 8062249648076403993
        function func_45(var_43::String="D42FzkNp",var_44::String="QVktoUuw")
            return var_43
        end
        local var_34::Int64 = -6982312523886405890
        function func_25(var_24::Int64=5926471544133193903)
            return var_24
        end
        function func_9(var_8::Int8=-18)
            local var_123::Int64 = 2850089338817388517
            local var_85::Int16 = -29091
            local var_76::Int64 = -8364194871863581978
            local var_57::Bool = true
            local var_28::Int64 = -5547387289894786475
            local var_26::String = "zSGt1MST"
            local var_16::Bool = true
            local var_14::Int8 = 115
            local var_13::Int16 = 31438
            Creature.eatDown(o,Int(var_14))
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            o.mem[var_85] = var_13
            if var_28 > var_76
                Creature.stepUp(o)
                Creature.stepUp(o)
            end
            o.mem[var_13] = var_13
            Creature.eatUp(o,Int(var_8))
            var_26 = var_26 * var_26
            Creature.eatLeft(o,Int(var_14))
            Creature.stepLeft(o)
            var_26 = var_26[1:if length(var_26) > length(var_26)
                            0
                        else
                            length(var_26) - length(var_26)
                        end]
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepDown(o)
            Creature.eatLeft(o,Int(var_8))
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            var_28 = Int(Creature.getEnergy(o,Int(var_85),Int(var_13)))
            Creature.eatDown(o,Int(var_14))
            var_13 = var_13 - var_13
            var_85 = if haskey(o.mem,var_13)
                    o.mem[var_13]
                else
                    var_85
                end
            Creature.eatDown(o,Int(var_14))
            if var_28 !== var_28
                local var_169::Int8 = 65
                Creature.stepUp(o)
            end
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepLeft(o)
            var_76 = var_76 * var_76
            Creature.eatDown(o,Int(var_14))
            o.mem[var_85] = var_85
            Creature.stepDown(o)
            if var_8 !== var_14
                local var_170::String = "jKh2LEpo"
                Creature.stepUp(o)
            end
            Creature.eatRight(o,Int(var_8))
            if var_26 === var_26
                Creature.stepDown(o)
                Creature.stepDown(o)
            end
            Creature.eatRight(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            if var_123 === var_123
                Creature.stepDown(o)
            end
            Creature.stepDown(o)
            Creature.eatLeft(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            var_123 = var_123 + var_76
            Creature.eatUp(o,Int(var_8))
            if var_14 !== var_14
                local var_171::Bool = false
                Creature.stepUp(o)
                Creature.stepUp(o)
            end
            if var_16 === var_16
                Creature.stepUp(o)
                Creature.stepRight(o)
                Creature.stepRight(o)
            end
            var_26 = var_26 * var_26
            Creature.eatDown(o,Int(var_14))
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.eatLeft(o,Int(var_8))
            return var_8
        end
        local var_1::Int8 = 59
        function func_135(var_134::Int64=6349986163145892178)
            local var_177::Int64 = -5467594387861824762
            local var_173::Bool = false
            local var_174::Int64 = -6626064387828751035
            return var_134
        end
        var_12 = func_9(var_1)
        var_12 = func_9(var_12)
        var_15 = func_9(var_12)
        var_1 = func_9(var_1)
        var_15 = func_9(var_1)
        Creature.stepDown(o)
        var_131 = if haskey(o.mem,var_131)
                o.mem[var_131]
            else
                var_131
            end
        Creature.stepRight(o)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        if var_55 == var_34
            Creature.stepLeft(o)
        end
        var_12 = func_9(var_12)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_12))
        o.mem[var_82] = var_82
        var_34 = var_34 - var_34
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.stepUp(o)
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_15))
        Creature.stepUp(o)
        Creature.stepDown(o)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.stepUp(o)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.stepRight(o)
        Creature.stepUp(o)
        if var_1 != var_1
            local var_160::Int64 = 6104843260668152792
            Creature.stepRight(o)
            Creature.stepDown(o)
            var_160 = var_160 * var_160
        end
        Creature.stepUp(o)
        var_131 = var_131 * var_82
        Creature.stepUp(o)
        Creature.eatLeft(o,Int(var_12))
        o.mem[var_82] = var_131
        if var_12 <= var_12
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepLeft(o)
            Creature.stepDown(o)
        end
        Creature.stepRight(o)
        var_55 = Int(Creature.getEnergy(o,Int(var_82),Int(var_82)))
        Creature.stepLeft(o)
        return true
    end),[100,300,95,0,1,1,1],27,6924,35,1119017,0x00000335,Dict(0=>0,31438=>31438,-28253=>20703,-29091=>31438,-2660=>-29091,20703=>-27455,-5320=>-5320,-572=>-572,1=>1),[41,260],155),RpcApi.SimpleOrganism(0x000000000003447d,:(function (o::Creature.Organism,)
        local var_161::Int8 = 81
        local var_131::Int16 = 20703
        local var_125::Bool = true
        function func_96(var_95::String="CMsQ6J5t")
            return var_95
        end
        local var_82::Int16 = -28253
        function func_63(var_62::Int64=-5487471262987408691)
            Creature.stepRight(o)
            Creature.stepDown(o)
            return var_62
        end
        local var_55::Int64 = 8062249648076403993
        function func_45(var_43::String="D42FzkNp",var_44::String="QVktoUuw")
            local var_173::Int64 = 6699367592251067232
            var_173 = var_173 / var_173
            return var_43
        end
        local var_34::Int64 = -6982312523886405890
        function func_25(var_24::Int64=5926471544133193903)
            return var_24
        end
        function func_9(var_8::Int8=-18)
            local var_123::Int64 = 2850089338817388517
            local var_85::Int16 = -29091
            local var_76::Int64 = -8364194871863581978
            local var_57::Bool = true
            local var_28::Int64 = -5547387289894786475
            local var_26::String = "zSGt1MST"
            local var_16::Bool = true
            local var_14::Int8 = 115
            local var_13::Int16 = 31438
            Creature.eatDown(o,Int(var_14))
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            o.mem[var_85] = var_13
            if var_28 > var_76
                Creature.stepUp(o)
                Creature.stepUp(o)
            end
            o.mem[var_13] = var_13
            Creature.eatUp(o,Int(var_8))
            var_26 = var_26 * var_26
            Creature.eatLeft(o,Int(var_14))
            Creature.stepLeft(o)
            var_26 = var_26[1:if length(var_26) > length(var_26)
                            0
                        else
                            length(var_26) - length(var_26)
                        end]
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepDown(o)
            Creature.eatLeft(o,Int(var_8))
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_8))
            var_13 = var_13 - var_13
            var_85 = if haskey(o.mem,var_13)
                    o.mem[var_13]
                else
                    var_85
                end
            Creature.eatDown(o,Int(var_14))
            if var_28 !== var_28
                Creature.stepUp(o)
            end
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepLeft(o)
            var_76 = var_76 * var_76
            Creature.eatDown(o,Int(var_14))
            o.mem[var_85] = var_85
            Creature.stepDown(o)
            if var_8 !== var_14
                Creature.stepUp(o)
            end
            Creature.eatRight(o,Int(var_8))
            if var_26 === var_26
                Creature.stepDown(o)
                Creature.stepDown(o)
            end
            Creature.eatRight(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            if var_123 === var_123
                Creature.stepDown(o)
            end
            Creature.stepDown(o)
            Creature.eatLeft(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            var_123 = var_123 + var_76
            Creature.eatUp(o,Int(var_8))
            if var_14 !== var_14
                local var_171::Bool = false
                Creature.stepUp(o)
            end
            if var_16 === var_16
                Creature.stepUp(o)
                Creature.stepRight(o)
                Creature.stepRight(o)
            end
            var_26 = var_26 * var_26
            Creature.eatDown(o,Int(var_14))
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.eatLeft(o,Int(var_8))
            return var_8
        end
        local var_1::Int8 = 59
        function func_135(var_134::Int64=6349986163145892178)
            return var_134
        end
        var_12 = func_9(var_1)
        var_12 = func_9(var_12)
        var_15 = func_9(var_12)
        var_1 = func_9(var_1)
        Creature.eatDown(o,Int(var_1))
        var_15 = func_9(var_1)
        Creature.stepDown(o)
        var_131 = if haskey(o.mem,var_131)
                o.mem[var_131]
            else
                var_131
            end
        Creature.stepRight(o)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        if var_55 == var_34
            Creature.stepLeft(o)
            Creature.stepRight(o)
            Creature.stepRight(o)
        end
        var_12 = func_9(var_12)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_12))
        o.mem[var_82] = var_82
        var_34 = var_34 - var_34
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.stepUp(o)
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_15))
        Creature.stepUp(o)
        Creature.stepDown(o)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.stepUp(o)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.stepRight(o)
        Creature.stepUp(o)
        if var_1 != var_1
            local var_160::Int64 = 6104843260668152792
            local var_166::Int64 = -7678350092020504724
            Creature.stepRight(o)
            Creature.stepDown(o)
            var_160 = var_160 * var_160
        end
        Creature.stepUp(o)
        var_131 = var_131 * var_82
        Creature.stepUp(o)
        Creature.eatLeft(o,Int(var_12))
        if var_12 <= var_12
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepLeft(o)
            Creature.stepDown(o)
        end
        Creature.stepRight(o)
        var_55 = Int(Creature.getEnergy(o,Int(var_82),Int(var_82)))
        Creature.eatDown(o,Int(var_15))
        return true
    end),[100,300,95,0,1,1,1],27,6924,84,1011125,0x00000333,Dict(0=>0,31438=>31438,-28253=>20703,-29091=>31438,-2660=>-29091,20703=>20703,-5320=>-5320,-572=>-572,1=>1),[146,289],152),RpcApi.SimpleOrganism(0x0000000000034497,:(function (o::Creature.Organism,)
        local var_161::Int8 = 81
        local var_131::Int16 = 20703
        local var_125::Bool = true
        function func_96(var_95::String="CMsQ6J5t")
            var_95 = var_95[1:if length(var_95) > length(var_95)
                            0
                        else
                            length(var_95) - length(var_95)
                        end]
            return var_95
        end
        local var_82::Int16 = -28253
        function func_63(var_62::Int64=-5487471262987408691)
            Creature.stepDown(o)
            return var_62
        end
        local var_55::Int64 = 8062249648076403993
        function func_45(var_43::String="D42FzkNp",var_44::String="QVktoUuw")
            local var_172::Int64 = 7998535106955226490
            return var_43
        end
        local var_34::Int64 = -6982312523886405890
        function func_25(var_24::Int64=5926471544133193903)
            return var_24
        end
        function func_9(var_8::Int8=-18)
            local var_123::Int64 = 2850089338817388517
            local var_85::Int16 = -29091
            local var_76::Int64 = -8364194871863581978
            local var_57::Bool = true
            local var_28::Int64 = -5547387289894786475
            local var_26::String = "zSGt1MST"
            local var_16::Bool = true
            local var_14::Int8 = 115
            local var_13::Int16 = 31438
            Creature.eatDown(o,Int(var_14))
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            o.mem[var_85] = var_13
            if var_28 > var_76
                Creature.stepUp(o)
                Creature.stepUp(o)
            end
            o.mem[var_13] = var_13
            Creature.eatUp(o,Int(var_8))
            var_26 = var_26 * var_26
            Creature.eatLeft(o,Int(var_14))
            Creature.stepLeft(o)
            var_26 = var_26[1:if length(var_26) > length(var_26)
                            0
                        else
                            length(var_26) - length(var_26)
                        end]
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepDown(o)
            Creature.eatLeft(o,Int(var_8))
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_8))
            var_13 = var_13 - var_13
            var_85 = if haskey(o.mem,var_13)
                    o.mem[var_13]
                else
                    var_85
                end
            Creature.eatDown(o,Int(var_14))
            if var_28 !== var_28
                local var_169::Int8 = 65
                Creature.stepUp(o)
            end
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            Creature.stepLeft(o)
            var_76 = var_76 * var_76
            Creature.eatDown(o,Int(var_14))
            o.mem[var_85] = var_85
            Creature.stepDown(o)
            if var_8 !== var_14
                local var_170::String = "jKh2LEpo"
                Creature.stepUp(o)
            end
            Creature.eatRight(o,Int(var_8))
            if var_26 === var_26
                Creature.stepDown(o)
                Creature.stepDown(o)
            end
            Creature.eatRight(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            if var_123 === var_123
                Creature.stepDown(o)
            end
            Creature.stepDown(o)
            Creature.eatLeft(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            Creature.eatDown(o,Int(var_14))
            var_123 = var_123 + var_76
            Creature.eatUp(o,Int(var_8))
            if var_14 !== var_14
                local var_171::Bool = false
                Creature.stepUp(o)
            end
            if var_16 === var_16
                Creature.stepUp(o)
                Creature.stepRight(o)
                Creature.stepRight(o)
            end
            var_26 = var_26 * var_26
            Creature.eatDown(o,Int(var_14))
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.eatLeft(o,Int(var_8))
            return var_8
        end
        local var_1::Int8 = 59
        function func_135(var_134::Int64=6349986163145892178)
            return var_134
        end
        var_12 = func_9(var_1)
        var_12 = func_9(var_12)
        var_15 = func_9(var_12)
        var_1 = func_9(var_1)
        var_15 = func_9(var_1)
        Creature.stepDown(o)
        var_131 = if haskey(o.mem,var_131)
                o.mem[var_131]
            else
                var_131
            end
        Creature.stepRight(o)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        if var_55 == var_34
            Creature.stepLeft(o)
        end
        var_12 = func_9(var_12)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_12))
        o.mem[var_82] = var_82
        var_34 = var_34 - var_34
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.stepUp(o)
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_15))
        Creature.stepUp(o)
        Creature.stepDown(o)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.stepUp(o)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.stepRight(o)
        Creature.stepUp(o)
        if var_1 != var_1
            local var_160::Int64 = 6104843260668152792
            local var_166::Int64 = -7678350092020504724
            Creature.stepDown(o)
            Creature.stepRight(o)
            Creature.stepDown(o)
            var_160 = var_160 * var_160
        end
        Creature.stepUp(o)
        var_131 = var_131 * var_82
        Creature.stepUp(o)
        Creature.eatLeft(o,Int(var_12))
        o.mem[var_82] = var_131
        if var_12 <= var_12
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        for i::Int8 = 1:div(var_1,_LOOP_STEPS_DIVIDER)
            Creature.stepDown(o)
        end
        Creature.stepRight(o)
        var_55 = Int(Creature.getEnergy(o,Int(var_82),Int(var_82)))
        Creature.eatDown(o,Int(var_15))
        return true
    end),[100,300,95,0,1,1,1],27,6924,35,936169,0x00000322,Dict(0=>0,31438=>31438,-28253=>20703,-29091=>31438,-2660=>-29091,20703=>-6463,-5320=>-5320,-572=>-572,1=>1),[116,289],151),RpcApi.SimpleOrganism(0x00000000000343fb,:(function (o::Creature.Organism,)
        function func_96(var_95::String="CMsQ6J5t")
            return var_95
        end
        local var_82::Int16 = -28253
        function func_63(var_62::Int64=-5487471262987408691)
            return var_62
        end
        local var_55::Int64 = 8062249648076403993
        function func_45(var_43::String="D42FzkNp",var_44::String="QVktoUuw")
            Creature.stepRight(o)
            Creature.stepLeft(o)
            Creature.stepUp(o)
            return var_43
        end
        local var_34::Int64 = -6982312523886405890
        function func_25(var_24::Int64=5926471544133193903)
            return var_24
        end
        function func_9(var_8::Int8=-18)
            local var_139::Int64 = -4013247465467956436
            local var_137::Bool = true
            local var_131::Int8 = -38
            local var_123::Int64 = 2850089338817388517
            local var_85::Int16 = -29091
            local var_76::Int64 = -8364194871863581978
            local var_57::Bool = true
            local var_28::Int64 = -5547387289894786475
            local var_26::String = "zSGt1MST"
            local var_16::Bool = true
            local var_14::Int8 = 115
            local var_13::Int16 = 31438
            Creature.stepLeft(o)
            Creature.eatDown(o,Int(var_14))
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.eatLeft(o,Int(var_14))
            var_131 = var_14 * var_8
            Creature.stepUp(o)
            o.mem[var_85] = var_13
            if var_28 > var_76
            end
            o.mem[var_13] = var_13
            Creature.eatUp(o,Int(var_8))
            Creature.eatLeft(o,Int(var_8))
            var_26 = var_26 * var_26
            Creature.eatLeft(o,Int(var_14))
            var_13 = if haskey(o.mem,var_13)
                    o.mem[var_13]
                else
                    var_13
                end
            Creature.eatLeft(o,Int(var_8))
            Creature.stepLeft(o)
            var_26 = var_26 * var_26
            Creature.stepLeft(o)
            Creature.stepDown(o)
            Creature.eatDown(o,Int(var_14))
            o.mem[var_85] = var_85
            var_76 = Int(Creature.getEnergy(o,Int(var_85),Int(var_85)))
            Creature.eatLeft(o,Int(var_8))
            Creature.stepDown(o)
            if var_26 == var_26
            end
            if var_26 !== var_26
                local var_138::Int64 = 4138323514544043370
                var_138 = var_138 * var_138
                var_138 = var_138 - var_138
                Creature.stepRight(o)
            end
            Creature.eatDown(o,Int(var_8))
            Creature.eatDown(o,Int(var_8))
            Creature.eatDown(o,Int(var_14))
            var_13 = var_13 - var_13
            Creature.eatRight(o,Int(var_14))
            Creature.stepDown(o)
            Creature.eatLeft(o,Int(var_14))
            Creature.stepUp(o)
            Creature.eatDown(o,Int(var_14))
            Creature.stepLeft(o)
            var_16 = var_137 | var_16
            Creature.eatDown(o,Int(var_14))
            o.mem[var_13] = var_13
            Creature.stepDown(o)
            if var_8 !== var_14
                Creature.stepUp(o)
            end
            var_57 = var_16 & var_137
            Creature.eatRight(o,Int(var_8))
            Creature.stepUp(o)
            var_85 = var_85 * var_13
            Creature.stepDown(o)
            Creature.eatUp(o,Int(var_8))
            if var_14 !== var_14
                Creature.stepUp(o)
            end
            if var_16 === var_16
                local var_124::Int16 = 1670
                Creature.stepRight(o)
                var_124 = var_124 / var_124
                Creature.stepUp(o)
                Creature.stepRight(o)
            end
            Creature.eatDown(o,Int(var_14))
            o.mem[var_85] = var_13
            Creature.stepUp(o)
            Creature.eatRight(o,Int(var_14))
            return var_8
        end
        local var_1::Int8 = 59
        var_12 = func_9(var_1)
        var_1 = func_9(var_12)
        var_1 = func_9(var_1)
        var_1 = var_1 + var_12
        var_55 = Int(Creature.getEnergy(o,Int(var_82),Int(var_82)))
        Creature.stepRight(o)
        var_1 = var_1 / var_12
        if var_55 == var_34
            Creature.stepDown(o)
        end
        var_12 = func_9(var_12)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.eatRight(o,Int(var_12))
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.eatUp(o,Int(var_1))
        Creature.stepRight(o)
        Creature.eatDown(o,Int(var_1))
        Creature.stepUp(o)
        Creature.stepRight(o)
        Creature.stepUp(o)
        var_34 = Int(Creature.getEnergy(o,Int(var_82),Int(var_82)))
        Creature.eatLeft(o,Int(var_12))
        Creature.stepRight(o)
        Creature.stepDown(o)
        Creature.eatLeft(o,Int(var_1))
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.stepUp(o)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.stepRight(o)
        var_55 = Int(Creature.getEnergy(o,Int(var_82),Int(var_82)))
        Creature.eatRight(o,Int(var_12))
        Creature.eatRight(o,Int(var_1))
        Creature.stepRight(o)
        Creature.stepRight(o)
        var_82 = if haskey(o.mem,var_82)
                o.mem[var_82]
            else
                var_82
            end
        Creature.stepUp(o)
        Creature.eatLeft(o,Int(var_12))
        Creature.stepUp(o)
        if var_55 <= var_34
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
        end
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.stepRight(o)
        return true
    end),[100,300,95,0,1,1,1],23,8078,45,932620,0x000002ef,Dict(0=>0,31438=>31438,-28253=>-28253,-29091=>-29091,-2660=>-29091,-5320=>-5320,-572=>-572,1=>1),[22,4],134)]

max_stars_repo_name: tmptrash/jevo

max_issues_repo_name: tmptrash/jevo

max_forks_repo_name: tmptrash/jevo


text:
module MonteCarlos

using ExprRules

using ExprOptimization: ExprOptAlgorithm, ExprOptResult, BoundedPriorityQueue, enqueue!
import ExprOptimization: optimize

export MonteCarlo

abstract type TrackingMethod end

"""
    MonteCarlo

Monte Carlo.
# Arguments:
- `num_samples::Int`: number of samples
- `max_depth::Int`: maximum depth of derivation tree
- `track_method::TrackingMethod`: additional tracking, e.g., track top k exprs (default: no additional tracking)
"""
struct MonteCarlo <: ExprOptAlgorithm
    num_samples::Int
    max_depth::Int
    track_method::TrackingMethod

    function MonteCarlo(
        num_samples::Int,
        max_depth::Int;
        track_method::TrackingMethod=NoTracking())   #tracking method

        new(num_samples, max_depth, track_method)
    end
end

"""
    NoTracking

No additional tracking of expressions.
"""
struct NoTracking <: TrackingMethod end

"""
    TopKTracking

Track the top k expressions.
"""
struct TopKTracking <: TrackingMethod
    k::Int
    q::BoundedPriorityQueue{RuleNode,Float64}

    function TopKTracking(k::Int)
        q = BoundedPriorityQueue{RuleNode,Float64}(k,Base.Order.Reverse) #lower is better
        obj = new(k, q)
        obj
    end
end

"""
    optimize(p::MonteCarlo, grammar::Grammar, typ::Symbol, loss::Function; kwargs...)

    Expression tree optimization using Monte Carlo with parameters p, grammar 'grammar', start symbol typ, and loss function 'loss'.  Loss function has the form: los::Float64=loss(node::RuleNode, grammar::Grammar).
"""
function optimize(p::MonteCarlo, grammar::Grammar, typ::Symbol, loss::Function; kwargs...)
    monte_carlo(p, grammar, typ, loss; kwargs...)
end

"""
    monte_carlo(p::MonteCarlo, grammar::Grammar, typ::Symbol, loss::Function)

Expression tree optimization using Monte Carlo with parameters p, grammar 'grammar', start symbol typ, and loss function 'loss'.  Loss function has the form : los::Float64=loss(node::RuleNode, grammar::Grammar).  Draw Monte Carlo samples from the grammar and return the one with the best loss.
"""
function monte_carlo(p::MonteCarlo, grammar::Grammar, typ::Symbol, loss::Function;
    verbose::Bool=false)
    dmap = mindepth_map(grammar)

    trees = Vector{RuleNode}(undef, p.num_samples)
    losses = Vector{Float64}(undef, p.num_samples)
    Threads.@threads for i in 1:length(losses)
        # Only verbose if not in multi-threading
        verbose && Threads.nthreads() == 1 && println("samples: $i of $(p.num_samples)")
        tree = rand(RuleNode, grammar, typ, dmap, p.max_depth)
        trees[i] = tree
        losses[i] = float(loss(tree, grammar))
    end

    # A loop is used as `_update_tracker` might not be thread-safe
    best_tree, best_loss = RuleNode(0), Inf
    for (tree, los) in zip(trees, losses)
        if los < best_loss
            best_tree, best_loss = tree, los
        end
        _update_tracker!(p.track_method, tree, los)
    end

    alg_result = Dict{Symbol,Any}()
    _add_result!(alg_result, p.track_method)
    ExprOptResult(best_tree, best_loss, get_executable(best_tree, grammar), alg_result)
end

"""
    _add_result!(d::Dict{Symbol,Any}, t::NoTracking)

Add tracking results to alg_result.  No op for NoTracking.
"""
_add_result!(d::Dict{Symbol,Any}, t::NoTracking) = nothing
"""
    _add_result!(d::Dict{Symbol,Any}, t::TopKTracking)

Add tracking results to alg_result.
"""
function _add_result!(d::Dict{Symbol,Any}, t::TopKTracking)
    d[:top_k] = collect(t.q)
    d
end

"""
    _update_tracker!(t::NoTracking, tree::RuleNode, los::Float64)

Update the tracker.  No op for NoTracking.
"""
_update_tracker!(t::NoTracking, tree::RuleNode, los::Float64) = nothing
"""
    _update_tracker!(t::TopKTracking, tree::RuleNode, los::Float64)

Update the tracker.  Track top k expressions.
"""
_update_tracker!(t::TopKTracking, tree::RuleNode, los::Float64) = enqueue!(t.q, tree, los)

end #module


text:
"""
	vav2tsoft(file_results,file_output;sitename)
Convert VAV06 results (Earth tides) to TSoft tidal group info (written
parameters can be used in "LOCAT.TSD")

**Input**
* file_results: file containing VAV results (="analysisXX.dat") of gravity tidal analysis
* file_output: output file with tidal groups in tsoft format. Paste these results to TSoft/Tidal parameter set
* site: name of the site (identical to TSoft database)
* name: name of the tidal parameters (unique for given site)
* filemode: write new file ("w", default) or append to existing ("a")

file_vav = "test/input/vav_analysis.dat";
file_tsoft = "test/output/vav2tsoft.txt"
vav2tsoft(file_vav,file_tsoft,site="Cantlay",name="test");
"""
function vav2tsoft(file_results::String,file_output::String;
					site::String="Site",name::String="Name",
					filemode::String="w")::Nothing
	# Get number of header lines
	hl = FileTools.headlines(file_results,"results at filter frequency")
	# open file for writting + add header
	fo = tide2tsoft(file_output,site,name,filemode);
	# write parameters
	if hl != 0
		open(file_results,"r") do fid
			for i in 1:hl+1;readline(fid); end
			row = readline(fid);
			while !occursin(">",row)
				if !occursin("---",row) && !occursin("results",row)
					vav2tsoft_write(fo,row);
				end
				row = readline(fid);
				eof(fid) ? break : nothing;
			end
		end
	end
	close(fo);
end
"""
Auxiliary function to write the output file of vav2tsoft function
"""
function vav2tsoft_write(f::IOStream,s::String)::Nothing
	@printf(f,"COMP: %s  %s  %s  %s  %s\n",
			s[1:10],s[13:20],s[50:57],s[65:73],replace(s[27:31]," "=>""));
end

"""
	eterna2tsoft(file_results,file_output;file_groups,sitename)
Convert ETERNA34 "PRN" results (Earth tides) to TSoft tidal group info (written
parameters can be used in "LOCAT.TSD")
> Make sense only when the analyze parameter TIDALPOTEN= 4

**Input**
* file_results: file containing tidal analysis results (="projectname.prn")
* file_output: output file with tidal groups in tsoft format. Paste these results to TSoft/Tidal parameter set
* site: name of the site (identical to TSoft database)
* name: name of the tidal parameters (unique for given site)
* filemode: write new file ("w", default) or append to existing ("a")

file_eterna = "test/input/eterna_analysis.prn";
file_tsoft = "test/output/eterna2tsoft.txt"
eterna2tsoft(file_eterna,file_tsoft,site="Cantlay",name="test");
"""
function eterna2tsoft(file_results::String,file_output::String;
					site::String="Site",name::String="Name",
					filemode::String="w")::Nothing
	# Get number of header lines
	hl = FileTools.headlines(file_results,"Adjusted tidal parameters :")
	# open file for writting + add header
	fo = tide2tsoft(file_output,site,name,filemode);
	# write parameters
	if hl != 0
		open(file_results,"r") do fid
			for i in 1:hl+5;readline(fid); end
			row = readline(fid);
			while !occursin("Adjusted",row)
				length(row)>73 ? eterna2tsoft_write(fo,row) : nothing
				row = readline(fid);
				eof(fid) ? break : nothing;
			end
		end
	end
	close(fo);
end
"""
Auxiliary function to write the output file of eterna2tsoft function
"""
function eterna2tsoft_write(f::IOStream,s::String)::Nothing
	@printf(f,"COMP: %s %s %s %s %s\n",
			s[7:15],s[16:24],s[39:48],s[57:66],replace(s[25:29]," "=>""));
end
"""
Auxiliary function to write TSD header
"""
function tide2tsoft(filein::String,site::String,name::String,filemode::String)::IOStream
	f = open(filein,filemode);
	@printf(f,"[TIDECOMP] %s\n",site)
	@printf(f,"NAME: %s\nTYPE: 1\nAZIM: 0.0000000\nGRAV: 0.0000000\n",name);
	return f
end


text:
function is_crossing(lb::Float64, ub::Float64)
    lb < 0 && ub > 0 && return true
    return false
end

function merge_into_network(network::Network, coeffs::Vector{N} where N<:Number)
    layers = []
    for l in network.layers[1:end-1]
        Ŵ = copy(l.weights)
        b̂ = copy(l.bias)
        σ = l.activation
        push!(layers, Layer(Ŵ, b̂, σ))
    end

    l = network.layers[end]
    if typeof(l.activation) == Id
        Ŵ = coeffs' * l.weights
        b̂ = coeffs' * l.bias
        push!(layers, Layer(Array(Ŵ), [b̂], Id()))
    elseif typeof(l.activation) == ReLU
        Ŵ = copy(l.weights)
        b̂ = copy(l.bias)
        push!(layers, Layer(Ŵ, b̂, ReLU()))
        # just add an additional layer with the linear objective
        push!(layers, Layer(Array(coeffs'), zeros(1), Id()))
    else
        throw(DomainError(l.activation, ": the activation function is not supported!"))
    end

    return Network(layers)
end

# TODO: merge upper function for vectors coeffs into this function
function merge_into_network(network::Network, A::Matrix{N}, b::Vector{N}) where N<:Number
    layers = []
    for l in network.layers[1:end-1]
        Ŵ = copy(l.weights)
        b̂ = copy(l.bias)
        σ = l.activation
        push!(layers, Layer(Ŵ, b̂, σ))
    end

    l = network.layers[end]
    if typeof(l.activation) == Id
        Ŵ = A * l.weights
        # use -b, as we want everything to be satisfied, if output ≤ 0 (Ax ≤ b <-> Ax - b ≤ 0)
        b̂ = A * l.bias - b
        push!(layers, Layer(Ŵ, b̂, Id()))
    elseif typeof(l.activation) == ReLU
        Ŵ = copy(l.weights)
        b̂ = copy(l.bias)
        push!(layers, Layer(Ŵ, b̂, ReLU()))
        # just add an additional layer with the linear objective
        push!(layers, Layer(A, -b, Id()))
    else
        throw(DomainError(l.activation, ": the activation function is not supported!"))
    end

    return Network(layers)
end


text:
# importing converter
using Weave

old_dir = pwd()
cd(@__DIR__)
files = readdir()

# for each file check to see if it is a Jupyter notebook. If so make a converted version
for file in files

    # prevents short file names from causing errors
    if length(file) < 6
		continue
	end
	if ".ipynb"==file[end-5:end]
    	println(file)
        convert_doc(file, file[1:end-6] * ".jmd")
	end

end

# change back to the upper directory
cd(old_dir)

max_stars_repo_name: christiangil/Optimization-Tutorial

max_issues_repo_name: christiangil/Optimization-Tutorial

max_forks_repo_name: christiangil/Optimization-Tutorial


text:
# include("../../src/SFFM.jl")
using LinearAlgebra, Plots, JLD2, GLM

## define the model(s)
# include("exampleModelDef.jl")

## load sims
@load pwd()*"/examples/baseAdvComparison/dump/sims.jld2" sims

## analytic X distribution for comparison
# construction
Ψₓ = SFFM.PsiFunX(approxModel)
ξₓ = SFFM.MakeXiX(approxModel, Ψₓ)
pₓ, πₓ, Πₓ, Kₓ = SFFM.StationaryDistributionX(approxModel, Ψₓ, ξₓ)

## section 4.5: error for approximation of stationary distribution of X
Basis = "lagrange"
Δs = [1.6; 0.8; 0.4; 0.2; 0.1; 0.05]
NBasesRange = [1; 2; 3; 4]

πnorms = zeros(length(Δs), length(NBasesRange))
πnormsAdv = zeros(length(Δs), length(NBasesRange))
times = Array{Any}(undef, length(Δs), length(NBasesRange))
timesAdv = Array{Any}(undef, length(Δs), length(NBasesRange))
gctimes = Array{Any}(undef, length(Δs), length(NBasesRange))
gctimesAdv = Array{Any}(undef, length(Δs), length(NBasesRange))
mems = Array{Any}(undef, length(Δs), length(NBasesRange))
memsAdv = Array{Any}(undef, length(Δs), length(NBasesRange))
alloc = Array{Any}(undef, length(Δs), length(NBasesRange))
allocAdv = Array{Any}(undef, length(Δs), length(NBasesRange))
approxSpec = Array{Any}(undef, length(Δs), length(NBasesRange))

for d = 1:length(Δs), n = 1:length(NBasesRange)
    if d + 2 * n <= 10
        # define the mesh for each iteration
        nBases = NBasesRange[n]
        Δtemp = Δs[d]
        println("mesh details; h = ", Δtemp, " NBases = ", nBases)

        # collect time and memory stats
        ~, times[d, n], mems[d, n], gctimes[d, n], alloc[d, n] = @timed begin
            Nodes = collect(approxBounds[1, 1]:Δtemp:approxBounds[1, 2])
            mesh = SFFM.DGMesh(
                approxModel,
                Nodes,
                nBases,
                Basis = Basis,
            )
            approxSpec[d, n] = (Δtemp, nBases, SFFM.TotalNBases(mesh) * SFFM.NPhases(approxModel))

            # compute the marginal via DG
            Matrices = SFFM.MakeMatrices(approxModel, mesh,probTransform=false)
            MatricesR = SFFM.MakeMatricesR( approxModel, mesh)
            B = SFFM.MakeB( approxModel, mesh, Matrices,probTransform=false)
            Dr = SFFM.MakeDR(
                Matrices,
                MatricesR,
                approxModel,
                mesh,
                B,
            )
            Ψ = SFFM.PsiFun(Dr.DDict)
            R = SFFM.MakeR( approxModel, mesh, approxType="projection", probTransform=false)

            # the distribution of X when Y first returns to 0
            ξ = SFFM.MakeXi( B.BDict, Ψ, mesh = mesh, model = approxModel, probTransform = false)

            marginalX, p, K = SFFM.MakeLimitDistMatrices(
                B.BDict,
                Dr.DDict,
                R.RDict,
                Ψ,
                ξ,
                mesh,
                approxModel,
                probTransform = false,
            )
        end
        # convert marginalX to a distribution for analysis
        DGStationaryDist = SFFM.Coeffs2Dist(
            approxModel,
            mesh,
            marginalX,
            SFFM.SFFMProbaility,
            probTransform = false,
        )

        ## stationary distirbution stuff
        # evaluate the analytic result given the mesh
        analyticX = SFFM.SFFMProbability(
            [pₓ[:]; 0; 0],
            Πₓ(Matrix(mesh.Nodes[2:end]')) - Πₓ(Matrix(mesh.Nodes[1:end-1]')),
            mesh.Nodes[1:end-1] + SFFM.Δ(mesh) / 2,
        )

        # save them
        πnorms[d, n] = SFFM.starSeminorm(DGStationaryDist, analyticX)
    else
        πnorms[d, n] = NaN
        times[d, n], mems[d, n], gctimes[d, n], alloc[d, n] = NaN, NaN, NaN, NaN
    end
end

let p = plot()
    types = [:solid,:dash,:dashdot,:dashdotdot]
    for n = 1:length(NBasesRange)
        p = plot!(
            Δs,
            πnorms[:, n],
            xaxis = :log,
            yaxis = :log,
            xlabel = "log(h)",
            ylabel = "log error",
            label = "N_k = " * string(NBasesRange[n]),
            legend = :outertopright,
            linestyle = types[n],
            seriestype = :line,
            markershape = :auto,
            title = "Error",
            grid = false,
        )
    end
    display(p)
    savefig(pwd()*"/examples/baseAdvComparison/dump/piErrorVsDelta.png")
end

let p = plot()
    types = [:solid,:dash,:dashdot,:dashdotdot,:solid,:dash]
    for d = 1:length(Δs)
        p = plot!(
            NBasesRange,
            πnorms[d, :],
            yaxis = :log,
            xlabel = "N_k",
            ylabel = "log error",
            label = "h = " * string(Δs[d]),
            legend = :outertopright,
            linestyle = types[d],
            seriestype = :line,
            markershape = :auto,
            title = "Error",
            grid = false,
        )
    end
    display(p)
    savefig(pwd()*"/examples/baseAdvComparison/dump/piErrorVsNBases.png")
end

begin
    n = 1
    data = log.(πnorms[:,n])
    ind = .!isnan.(data)
    data = data[ind]
    println("rate of convergence for ", n, " basis functions is ")
    display(
        lm([ones(length(Δs[ind])) log.(Δs[ind])], data)
    )
    println("")

    n = 2
    data = log.(πnorms[:,n])
    ind = .!isnan.(data)
    data = data[ind]
    println("rate of convergence for ", n, " basis functions is ")
    display(
        lm([ones(length(Δs[ind])) log.(Δs[ind])], data)
    )
    println("")

    n = 3
    data = log.(πnorms[:,n])
    ind = .!isnan.(data)
    ind[4] = false
    data = data[ind]
    data = data
    println("rate of convergence for ", n, " basis functions is ")
    display(
        lm([ones(length(Δs[ind])) log.(Δs[ind])], data)
    )
    println("")
end

for d = 1:min(4,length(Δs))
    data = log.(πnorms[d,:])
    ind = .!isnan.(data)
    data = data[ind]
    println("rate of convergence for h = ", Δs[d])
    display(
        lm([ones(length(NBasesRange[ind])) NBasesRange[ind]], data)
    )
    println("")
end

mp =
    (log.(πnorms[1:end-1, :]) .- log.(πnorms[2:end, :])) ./
    (log.(Δs[1:end-1]) - log.(Δs[2:end]))
np =
    (log.(πnorms[:, 1:end-1]) .- log.(πnorms[:, 2:end])) ./
    ((NBasesRange[1:end-1]) - (NBasesRange[2:end]))'

stats = Array{Any}(undef,length(Δs)+1,length(NBasesRange)+1)
for n in 1:length(NBasesRange), d in 1:length(Δs)
    if d + 2 * n <= 10
        stats[d+1,n+1] = (πnorms[d,n], times[d,n], mems[d,n]/(1024*1024), approxSpec[d,n][3])
    else
        stats[d+1,n+1] = (0,0,0,0)
    end
end
stats[1,2:end] = NBasesRange
stats[2:end,1] = Δs
display(stats)
using NumericIO
innards = stats[2:end,2:end]
asciiexponentfmt = NumericIO.IOFormattingExpNum(
	"\\times10^{", false, '+', '-', NumericIO.ASCII_SUPERSCRIPT_NUMERALS
)
fmt = NumericIO.IOFormattingReal(asciiexponentfmt,
	ndigits=3, decpos=0, decfloating=true, eng=false, minus='-', inf="Inf"
)

begin
    println("\\begin{tabular}{ | c | l | l | l | l | l | }")
    println("\\hline")
    println("\\multirow{2}{*}{\\(\\Delta\\)} & \\multirow{2}{*}{}& \\multicolumn{4}{c|}{Number of basis functions, \\(N_k\\)} \\\\ \\cline{3-6}
          &      & 1            & 2           & 3           & 4           \\\\\\hline"
        )
    for d in 1:length(Δs)
        println(Δs[d], " &")
        println("
        \\(\\begin{array}{l}
            \\mbox{error}
            \\\\ \\mbox{time (sec)}
            \\\\ \\mbox{memory (MB)}
            \\\\ n_\\varphi
        \\end{array}\\)"
        )
        for n in 1:length(NBasesRange)
            println("&")
            if d + 2 * n <= 10
                println("
                \\(\\begin{array}{l}
                    ", formatted(innards[d,n][1],fmt),"}
                    \\\\",round(innards[d,n][2],sigdigits=3),"
                    \\\\",round(innards[d,n][3],sigdigits=3),"
                    \\\\",convert(Int,round(innards[d,n][4],digits=0)),"
                \\end{array}\\)"
                )
            else
                println(" - ")
            end
        end
        println("\\\\ \\hline")
    end
    println("\\end{tabular}")
end

max_stars_repo_name: angus-lewis/SFFM

max_issues_repo_name: angus-lewis/SFFM

max_forks_repo_name: angus-lewis/SFFM


text:
using Color, Images, FixedPointNumbers

function hexify(pxl::RGB)
    p = reinterpret(Uint8, [pxl.r, pxl.g, pxl.b])
    join(map(x->hex(x, 2), p))
end

function showimagehex(a::Image)
    s = "    "
    for i in 1:height(a)
        for j in 1:width(a)
            s *= " "*hexify(a["x", j, "y", i])
        end
        s *= "\n    "
    end
    return s
end

w = 5
h = 7
cback = RGB(1, 0, 1)
cfore = RGB(0, 1, 0)

a = Array(RGB{Ufixed8}, h, w)
img = Image(a)

println("Uninitialized image:")
println(showimagehex(img))

fill!(img, cback)
println("Image filled with background color:")
println(showimagehex(img))

img["x", 2, "y", 3] = cfore
println("Image with a pixel set for foreground color:")
println(showimagehex(img))

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode