text:
import Random
using Knet: gpu, KnetArray

function train_house_rentals(; epochs=1)
    hr = house_rentals()
    trn, tst = splitdata(hr; trainprop=0.8)

    hrtrn = csv2data(trn)
    hrtst = csv2data(tst)

    hrinputs = [("neighborhood", "String"),
                 ("number_of_bathrooms", "Int"),
                 ("location", "String"),
                 ("days_on_market", "Int"),
                 ("initial_price", "Float"),
                 ("number_of_rooms", "Int"),
                 ("sqft", "Float")]
    hroutputs = [("rental_price", "Float")]

    model = Model(hrinputs, hroutputs; name="houserentals")
    model, dtrn = train(model, hrtrn; epochs=epochs)
    dtst = getbatches(model, hrtst)

    println("Train error:")
    println(model.model(dtrn.x, dtrn.y))

    println("Test error:")
    println(model.model(dtst.x, dtst.y))

    model, dtrn, dtst
end

function train_gene_sequences(; epochs=1)
    gs = splice_junction()
    trn, tst = splitdata(gs, gs.Class; trainprop=0.8)

    gstrn = csv2data(trn)
    gstst = csv2data(tst)

    gsinputs = [("attribute_$i", "Category") for i in 1:60]
    gsoutputs = [("Class", "Category")]

    model = Model(gsinputs, gsoutputs; name="genesequences")
    model, dtrn = train(model, gstrn; epochs=epochs)
    dtst = getbatches(model, gstst)

    println("Train accuracy:")
    println(accuracy(model.model, dtrn))

    println("Test accuracy:")
    println(accuracy(model.model, dtst))

    return model, dtrn, dtst
end

function train_cifar_100(; epochs=1, datapath=nothing)
    cifarinputs = [("image_path", "Image")]
    cifaroutputs = [("class", "Category")]

    model = Model(cifarinputs, cifaroutputs; name="cifar100")

    if datapath == nothing
        println("Preprocessing from scratch...")
        model, dtrn = train(model, CIFAR100TRAIN; epochs=epochs)
        dtst = getbatches(model, CIFAR100TEST)
    else
        datapath = joinpath(SAVEDIR, datapath)
        !isfile(datapath) ? throw("Datapath is invalid") : println("Loading data...")
        dtrn, dtst = Knet.load(datapath, "dtrn", "dtst")
        model, dtrn = train(model, dtrn; epochs=epochs)
    end

    println("Train accuracy:")
    println(accuracy(model.model, dtrn))

    println("Test accuracy:")
    println(accuracy(model.model, dtst))

    model, dtrn, dtst
end

function train_imdb(; epochs=1, datapath=nothing)
    imdbinputs = [("review", "Text")]
    imdboutputs = [("sentiment", "Category")]

    model = Model(imdbinputs, imdboutputs; name="imdbreviews")

    if datapath == nothing
        println("Preprocessing from scratch...")
        model, dtrn = train(model, IMDBTRAIN; epochs=epochs)
        dtst = getbatches(model, IMDBTEST)
    else
        datapath = joinpath(SAVEDIR, datapath)
        !isfile(datapath) ? throw("Datapath is invalid") : println("Loading data...")
        dtrn, dtst = Knet.load(datapath, "dtrn", "dtst")
        model, dtrn = train(model, dtrn; epochs=epochs)
    end

    println("Train accuracy:")
    println(accuracy(model.model, dtrn))

    println("Test accuracy:")
    println(accuracy(model.model, dtst))

    model, dtrn, dtst
end

function train_quora(; epochs=1)
    trn, tst = quora_questions()

    quoratrn = csv2data(trn)
    quoratst = csv2data(tst[2:end, :])

    quorainputs = [("question1", "Text"), ("question2", "Text")]
    quoraoutputs = [("is_duplicate", "Binary Category")]

    model = Model(quorainputs, quoraoutputs; name="quora")
    model, dtrn = train(model, quoratrn; epochs=epochs)
    dtst = getbatches(model, quoratst)

    println("Train accuracy:")
    println(accuracy(model.model, dtrn))

    println("Test accuracy:")
    println(accuracy(model.model, dtst))

    model, dtrn, dtst
end

function train_default_of_credit(; epochs=1)
    trn, tst = default_of_credit()

    credittrn = csv2data(trn)
    credittst = csv2data(tst)

    creditinputs = [(x[1], "Int") for x in credittrn
                     if x != "default.payment.next.month"]
    creditoutputs = [("default.payment.next.month", "Binary Category")]

    model = Model(creditinputs, creditoutputs; name="defaultofcredit")
    model, dtrn = train(model, credittrn; epochs=epochs)
    dtst = getbatches(model, credittst)

    println("Train accuracy:")
    println(accuracy(model.model, dtrn))

    println("Test accuracy:")
    println(accuracy(model.model, dtst))

    model, dtrn, dtst
end

function train_prediction_of_return(; epochs=1)
    portrn, portst = prediction_of_return()

    porinputs = [("customerID", INT),
                 ("creationDate", DATE),
                 ("manufacturerID", INT),
                 ("price", FLOAT),
                 ("deliveryDate", DATE),
                 ("salutation", CATEGORY),
                 ("dateOfBirth", DATE),
                 ("state", CATEGORY),
                 ("itemID", INT),
                 ("orderDate", DATE),
                 ("size", CATEGORY),
                 ("color", CATEGORY),
                 ("orderItemID", INT)]
    poroutputs = [("returnShipment", BINARYCATEGORY)]

    model = Model(porinputs, poroutputs; name="predictofreturn")
    model, dtrn = train(model, portrn; epochs=epochs)
    dtst = getbatches(model, portst)

    println("Train accuracy:")
    println(accuracy(model.model, dtrn))

    println("Test accuracy:")
    println(accuracy(model.model, dtst))

    model, dtrn, dtst
end

function train_sensor(; epochs=1)
    sd = sensor()
    trn, tst = splitdata(sd; trainprop=0.8)

    sdtrn = csv2data(trn)
    sdtst = csv2data(tst)

    sdinputs = [("sensor 1", INT),
                ("sensor 2", INT),
                ("sensor 3", INT),
                ("sensor4", INT)]
    sdoutputs = [("output", CATEGORY)]

    model = Model(sdinputs, sdoutputs; name="sensordata")
    model, dtrn = train(model, sdtrn; epochs=epochs)
    dtst = getbatches(model, sdtst)

    println("Train accuracy:")
    println(accuracy(model.model, dtrn))

    println("Test accuracy:")
    println(accuracy(model.model, dtst))

    model, dtrn, dtst
end

function train_spam(; epochs=1)
    spam = spam()
    trn, tst = splitdata(spam; trainprop=0.8)

    spamtrn = csv2data(trn)
    spamtst = csv2data(tst)

    spaminputs = [("v2", TEXT)]
    spamoutputs = [("v1", BINARYCATEGORY)]

    model = Model(spaminputs, spamoutputs; name="spam")
    model, dtrn = train(model, spamtrn; epochs=epochs)
    dtst = getbatches(model, spamtst)

    println("Train accuracy:")
    println(accuracy(model.model, dtrn))

    println("Test accuracy:")
    println(accuracy(model.model, dtst))

    model, dtrn, dtst
end

max_stars_repo_name: alperkesen/AutoML

max_issues_repo_name: alperkesen/AutoML


text:
using EvolutionaryPlus
using Test

## Evolutionary Algorithm
println("=====Evolutionary Algorithm=====")
function f1(pop::DE.Population)
    for i in 1:size(pop.x, 1)
        pop.fit[i] = sum(pop.x[i, j]^2 for j in 1:size(pop.x, 2))
    end
end

DE.DE_evolution(f1, 50, 50, 1000)

## Covariance Matrix Adaptation Evolution Strategy
println("=====Covariance Matrix Adaptation Evolution Strategy=====")
function f2(p::CMA_ES.Population)
    for i in 1:size(p.x, 1)
        p.fit[i] = sum((-1 + 2 * p.x[i, j])^2 for j in 1:size(p.x, 2))
    end
end

CMA_ES.CMAES_evolution(f2, 50, 1000)

## Surrogate Model using Gaussian Processes
println("=====Surrogate Model using Gaussian Processes=====")
f(x) = sin(x)

tr_x = Array(0:0.5:10)
tr_y = f.(tr_x)

σ_f, l, L, α = GPs.model_training(tr_x, tr_y)

pr_x = Array(0:0.2:10)
pr_y = Array{Float64}(undef, length(pr_x), 2)
for i in 1:length(pr_x)
    pr_y[i, 1], pr_y[i, 2] = GPs.predict(σ_f, l, L, α, tr_x, pr_x[i])
end
te_y = f.(pr_x)

RMSE = sum((te_y[i] - pr_y[i, 1])^2 for i in length(te_y))^(1/2)

println("RMSE: ", RMSE)

#
# @testset "EvolutionaryPlus.jl" begin
#     # Write your own tests here.
#     f(x) = sin(x)
#
#     tr_x = Array(0:0.5:10)
#     tr_y = f.(tr_x)
#
#     σ_f, l, L, α = model_training(tr_x, tr_y)
#
#     pr_x = Array(0:0.2:10)
#     pr_y = Array{Float64}(undef, length(pr_x), 2)
#     for i in 1:length(pr_x)
#         pr_y[i, 1], pr_y[i, 2] = predict(σ_f, l, L, α, tr_x, pr_x[i])
#     end
#
#     @test abs(pr_y[1, 1] - tr_y[1]) < 1
# end
#

ext: jl


text:
using DiffEqSensitivity, SafeTestsets
using Test

const GROUP = get(ENV, "GROUP", "All")
const is_APPVEYOR = Sys.iswindows() && haskey(ENV,"APPVEYOR")
const is_TRAVIS = haskey(ENV,"TRAVIS")

@time begin
if GROUP == "All" || GROUP == "Core1" || GROUP == "Downstream"
    @time @safetestset "Forward Sensitivity" begin include("local_sensitivity/forward.jl") end
    @time @safetestset "Adjoint Sensitivity" begin include("local_sensitivity/adjoint.jl") end
    @time @safetestset "Second Order Sensitivity" begin include("local_sensitivity/second_order.jl") end
    @time @safetestset "Concrete Solve Derivatives" begin include("local_sensitivity/concrete_solve_derivatives.jl") end
end

if GROUP == "All" || GROUP == "Core2"
    @time @safetestset "Steady State Adjoint" begin include("local_sensitivity/steady_state.jl") end
    @time @safetestset "SDE Adjoint" begin include("local_sensitivity/sde.jl") end
    @time @safetestset "Concrete Solve Derivatives of Second Order ODEs" begin include("local_sensitivity/second_order_odes.jl") end
end

if GROUP == "All" || GROUP == "Core3"
    @time @safetestset "Stiff Adjoints" begin include("local_sensitivity/stiff_adjoints.jl") end
end

if GROUP == "All" || GROUP == "GSA"
    @time @safetestset "Morris Method" begin include("global_sensitivity/morris_method.jl") end
    @time @safetestset "Sobol Method" begin include("global_sensitivity/sobol_method.jl") end
    @time @safetestset "DGSM Method" begin include("global_sensitivity/DGSM.jl") end
    @time @safetestset "eFAST Method" begin include("global_sensitivity/eFAST_method.jl") end
    @time @safetestset "RegressionGSA Method" begin include("global_sensitivity/regression_sensitivity.jl") end
end

if GROUP == "DiffEqFlux"
    using Pkg
    if is_TRAVIS
      using Pkg
      Pkg.add("DiffEqFlux")
    end
    @time Pkg.test("DiffEqFlux")
end
end


text:
#-------------------------------------------------------------------
#* EMSO Model Library (EML) Copyright (C) 2004 - 2007 ALSOC.
#*
#* This LIBRARY is free software; you can distribute it and/or modify
#* it under the therms of the ALSOC FREE LICENSE as available at
#* http://www.enq.ufrgs.br/alsoc.
#*
#* EMSO Copyright (C) 2004 - 2007 ALSOC, original code
#* from http://www.rps.eng.br Copyright (C) 2002-2004.
#* All rights reserved.
#*
#* EMSO is distributed under the therms of the ALSOC LICENSE as
#* available at http://www.enq.ufrgs.br/alsoc.
#*
#*--------------------------------------------------------------------
#* Model of basic streams
#*----------------------------------------------------------------------
#* Author: Paula B. Staudt and Rafael de P. Soares
#* $Id$
#*---------------------------------------------------------------------
type stream
	stream()=begin
		NComp=outers.NComp
		new(
			DanaInteger(Dict{Symbol,Any}(
				:Brief=>"Number of chemical components",
				:Lower=>1
			)),
			flow_mol(Dict{Symbol,Any}(
				:Brief=>"Stream Molar Flow Rate"
			)),
			temperature(Dict{Symbol,Any}(
				:Brief=>"Stream Temperature"
			)),
			pressure(Dict{Symbol,Any}(
				:Brief=>"Stream Pressure"
			)),
			enth_mol(Dict{Symbol,Any}(
				:Brief=>"Stream Enthalpy",
				:Protected=>true
			)),
			fraction(Dict{Symbol,Any}(
				:Brief=>"Vapourization fraction"
			)),
			fill(fraction(Dict{Symbol,Any}(
				:Brief=>"Stream Molar Fraction"
			)),(NComp)),
			[:NComp,],
			[:F,:T,:P,:h,:v,:z,]
		)
	end
	NComp::DanaInteger
	F::flow_mol
	T::temperature
	P::pressure
	h::enth_mol
	v::fraction
	z::Array{fraction}
	parameters::Array{Symbol,1}
	variables::Array{Symbol,1}
	attributes::Dict{Symbol,Any}
end
export stream
function atributes(in::stream,_::Dict{Symbol,Any})
	fields::Dict{Symbol,Any}=Dict{Symbol,Any}()
	fields[:Pallete]=false
	fields[:Brief]="General Material Stream"
	fields[:Info]="This is the basic building block for the EML models.
	Every model should have input and output streams derived
	from this model."
	drive!(fields,_)
	return fields
end
stream(_::Dict{Symbol,Any})=begin
	newModel=stream()
	newModel.attributes=atributes(newModel,_)
	newModel
end


text:
using LibSDL2
using Test

const SDL = LibSDL2

# Need on systems without system libSDL2
#= using SDL2_jll =#
#= @eval SDL const libsdl2 = $(SDL2_jll.libsdl2) =#

# We're just going to test that none of these programs crash.

@testset "Hello!" begin
    function helloSDL()
        sdlerror() = unsafe_string(SDL.GetError())

        # TODO: checkptr is a bad name
        function checkptr(ptr)
            if ptr == C_NULL
                error(sdlerror())
            else
                ptr
            end
        end

        checkptr(SDL.Init(SDL.INIT_VIDEO))

        window = checkptr(SDL.CreateWindow("Hello!", 100, 100, 640, 480, SDL.WINDOW_SHOWN))

        renderer = checkptr(SDL.CreateRenderer(window, -1, SDL.RENDERER_ACCELERATED))

        surface = checkptr(SDL.LoadBMP("$(@__DIR__)/res/Lesson1/hello.bmp"))
        texture = checkptr(SDL.CreateTextureFromSurface(renderer, surface))

        SDL.FreeSurface(surface)
        surface = C_NULL

        for _ in 1:3
            SDL.RenderClear(renderer)
            SDL.RenderCopy(renderer, texture, C_NULL, C_NULL)
            SDL.RenderPresent(renderer)
        end

        SDL.DestroyTexture(texture)
        SDL.DestroyRenderer(renderer)
        SDL.DestroyWindow(window)
        SDL.Quit()

        # We only care that this didn't error.
        return true
    end

    @test helloSDL()

    include("lesson4.jl")

    @test lesson4.main()
end


text:
using Test
using StaticArrays
using VariableTemplates

@testset "Variable Templates" begin
    include("base_functionality.jl")
    include("test_simple_models.jl")
    include("test_complex_models.jl")
    include("test_varsindex.jl")
end


text:
function show_example(Mat_Label, labels, Mat_Unlabel, unlabel_data_labels)
    mat = vcat(Mat_Label, Mat_Unlabel)
    label = vcat(labels, unlabel_data_labels)
    df = DataFrame(x = mat[:,1], y = mat[:,2], class = label)
    println("Computing finished")
    println("Drawing the plot.....Please Wait(Actually Gadfly is quite slow in drawing the first plot)")
    Gadfly.plot(df, x = "x", y = "y", color = "class", Geom.point)
end

function show_example(Mat_Label, labels, Mat_Unlabel, unlabel_data_labels :: Array{Float64,2})
    iter_size = size(unlabel_data_labels,2)
    num_size = size(unlabel_data_labels, 1) + size(labels,1)
    mat = vcat(Mat_Label, Mat_Unlabel)
    mat = repmat(mat,iter_size,1)
    labels = repmat(labels,1, iter_size)
    label = vcat(labels, unlabel_data_labels)
    group = zeros(num_size * iter_size, 1)
    for i = 1:iter_size
        group[((i-1)*num_size+1):num_size*i] = i
    end
    df = DataFrame(x = mat[:,1], y = mat[:,2], iteration = vec(group), class = label[:])
    println("Computing finished")
    println("drawing the plot....Please Wait")
    Gadfly.plot(df, x = "x", y = "y", xgroup = "iteration", color = "class", Geom.subplot_grid(Geom.point))
end

function loadCircleData(num_data)
    center = [5.0, 5.0]
    radiu_inner = 2
    radiu_outer = 4
    num_inner = floor(num_data / 3)
    num_outer = num_data - num_inner

    data = []
    theta = 0.0
    for i in 1:num_inner
        pho = (theta % 360) * pi / 180
        tmp = zeros(1,2)
        tmp[1] = radiu_inner * cos(pho) + rand() + center[1]
        tmp[2] = radiu_inner * sin(pho) + rand() + center[2]
        push!(data,tmp)
        theta += 2
    end

    theta = 0.0
    for i in 1:num_outer
        pho = (theta % 360) * pi / 180
        tmp = zeros(1,2)
        tmp[1] = radiu_outer * cos(pho) + rand() + center[1]
        tmp[2] = radiu_outer * sin(pho) + rand() + center[2]
        push!(data,tmp)
        theta += 1
    end

    Mat_Label = zeros(2, 2)
    Mat_Label[1,:] = center + [ 0.5 - radiu_inner , 0]
    Mat_Label[2,:] = center + [ 0.5 - radiu_outer , 0]
    labels = [1, 2]
    Mat_Unlabel = reduce(vcat,data)
    return Mat_Label, labels, Mat_Unlabel
end

function loadBandData(num_unlabel_samples)
    #Mat_Label = np.array([[5.0, 2.], [5.0, 8.0]])
    #labels = [0, 1]
    #Mat_Unlabel = np.array([[5.1, 2.], [5.0, 8.1]])

    Mat_Label = [5.0 2;5.0 8.0]
    labels = [1, 2]
    num_dim = size(Mat_Label,2)
    Mat_Unlabel = zeros(num_unlabel_samples, num_dim)
    Mat_Unlabel[num_unlabel_samples/2, :] = (rand(num_unlabel_samples/2, num_dim) - 0.5) * np.array([3, 1]) + Mat_Label[0]
    Mat_Unlabel[num_unlabel_samples/2 : num_unlabel_samples, :] = (np.random.rand(num_unlabel_samples/2, num_dim) - 0.5) * np.array([3, 1]) + Mat_Label[1]
    return Mat_Label, labels, Mat_Unlabel
end

function navie_knn(dataSet, query, k)
    numSamples = size(dataSet,1)
    ## step 1: calculate Euclidean distance
    diff = repmat(query,1,numSamples)' - dataSet
    squaredDiff = diff.^2
    squaredDist = vec(sum(squaredDiff, 2))

    sortedDistIndices = sortperm(squaredDist)
    if k > length(sortedDistIndices)
        k = length(sortedDistIndices)
    end
    return sortedDistIndices[1:k]
end

# build a big graph (normalized weight matrix)
function buildGraph(MatX, kernel_type, rbf_sigma = nothing, knn_num_neighbors = nothing)
    num_samples = size(MatX,1)
    affinity_matrix = zeros(num_samples, num_samples)
    if kernel_type == "rbf"
        if rbf_sigma == nothing
          error("You should input a sigma of rbf kernel!")
        end
        for i in 1:num_samples
            row_sum = 0.0
            for j in 1:num_samples
                diff = MatX[i, :] - MatX[j, :]
                affinity_matrix[i,j] = exp(sum(diff.^2) / (-2.0 * rbf_sigma^2))
                row_sum += affinity_matrix[i,j]
            end
            affinity_matrix[i,:] /= row_sum
        end
    elseif kernel_type == "knn"
        if knn_num_neighbors == nothing
          error("You should input a k of knn kernel!")
        end
        for i in 1:num_samples
          k_neighbors = navie_knn(MatX, MatX[i, :], knn_num_neighbors)
          affinity_matrix[i, k_neighbors] = 1.0 / knn_num_neighbors
        end
    else
        erro("Not support kernel type! You can use knn or rbf!")
    end

    return affinity_matrix
end

# label propagation
function label_propagation(Mat_Label, Mat_Unlabel, labels; kernel_type = "rbf", rbf_sigma = 1.5,
                    knn_num_neighbors = 10, max_iter = 500, tol = 1e-3)
    # initialize
    num_label_samples = size(Mat_Label,1)
    num_unlabel_samples = size(Mat_Unlabel,1)
    num_samples = num_label_samples + num_unlabel_samples
    labels_list = unique(labels)
    num_classes = length(labels_list)

    MatX = vcat(Mat_Label, Mat_Unlabel)
    clamp_data_label = zeros(num_label_samples, num_classes)
    if any(labels == 0)
      for i in 1:num_label_samples
        clamp_data_label[i,labels[i]+1] = 1.0
      end
    else
      for i in 1:num_label_samples
        clamp_data_label[i,labels[i]] = 1.0
      end
    end
    label_function = zeros(num_samples, num_classes)
    label_function[1:num_label_samples,:] = clamp_data_label
    label_function[num_label_samples+1:num_samples,:] = -1

    # graph construction
    affinity_matrix = buildGraph(MatX, kernel_type, rbf_sigma, knn_num_neighbors)

    # start to propagation
    iter = 0;
    pre_label_function = zeros(num_samples, num_classes)
    changed = sum(abs(pre_label_function - label_function))
    while iter < max_iter && changed > tol
      ##if iter % 1 == 0
      #  println("---> Iteration $(iter)/$(max_iter), changed: $changed")
      #end
      pre_label_function = label_function
      iter += 1

      # propagation
      label_function = affinity_matrix * label_function

      # clamp
      label_function[1 : num_label_samples, :] = clamp_data_label

      # check converge
      changed = sum(abs(pre_label_function - label_function))
    end
    # get terminate label of unlabeled data
    unlabel_data_labels = zeros(num_unlabel_samples)
    for i in 1:num_unlabel_samples
      unlabel_data_labels[i] = indmax(label_function[i+num_label_samples,:])
    end
    return unlabel_data_labels
  end

# if affinity_matrix is given
function label_propagation(affinity_matrix, labels; kernel_type = "rbf", rbf_sigma = 1.5,
                    knn_num_neighbors = 10, max_iter = 500, tol = 1e-3)
    # initialize
    num_label_samples = size(labels,1)
    num_samples = size(affinity_matrix,1)
    num_unlabel_samples = num_samples - num_label_samples
    labels_list = unique(labels)
    num_classes = length(labels_list)

    clamp_data_label = zeros(num_label_samples, num_classes)
    if any(labels == 0)
      for i in 1:num_label_samples
        clamp_data_label[i,labels[i]+1] = 1.0
      end
    else
      for i in 1:num_label_samples
        clamp_data_label[i,labels[i]] = 1.0
      end
    end
    label_function = zeros(num_samples, num_classes)
    label_function[1:num_label_samples,:] = clamp_data_label
    label_function[num_label_samples+1:num_samples,:] = -1

    # start to propagation
    iter = 0;
    pre_label_function = zeros(num_samples, num_classes)
    changed = sum(abs(pre_label_function - label_function))
    while iter < max_iter && changed > tol
      ##if iter % 1 == 0
      #  println("---> Iteration $(iter)/$(max_iter), changed: $changed")
      #end
      pre_label_function = label_function
      iter += 1

      # propagation
      label_function = affinity_matrix * label_function

      # clamp
      label_function[1 : num_label_samples, :] = clamp_data_label

      # check converge
      changed = sum(abs(pre_label_function - label_function))
    end
    # get terminate label of unlabeled data
    unlabel_data_labels = zeros(num_unlabel_samples)
    for i in 1:num_unlabel_samples
      unlabel_data_labels[i] = indmax(label_function[i+num_label_samples,:])
    end
    return unlabel_data_labels
  end

function test_label_propagation()
  num_unlabel_samples = 800
  Mat_Label, labels, Mat_Unlabel = loadCircleData(num_unlabel_samples)
  iter = round(linspace(1,70,5))
  res = []
  for i in iter
      unlabel_data_labels = label_propagation(Mat_Label, Mat_Unlabel, labels, kernel_type = "knn", knn_num_neighbors = 10, max_iter = i)
      push!(res, unlabel_data_labels)
  end
  res = reduce(hcat, res)
  show_example(Mat_Label, labels, Mat_Unlabel, res)
end


text:
using seisimu

function extrap!{T1,T2<:Real}(model::elmod3d, threadim::Array{Int64}, CPU_mem::T1, GPU_mem::T2; num_stream=1)

    if length(threadim) != 3
        error("Thread dimension should be 3. Use [threadim1, threadim2, threadim3].")
    else
        chk_group_full, chk_group_half, chk_stream_full, chk_stream_half = gpuchunk("elastic",
        model.medium.BDnDZ, model.medium.BDnHX,
        model.medium.BDnHY,"double",GPU_mem, CPU_mem, num_stream)

        Num_group = length(chk_group_half[2:end])
        Max_group_dim = maximum(chk_group_half)
        Max_stream_dim = maximum(chk_stream_half[3:end,:])
        Max_num_stream = maximum(chk_stream_half[1,:])

        blockdim = [Int64(ceil(model.medium.BDnHX/threadim[1])),
        Int64(ceil(Max_stream_dim/threadim[2])),
        Int64(ceil(model.medium.BDnDZ/threadim[3]))]

        path="/home/lzh/Dropbox/Zhenhua/Ongoing/Seisimu/deps/src/cump/el3d_cump.so"
        ccall((:el3d_cump,path),
        Void,
        (Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Cint, Cint, Cint,
         Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Cdouble, Cdouble, Cdouble, Cdouble, Cint,
         Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cint}, Ptr{Cint}, Cint, Cint,
         Ptr{Cint}, Ptr{Cint}, Cint, Cint,
         Ptr{Cint}, Ptr{Cint}),
         model.wf.vx, model.nwf.BDnvx[2], model.nwf.BDnvx[3], model.nwf.BDnvx[1],
         model.pml.PVxBTxx, model.pml.PVxBTxy, model.pml.PVxBTxz,
         model.wf.vy, model.nwf.BDnvy[2], model.nwf.BDnvy[3], model.nwf.BDnvy[1],
         model.pml.PVyBTxy, model.pml.PVyBTyy, model.pml.PVyBTyz,
         model.wf.vz, model.nwf.BDnvz[2], model.nwf.BDnvz[3], model.nwf.BDnvz[1],
         model.pml.PVzBTxz, model.pml.PVzBTyz, model.pml.PVzBTzz,
         model.wf.txx, model.pml.PTxxBVx, model.pml.PTxxBVy, model.pml.PTxxBVz,
         model.wf.tyy, model.pml.PTyyBVx, model.pml.PTyyBVy, model.pml.PTyyBVz,
         model.wf.tzz, model.pml.PTzzBVx, model.pml.PTzzBVy, model.pml.PTzzBVz,
         model.nwf.BDntpp[2], model.nwf.BDntpp[3], model.nwf.BDntpp[1],
         model.wf.txy, model.nwf.BDntxy[2], model.nwf.BDntxy[3], model.nwf.BDntxy[1],
         model.pml.PTxyBVx, model.pml.PTxyBVy,
         model.wf.tyz, model.nwf.BDntyz[2], model.nwf.BDntyz[3], model.nwf.BDntyz[1],
         model.pml.PTyzBVy, model.pml.PTyzBVz,
         model.wf.txz, model.nwf.BDntxz[2], model.nwf.BDntxz[3], model.nwf.BDntxz[1],
         model.pml.PTxzBVx, model.pml.PTxzBVz,
         model.medium.rho, model.medium.lambda, model.medium.mu, model.fdc,
         model.medium.dt, model.medium.dx, model.medium.dy, model.medium.dz, model.medium.ext,
         model.pml.bhalf, model.pml.ahalf, model.pml.bfull, model.pml.afull,
         chk_group_full, chk_group_half, Num_group, Max_group_dim,
         chk_stream_full, chk_stream_half, Max_num_stream, Max_stream_dim,
         threadim, blockdim)
    end
end

function extrap!(model::elmod3d)

        path="/home/lzh/Dropbox/Zhenhua/Ongoing/Seisimu/deps/src/cump/el3d_openmp.so"

        ccall((:el3d_openmp,path),
        Void,
        (Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Cint, Cint, Cint,
         Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble},
         Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
         Cdouble, Cdouble, Cdouble, Cdouble, Cint,
         Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}),
         model.wf.vx, model.nwf.BDnvx[2], model.nwf.BDnvx[3], model.nwf.BDnvx[1],
         model.pml.PVxBTxx, model.pml.PVxBTxy, model.pml.PVxBTxz,
         model.wf.vy, model.nwf.BDnvy[2], model.nwf.BDnvy[3], model.nwf.BDnvy[1],
         model.pml.PVyBTxy, model.pml.PVyBTyy, model.pml.PVyBTyz,
         model.wf.vz, model.nwf.BDnvz[2], model.nwf.BDnvz[3], model.nwf.BDnvz[1],
         model.pml.PVzBTxz, model.pml.PVzBTyz, model.pml.PVzBTzz,
         model.wf.txx, model.pml.PTxxBVx, model.pml.PTxxBVy, model.pml.PTxxBVz,
         model.wf.tyy, model.pml.PTyyBVx, model.pml.PTyyBVy, model.pml.PTyyBVz,
         model.wf.tzz, model.pml.PTzzBVx, model.pml.PTzzBVy, model.pml.PTzzBVz,
         model.nwf.BDntpp[2], model.nwf.BDntpp[3], model.nwf.BDntpp[1],
         model.wf.txy, model.nwf.BDntxy[2], model.nwf.BDntxy[3], model.nwf.BDntxy[1],
         model.pml.PTxyBVx, model.pml.PTxyBVy,
         model.wf.tyz, model.nwf.BDntyz[2], model.nwf.BDntyz[3], model.nwf.BDntyz[1],
         model.pml.PTyzBVy, model.pml.PTyzBVz,
         model.wf.txz, model.nwf.BDntxz[2], model.nwf.BDntxz[3], model.nwf.BDntxz[1],
         model.pml.PTxzBVx, model.pml.PTxzBVz,
         model.medium.rho, model.medium.lambda, model.medium.mu, model.fdc,
         model.medium.dt, model.medium.dx, model.medium.dy, model.medium.dz, model.medium.ext,
         model.pml.bhalf, model.pml.ahalf, model.pml.bfull, model.pml.afull)
    end


text:
using Oceananigans.Operators: Δzᵃᵃᶜ, Δzᵃᵃᶠ
using Oceananigans.AbstractOperations: flip
using Oceananigans.Solvers: BatchedTridiagonalSolver, solve!

#####
##### implicit_step! interface
#####
##### Closures with `VerticallyImplicitTimeDiscretization` can define
#####
##### 1. "Coefficient extractors" `νz` and `κz` to support vertically-implicit
#####    treatment of a diffusive term iwth the form `∂z κz ∂z ϕ` for a variable `ϕ`.
#####    There are three extractors for momentum (`νz`) and one for tracers (`κz`)
#####    relevant to implicit vertical diffusion.
#####
##### 2. `implicit_linear_coefficient` to support the implicit treament of a _linear_ term.
#####

# Fallbacks: extend these function for `closure` to support.
# TODO: docstring
@inline implicit_linear_coefficient(i, j, k, grid, closure, diffusivity_fields, tracer_index, LX, LY, LZ, clock, Δt, κz) =
    zero(grid)

@inline νzᶠᶜᶠ(i, j, k, grid, closure, diffusivity_fields, clock) = zero(grid) # u
@inline νzᶜᶠᶠ(i, j, k, grid, closure, diffusivity_fields, clock) = zero(grid) # v
@inline νzᶜᶜᶜ(i, j, k, grid, closure, diffusivity_fields, clock) = zero(grid) # w
@inline κzᶜᶜᶠ(i, j, k, grid, closure, diffusivity_fields, tracer_index, clock) = zero(grid) # tracers

#####
##### Batched Tridiagonal solver for implicit diffusion
#####

implicit_step!(field, ::Nothing, args...; kwargs...) = NoneEvent()
implicit_diffusion_solver(::ExplicitTimeDiscretization, args...; kwargs...) = nothing

#####
##### Solver kernel functions for tracers / horizontal velocities and for vertical velocities
##### Note: "ivd" stands for implicit vertical diffusion.
#####

@inline κ_Δz²(i, j, kᶜ, kᶠ, grid, κ) = κ / Δzᵃᵃᶜ(i, j, kᶜ, grid) / Δzᵃᵃᶠ(i, j, kᶠ, grid)

instantiate(X) = X()

# Tracers and horizontal velocities at cell centers in z

@inline function ivd_upper_diagonal(i, j, k, grid, closure, K, id, LX, LY, ::Center, clock, Δt, κz)
    closure_ij = getclosure(i, j, closure)
    κᵏ⁺¹ = κz(i, j, k+1, grid, closure_ij, K, id, clock)

    return ifelse(k > grid.Nz-1,
                  zero(eltype(grid)),
                  - Δt * κ_Δz²(i, j, k, k+1, grid, κᵏ⁺¹))
end

@inline function ivd_lower_diagonal(i, j, k, grid, closure, K, id, LX, LY, ::Center, clock, Δt, κz)
    k′ = k + 1 # Shift to adjust for Tridiagonal indexing convenction
    closure_ij = getclosure(i, j, closure)
    κᵏ = κz(i, j, k′, grid, closure_ij, K, id, clock)

    return ifelse(k < 1,
                  zero(eltype(grid)),
                  - Δt * κ_Δz²(i, j, k′, k′, grid, κᵏ))
end

# Vertical velocity kernel functions (at cell interfaces in z)
#
# Note: these coefficients are specific to vertically-bounded grids (and so is
# the BatchedTridiagonalSolver).
@inline function ivd_upper_diagonal(i, j, k, grid, closure, K, id, LX, LY, ::Face, clock, Δt, νzᶜᶜᶜ)
    closure_ij = getclosure(i, j, closure)
    νᵏ = νzᶜᶜᶜ(i, j, k, grid, closure_ij, K, clock)

    return ifelse(k < 1, # should this be k < 2? #should this be grid.Nz - 1?
                  zero(eltype(grid)),
                  - Δt * κ_Δz²(i, j, k, k, grid, νᵏ))
end

@inline function ivd_lower_diagonal(i, j, k, grid, closure, K, id, LX, LY, ::Face, clock, Δt, νzᶜᶜᶜ)
    k′ = k + 1 # Shift to adjust for Tridiagonal indexing convenction
    closure_ij = getclosure(i, j, closure)
    νᵏ⁻¹ = νzᶜᶜᶜ(i, j, k′-1, grid, closure_ij, K, clock)
    return ifelse(k < 1,
                  zero(eltype(grid)),
                  - Δt * κ_Δz²(i, j, k′, k′-1, grid, νᵏ⁻¹))
end

### Diagonal terms

@inline ivd_diagonal(i, j, k, grid, closure, K, id, LX, LY, LZ, clock, Δt, κz) =
    one(eltype(grid)) -
        Δt * maybe_tupled_implicit_linear_coefficient(i, j, k,   grid, closure, K, id, LX, LY, LZ, clock, Δt, κz) -
                      maybe_tupled_ivd_upper_diagonal(i, j, k,   grid, closure, K, id, LX, LY, LZ, clock, Δt, κz) -
                      maybe_tupled_ivd_lower_diagonal(i, j, k-1, grid, closure, K, id, LX, LY, LZ, clock, Δt, κz)

@inline maybe_tupled_implicit_linear_coefficient(args...) = implicit_linear_coefficient(args...)
@inline maybe_tupled_ivd_upper_diagonal(args...) = ivd_upper_diagonal(args...)
@inline maybe_tupled_ivd_lower_diagonal(args...) = ivd_lower_diagonal(args...)

#####
##### Solver constructor
#####

"""
    implicit_diffusion_solver(::VerticallyImplicitTimeDiscretization, grid)

Build tridiagonal solvers for the elliptic equations

```math
(1 - Δt ∂z κz ∂z - Δt L) cⁿ⁺¹ = c★
```

and

```math
(1 - Δt ∂z νz ∂z - Δt L) wⁿ⁺¹ = w★
```

where `cⁿ⁺¹` and `c★` live at cell `Center`s in the vertical,
and `wⁿ⁺¹` and `w★` lives at cell `Face`s in the vertical.
"""
function implicit_diffusion_solver(::VerticallyImplicitTimeDiscretization, grid)
    topo = topology(grid)

    topo[3] == Periodic && error("VerticallyImplicitTimeDiscretization can only be specified on " *
                                 "grids that are Bounded in the z-direction.")

    z_solver = BatchedTridiagonalSolver(grid;
                                        lower_diagonal = maybe_tupled_ivd_lower_diagonal,
                                        diagonal = ivd_diagonal,
                                        upper_diagonal = maybe_tupled_ivd_upper_diagonal)

    return z_solver
end

#####
##### Implicit step functions
#####

# Special viscosity extractors with tracer_index === nothing
@inline νzᶠᶜᶠ(i, j, k, grid, closure, K, ::Nothing, clock) = νzᶠᶜᶠ(i, j, k, grid, closure, K, clock)
@inline νzᶜᶠᶠ(i, j, k, grid, closure, K, ::Nothing, clock) = νzᶜᶠᶠ(i, j, k, grid, closure, K, clock)

is_vertically_implicit(closure) = time_discretization(closure) isa VerticallyImplicitTimeDiscretization

"""
    implicit_step!(field, implicit_solver::BatchedTridiagonalSolver,
                   closure, diffusivity_fields, tracer_index, clock, Δt;
                   dependencies)

Initialize the right hand side array `solver.batched_tridiagonal_solver.f`, and then solve the
tridiagonal system for vertically-implicit diffusion, passing the arguments
`clock, Δt, κ⁻⁻ᶠ, κ` into the coefficient functions that return coefficients of the
lower diagonal, diagonal, and upper diagonal of the resulting tridiagonal system.

`args...` are passed into `z_diffusivity` and `z_viscosity` appropriately for the purpose of retrieving
the diffusivities / viscosities associated with `closure`.
"""
function implicit_step!(field::Field,
                        implicit_solver::BatchedTridiagonalSolver,
                        closure::Union{AbstractTurbulenceClosure, AbstractArray{<:AbstractTurbulenceClosure}, Tuple},
                        diffusivity_fields,
                        tracer_index,
                        clock,
                        Δt; dependencies)

   loc = location(field)

   # << Look at all these assumptions >>
   # Or put another way, `location(field)` serves to identify velocity components.
   # Change this if `location(field)` does not uniquely identify velocity components.
   κz = # "Extractor function
       loc === (Center, Center, Center) ? κzᶜᶜᶠ :
       loc === (Face, Center, Center)   ? νzᶠᶜᶠ :
       loc === (Center, Face, Center)   ? νzᶜᶠᶠ :
       loc === (Center, Center, Face)   ? νzᶜᶜᶜ :
       error("Cannot take an implicit_step! for a field at $location")

    # Nullify tracer_index if `field` is not a tracer
    κz === κzᶜᶜᶠ || (tracer_index = nothing)

    # Filter explicit closures for closure tuples
    if closure isa Tuple
        closure_tuple = closure
        N = length(closure_tuple)
        vi_closure = Tuple(closure[n] for n = 1:N if is_vertically_implicit(closure[n]))
        vi_diffusivity_fields = Tuple(diffusivity_fields[n] for n = 1:N if is_vertically_implicit(closure[n]))
    else
        vi_closure = closure
        vi_diffusivity_fields = diffusivity_fields
    end

    return solve!(field, implicit_solver, field,
                  # ivd_*_diagonal gets called with these args after (i, j, k, grid):
                  vi_closure, vi_diffusivity_fields, tracer_index, instantiate.(loc)..., clock, Δt, κz;
                  dependencies)
end


text:
# test load order

using Caesar

fg31bd = initfg()
loadDFG(joinpath(ENV["HOME"],"Downloads/test/fg_beforedownsolve"), Main, fg31bd)

sfg31bd = buildSubgraphFromLabels!(fg31bd, [:x167;:x168;:x169;:x170])

fct = getFactor(sfg31bd, :x168x169f1)
@show getFactorType(fct)
getData(fct).fncargvID


text:
#!/usr/bin/env julia

### Test suite for NIntegration.jl

using NIntegration
using Test

### Tests

@time @testset "Integration" begin include("integration.jl") end


text:
"""
    ThermInt([rng::AbstractRNG], n_steps=30; n_samples=2000, n_warmup=500)
    ThermInt([rng::AbstractRNG], schedule; n_samples=2000, n_warmup=500)

- `schedule` can be any iterable object
- `n_steps` is the number of steps for the schedule using the formula
`(1:n_steps) ./ n_steps).^5`

A `ThermInt` object can then be used as a function:
```julia
alg = ThermInt(30)
alg(loglikelihood, logprior, x_init)
```
"""
struct ThermInt{AD,TRNG,V}
    schedule::V
    n_samples::Int
    n_warmup::Int
    rng::TRNG
end

function ThermInt(rng::AbstractRNG, schedule; n_samples::Int=2000, n_warmup::Int=500)
    return ThermInt{ADBACKEND[],typeof(rng),typeof(schedule)}(
        schedule, n_samples, n_warmup, rng
    )
end

function ThermInt(schedule; n_samples::Int=2000, n_warmup::Int=500)
    return ThermInt(GLOBAL_RNG, schedule; n_samples=n_samples, n_warmup=n_warmup)
end

function ThermInt(rng::AbstractRNG, n_steps::Int; n_samples::Int=2000, n_warmup::Int=500)
    return ThermInt(rng, ((1:n_steps) ./ n_steps) .^ 5, n_samples, n_warmup, rng)
end

function ThermInt(n_steps::Int=30; n_samples::Int=2000, n_warmup::Int=500)
    return ThermInt(
        GLOBAL_RNG, ((1:n_steps) ./ n_steps) .^ 5; n_samples=n_samples, n_warmup=n_warmup
    )
end

function (alg::ThermInt)(loglikelihood, logprior, x_init::AbstractVector)
    ΔlogZ = @showprogress [
        evaluate_loglikelihood(loglikelihood, logprior, alg, x_init, β) for
        β in alg.schedule
    ]
    return trapz(alg.schedule, ΔlogZ)
end

function evaluate_loglikelihood(loglikelihood, logprior, alg::ThermInt, x_init, β::Real)
    powerlogπ(θ) = β * loglikelihood(θ) + logprior(θ)
    samples = sample_powerlogπ(powerlogπ, alg, x_init)
    x_init .= samples[end] # Update the initial sample to be the last one of the chain
    return mean(loglikelihood, samples)
end

function sample_powerlogπ(powerlogπ, alg::ThermInt, x_init)
    D = length(x_init)
    metric = DiagEuclideanMetric(D)
    hamiltonian = get_hamiltonian(metric, powerlogπ, alg)

    initial_ϵ = find_good_stepsize(hamiltonian, x_init)
    integrator = Leapfrog(initial_ϵ)

    proposal = AdvancedHMC.NUTS{MultinomialTS,GeneralisedNoUTurn}(integrator)
    adaptor = StanHMCAdaptor(MassMatrixAdaptor(metric), StepSizeAdaptor(0.8, integrator))

    samples, stats = sample(
        alg.rng,
        hamiltonian,
        proposal,
        x_init,
        alg.n_samples,
        adaptor,
        alg.n_warmup;
        verbose=false,
        progress=false,
    )
    return samples
end

function get_hamiltonian(metric, powerlogπ, ::ThermInt{:ForwardDiff})
    return Hamiltonian(metric, powerlogπ, ForwardDiff)
end
function get_hamiltonian(metric, powerlogπ, ::ThermInt{:Zygote})
    return Hamiltonian(metric, powerlogπ, Zygote)
end
function get_hamiltonian(metric, powerlogπ, ::ThermInt{:ReverseDiff})
    return Hamiltonian(metric, powerlogπ, ReverseDiff)
end


text:
# check examples are running:
dirr = dirname(Base.source_path())
ls = split(readall(`ls $dirr`))

for l in ls
    ll = joinpath(dirr,l)
    if l[end-2:end]==".jl" && !(l=="runexamples.jl")
        println("Running example: $l")
        println("----------------")
        include(ll)
        println(" ")
        println("Finished example: $l")
        println("----------------")
        println(" ")
    end
end


text:
module AffineMapsTests

using Gridap.TensorValues
using Gridap.Arrays
using Gridap.Fields
using FillArrays
using Test

origin = Point(1,1)
g = TensorValue(2,0,0,2)

h = AffineMap(g,origin)
@test isa(∇(h),ConstantField)
@test isa(Broadcasting(∇)(h),ConstantField)

x1 = Point(0,0)
x2 = Point(1,1)
x3 = Point(2,1)
x = [x1,x2,x3]
hx = h(x)
∇hx = ∇(h)(x)

r = Point{2,Int}[(1, 1), (3, 3), (5, 3)]
∇r = TensorValue{2,2,Int,4}[(2, 0, 0, 2), (2, 0, 0, 2), (2, 0, 0, 2)]
test_field(h,x,r,grad=∇r)
test_field(h,x1,x1⋅g+origin,grad=g)

ncells = 10
cell_to_h = fill(h,ncells)
cell_to_∇h = lazy_map(Broadcasting(∇),cell_to_h)
cell_to_x = Fill(x,ncells)

cell_to_hx = lazy_map(evaluate,cell_to_h,cell_to_x)
cell_to_∇hx = lazy_map(evaluate,cell_to_∇h,cell_to_x)

test_array(cell_to_hx,fill(hx,ncells))
test_array(cell_to_∇hx,fill(∇hx,ncells))

#display(cell_to_hx)
#display(cell_to_∇hx)
#print_op_tree(cell_to_hx)
#print_op_tree(cell_to_∇hx)

#using BenchmarkTools
#
#c = return_cache(h,x)
#@btime evaluate!($c,$h,$x)
#
#c = return_cache(h,x1)
#@btime evaluate!($c,$h,$x1)

end # module


text:
# automatically generated by the FlatBuffers compiler, do not modify

MyGame.Example2.eval(quote

mutable struct Monster
end
FlatBuffers.@ALIGN(Monster, 1)

Monster(buf::AbstractVector{UInt8}) = FlatBuffers.read(Monster, buf)
Monster(io::IO) = FlatBuffers.deserialize(io, Monster)

end)

max_stars_repo_name: rjkat/flatbuffers-julia

max_issues_repo_name: rjkat/flatbuffers-julia

max_forks_repo_name: rjkat/flatbuffers-julia


text:
using Test, LinearMaps, LinearAlgebra, BenchmarkTools

@testset "scaledmap" begin
    N = 7
    A = LinearMap(cumsum, reverse ∘ cumsum ∘ reverse, N)
    AM = Matrix(A)

    # real case
    α = float(π)
    B = @inferred α * A
    @test occursin("7×7 LinearMaps.ScaledMap{Float64} with scale: $α", sprint((t, s) -> show(t, "text/plain", s), B))
    @test parent(B) == (α, A)
    x = rand(N)

    @test @inferred size(B) == size(A)
    @test @inferred isreal(B)
    @test @inferred issymmetric(B) == issymmetric(A)
    @test @inferred ishermitian(B) == ishermitian(A)
    @test @inferred isposdef(B) == isposdef(A)
    @test @inferred transpose(B) == α * transpose(A)

    @test B == A * α
    @test B * x == α * (A * x)
    @test @inferred Matrix(B) == α * Matrix(A)
    @test @inferred Matrix(B') == Matrix(B)'

    @test -A == (-1) * A

    @test A * (α * I) == B
    @test (α * I) * A == B

    # complex case
    β = π + 2π * im
    C = @inferred β * A
    @test_throws AssertionError LinearMaps.ScaledMap{Float64}(β, A)
    @inferred conj(β) * A' # needed in left-mul
    T = ComplexF64
    xc = rand(T, N)

    @test @inferred !isreal(C)
    @test @inferred !issymmetric(C)
    @test @inferred ishermitian(C) == ishermitian(A)
    @test @inferred !isposdef(C)
    @test @inferred transpose(C) == β * transpose(A)
    @test @inferred adjoint(C) == conj(β) * adjoint(A)
    for transform in (identity, transpose, adjoint)
        @test transform(C) * xc ≈ transform(β * AM) * xc
    end

    @test C == @inferred A * β
    @test convert(Array{T}, C * xc) ≈ β * (A * xc)
    @test @inferred Matrix(C) == β * Matrix(A)
    @test @inferred Matrix(adjoint(C)) == conj(β) * Matrix(adjoint(A))
    @test @inferred Matrix(C') == Matrix(C)'

    # composition
    BA = @inferred B*A
    @test BA isa LinearMaps.ScaledMap
    @test BA.λ == B.λ
    AB = @inferred A*B
    @test AB isa LinearMaps.ScaledMap
    @test AB.λ == B.λ
    BC = @inferred B * C
    @test BC isa LinearMaps.ScaledMap
    @test BC.λ == α * β
    @test Matrix(BC) ≈ α * β * Matrix(A) * Matrix(A)

    @test Matrix(@inferred α * BC) ≈ α * Matrix(BC)
    @test Matrix(@inferred BC * β) ≈ β * Matrix(BC)

    # in-place
    y1 = β * (A * xc)
    y2 = similar(y1)
    @test mul!(y2, C, xc) == y1

    x1 = conj(β) * (A' * y1)
    x2 = similar(x1)
    @test mul!(x2, C', y1) == x1

    # check scale*conj(scale)
    A = LinearMap{Float32}(rand(N, 2)) # rank=2 w.p.1
    B = @inferred β * A
    C = @inferred B' * B
    @test @inferred isposdef(C)

    N = 2^8
    A0 = LinearMap{T}(cumsum, reverse ∘ cumsum ∘ reverse, N) # out-of-place
    forw! = cumsum!
    back! = (x, y) -> reverse!(cumsum!(x, reverse!(copyto!(x, y))))
    A1 = @inferred LinearMap{T}(forw!, back!, N) # in-place
    λ = 4.2
    B0 = @inferred λ * A0
    B1 = @inferred λ * A1
    for (A, alloc) in ((A0, 1), (A1, 0), (B0, 1), (B1, 0), (A0', 3), (A1', 0), (B0', 3), (B1', 0))
        x = rand(N)
        y = similar(x)
        b = @benchmarkable mul!($y, $A, $x)
        @test run(b, samples = 3).allocs <= alloc
    end
end


text:
using Test

println("Running tests:")

for x in (:CampbellCochrane, :Wachter, :BansalYaron, :GarleanuPanageas, :DiTella, :Haddad, :ArbitrageHoldingCosts)
	try
		include("../examples/AssetPricing/$(x).jl")
		println("\t\033[1m\033[32mPASSED\033[0m: $(x)")
	catch e
		println("\t\033[1m\033[31mFAILED\033[0m: $(x)")
		showerror(stdout, e, backtrace())
		rethrow(e)
	end
end

for x in (:WangWangYang, :AchdouHanLasryLionsMoll_OneAsset, :AchdouHanLasryLionsMoll_TwoAssets)
	try
		include("../examples/ConsumptionProblem/$(x).jl")
		println("\t\033[1m\033[32mPASSED\033[0m: $(x)")
	catch e
		println("\t\033[1m\033[31mFAILED\033[0m: $(x)")
		showerror(stdout, e, backtrace())
		rethrow(e)
	end
end

for x in (:BoltonChenWang, )
	try
		include("../examples/InvestmentProblem/$(x).jl")
		println("\t\033[1m\033[32mPASSED\033[0m: $(x)")
	catch e
		println("\t\033[1m\033[31mFAILED\033[0m: $(x)")
		showerror(stdout, e, backtrace())
		rethrow(e)
	end
end

for x in (:Leland, )
	try
		include("../examples/OptimalStoppingTime/$(x).jl")
		println("\t\033[1m\033[32mPASSED\033[0m: $(x)")
	catch e
		println("\t\033[1m\033[31mFAILED\033[0m: $(x)")
		showerror(stdout, e, backtrace())
		rethrow(e)
	end
end


text:
using ArrayViewsAPL, Base.Test

# subview
A = reshape(1:120, 3, 5, 8)
sA = subview(A, 2, 1:5, :)
@test parent(sA) == A
@test parentindexes(sA) == (2:2, 1:5, 1:8)
@test Base.parentdims(sA) == [1:3]
@test size(sA) == (1, 5, 8)
@test_throws BoundsError sA[2, 1:8]
@test sA[1, 2, 1:8][:] == [5:15:120]
sA[2:5:end] = -1
@test all(sA[2:5:end] .== -1)
@test all(A[5:15:120] .== -1)
@test strides(sA) == (1,3,15)
@test stride(sA,3) == 15
@test stride(sA,4) == 120
sA = subview(A, 1:3, 1:5, 5)
@test Base.parentdims(sA) == [1:2]
sA[1:3,1:5] = -2
@test all(A[:,:,5] .== -2)
sA[:] = -3
@test all(A[:,:,5] .== -3)
@test strides(sA) == (1,3)
sA = subview(A, 1:3, 3, 2:5)
@test Base.parentdims(sA) == [1:3]
@test size(sA) == (3,1,4)
@test sA == A[1:3,3,2:5]
@test sA[:] == A[1:3,3,2:5][:]
sA = subview(A, 1:2:3, 1:3:5, 1:2:8)
@test Base.parentdims(sA) == [1:3]
@test strides(sA) == (2,9,30)
@test sA[:] == A[1:2:3, 1:3:5, 1:2:8][:]

# subview logical indexing #4763
A = subview([1:10], 5:8)
@test A[A.<7] == [5, 6]
B = reshape(1:16, 4, 4)
sB = subview(B, 2:3, 2:3)
@test sB[sB.>8] == [10, 11]

# sliceview
A = reshape(1:120, 3, 5, 8)
sA = sliceview(A, 2, :, 1:8)
@test parent(sA) == A
@test parentindexes(sA) == (2, 1:5, 1:8)
@test Base.parentdims(sA) == [2:3]
@test size(sA) == (5, 8)
@test strides(sA) == (3,15)
@test sA[2, 1:8][:] == [5:15:120]
@test sA[:,1] == [2:3:14]
@test sA[2:5:end] == [5:15:110]
sA[2:5:end] = -1
@test all(sA[2:5:end] .== -1)
@test all(A[5:15:120] .== -1)
sA = sliceview(A, 1:3, 1:5, 5)
@test Base.parentdims(sA) == [1:2]
@test size(sA) == (3,5)
@test strides(sA) == (1,3)
sA = sliceview(A, 1:2:3, 3, 1:2:8)
@test Base.parentdims(sA) == [1,3]
@test size(sA) == (2,4)
@test strides(sA) == (2,30)
@test sA[:] == A[sA.indexes...][:]

a = [5:8]
@test parent(a) == a
@test parentindexes(a) == (1:4,)

# # Out-of-bounds construction. See #4044
# A = rand(7,7)
# rng = 1:4
# sA = subview(A, 2, rng-1)
# @test_throws BoundsError sA[1,1]
# @test sA[1,2] == A[2,1]
# sA = subview(A, 2, rng)
# B = subview(sA, 1, rng-1)
# C = subview(B, 1, rng+1)
# @test C == sA
# sA = sliceview(A, 2, rng-1)
# @test_throws BoundsError sA[1]
# @test sA[2] == A[2,1]
# sA = sliceview(A, 2, rng)
# B = sliceview(sA, rng-1)
# C = subview(B, rng+1)
# @test C == sA

# issue #6218 - logical indexing
A = rand(2, 2, 3)
msk = ones(Bool, 2, 2)
msk[2,1] = false
sA = subview(A, :, :, 1)
sA[msk] = 1.0
@test sA[msk] == ones(countnz(msk))

# of a subarray
a = rand(5,5)
s = subview(a,2:3,2:3)
# p = permutedims(s, [2,1])
# @test p[1,1]==a[2,2] && p[1,2]==a[3,2]
# @test p[2,1]==a[2,3] && p[2,2]==a[3,3]

## large matrices transpose ##

for i = 1 : 3
    a = rand(200, 300)
    @test isequal(a', permutedims(a, [2, 1]))
end

begin
    local A, A1, A2, A3, v, v2, cv, cv2, c, R, T

    A = rand(4,4)
    for s in {A[1:2:4, 1:2:4], subview(A, 1:2:4, 1:2:4)}
        c = cumsum(s, 1)
        @test c[1,1] == A[1,1]
        @test c[2,1] == A[1,1]+A[3,1]
        @test c[1,2] == A[1,3]
        @test c[2,2] == A[1,3]+A[3,3]

        c = cumsum(s, 2)
        @test c[1,1] == A[1,1]
        @test c[2,1] == A[3,1]
        @test c[1,2] == A[1,1]+A[1,3]
        @test c[2,2] == A[3,1]+A[3,3]
    end
end

# fill
@test fill!(Array(Float64,1),-0.0)[1] === -0.0
A = ones(3,3)
S = subview(A, 2, 1:3)
fill!(S, 2)
S = subview(A, 1:2, 3)
fill!(S, 3)
@test A == [1 1 3; 2 2 3; 1 1 1]
rt = Base.return_types(fill!, (Array{Int32, 3}, Uint8))
@test length(rt) == 1 && rt[1] == Array{Int32, 3}


text:
#gtk_top.jl: Top-level gtk functionnality
#-------------------------------------------------------------------------------

#==Constants
===============================================================================#
const MSG_DELETE = "Supprimer dernière entrée"

#==Types
===============================================================================#

#==Helper functions
===============================================================================#
function _subjects_updatecb(explore::ExploreWnd)
	ensure_updating(explore) #Inhibit infinite recursion
	sel = explore.sel #Alias
	subject_list = read_subjects(explore.db)
		if length(subject_list)<1; subject_list = ["Français"]; end
		empty!(explore.cb_subjects)
		for v in subject_list
		  push!(explore.cb_subjects, v)
		end
		idx = findfirst((x)->(sel.subject==x), subject_list)
		if isnothing(idx); idx = 1; end
		set_gtk_property!(explore.cb_subjects, "active", idx-1) #Set active element
	return
end
function subjects_updatecb(::WSNormal, explore::ExploreWnd)
	state_set!(explore, WSUpdating())
	try
		_subjects_updatecb(explore)
	catch e #Should not happen
		@warn(e)
		rethrow(e)
	finally #Make sure we recover
		state_set!(explore, WSNormal())
	end
	return
end

#==GUI scanners/builders
===============================================================================#
function _scan(explore::ExploreWnd)
	sel = explore.sel #Alias
		sel.grade_idx = 1
		sel.domain_idx = 1
		sel.attente_idx = 1
		sel.content_idx = 1

	sel_subject = GAccessor.active_text(explore.cb_subjects)
	sel.subject = (sel_subject != C_NULL) ? unsafe_string(sel_subject) : ""

	for (idx, rb) in enumerate(explore.rb_grade_list)
		if GAccessor.active(rb)
			sel.grade_idx = idx
			break
		end
	end
		#gtk_toggle_button_set_active(e, active::Bool)

	_sel = GAccessor.selection(explore.tv_domains)
	if Gtk.hasselection(_sel)
		elem = explore.ls_domains[Gtk.selected(_sel)]
		sel.domain_idx = elem[1]
	end

	_sel = GAccessor.selection(explore.tv_attentes)
	if Gtk.hasselection(_sel)
		elem = explore.ls_attentes[Gtk.selected(_sel)]
		sel.attente_idx = elem[1]
	end

	_sel = GAccessor.selection(explore.tv_content)
	if Gtk.hasselection(_sel)
		elem = explore.ls_content[Gtk.selected(_sel)]
		sel.content_idx = elem[1]
	end

#@show _sel
#	_sel = GAccessor.selection(explore.cb_subjects)
#	@show Gtk.selected(_sel)

#	@show sel
	return sel
end

function _populate(explore::ExploreWnd)
	_subjects_updatecb(explore) #calls ensure_updating
	sel = explore.sel #Alias

	sel.grade_idx = max(1, min(sel.grade_idx, length(explore.rb_grade_list)))
	Gtk.gtk_toggle_button_set_active(explore.rb_grade_list[sel.grade_idx], true)

	sdinfo = read_sourcedoc(explore.db, sel)
		if isnothing(sdinfo); sdinfo = MSG_NODATA; end
		set_gtk_property!(explore.ent_sourcedoc, "text", sdinfo)

	dlist = read_domain_list(explore.db, sel)
		if isnothing(dlist)||isempty(dlist); dlist = [DATA_NODOMAIN]; end
		sel.domain_idx = clamp(sel.domain_idx, 1, length(dlist))
		empty!(explore.ls_domains)
		for d in dlist
			push!(explore.ls_domains, d)
		end
		iter = Gtk.iter_from_index(explore.ls_domains, sel.domain_idx) #1-based wrapper!
		Gtk.select!(GAccessor.selection(explore.tv_domains), iter)

	alist = read_attente_list(explore.db, sel)
		if isnothing(alist)||isempty(alist); alist = [DATA_NOATTENTE]; end
		sel.attente_idx = clamp(sel.attente_idx, 1, length(alist))
		descr = ""
		empty!(explore.ls_attentes)
		for a in alist
			push!(explore.ls_attentes, a)
		end
		iter = Gtk.iter_from_index(explore.ls_attentes, sel.attente_idx) #1-based wrapper!
		Gtk.select!(GAccessor.selection(explore.tv_attentes), iter)
		descr = alist[sel.attente_idx][4]
		set_gtk_property!(explore.ent_attentesdesc, "text", descr)

	clist = read_content_list(explore.db, sel)
		if isnothing(clist)||isempty(clist); clist = [DATA_NOCONTENT]; end
		sel.content_idx = clamp(sel.content_idx, 1, length(clist))
		descr = ""
		empty!(explore.ls_content)
		for c in clist
			push!(explore.ls_content, c)
		end
		iter = Gtk.iter_from_index(explore.ls_content, sel.content_idx) #1-based wrapper!
		Gtk.select!(GAccessor.selection(explore.tv_content), iter)

	return
end

#==State-dependent functions
===============================================================================#
function refresh!(::WSNormal, explore::ExploreWnd)
	state_set!(explore, WSUpdating())
	try
		_scan(explore)
		_populate(explore)
		if isa(explore.editdlg, ExploreEditDlg)
			show_editdlg(explore)
		end
	catch e
		@warn(e)
		rethrow(e)
	finally
		state_set!(explore, WSNormal())
	end
	return
end

#==Callback wrapper functions
===============================================================================#
@guarded function cb_wnddestroyed(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	close(explore.db)
	@info("Fermeture de données")
	close(explore.editdlg)
	return #Known value
end
@guarded function cb_mnufileclose(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	close(explore)
	nothing #Known value
end
@guarded function cb_mnucopy(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	opt = FieldViewOpts()
	afview = _activefieldview(explore)
	copystr = copyfv(afview, explore, opt)
	clipboard_set_text(explore, copystr)
	@info("Copié:\n$copystr")
	nothing #Known value
end
@guarded function cb_mnucopyall(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	opt = FieldViewOpts()
	afview = _activefieldview(explore)
	copystr = copyallfv(afview, explore, opt)
	clipboard_set_text(explore, copystr)
	@info("Copié tout:\n$copystr")
	nothing #Known value
end
@guarded function cb_mnuaddsubject(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	subject = dialog_inputbox("Nouveau sujet:", "")
	if isnothing(subject); return; end
	if isempty_subject(subject); return; end

	sel = deepcopy(explore.sel)
	sel.subject = subject
	createslot_subject(explore.db, sel)
	explore.sel.subject = subject #Make active
	subjects_updatecb(explore) #Make active before "scanning" interface for current value
	refresh!(explore)
	nothing
end
@guarded function cb_mnuaddentry(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	afview = _activefieldview(explore)
	try
		addentry(afview, explore.db, explore.sel)
	catch e
		@warn(e)
	end
	refresh!(explore)
	nothing #Known value
end
@guarded function cb_mnuremoveentry(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	afview = _activefieldview(explore)
	id = getlabelledid(afview, explore.sel)
	if !isremovable(afview)
		@warn(string("$id: ", MSG_CANNOTREMOVE))
		return
	end

	proceed = dialog_confirm(string(MSG_DELETE, " ($id)?"))
	if !proceed; return; end
	try
		removelastentry(afview, explore.db, explore.sel)
	catch e
		@warn(e)
	end
	refresh!(explore)
	nothing #Known value
end
@guarded function cb_mnueditfield(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	show_editdlg(explore)
	nothing #Known value
end
@guarded function cb_cb_subjects_changed(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	refresh!(explore)
	return #Known value
end
@guarded function cb_rb_gradelist_changed(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	refresh!(explore)
	return #Known value
end
@guarded function cb_sel_domains_changed(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	refresh!(explore)
	return #Known value
end
@guarded function cb_sel_attentes_changed(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	refresh!(explore)
	return #Known value
end
@guarded function cb_sel_content_changed(w::Ptr{Gtk.GObject}, explore::ExploreWnd)
	refresh!(explore)
	return #Known value
end
@guarded function cb_field_focus_changed(w::Ptr{Gtk.GObject}, event::Ptr{Nothing}, explore::ExploreWnd)
	#Ptr{Nothing}: GdkEventFocus not implementd, so crashes if we don't handle event as pointer!

	#Purpose: Want to update contents of ExploreEditDlg:
	refresh!(explore) #Excessive, but easier/safer
	return Cint(true) #Continue handling events
end

#=="Constructors"
===============================================================================#

function ExploreWnd(dbpath=PATH_DB[])
	#Rendering types for tree views:
	#rTog = _Gtk.CellRendererToggle()
	rTxt = _Gtk.CellRendererText()
		#@show get_gtk_property(rTxt, "yalign")
		set_gtk_property!(rTxt, "yalign", 0)
	rTxt_mline = _Gtk.CellRendererText()
		set_gtk_property!(rTxt_mline, "wrap-width", 400) #Could update with wndsize
		set_gtk_property!(rTxt_mline, "yalign", 0)

	vbox = _Gtk.Box(true, 0) #Main vbox for all widgets

	#Menu bar:
	mb = _Gtk.MenuBar()
		push!(vbox, mb) #Menu bar
	mnufile = Gtk_addmenu(mb, "_Fichier")
		Gtk_addsep(mnufile)
		mnuquit = Gtk_addmenuitem(mnufile, "_Quitter")
	mnuedit = Gtk_addmenu(mb, "_Édition")
		mnucopy = Gtk_addmenuitem(mnuedit, "Copier")
		mnucopyall = Gtk_addmenuitem(mnuedit, "Copier Tout")
		Gtk_addsep(mnuedit)
		mnuaddsubject = Gtk_addmenuitem(mnuedit, "Nouveau Sujet")
		Gtk_addsep(mnuedit)
		mnuaddentry = Gtk_addmenuitem(mnuedit, "Ajouter Entrée")
		mnuremoveentry = Gtk_addmenuitem(mnuedit, "Supprimer Dernière Entrée")
		mnueditfield = Gtk_addmenuitem(mnuedit, "Modifier Élément/Champ")

	#Add accelerator keys to menu items:
	accel_group = Gtk.GtkAccelGroupLeaf()
		push!(mnucopy, "activate", accel_group, GConstants.GDK_KEY_F,
			GdkModifierType.CONTROL, GtkAccelFlags.VISIBLE
		)
		push!(mnucopyall, "activate", accel_group, GConstants.GDK_KEY_F,
			GdkModifierType.GDK_CONTROL_MASK|GdkModifierType.SHIFT, GtkAccelFlags.VISIBLE
		)
		push!(mnuaddentry, "activate", accel_group, GConstants.GDK_KEY_KP_Add,
			GdkModifierType.GDK_CONTROL_MASK, GtkAccelFlags.VISIBLE
		)
		push!(mnuremoveentry, "activate", accel_group, GConstants.GDK_KEY_KP_Subtract,
			GdkModifierType.GDK_CONTROL_MASK, GtkAccelFlags.VISIBLE
		)
		push!(mnueditfield, "activate", accel_group, GConstants.GDK_KEY_E,
			GdkModifierType.GDK_CONTROL_MASK, GtkAccelFlags.VISIBLE
		)

	cb_subjects = _Gtk.ComboBoxText(false) #No entry
		push!(vbox, cb_subjects)

	#Radio buttons for grade:
	grp_grades = _Gtk.RadioButtonGroup()
		set_gtk_property!(grp_grades.handle, "orientation", GtkOrientation.HORIZONTAL)
		push!(vbox, grp_grades)
		rb_grade_list = _Gtk.RadioButton[]

		for (i, id) in enumerate(LIST_GRADEID)
			rb = _Gtk.RadioButton(id)
			push!(rb_grade_list, rb)
			push!(grp_grades, rb)
		end
		#gtk_toggle_button_set_active(e, active::Bool)

	#Textbox for source documentation info:
	ent_sourcedoc = _Gtk.Entry()
		push!(vbox, ent_sourcedoc)
		set_gtk_property!(ent_sourcedoc, "text", "")
		set_gtk_property!(ent_sourcedoc, "editable", false)

	#List for domain:
	ls_domains = _Gtk.ListStore(Int, String, String) #index, id, domain
	tv_domains = _Gtk.TreeView(_Gtk.TreeModel(ls_domains))
		c1 = _Gtk.TreeViewColumn("ID", rTxt, Dict("text"=>1))
		c2 = _Gtk.TreeViewColumn("Domaine", rTxt, Dict("text"=>2))
		push!(tv_domains, c1, c2)

	#List for "attentes":
	ls_attentes = _Gtk.ListStore(Int, String, String, String) #index, id, shortdescr, descr
	tv_attentes = _Gtk.TreeView(_Gtk.TreeModel(ls_attentes))
		c1 = _Gtk.TreeViewColumn("ID", rTxt, Dict("text"=>1))
		c2 = _Gtk.TreeViewColumn("Attente", rTxt, Dict("text"=>2))
		push!(tv_attentes, c1, c2)

	pane_da = _Gtk.Paned(false, 0) #_Gtk.Box(false, 0) #hbox for domains & "attentes"
		push!(vbox, pane_da)
		#Use scrolled windows to inhibit "natural" width (allow smaller)
		swleft = _Gtk.ScrolledWindow()
			push!(swleft, tv_domains)
			GAccessor.policy(swleft, GtkPolicyType.EXTERNAL, GtkPolicyType.NEVER)
		swright = _Gtk.ScrolledWindow()
			push!(swright, tv_attentes)
			GAccessor.policy(swright, GtkPolicyType.EXTERNAL, GtkPolicyType.NEVER)
		push!(pane_da, swleft, swright)
		set_gtk_property!(pane_da, "position", 250)
		set_gtk_property!(pane_da, "position-set", true)
		set_gtk_property!(pane_da, "wide-handle", true)

	#Textbox for "attentes" description:
	ent_attentesdesc = _Gtk.Entry()
		push!(vbox, ent_attentesdesc)
		set_gtk_property!(ent_attentesdesc, "text", "")
		set_gtk_property!(ent_attentesdesc, "editable", false)

	#List for content:
	swnd = _Gtk.ScrolledWindow() #Inhibit "natural" width
		push!(vbox, swnd)
	ls_content = _Gtk.ListStore(Int, String, String) #index, id, description
	tv_content = _Gtk.TreeView(_Gtk.TreeModel(ls_content))
		push!(swnd, tv_content)
			GAccessor.policy(swnd, GtkPolicyType.EXTERNAL, GtkPolicyType.ALWAYS)
		c1 = _Gtk.TreeViewColumn("ID", rTxt, Dict("text"=>1))
		c2 = _Gtk.TreeViewColumn("Contenu d'apprentissage", rTxt_mline, Dict("text"=>2))
		push!(tv_content, c1, c2)
		set_gtk_property!(tv_content, "vexpand", true)

	#Set single-selction ("browse"):
	for w in (tv_content, tv_content, tv_content)
		sel = GAccessor.selection(w)
		sel = GAccessor.mode(sel, GtkSelectionMode.BROWSE)
	end

	#Create container object & callbacks:
	db = open_database(dbpath, "r+")
	wnd = Gtk.Window(vbox, "", 640, 480, true)
		push!(wnd, accel_group)
		set_gtk_property!(wnd, "title", "ExploreCMEO")

	explore = ExploreWnd(WSNormal(), ExploreSelection(), db,
		wnd, cb_subjects, rb_grade_list, ent_sourcedoc,
		ls_domains, tv_domains, ls_attentes, tv_attentes, ent_attentesdesc,
		ls_content, tv_content, NoDialog()
	)
	signal_connect(cb_wnddestroyed, wnd, "destroy", Nothing, (), false, explore)
	signal_connect(cb_mnufileclose, mnuquit, "activate", Nothing, (), false, explore)
	signal_connect(cb_mnucopy, mnucopy, "activate", Nothing, (), false, explore)
	signal_connect(cb_mnucopyall, mnucopyall, "activate", Nothing, (), false, explore)
	signal_connect(cb_mnuaddsubject, mnuaddsubject, "activate", Nothing, (), false, explore)
	signal_connect(cb_mnuaddentry, mnuaddentry, "activate", Nothing, (), false, explore)
	signal_connect(cb_mnuremoveentry, mnuremoveentry, "activate", Nothing, (), false, explore)
	signal_connect(cb_mnueditfield, mnueditfield, "activate", Nothing, (), false, explore)

	signal_connect(cb_cb_subjects_changed, cb_subjects, "changed", Nothing, (), false, explore)
	for rb in rb_grade_list
		signal_connect(cb_rb_gradelist_changed, rb, "toggled", Nothing, (), false, explore)
	end
	sel_domains = GAccessor.selection(explore.tv_domains)
	signal_connect(cb_sel_domains_changed, sel_domains, "changed", Nothing, (), false, explore)
	sel_attentes = GAccessor.selection(explore.tv_attentes)
	signal_connect(cb_sel_attentes_changed, sel_attentes, "changed", Nothing, (), false, explore)
	sel_content = GAccessor.selection(explore.tv_content)
	signal_connect(cb_sel_content_changed, sel_content, "changed", Nothing, (), false, explore)

	for w in [cb_subjects, grp_grades, ent_sourcedoc, tv_domains, tv_attentes, tv_content]
		signal_connect(cb_field_focus_changed, w, "focus-in-event", Cint, (Ptr{Nothing},), false, explore)
	end

	#Populate, show & return:
	refresh!(explore)
	Gtk.showall(explore.wnd)
	return explore
end


text:
#=
Implement a stack that has the following methods:

    push(val), which pushes an element onto the stack
    pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null.
    max(), which returns the maximum value in the stack currently. If there are no elements in the stack, then it should throw an error or return null.

Each method should run in constant time.
=#

global stack = []

function push(val)
    global stack = vcat(stack, val)
end

function pop()
    if length(stack) == 0
        return nothing
    else
        out = stack[end]
        global stack = stack[1:end-1]
        return out
    end
end

function max()
    if length(stack) == 0
        return nothing
    else
        return maximum(stack)
    end
end

max_stars_repo_name: DominiqueCaron/daily-coding-problem

max_issues_repo_name: DominiqueCaron/daily-coding-problem

max_forks_repo_name: DominiqueCaron/daily-coding-problem


text:
using IcanProj
using JLD2
using PyPlot

"""
Plot results over elevation for resolutions 1 to 25km.
"""
function plot_elevation(opt, var_name, ylabel_name, scaling)

    ioff()

    # Loop over watersheds

    for watershed in opt["stat_sel"]

        fig = figure(figsize=(12, 12))

        subplots_adjust(hspace = 0.0)

        data_min, data_max = 0, 0
        elev_min, elev_max = 0, 0

        res_vic = []

        # Loop over resolutions

        i = 1

        for resolution in opt["resolutions"][1:4]

            # Load results

            file = joinpath(opt["eval_folder"], watershed, "res_$(resolution).jld2")

            @load file res_vic

            # Get variables

            if var_name == "total_runoff"

                irunoff = find(res_vic.var_names .== "runoff")
                ibaseflow = find(res_vic.var_names .== "baseflow")

                data_runoff = res_vic.data_all[:,irunoff[1],:]
                data_baseflow = res_vic.data_all[:,ibaseflow[1],:]

                data_all = data_runoff + data_baseflow

            else

                ivar = find(res_vic.var_names .== var_name)

                data_all = res_vic.data_all[:,ivar[1],:]

            end

            # Average data for each grid

            data_mean = mean(data_all,1)[1,:]

            # Get range from of variables

            if resolution == "1km"
                data_min = minimum(data_mean)
                data_max = maximum(data_mean)
                elev_min = minimum(res_vic.elev)
                elev_max = maximum(res_vic.elev)
            end

            # Plot data against elevation

            ax = fig[:add_subplot]("41$(i)")

            scatter(data_mean*scaling, res_vic.elev)
            axvline(mean(data_mean)*scaling, color = "red")

            xlabel(ylabel_name)
            ylabel("Elevation (m)")

            ax[:set_xlim]([data_min*scaling, data_max*scaling])
            ax[:set_ylim]([elev_min, elev_max])

            if resolution == "1km"
                title(res_vic.name)
            end

            i += 1

        end

        file_name = Pkg.dir("IcanProj", "plots", "elevation_$(var_name)_$(watershed).png")

        rm(file_name, force=true)
        savefig(file_name, dpi = 300)

        close(fig)

    end

end

# Get options

opt = get_options()

info("Plot evapotranspiration")

var_name = "evap"
ylabel_name = "Evapotranspiration (mm/year)"
scaling = 365

plot_elevation(opt, var_name, ylabel_name, scaling)

info("Plot precipitation")

var_name = "prec"
ylabel_name = "Precipitation (mm/year)"
scaling = 365

plot_elevation(opt, var_name, ylabel_name, scaling)

info("Plot snow water equivalent")

var_name = "swe"
ylabel_name = "Snow water equivalent (mm)"
scaling = 1

plot_elevation(opt, var_name, ylabel_name, scaling)

info("Plot total runoff")

var_name = "total_runoff"
ylabel_name = "Total runoff (mm/year)"
scaling = 365

plot_elevation(opt, var_name, ylabel_name, scaling)

info("Plot wind speed")

var_name = "wind"
ylabel_name = "Wind speed (m/s)"
scaling = 1

plot_elevation(opt, var_name, ylabel_name, scaling)

info("Plot air temperature")

var_name = "air_temp"
ylabel_name = "Air temperature (C)"
scaling = 1

plot_elevation(opt, var_name, ylabel_name, scaling)

info("Plot rainfall")

var_name = "rainf"
ylabel_name = "Rainfall (mm/year)"
scaling = 365

plot_elevation(opt, var_name, ylabel_name, scaling)

info("Plot snowfall")

var_name = "snowf"
ylabel_name = "Snowfall (mm/year)"
scaling = 365

plot_elevation(opt, var_name, ylabel_name, scaling)

info("Plot potential evapotranspiration")

var_name = "pet_short"
ylabel_name = "PET short crop (mm/year)"
scaling = 365

plot_elevation(opt, var_name, ylabel_name, scaling)


text:
@calibration :ONDA_AH_2020_100_1238 [
000.0500 18.82 43.83 7.08
000.0510 18.84 42.97 7.08
000.0520 18.86 42.16 7.08
000.0530 18.88 41.38 7.08
000.0540 18.90 40.64 7.08
000.0550 18.91 39.91 7.08
000.0560 18.93 39.22 7.08
000.0570 18.95 38.48 7.08
000.0580 18.96 37.79 7.08
000.0590 18.97 37.20 7.08
000.0600 18.99 36.66 7.08
000.0610 19.00 36.05 7.08
000.0620 19.01 35.44 7.08
000.0630 19.01 34.88 7.08
000.0640 19.03 34.40 7.08
000.0650 19.03 33.91 7.08
000.0660 19.04 33.41 7.08
000.0670 19.04 32.93 7.08
000.0680 19.04 32.48 7.08
000.0690 19.05 32.06 7.08
000.0700 19.05 31.67 7.08
000.0710 19.05 31.29 7.08
000.0720 19.06 30.92 7.08
000.0730 19.07 30.53 7.08
000.0740 19.08 30.14 7.08
000.0750 19.08 29.78 7.08
000.0760 19.09 29.44 7.08
000.0770 19.09 29.14 7.08
000.0780 19.10 28.84 7.08
000.0790 19.11 28.55 7.08
000.0800 19.11 28.27 7.08
000.0810 19.12 27.99 7.08
000.0820 19.12 27.72 7.08
000.0830 19.13 27.45 7.08
000.0840 19.14 27.18 7.08
000.0850 19.15 26.90 7.08
000.0860 19.16 26.67 7.08
000.0870 19.17 26.44 7.08
000.0880 19.18 26.24 7.08
000.0890 19.19 26.04 7.08
000.0900 19.20 25.81 7.08
000.0910 19.20 25.57 7.08
000.0920 19.22 25.31 7.08
000.0930 19.23 25.05 7.08
000.0940 19.24 24.85 7.08
000.0950 19.25 24.68 7.08
000.0960 19.26 24.49 7.08
000.0970 19.27 24.28 7.08
000.0980 19.28 24.06 7.08
000.0990 19.28 23.85 7.08
000.1000 19.28 23.64 7.08
000.1100 19.39 21.80 7.08
000.1200 19.46 20.11 7.08
000.1300 19.50 18.67 7.08
000.1400 19.54 17.37 7.08
000.1500 19.57 16.24 7.08
000.1600 19.60 15.24 7.08
000.1700 19.63 14.39 7.08
000.1800 19.65 13.57 7.08
000.1900 19.66 12.88 7.08
000.2000 19.68 12.25 7.08
000.2100 19.69 11.69 7.08
000.2200 19.69 11.15 7.08
000.2300 19.70 10.64 7.08
000.2400 19.72 10.26 7.08
000.2500 19.73 9.78 7.08
000.2600 19.73 9.41 7.08
000.2700 19.75 9.10 7.08
000.2800 19.75 8.80 7.08
000.2900 19.76 8.46 7.08
000.3000 19.76 8.18 7.08
000.3100 19.76 7.95 7.08
000.3200 19.77 7.63 7.08
000.3300 19.77 7.42 7.08
000.3400 19.78 7.23 7.08
000.3500 19.79 6.96 7.08
000.3600 19.78 6.78 7.08
000.3700 19.79 6.55 7.08
000.3800 19.80 6.39 7.08
000.3900 19.80 6.21 7.08
000.4000 19.80 6.10 7.08
000.4100 19.80 5.88 7.08
000.4200 19.81 5.77 7.08
000.4300 19.81 5.65 7.08
000.4400 19.81 5.48 7.08
000.4500 19.82 5.33 7.08
000.4600 19.82 5.19 7.08
000.4700 19.81 5.04 7.08
000.4800 19.82 4.96 7.08
000.4900 19.83 4.88 7.08
000.5000 19.83 4.76 7.08
000.5100 19.84 4.64 7.08
000.5200 19.84 4.54 7.08
000.5300 19.84 4.42 7.08
000.5400 19.84 4.28 7.08
000.5500 19.84 4.22 7.08
000.5600 19.84 4.12 7.08
000.5700 19.84 4.06 7.08
000.5800 19.85 3.98 7.08
000.5900 19.85 3.86 7.08
000.6000 19.85 3.71 7.08
000.6100 19.86 3.66 7.08
000.6200 19.86 3.63 7.08
000.6300 19.85 3.53 7.08
000.6400 19.86 3.47 7.08
000.6500 19.86 3.38 7.08
000.6600 19.87 3.26 7.08
000.6700 19.87 3.21 7.08
000.6800 19.87 3.16 7.08
000.6900 19.87 3.11 7.08
000.7000 19.88 3.03 7.08
000.7100 19.88 2.95 7.08
000.7200 19.88 2.91 7.08
000.7300 19.88 2.86 7.08
000.7400 19.88 2.80 7.08
000.7500 19.88 2.72 7.08
000.7600 19.89 2.63 7.08
000.7700 19.89 2.58 7.08
000.7800 19.89 2.54 7.08
000.7900 19.89 2.52 7.08
000.8000 19.89 2.46 7.08
000.8100 19.90 2.38 7.08
000.8200 19.90 2.33 7.08
000.8300 19.90 2.29 7.08
000.8400 19.90 2.21 7.08
000.8500 19.90 2.12 7.08
000.8600 19.91 2.08 7.08
000.8700 19.91 2.04 7.08
000.8800 19.91 2.02 7.08
000.8900 19.90 2.00 7.08
000.9000 19.91 1.94 7.08
000.9100 19.91 1.89 7.08
000.9200 19.91 1.83 7.08
000.9300 19.92 1.78 7.08
000.9400 19.92 1.74 7.08
000.9500 19.92 1.70 7.08
000.9600 19.92 1.65 7.08
000.9700 19.92 1.59 7.08
000.9800 19.92 1.54 7.08
000.9900 19.92 1.49 7.08
001.0000 19.92 1.44 7.08
001.1000 19.93 1.07 7.08
001.2000 19.94 0.69 7.08
001.3000 19.95 0.35 7.08
001.4000 19.96 0.05 7.08
001.5000 19.96 -0.24 7.08
001.6000 19.98 -0.56 7.08
001.7000 19.98 -0.83 7.08
001.8000 19.99 -1.13 7.08
001.9000 19.99 -1.40 7.08
002.0000 20.00 -1.70 7.08
002.1000 19.99 -1.96 7.08
002.2000 19.99 -2.22 7.08
002.3000 19.99 -2.41 7.08
002.4000 19.99 -2.62 7.08
002.5000 19.99 -2.85 7.08
002.6000 20.00 -3.06 7.09
002.7000 19.99 -3.28 7.09
002.8000 20.00 -3.54 7.09
002.9000 19.99 -3.70 7.09
003.0000 19.98 -3.89 7.09
003.1000 19.98 -4.04 7.09
003.2000 19.98 -4.30 7.09
003.3000 19.97 -4.49 7.09
003.4000 19.98 -4.72 7.09
003.5000 19.99 -4.92 7.09
003.6000 19.98 -5.09 7.09
003.7000 19.98 -5.24 7.09
003.8000 19.98 -5.52 7.09
003.9000 19.97 -5.63 7.09
004.0000 19.97 -5.84 7.09
004.1000 19.97 -6.01 7.09
004.2000 19.98 -6.19 7.09
004.3000 19.98 -6.38 7.09
004.4000 19.98 -6.58 7.09
004.5000 19.97 -6.73 7.09
004.6000 19.97 -6.86 7.09
004.7000 19.97 -7.07 7.09
004.8000 19.98 -7.24 7.09
004.9000 19.97 -7.46 7.09
005.0000 19.97 -7.62 7.09
005.1000 19.97 -7.82 7.09
005.2000 19.98 -7.98 7.09
005.3000 19.98 -8.14 7.09
005.4000 19.97 -8.32 7.09
005.5000 19.97 -8.48 7.09
005.6000 19.97 -8.72 7.09
005.7000 19.97 -8.86 7.09
005.8000 19.98 -9.00 7.09
005.9000 19.97 -9.20 7.09
006.0000 19.97 -9.39 7.09
006.1000 19.97 -9.54 7.09
006.2000 19.97 -9.71 7.09
006.3000 19.96 -9.93 7.09
006.4000 19.96 -10.09 7.09
006.5000 19.97 -10.24 7.09
006.6000 19.97 -10.39 7.09
006.7000 19.97 -10.59 7.09
006.8000 19.96 -10.77 7.09
006.9000 19.96 -10.92 7.10
007.0000 19.96 -11.10 7.10
007.1000 19.97 -11.27 7.10
007.2000 19.96 -11.45 7.10
007.3000 19.96 -11.63 7.10
007.4000 19.96 -11.80 7.10
007.5000 19.95 -11.95 7.10
007.6000 19.95 -12.10 7.10
007.7000 19.95 -12.29 7.10
007.8000 19.95 -12.47 7.10
007.9000 19.95 -12.64 7.10
008.0000 19.95 -12.80 7.10
008.1000 19.95 -12.96 7.10
008.2000 19.95 -13.14 7.10
008.3000 19.95 -13.33 7.10
008.4000 19.95 -13.48 7.10
008.5000 19.94 -13.63 7.10
008.6000 19.94 -13.77 7.10
008.7000 19.94 -13.90 7.10
008.8000 19.94 -14.07 7.10
008.9000 19.94 -14.25 7.10
009.0000 19.93 -14.44 7.10
009.1000 19.93 -14.62 7.10
009.2000 19.93 -14.80 7.10
009.3000 19.93 -14.98 7.10
009.4000 19.93 -15.14 7.10
009.5000 19.93 -15.29 7.10
009.6000 19.92 -15.43 7.10
009.7000 19.92 -15.59 7.10
009.8000 19.92 -15.74 7.10
009.9000 19.92 -15.91 7.10
010.0000 19.92 -16.07 7.10
011.0000 19.89 -17.71 7.11
012.0000 19.87 -19.30 7.11
013.0000 19.85 -20.88 7.11
014.0000 19.83 -22.44 7.12
015.0000 19.81 -23.99 7.12
016.0000 19.79 -25.44 7.12
017.0000 19.78 -26.98 7.13
018.0000 19.78 -28.41 7.13
019.0000 19.77 -29.91 7.13
020.0000 19.77 -31.37 7.14
021.0000 19.78 -32.92 7.14
022.0000 19.78 -34.46 7.15
023.0000 19.78 -36.01 7.15
024.0000 19.80 -37.62 7.16
025.0000 19.80 -39.20 7.16
026.0000 19.80 -40.81 7.17
027.0000 19.80 -42.39 7.17
028.0000 19.79 -44.07 7.18
029.0000 19.79 -45.69 7.18
030.0000 19.77 -47.33 7.19
031.0000 19.76 -48.99 7.19
032.0000 19.76 -50.60 7.20
033.0000 19.75 -52.23 7.20
034.0000 19.73 -53.85 7.21
035.0000 19.71 -55.47 7.21
036.0000 19.70 -57.10 7.22
037.0000 19.68 -58.73 7.23
038.0000 19.66 -60.40 7.23
039.0000 19.64 -61.96 7.24
040.0000 19.63 -63.62 7.25
041.0000 19.60 -65.18 7.25
042.0000 19.59 -66.76 7.26
043.0000 19.57 -68.34 7.27
044.0000 19.54 -69.94 7.27
045.0000 19.51 -71.57 7.28
046.0000 19.50 -73.16 7.29
047.0000 19.48 -74.71 7.29
048.0000 19.46 -76.29 7.30
049.0000 19.44 -77.84 7.31
050.0000 19.42 -79.41 7.32
051.0000 19.39 -80.99 7.32
052.0000 19.36 -82.56 7.33
053.0000 19.34 -84.15 7.34
054.0000 19.32 -85.74 7.35
055.0000 19.30 -87.31 7.36
056.0000 19.27 -88.85 7.36
057.0000 19.26 -90.41 7.37
058.0000 19.24 -91.97 7.38
059.0000 19.21 -93.55 7.39
060.0000 19.18 -95.07 7.40
061.0000 19.16 -96.68 7.41
062.0000 19.14 -98.30 7.42
063.0000 19.12 -99.87 7.43
064.0000 19.09 -101.42 7.44
065.0000 19.07 -102.98 7.45
066.0000 19.05 -104.55 7.46
067.0000 19.02 -106.13 7.46
068.0000 19.00 -107.71 7.47
069.0000 18.97 -109.29 7.48
070.0000 18.95 -110.89 7.49
071.0000 18.92 -112.49 7.50
072.0000 18.89 -114.08 7.52
073.0000 18.87 -115.66 7.53
074.0000 18.85 -117.22 7.54
075.0000 18.82 -118.82 7.55
076.0000 18.79 -120.42 7.56
077.0000 18.75 -122.03 7.57
078.0000 18.72 -123.63 7.58
079.0000 18.69 -125.21 7.59
080.0000 18.65 -126.79 7.60
081.0000 18.62 -128.36 7.61
082.0000 18.59 -129.98 7.62
083.0000 18.57 -131.62 7.64
084.0000 18.53 -133.19 7.65
085.0000 18.49 -134.74 7.66
086.0000 18.46 -136.38 7.67
087.0000 18.43 -138.03 7.68
088.0000 18.39 -139.64 7.70
089.0000 18.36 -141.24 7.71
090.0000 18.32 -142.81 7.72
091.0000 18.28 -144.38 7.73
092.0000 18.23 -146.00 7.75
093.0000 18.19 -147.62 7.76
094.0000 18.15 -149.22 7.77
095.0000 18.11 -150.82 7.78
096.0000 18.07 -152.43 7.80
097.0000 18.04 -154.06 7.81
098.0000 18.00 -155.68 7.82
099.0000 17.95 -157.25 7.84
100.0000 17.91 -158.82 7.85
]


text:
@doc raw"""
    AbstractRectangleWindow{T<:Float64} <: AbstractSpatialWindow{T}

Abstract type representing a [hyperrectangle](https://en.wikipedia.org/wiki/Hyperrectangle) ``\prod_i [c_i, c_i + w_i]``

**See also**

- [`PRS.RectangleWindow`](@ref),
- [`PRS.SquareWindow`](@ref).
"""
abstract type AbstractRectangleWindow{T<:Float64} <: AbstractSpatialWindow{T} end

@doc raw"""
    RectangleWindow{T<:Float64} <: AbstractRectangleWindow{T}

Structure representing a hyperrectangle ``\prod_i [c_i, c_i + w_i]``, with fields
- `c` lower left corner of the hyperrectangle
- `w` width vector of the hyperrectangle along each coordinate
"""
struct RectangleWindow{T<:Float64} <: AbstractRectangleWindow{T}
    # Corner
    c::Vector{T}
    # Width
    w::Vector{T}
end

function Base.show(io::IO, win::RectangleWindow)
    win_format = ""
    if allequal(win.c) && allequal(win.w)
        win_format = "[$(win.c[1]), $(win.w[1])]^$(dimension(win))"
    else
        win_format = join(["[$(c), $(c + w)]" for (c, w) in zip(win.c, win.w)], "x")
    end
    print(io, "RectangleWindow $(win_format)")
end

"""
    RectangleWindow(c::AbstractVector, w::Vector)

Construct a [`PRS.RectangleWindow`](@ref).
"""
function RectangleWindow(c::AbstractVector, w::Vector)
    @assert length(c) == length(w)
    @assert all(w .> 0)
    return RectangleWindow{Float64}(c, w)
end

@doc raw"""
    SquareWindow{T<:Float64} <: AbstractRectangleWindow{T}

Structure representing a [hypercube](https://fr.wikipedia.org/wiki/Hypercube) ``\prod_i [c_i, c_i + w]``, with fields
- `c` lower left corner of the hypercube,
- `w` length of the hypercube.
"""
struct SquareWindow{T<:Float64} <: AbstractRectangleWindow{T}
    # Corner
    c::Vector{T}
    # Width
    w::T
end

function Base.show(io::IO, win::SquareWindow)
    win_format = ""
    if allequal(win.c)
        win_format = "[$(win.c[1]), $(win.w)]^$(dimension(win))"
    else
        win_format = join(["[$(c), $(c + win.w)]" for c in win.c], "x")
    end
    print(io, "SquareWindow $(win_format)")
end

"""
    SquareWindow(c::AbstractVector=zeros(2), w::Real=1)

Construct a [`PRS.SquareWindow`](@ref).
"""
function SquareWindow(c::AbstractVector=zeros(2), w::Real=1)
    @assert w > 0
    return SquareWindow{Float64}(c, w)
end

"""
    rectangle_square_window(c, w)

Construct a [`PRS.RectangleWindow`](@ref) or a [`PRS.SquareWindow`](@ref) depending .on whether all coordinates of `w` are the same.
"""
function rectangle_square_window(c, w)
    return allequal(w) ? SquareWindow(c, w[1]) : RectangleWindow(c, w)
end

@doc raw"""
    BallWindow{T<:Float64} <: AbstractSpatialWindow{T}

Structure representing a closed [ball](https://en.wikipedia.org/wiki/Ball_(mathematics)) ``B(c, r)``, with fields
- `c` center of the ball,
- `r` radius of the ball.
"""
struct BallWindow{T<:Float64} <: AbstractSpatialWindow{T}
    # Center
    c::Vector{T}
    # Radius
    r::T
end

"""
    BallWindow(c::AbstractVector=zeros(2), r::Real)

Construct a [`PRS.BallWindow`](@ref).
"""
function BallWindow(c::AbstractVector=zeros(2), r::Real=1)
    @assert r > 0
    return BallWindow{Float64}(c, r)
end

"""
    dimension(win::AbstractSpatialWindow) = length(win.c)

Return the dimension of window `win`.
"""
dimension(win::AbstractSpatialWindow) = length(win.c)

"""
    volume(win::RectangleWindow) = prod(win.w)
"""
volume(win::RectangleWindow) = prod(win.w)

"""
    volume(win::SquareWindow) = win.w^dimension(win)
"""
volume(win::SquareWindow) = win.w^dimension(win)

@doc raw"""
    volume(win::BallWindow) =

Return the [volume of the ball](https://en.wikipedia.org/wiki/Volume_of_an_n-ball) ``B(c, r)\subseteq R^d`` as

```math
    \frac{π^{d/2} r^d}{\Gamma(d/2 + 1)} \cdot
```
"""
function volume(win::BallWindow)
    d = dimension(win)
    return π^(d/2) * win.r^d / SF.gamma(d/2 + 1)
end

@doc raw"""
    Base.in(
        x::AbstractVector,
        win::AbstractRectangleWindow
    )

Check if ``x \in \prod_{i} [c_i, c_i + w_i]``.
"""
function Base.in(
    x::AbstractVector,
    win::AbstractRectangleWindow
)
    return all(win.c .<= x) && all(x .<= win.c .+ win.w)
end

@doc raw"""
    Base.in(
        x::AbstractVector,
        win::AbstractRectangleWindow
    )

Check if ``x \in B(c, r)``, i.e., ``\left\| x - c \right\| \leq r``.
"""
function Base.in(
    x::AbstractVector,
    win::BallWindow
)
    return Distances.euclidean(x, win.c) <= win.r
end

Base.rand(win::AbstractSpatialWindow) = rand(Random.default_rng(), win)
Base.rand(win::AbstractSpatialWindow, n::Int) = rand(Random.default_rng(), win, n)

"""
    Base.rand(
        [rng::Random.AbstractRNG,]
        win::AbstractRectangleWindow{T}
    )::Vector{T} where {T}

Sample uniformly at random in window `win`.
"""
function Base.rand(
    rng::Random.AbstractRNG,
    win::AbstractRectangleWindow{T}
)::Vector{T} where {T}
    return win.w .* rand(rng, dimension(win)) .+ win.c
end

"""
    Base.rand(
        [rng::Random.AbstractRNG,]
        win::AbstractRectangleWindow{T},
        n::Int
    )::Matrix{T} where {T}

Sample `n` points uniformly at random in window `win`.
"""
function Base.rand(
    rng::Random.AbstractRNG,
    win::AbstractRectangleWindow{T},
    n::Int
)::Matrix{T} where {T}
    x = Matrix{T}(undef, dimension(win), n)
    rand!(rng, x)
    return win.w .* x .+ win.c
end

"""
    Base.rand(
        [rng::Random.AbstractRNG,]
        win::BallWindow{T}
    )::Vector{T} where {T}

Sample uniformly at random in window `win`.
"""
function Base.rand(
    rng::Random.AbstractRNG,
    win::BallWindow{T}
)::Vector{T} where {T}
    d = dimension(win)
    x = Vector{T}(undef, d+2)
    randn!(rng, x)
    normalize!(x)
    return win.r .* x[1:d] .+ win.c
end

"""
    Base.rand(
        [rng::Random.AbstractRNG,]
        win::BallWindow{T},
        n::Int
    )::Matrix{T} where {T}

Sample `n` points uniformly at random in window `win`.
"""
function Base.rand(
    rng::Random.AbstractRNG,
    win::BallWindow{T},
    n::Int
)::Matrix{T} where {T}
    d = dimension(win)
    X = Matrix{T}(undef, d+2, n)
    Random.randn!(rng, X)
    normalize_columns!(X, 2)
    return win.r .* X[1:d, :] .+ win.c
end


text:
# αscheme
using PoreFlow
using ADCME
using PyPlot

m = 15
n = 15
h = 1/m
NT = 100
Δt = 1/NT
bd = bcnode("all", m, n, h)
function solver(A, rhs, i)
    A, Abd = fem_impose_Dirichlet_boundary_condition(A, bd, m, n, h)
    rhs = rhs - Abd * abd[i]
    rhs = scatter_update(rhs, [bd; bd .+ (m+1)*(n+1)], abd[i])
    # op = tf.print(i, sum(Abd * abd[i]))
    # rhs = bind(rhs, op)
    return A\rhs
end

M = compute_fem_mass_matrix(m, n, h)
K = compute_fem_stiffness_matrix(H, m, n, h)
F = zeros(NT, 2(m+1)*(n+1))

nbd = ones(Bool, (m+1)*(n+1)*2)
nbd[[bd; bd.+(m+1)*(n+1)]] .= false
ts = αscheme_time(Δt*ones(NT); ρ=0.0)
for i = 1:NT
    t = ts[i]
    f1 = (x,y)->0.1*(x^2 + y^2)*exp(-t) - 0.790123456790123*exp(-t)
    f2 = (x,y)->0.1*(x^2 - y^2)*exp(-t) + 0.493827160493827*exp(-t)
    f1 = eval_f_on_gauss_pts(f1, m, n, h)
    f2= eval_f_on_gauss_pts(f2, m, n, h)
    F[i,:] = compute_fem_source_term(f1, f2, m, n, h)

    F[i, [bd; bd.+(m+1)*(n+1)]] .= 0.0
    # @info sum(F[i,:])
    # globdat.time = t
    # fbody = getBodyForce(domain, globdat)
    # g = zeros((m+1)*(n+1)*2)
    # g[nbd] = fbody
    # @info norm(F[i,:] - g[nbd])
end
x = Float64[]
y = Float64[]
for j = 1:n+1
    for i = 1:m+1
        push!(x, (i-1)*h)
        push!(y, (j-1)*h)
    end
end
abd = zeros(NT, 2length(bd))
for i = 1:NT
    t = ts[i]
    abd[i, :] = [(@. x[bd]^2+y[bd]^2);(@. x[bd]^2-y[bd]^2)]* exp(-t) * 0.1
end
abd = constant(abd)

dbd = zeros(NT, 2length(bd))
for i = 1:NT
    t = ts[i]
    dbd[i, :] = [(@. x[bd]^2+y[bd]^2);(@. x[bd]^2-y[bd]^2)]* exp(-t) * 0.1
end

d0 = @. [x^2+y^2;x^2-y^2]* 0.1
u0 =  @. -[x^2+y^2;x^2-y^2]* 0.1
a0 =  @. [x^2+y^2;x^2-y^2]* 0.1
d, u, a = αscheme(M, spzero(2(m+1)*(n+1)), K, F, d0, u0, a0, Δt*ones(NT); extsolve=solver, ρ = 0.0  )
# d, u, a = fast_αscheme(m, n, h, M, spzero(2(m+1)*(n+1)), K, F, d0, u0, a0, Δt, bd, dbd, -dbd, abd )

sess = Session(); init(sess)
d_ = run(sess, d)
# PoreFlow.visualize_displacement(D, m, n, h)

# plot(D[:,(div(n,2)+1)*(m+1)+div(m,2)+1])

# ts = LinRange(0,1,NT+1)
# x0 = div(m,2)*h
# y0 = (div(n,2)+1)*h
# plot((@. (x0^2+y0^2)*exp(-ts))*0.1,"--")

# d_ = hcat(domain.history["state"]...)'
i = 3
j = 4
plot(d_[:,(j-1)*(m+1)+i])
x0 = (i-1)*h
y0 = (j-1)*h
plot((@. (x0^2+y0^2)*exp(-ts))*0.1,"--")


text:
using HorizonSideRobots
include("../basics.jl")

md"""
        # Подсчитать число и прямоугольных и прямолинейных (вертикальных и горизонтальных)
"""

"""Решение задачи 23"""
function solve_23!(r)

end


text:
#Computed using Wolframalpha EllipticK and EllipticE functions.
@testset "elliptic integrals" begin
    @testset "complete of 1st kind" begin
        @test ellipk(-0.5)  ≈ 1.41573720842595619           rtol=2*eps()
        @test ellipk(0)     ≈ 1.570796326794896619231322    rtol=2*eps()
        @test ellipk(0.01)  ≈ 1.57474556151735595           rtol=2*eps()
        @test ellipk(0.17)  ≈ 1.6448064907988806            rtol=2*eps()
        @test ellipk(0.25)  ≈ 1.685750354812596             rtol=2*eps()
        @test ellipk(0.33)  ≈ 1.73186477825209792           rtol=2*eps()
        @test ellipk(0.45)  ≈ 1.81388393681698264           rtol=2*eps()
        @test ellipk(0.5)   ≈ 1.854074677301371918          rtol=2*eps()
        @test ellipk(0.69)  ≈ 2.0608816467301313            rtol=2*eps()
        @test ellipk(0.75)  ≈ 2.15651564749964323           rtol=2*eps()
        @test ellipk(0.84)  ≈ 2.3592635547450067            rtol=2*eps()
        @test ellipk(0.88)  ≈ 2.492635323239715564          rtol=2*eps()
        @test ellipk(0.92)  ≈ 2.683551406315229344          rtol=2*eps()
        @test ellipk(1.0) == Inf
        @test ellipk(Float16(0.92)) ≈ 2.683551406315229344  rtol=2*eps(Float16)
        @test ellipk(Float32(0.92)) ≈ 2.683551406315229344  rtol=2*eps(Float32)
        @test_throws MethodError ellipk(BigFloat(0.5))
        @test_throws DomainError ellipk(1.1)
    end

    @testset "complete of 2nd kind" begin
        @test ellipe(-0.1)  ≈ 1.6093590249375295            rtol=2*eps()
        @test ellipe(0)     ≈ 1.570796326794896619231322    rtol=2*eps()
        @test ellipe(0.01)  ≈ 1.5668619420216682            rtol=2*eps()
        @test ellipe(0.15)  ≈ 1.5101218320928197            rtol=2*eps()
        @test ellipe(0.21)  ≈ 1.4847605813318776            rtol=2*eps()
        @test ellipe(0.3)   ≈ 1.4453630644126652            rtol=2*eps()
        @test ellipe(0.42)  ≈ 1.3898829914929717            rtol=2*eps()
        @test ellipe(0.5)   ≈ 1.3506438810476755            rtol=2*eps()
        @test ellipe(0.66)  ≈ 1.2650125751607508            rtol=2*eps()
        @test ellipe(0.76)  ≈ 1.2047136418292115            rtol=2*eps()
        @test ellipe(0.8)   ≈ 1.17848992432783852           rtol=2*eps()
        @test ellipe(0.865) ≈ 1.1322436887003925            rtol=2*eps()
        @test ellipe(0.99)  ≈ 1.0159935450252239            rtol=2*eps()
        @test ellipe(1.0)   ≈ 1.00                          rtol=2*eps()
        @test ellipe(Float16(0.865)) ≈ 1.1322436887003925   rtol=2*eps(Float16)
        @test ellipe(Float32(0.865)) ≈ 1.1322436887003925   rtol=2*eps(Float32)
        @test_throws MethodError ellipe(BigFloat(-1))
        @test_throws DomainError ellipe(1.2)
    end
end


text:
using Test
using Overseer

@testset "Indices"    begin include("test_indices.jl")    end
@testset "Components" begin include("test_components.jl") end
@testset "Ledger"     begin include("test_ledger.jl")     end


text:
using Inflation
using SymPy

# this is a 2-field non-minimally coupled model, published in https://arxiv.org/pdf/1304.0363.pdf

d = 2

function G(Phi,p)
    f = F(Phi,p)
    id = Matrix{Int64}(I,d,d)
    gf = [diff(f,phi) for phi in Phi]
    g = 1/(2*f) .* (id .+ 3*gf'.*gf./f)
    return g
end

xis = [symbols("xi$i",positive=true) for i in 1:d]
lambdas = [symbols("l$i",positive=true) for i in 1:d]
params = [xis; lambdas; symbols("g",positive=true) ]
pvalues = [ 1e3, 1.2*1e3, 1e-2, 0.75*1e-2, 1e-2]

function F(Phi,p)
    xi = p[1:d]
    return 1/2*(1 + xi' * (Phi.^2))
end

function V(Phi,p)
    λs = p[d+1:end-1]
    g = p[end]
    jordanV = g/2*prod(Phi.^2) + λs'*(Phi.^4)/4
    f = F(Phi,p)
    v = jordanV / (4*f^2)
    return v
end

funcs = inflation_setup(d,V,G,params)

ξϕ,ξχ = pvalues[1:2]
λϕ,λχ = pvalues[3:4]
r0 = 10*max(1/sqrt(ξϕ),1/sqrt(ξχ))

# scan the number of e-folds, as a function of angle in the ϕ, χ plane
ts = range(0,2*pi,length=100)
Nends = []
options = BackgroundOptions(
                            # these trajectories can have transients with very high ϵₕ
                            #allow 1 efold for them to clear
                            min_efolds = 1.0,
                            max_efolds = 805.0
                           )
for t0 in ts
    println("r0: $r0")
    println("t0: $t0")
    Phi0 = r0*[cos(t0),sin(t0)]
    Pi0 = zeros(d) # works well enough

    sol = background_evolve(Phi0,Pi0,pvalues,funcs,verbose=true,options=options)
    push!(Nends,sol.t[end])
end

using Plots
using LaTeXStrings
plot(ts,Nends,xlabel=L"\theta",ylabel=L"N_e")


text:
using CLIMA.VariableTemplates

function vars_diagnostic(FT)
  @vars begin
    # vertical coordinate
    z::FT
    # state and functions of state
    u::FT
    v::FT
    w::FT
    q_tot::FT
    e_tot::FT
    q_liq::FT
    thd::FT                # θ
    thl::FT                # θ_liq
    thv::FT                # θ_v
    e_int::FT
    h_m::FT
    h_t::FT
    qt_sgs::FT
    ht_sgs::FT

    # vertical fluxes
    vert_eddy_mass_flx::FT # <w′ρ′>
    vert_eddy_u_flx::FT    # <w′u′>
    vert_eddy_v_flx::FT    # <w′v′>
    vert_eddy_qt_flx::FT   # <w'q_tot'>
    vert_qt_flx::FT        # <w q_tot>
    vert_eddy_ql_flx::FT   # <w′q_liq′>
    vert_eddy_qv_flx::FT   # <w′q_vap′>
    vert_eddy_thd_flx::FT  # <w′θ′>
    vert_eddy_thv_flx::FT  # <w′θ_v′>
    vert_eddy_thl_flx::FT  # <w′θ_liq′>

    # variances
    uvariance::FT          # u′u′
    vvariance::FT          # v′v′
    wvariance::FT          # w′w′

    # skewness
    wskew::FT              # w′w′w′

    # turbulent kinetic energy
    TKE::FT
  end
end

num_diagnostic(FT) = varsize(vars_diagnostic(FT))
diagnostic_vars(array) = Vars{vars_diagnostic(eltype(array))}(array)

max_stars_repo_name: emassoud/CLIMA

max_issues_repo_name: emassoud/CLIMA

max_forks_repo_name: emassoud/CLIMA


text:
import RowEchelon
import LinearAlgebra

#=
Homework 6
Section 2.5
Problems 14
=#

# Create the matrix
A = [ 1 3 1 5 ; 5 20 6 31 ; -2 -1 -1 -4 ; -1 7 1 7]
LU = LinearAlgebra.lu(A)
print("L = \t")
println(LU.L)
print("U = \t")
println(LU.U)


text:
unittests = [
    "photoreceptor",
    "analysis"]

println("===================")
println("Running unit tests:")
println("===================")

for t in unittests
  tfile = t*".jl"
  println("  * $(tfile) *")
  include(string("unit/",tfile))
  println()
  println()
end


text:
# BEGIN ImageAxes v0.6

@deprecate data arraydata # PR#31

# END ImageAxes v0.6


text:
# This file was generated, do not modify it. # hide
preds = MLJ.predict(mach, features[test, :])

print(preds[1:5])


text:
# --------------------------------------------------------------------------- #
# The "U-Net-like" model from (Pen, Yang, Li, et al.; 2018)

struct UNetLike{I, BN} <: FCModel{I, BN}
  weights :: Vector{Any}     # weights of the convolutional layers
  bnmoments :: Vector{Any}   # knet moment objects used for batch normalization
end

# --------------------------------------------------------------------------- #
# Network architecture (no batch normalization)

function density{I <: Image}(w, s, x, ::Type{UNetLike{I, false}})
  y1 = rconv(w[2], rconv(w[1], x))
  y2 = rconv(w[4], rconv(w[3], pool(y1)))
  y3 = rconv(w[6], rconv(w[5], pool(y2)))
  y4 = rconv(w[8], rconv(w[7], pool(y3)))

  z3 = rconv(w[11], rconv(w[10], uconv(w[9], y3, y4)))
  z2 = rconv(w[14], rconv(w[13], uconv(w[12], y2, z3)))
  z1 = rconv(w[17], rconv(w[16], uconv(w[15], y1, z2)))

  y = conv4(w[18], z1, padding=pad(w[18]))
  return reshape(y, size(y)[[1,2,4]]...)
end

# --------------------------------------------------------------------------- #
# Initialization (no batch normalization)

function init_weights{I <: Image}(::Type{UNetLike{I, false}},
                                  wr :: Function = wr,
                                  wu :: Function = wu;
                                  potency :: Integer = 6,
                                  seed :: Integer = rand(1:10000))

  Knet.setseed(seed)
  c = imgchannels(I)
  s = 2^potency

  return Any[
    wr(c, s),   wr(s, s),  wr(s, s), wr(s, s),
    wr(s, s),  wr(s, s),  wr(s, s), wr(s, s),
    wu(s, s),  wr(2s, s), wr(s, s), wu(s, s),
    wr(2s, s), wr(s, s),  wu(s, s), wr(2s, s),
    wr(s, s),  wr(s, 1) ]
end

init_state{I<:Image}(::Type{UNetLike{I, false}}) = Any[]

# --------------------------------------------------------------------------- #
# Network architecture (batch normalization)

function density{I <: Image}(w, s, x, ::Type{UNetLike{I, true}})
  y1 = rbconv(w[4],  s[2], w[3],  rbconv(w[2],  s[1], w[1],  x))
  y2 = rbconv(w[8],  s[4], w[7],  rbconv(w[6],  s[3], w[5],  pool(y1)))
  y3 = rbconv(w[12], s[6], w[11], rbconv(w[10], s[5], w[9],  pool(y2)))
  y4 = rbconv(w[16], s[8], w[15], rbconv(w[14], s[7], w[13], pool(y3)))

  u3 = ubconv(w[18], s[9], w[17], y3, y4)
  z3 = rbconv(w[22], s[11], w[21], rbconv(w[20], s[10], w[19], u3))

  u2 = ubconv(w[24], s[12], w[23], y2, z3)
  z2 = rbconv(w[28], s[14], w[27], rbconv(w[26], s[13], w[25], u2))

  u1 = ubconv(w[30], s[15], w[29], y1, z2)
  z1 = rbconv(w[34], s[17], w[33], rbconv(w[32], s[16], w[31], u1))

  y = conv4(w[35], z1, padding=pad(w[35]))
  return reshape(y, size(y)[[1,2,4]]...)
end

# --------------------------------------------------------------------------- #
# Initialization (batch normalization)

function init_weights{I<:Image}(::Type{UNetLike{I, true}},
                                wr :: Function = wr,
                                wu :: Function = wu;
                                potency :: Integer = 6,
                                seed :: Integer = rand(1:10000))

  # Need the same convolutional weights as in the case without batch
  # normalization. However, also need to insert the trainable bn-values at
  # the right positions of the weights vector
  s = 2^potency

  weights = init_weights(UNetLike{I, false}, wr, wu,
                         potency = potency, seed = seed)
  return Any[ odd(i) ? weights[ceil(Int, i/2)] : bn(s) for i in 1:35 ]
end

function init_state{I<:Image}(::Type{UNetLike{I, true}})
  return Any[ bnmoments() for i in 1:17 ]
end

# --------------------------------------------------------------------------- #
# Convenience-constructor

function UNetLike(I,
                  wr :: Function = wr,
                  wu :: Function = wu;
                  bn :: Bool = false,
                  potency :: Integer = 6,
                  seed :: Integer = rand(1:10000))

  weights = init_weights(UNetLike{I, bn}, wr, wu,
                         potency = potency, seed = seed)
  state = init_state(UNetLike{I, bn})

  return UNetLike{I, bn}(weights, state)
end

max_stars_repo_name: tscode/DCellC

max_issues_repo_name: tscode/DCellC