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

mutable struct IoK8sApiCoreV1ContainerStatus <: SwaggerModel
    containerID::Any # spec type: Union{ Nothing, String } # spec name: containerID
    image::Any # spec type: Union{ Nothing, String } # spec name: image
    imageID::Any # spec type: Union{ Nothing, String } # spec name: imageID
    lastState::Any # spec type: Union{ Nothing, IoK8sApiCoreV1ContainerState } # spec name: lastState
    name::Any # spec type: Union{ Nothing, String } # spec name: name
    ready::Any # spec type: Union{ Nothing, Bool } # spec name: ready
    restartCount::Any # spec type: Union{ Nothing, Int32 } # spec name: restartCount
    started::Any # spec type: Union{ Nothing, Bool } # spec name: started
    state::Any # spec type: Union{ Nothing, IoK8sApiCoreV1ContainerState } # spec name: state

    function IoK8sApiCoreV1ContainerStatus(;containerID=nothing, image=nothing, imageID=nothing, lastState=nothing, name=nothing, ready=nothing, restartCount=nothing, started=nothing, state=nothing)
        o = new()
        validate_property(IoK8sApiCoreV1ContainerStatus, Symbol("containerID"), containerID)
        setfield!(o, Symbol("containerID"), containerID)
        validate_property(IoK8sApiCoreV1ContainerStatus, Symbol("image"), image)
        setfield!(o, Symbol("image"), image)
        validate_property(IoK8sApiCoreV1ContainerStatus, Symbol("imageID"), imageID)
        setfield!(o, Symbol("imageID"), imageID)
        validate_property(IoK8sApiCoreV1ContainerStatus, Symbol("lastState"), lastState)
        setfield!(o, Symbol("lastState"), lastState)
        validate_property(IoK8sApiCoreV1ContainerStatus, Symbol("name"), name)
        setfield!(o, Symbol("name"), name)
        validate_property(IoK8sApiCoreV1ContainerStatus, Symbol("ready"), ready)
        setfield!(o, Symbol("ready"), ready)
        validate_property(IoK8sApiCoreV1ContainerStatus, Symbol("restartCount"), restartCount)
        setfield!(o, Symbol("restartCount"), restartCount)
        validate_property(IoK8sApiCoreV1ContainerStatus, Symbol("started"), started)
        setfield!(o, Symbol("started"), started)
        validate_property(IoK8sApiCoreV1ContainerStatus, Symbol("state"), state)
        setfield!(o, Symbol("state"), state)
        o
    end
end # type IoK8sApiCoreV1ContainerStatus

const _property_map_IoK8sApiCoreV1ContainerStatus = Dict{Symbol,Symbol}(Symbol("containerID")=>Symbol("containerID"), Symbol("image")=>Symbol("image"), Symbol("imageID")=>Symbol("imageID"), Symbol("lastState")=>Symbol("lastState"), Symbol("name")=>Symbol("name"), Symbol("ready")=>Symbol("ready"), Symbol("restartCount")=>Symbol("restartCount"), Symbol("started")=>Symbol("started"), Symbol("state")=>Symbol("state"))
const _property_types_IoK8sApiCoreV1ContainerStatus = Dict{Symbol,String}(Symbol("containerID")=>"String", Symbol("image")=>"String", Symbol("imageID")=>"String", Symbol("lastState")=>"IoK8sApiCoreV1ContainerState", Symbol("name")=>"String", Symbol("ready")=>"Bool", Symbol("restartCount")=>"Int32", Symbol("started")=>"Bool", Symbol("state")=>"IoK8sApiCoreV1ContainerState")
Base.propertynames(::Type{ IoK8sApiCoreV1ContainerStatus }) = collect(keys(_property_map_IoK8sApiCoreV1ContainerStatus))
Swagger.property_type(::Type{ IoK8sApiCoreV1ContainerStatus }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiCoreV1ContainerStatus[name]))}
Swagger.field_name(::Type{ IoK8sApiCoreV1ContainerStatus }, property_name::Symbol) =  _property_map_IoK8sApiCoreV1ContainerStatus[property_name]

function check_required(o::IoK8sApiCoreV1ContainerStatus)
    (getproperty(o, Symbol("image")) === nothing) && (return false)
    (getproperty(o, Symbol("imageID")) === nothing) && (return false)
    (getproperty(o, Symbol("name")) === nothing) && (return false)
    (getproperty(o, Symbol("ready")) === nothing) && (return false)
    (getproperty(o, Symbol("restartCount")) === nothing) && (return false)
    true
end

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


text:
module CRN  # Chemical Reaction Network

include("utilities.jl")
include("gillespie.jl")
include("ode_solver.jl")
include("euler_step.jl")
include("c_mn.jl")
include("plotting.jl")
include("print_fields.jl")
include("master_op.jl")

end # module

ext: jl

max_stars_repo_name: mkurjahn/CRN

max_issues_repo_name: mkurjahn/CRN

max_forks_repo_name: mkurjahn/CRN


text:
function FieldCjSjCoefficient(arg0::RealFieldElement, arg1::RealFieldElement, arg2::Field)
    return FieldCjSjCoefficient((RealFieldElement, RealFieldElement, Field), arg0, arg1, arg2)
end

function get_cj(obj::FieldCjSjCoefficient, arg0::jint)
    return jcall(obj, "getCj", RealFieldElement, (jint,), arg0)
end

function get_dcj_dh(obj::FieldCjSjCoefficient, arg0::jint)
    return jcall(obj, "getDcjDh", RealFieldElement, (jint,), arg0)
end

function get_dcj_dk(obj::FieldCjSjCoefficient, arg0::jint)
    return jcall(obj, "getDcjDk", RealFieldElement, (jint,), arg0)
end

function get_dsj_dh(obj::FieldCjSjCoefficient, arg0::jint)
    return jcall(obj, "getDsjDh", RealFieldElement, (jint,), arg0)
end

function get_dsj_dk(obj::FieldCjSjCoefficient, arg0::jint)
    return jcall(obj, "getDsjDk", RealFieldElement, (jint,), arg0)
end

function get_sj(obj::FieldCjSjCoefficient, arg0::jint)
    return jcall(obj, "getSj", RealFieldElement, (jint,), arg0)
end


text:
function analyse_tmp_order(client, config, bot_path, trade_path)
    tmp = JSON.parsefile(trade_path)
    #
    ## Get trades of SELL order
    if !haskey(tmp, "order_trades")
        tmp["order_trades"] = client.get_my_trades(symbol=config["symbol"], orderId=tmp["order"]["orderId"])
        open(trade_path, "w") do f
            JSON.print(f, tmp, 4)
        end
    end
    if !haskey(tmp["order"], "fee")
        tmp["order"]["fee"] = Pinguu.calc_order_fee(client, tmp["order_trades"], config)
        open(trade_path, "w") do f
            JSON.print(f, tmp, 4)
        end
    end
    #
    ## Get trades of BUY order (if exists)
    if haskey(tmp, "buy_order")
        if !haskey(tmp, "buy_order_trades")
            tmp["buy_order_trades"] = client.get_my_trades(symbol=config["symbol"], orderId=tmp["buy_order"]["orderId"])
            open(trade_path, "w") do f
                JSON.print(f, tmp, 4)
            end
        end
        if !haskey(tmp["buy_order"], "fee")
            tmp["buy_order"]["fee"] = Pinguu.calc_order_fee(client, tmp["buy_order_trades"], config)
            open(trade_path, "w") do f
                JSON.print(f, tmp, 4)
            end
        end
    end
    if tmp["type"] == "normal"
        paid = typeof(tmp["buy_order"]["cummulativeQuoteQty"]) != Float64 ? parse(Float64, tmp["buy_order"]["cummulativeQuoteQty"]) : tmp["buy_order"]["cummulativeQuoteQty"]
        got = typeof(tmp["order"]["cummulativeQuoteQty"]) != Float64 ? parse(Float64, tmp["order"]["cummulativeQuoteQty"]) : tmp["order"]["cummulativeQuoteQty"]
        fees = tmp["buy_order"]["fee"] + tmp["order"]["fee"]
    elseif tmp["type"] == "initial"
        price = typeof(config["init_state"]["price"]) != Float64 ? parse(Float64, config["init_state"]["price"]) : config["init_state"]["price"]
        got = typeof(tmp["order"]["cummulativeQuoteQty"]) != Float64 ? parse(Float64, tmp["order"]["cummulativeQuoteQty"]) : tmp["order"]["cummulativeQuoteQty"]
        paid = got * price/parse(Float64, tmp["order"]["price"])
        fees = tmp["order"]["fee"]
        fees += config["init_state"]["fee"] * (paid / config["init_state"]["cummulativeQuoteQty"])
    end
    profit = got - paid - fees
    tmp["profit"] = profit

    current_volume = Pinguu.get_current_volume(config)

    tmp["profit_percent"] = tmp["profit"] * 100 / current_volume
    tmp["profit_thes"] = tmp["profit"] * config["thes_factor"]

    tmp["fee"] = fees
    tmp["analysed"] = 1
    open(trade_path, "w") do f
        JSON.print(f, tmp, 4)
    end
    return tmp
end
export analyse_tmp_order

function analyse_closed_order(client, config, bot_path, trade_path)
    tmp = Pinguu.analyse_tmp_order(client, config, bot_path, trade_path)

    #
    ## Write to closed orders
    yr, m = split(string(now()), "-")[1:2]
    current_closed_orders_path = joinpath(bot_path, "history/" * yr * "/" * m * ".json")
    !isdir(dirname(current_closed_orders_path)) ? mkpath(dirname(current_closed_orders_path)) : ""
    closed_orders = isfile(current_closed_orders_path) ? JSON.parsefile(current_closed_orders_path) : Dict()
    !haskey(closed_orders, string(today())) ? closed_orders[string(today())] = [] : ""
    push!(closed_orders[string(today())], tmp)
    open(current_closed_orders_path, "w") do f
        JSON.print(f, closed_orders, 4)
    end

    #
    ## Move to corresponding closed orders dir
    if tmp["type"] == "normal"
        mv(trade_path, joinpath(bot_path, "closed_orders/" * basename(trade_path)))
    elseif tmp["type"] == "initial"
        mv(trade_path, joinpath(bot_path, "closed_init_orders/" * basename(trade_path)))
    end

    trade_grid = JSON.parsefile(joinpath(bot_path, "trade_grid.json"))
    current_index = findfirst(x->x == tmp["price"], sort(string.(keys(trade_grid))))

    msg = "{" * config["name"] * "} Profit: " * string(round(tmp["profit"], digits=2)) * " €"
    msg *= " (" * string(current_index) * "/" * string(length(trade_grid)) * ")"
    if config["telegram"] == "1"
        a = @task send_telegram_msg(config, msg, "/home/felix/pinguu/wp_data/telegram.json")
        schedule(a)
    end
end
export analyse_closed_order

function anaylse_closed_orders(client, config, bot_path; limit=2)
    new_closed = glob(joinpath(bot_path[2:end], "temp/new_closed*.json"));
    if length(new_closed) > limit
        new_closed = new_closed[1:limit]
    end
    for trade_path in new_closed
        Pinguu.analyse_closed_order(client, config, bot_path, trade_path)
    end
end
export analyse_closed_orders

function send_telegram_msg(config, msg::String, telegram_path::String)
    telegram = JSON.parsefile(telegram_path)
    TelegramClient(telegram["token"]; chat_id=telegram[string(config["user_id"])])
    sendMessage(text = msg)
end
export send_telegram_msg


text:
using TSne
using Test
using Random, Statistics, Distances
using RDatasets, MLDatasets

include("test_tsne.jl")


text:
"""
Check whether the predictions are correct.
"""
function iscorrect(gold_ind, pred_ind)
    gold_ind == pred_ind
end

"""
Display prediction nicely.
"""
function display_pred(
    preds,
    i2f,
    grams,
    tokenized = false,
    sep_token = nothing,
    start_end_token = "#",
    output_sep_token = "",
)

    if length(preds) == 0
        println("No prediction for this utterance")
    else
        for i = 1:length(preds)
            println("Predict $i")
            println("support: $(preds[i].support)")
            pred = translate(
                preds[i].ngrams_ind,
                i2f,
                grams,
                tokenized,
                sep_token,
                start_end_token,
                output_sep_token,
            )
            println("prediction: $pred")
        end
    end
end

"""
Translate indices into words or utterances
"""
function translate(
    ngrams_ind,
    i2f,
    grams,
    tokenized,
    sep_token,
    start_end_token,
    output_sep_token,
)

    if isnothing(output_sep_token)
        output_sep_token = ""
    end

    if tokenized && !isnothing(sep_token)
        s1 = join(
            [split(i2f[i], sep_token)[1] for i in ngrams_ind],
            output_sep_token,
        )
        s2 = join(
            split(i2f[ngrams_ind[end]], sep_token)[2:end],
            output_sep_token,
        )
        out = replace(
            s1 * output_sep_token * s2,
            start_end_token * sep_token => "",
        )
        out = replace(out, sep_token * start_end_token => "")
    else
        s1 = join([split(i2f[i], "")[1] for i in ngrams_ind], output_sep_token)
        s2 = join(split(i2f[ngrams_ind[end]], "")[2:end], output_sep_token)
        out = replace(s1 * output_sep_token * s2, start_end_token => "")
    end

    out
end

"""
Append indices together to form a path
"""
function translate_path(ngrams_ind, i2f; sep_token = ":")

    join([i2f[i] for i in ngrams_ind], sep_token)
end

"""
Check whether a matrix is truly sparse regardless its format, where M is originally a sparse matrix format.
"""
function is_truly_sparse(M::SparseMatrixCSC; threshold = 0.05, verbose = false)
    verbose && println("Sparsity: $(length(M.nzval)/M.m/M.n)")
    return threshold > (length(M.nzval) / M.m / M.n)
end

"""
Check whether a matrix is truly sparse regardless its format, where M is originally a dense matrix format.
"""
function is_truly_sparse(M::Matrix; threshold = 0.05, verbose = false)
    M = sparse(M)
    verbose && println("Sparsity: $(length(M.nzval)/M.m/M.n)")
    return threshold > (length(M.nzval) / M.m / M.n)
end

"""
Check whether a gram can attach to another gram.
"""
function isattachable(a, b)

    a[2:end] == b[1:end-1]
end

"""
Check whether a gram can attach to another gram.
"""
function isattachable(a, c, A)

    convert(Bool, A[a[end], c])
end

"""
Check whether a path is complete.
"""
function iscomplete(a, i2f; tokenized = false, sep_token = nothing, start_end_token = "#")

    ngram = i2f[a[end]]

    if tokenized && !isnothing(sep_token)
        last_w = split(ngram, sep_token)[end]
    else
        last_w = split(ngram, "")[end]
    end

    last_w == start_end_token
end

"""
Check whether a gram can start a path.
"""
function isstart(c, i2f; tokenized = false, sep_token = nothing, start_end_token = "#")

    ngram = i2f[c]

    if tokenized && !isnothing(sep_token)
        start_w = split(ngram, sep_token)[1]
    else
        start_w = split(ngram, "")[1]
    end

    start_w == start_end_token
end

"""
Check whether a predicted path is in training data.
"""
function isnovel(gold_ind, pred_ngrams_ind)

    !(pred_ngrams_ind in gold_ind)
end

"""
Check whether there are tokens already used in dataset as n-gram components.
"""
function check_used_token(data, target_col, token, token_name)
    data_columns = data[:, target_col]
    res = filter(x -> !isnothing(findfirst(token, x)), data_columns)

    if length(res) > 0
        throw(ArgumentError("$token_name \"$token\" is already used in the dataset"))
    end
end

"""
Calculate the max timestep given training and validation datasets.
"""
function cal_max_timestep(
    data_train,
    data_val,
    target_col;
    tokenized = false,
    sep_token = "",
)
    words_train = data_train[:, target_col]
    words_val = data_val[:, target_col]

    if tokenized && !isnothing(sep_token)
        max_l_words_train =
            maximum(x -> length(split(x, sep_token)), words_train)
        max_l_words_val = maximum(x -> length(split(x, sep_token)), words_val)
    else
        max_l_words_train = maximum(x -> length(split(x, "")), words_train)
        max_l_words_val = maximum(x -> length(split(x, "")), words_val)
    end

    maximum([max_l_words_train, max_l_words_val]) + 1
end

"""
Calculate the max timestep given training datasets only.
"""
function cal_max_timestep(data, target_col; tokenized = false, sep_token = "")

    words = data[:, target_col]

    if tokenized && !isnothing(sep_token)
        max_l_words = maximum(x -> length(split(x, sep_token)), words)
    else
        max_l_words = maximum(x -> length(split(x, "")), words)
    end

    max_l_words + 1
end


text:
using ArgParse
using Images

const ASCII_PALETTE = "MWNXK0Okxdolc:;,'...   "
const CHAR_HEIGHT = 99 # font's height (A.U.)
const CHAR_WIDTH = 56 # font's width (A.U.)

function parse_commandline()
    s = ArgParseSettings()

    @add_arg_table! s begin
        "path_to_img"
        	help = "Path to the image to be converted to ASCII."
        	arg_type = String
        	required = true

		"--width", "-w"
			help = "Set a new width for the (rescaled) image."
			arg_type = Int64
			required = false
    end

    return parse_args(ARGS, s)
end

function load_image(path_to_image::String)
    img = load(path_to_image)
end

function rescale_img(image::Array,
					 char_height::Int64,
					 char_width::Int64,
					 new_width::Int64)
	new_size = (new_width, trunc(Int64, new_width*char_height/char_width))
	img_rescaled = imresize(image, new_size)
end

function grayscale_img(image::Array)
	Gray.(image)
end

function html_base_string(img::Array)
	img_width = size(img)[2]
	html_header =
		"<!DOCTYPE html>\n
		\n
		\n
		<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n
		<link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n
		<link href=\"https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@300&display=swap\" rel=\"stylesheet\">\n
		\n
		\n
		\n

\n
		\n"
end

function img_to_ascii(img::Array, ascii_palette::String)
	rgb_img = floor.(Int64, channelview(img) * 255)
	gray_img = grayscale_img(img)
	normalized_img = (channelview(gray_img) * (length(ascii_palette) - 1)) .+ 1
	normalized_img = round.(Int64, normalized_img)
	ascii_img = html_base_string(img)
	for i in 1:size(normalized_img)[1]
		for j in 1:size(normalized_img)[2]
			pixel = string(rgb_img[1, i, j],
			 			   ",",
						   rgb_img[2, i, j],
						   ",",
						   rgb_img[3, i, j])
			color = "rgb($pixel)"
			ascii_img *= "" *
						 ascii_palette[normalized_img[i,j]] *
						 ""
		end
		ascii_img *= "
\n" # HTML line break
	end
	# Now close body and html elements
	ascii_img *=
		"
\n
		\n
		"
	return ascii_img
end

function save_to_html(path_to_html::String, ascii_img::String)
	open(path_to_html, "w") do f
		write(f, ascii_img)
	end
end

function main()
	parsed_args = parse_commandline()
	path_to_img = parsed_args["path_to_img"]
    img = load_image(path_to_img)
	if parsed_args["width"] != nothing
		img = rescale_img(img, CHAR_HEIGHT, CHAR_WIDTH, parsed_args["width"])
	else
		img = rescale_img(img, CHAR_HEIGHT, CHAR_WIDTH, size(img)[2])
	end
	ascii_img = img_to_ascii(img, ASCII_PALETTE)
	idx = findlast(".", path_to_img)[1] # index of the last dot (.) character
	path_to_html = path_to_img[1:idx] * "html"
	save_to_html(path_to_html, ascii_img)
	println("ASCII image saved at $path_to_html")
end

main()

max_stars_repo_name: alflhomme/artscii

max_issues_repo_name: alflhomme/artscii

max_forks_repo_name: alflhomme/artscii


text:
# ## Objectives
#
# Here we will show you how to perform an aerodynamic analysis of a conventional aircraft.
# > **Recipe**
# > 1. Define the geometries of a wing, horizontal tail and vertical tail.
# > 2. Mesh and plot the geometries for numerical analyses.
# > 3. Perform an aerodynamic analysis of this aircraft configuration at given freestream conditions and reference values.
# > 4. Evaluate its drag polar for a given range of angles of attack.
# > 5. Plot the spanwise loading distribution for the wing.

# For this, we will need to import some packages which will be convenient for plotting.
using AeroMDAO      # Main package
using Plots         # Plotting library
gr(dpi = 300)       # Plotting backend
using LaTeXStrings  # For LaTeX printing in plots

# ## Your First Wing
#
# Here you will learn how to define a wing using an intuitive parametrization scheme. First, we define a `Vector` of `Foil`s.

## Define one airfoil
airfoil_1 = naca4(4,4,1,2)

## Define vector of airfoils
airfoils  = [ airfoil_1, naca4((0,0,1,2)) ]

#md # !!! note
#md #     Refer to the [Airfoil Aerodynamic Analysis](tutorials-airfoil.md) tutorial for an introduction to the `Foil` type.

# ### Parametrization
# The following function defines a symmetric wing and prints the relevant information. Named arguments corresponding to the foil shapes, chord and span lengths, twist, dihedral and sweep angles. The following parametrization is used for the wing, presented for visual understanding.
# ![](https://godot-bloggy.xyz/post/diagrams/WingGeometry.svg)
wing = Wing(
        foils     = airfoils,    # Foil profiles
        chords    = [1.0, 0.6],  # Chord lengths
        twists    = [2.0, 0.0],  # Twist angles (degrees)
        spans     = [8.0],       # Section span lengths
        dihedrals = [5.],        # Dihedral angles (degrees)
        sweeps    = [5.],        # Sweep angles (degrees)
        w_sweep   = 0.,          # Sweep angle location w.r.t. normalized chord lengths ∈ [0,1]
    )

#md # !!! info
#md #     See the [How-to Guide](howto.md) for the various ways of constructing wings.

# ### Visualization
#
# The following function generates the coordinates of the wing's outline.
wing_outline = plot_planform(wing)

# Let's plot the geometry!
plt = plot(
           wing_outline[:,1], wing_outline[:,2], wing_outline[:,3],
           label = "Wing",
           xaxis = "x", yaxis = "y", zaxis = "z",
           aspect_ratio = 1,
           camera = (30, 45),
           zlim = (-0.1, span(wing) / 2),
          )

# ## Your First Vortex Lattice Analysis
# Now we would like to analyze the aerodynamics of this wing in conjunction with other lifting surfaces pertinent to aircraft.
#
# ### Geometry
# We define the horizontal tail similarly to the wing. However, we also add additional position (by specifying a vector) and orientation attributes (by specifying an angle and axis of rotation) to place it at the desired location.

## Horizontal tail
htail = Wing(foils     = fill(naca4(0,0,1,2), 2),
             chords    = [0.7, 0.42],
             twists    = [0.0, 0.0],
             spans     = [2.5],
             dihedrals = [0.],
             sweeps    = [6.39],
             w_sweep   = 0.,
             position  = [4., 0, 0],
             angle     = -2.,
             axis      = [0., 1., 0.])

# For the vertical tail, we simply replace `Wing` with `HalfWing` to define its shape.
## Vertical tail
vtail = HalfWing(foils     = fill(naca4(0,0,0,9), 2),
                 chords    = [0.7, 0.42],
                 twists    = [0.0, 0.0],
                 spans     = [1.0],
                 dihedrals = [0.],
                 sweeps    = [7.97],
                 w_sweep   = 0.,
                 position  = [4., 0, 0],
                 angle     = 90.,
                 axis      = [1., 0., 0.])

# Let's visualize the geometry of the aircraft's configuration.
htail_outline = plot_planform(htail)
vtail_outline = plot_planform(vtail)

plot!(plt,
    htail_outline[:,1], htail_outline[:,2], htail_outline[:,3],
    label = "Horizontal Tail"
   )
plot!(plt,
   vtail_outline[:,1], vtail_outline[:,2], vtail_outline[:,3],
   label = "Vertical Tail"
  )

# ### Meshing
# To perform the aerodynamic analysis, we will need to discretize our geometry into a _mesh_. The following `WingMesh` function constructs a mesh for you by providing a `HalfWing` or `Wing` type with specification of spanwise panels and chordwise panels. As the wing has only one spanwise section, we provide a vector with a single  integer entry for the spanwise panel distribution.
wing_mesh = WingMesh(wing, [12], 6) # (Wing, [Spanwise panels], Chordwise panels)

# Let's see what this discretization looks like on the camber distribution of the wing.

## Compute camber panel distribution
wing_cam_panels = camber_panels(wing_mesh)

## Generate plotting points
plt_wing_pans   = plot_panels(wing_cam_panels)

[ plot!(plt, panel, label = "", color = :lightblue) for panel in plt_wing_pans ]
plot!(plt)

# Similarly we define the meshes for the other surfaces and plot them.
htail_mesh = WingMesh(htail, [6], 4)
vtail_mesh = WingMesh(vtail, [4], 3)

[ plot!(plt, panel, label = "", color = :orange)
    for panel in plot_panels(camber_panels(htail_mesh)) ]
[ plot!(plt, panel, label = "", color = :lightgreen)
    for panel in plot_panels(camber_panels(vtail_mesh)) ]
plot!(plt)

# ### Aerodynamic Analysis
# For the analysis, you have to assemble the meshes into a `ComponentVector`.
aircraft = ComponentVector(
                           wing  = make_horseshoes(wing_mesh),
                           htail = make_horseshoes(htail_mesh),
                           vtail = make_horseshoes(vtail_mesh)
                          )

# You can define the freestream condition as follows, by providing the angles of attack $\alpha$ and sideslip $\beta$ in degrees with a rotation vector $\Omega$.
fs  = Freestream(
                 alpha = 3.0, # degrees
                 beta  = 0.0, # degrees
                 omega = [0., 0., 0.]
                );

# You can define the reference values for the speed, area, span, chord, density, and location  as follows.
refs = References(speed    = 1.0,
                  area     = projected_area(wing),
                  span     = span(wing),
                  chord    = mean_aerodynamic_chord(wing),
                  density  = 1.225,
                  location = mean_aerodynamic_center(wing));

# You can run the aerodynamic analysis by providing the aircraft configuration, freestream, and reference values. Optionally you can also print the results.
system = solve_case(
        aircraft, fs, refs;
        print            = true, # Prints the results for only the aircraft
        print_components = true, # Prints the results for all components
    )

# You can obtain the aerodynamic coefficients from this system. The nearfield aerodynamic force and moment coefficients are ordered as $(C_{D_i}, C_Y, C_L, C_\ell, C_m, C_n)$.
nf = nearfield(system)

# !!! tip
#     Refer to the [how-to guide](howto.md) to see how to compute the aerodynamic coefficients of each component and perform stability analyses.

# ### Drag Polar

# Now let's analyze the drag polar of this aircraft configuration by varying the angle of attack and collecting the induced drag coefficient $C_{D_i}$.

## Define function to compute system varying with angle of attack.
vary_alpha(aircraft, α, refs) = solve_case(aircraft, Freestream(alpha = α), refs)

## Run loop
αs      = -5:0.5:5
systems = [ vary_alpha(aircraft, α, refs) for α in αs ]
## Cleaner: map(α -> vary_alpha(...), αs)

## Get coefficients
coeffs = nearfield.(systems)
CDis   = [ c[1] for c in coeffs ]
CLs    = [ c[3] for c in coeffs ];

# Let's plot the drag polar!
plot(CDis, CLs,
     label  = "",
     xlabel = L"C_{D_i}",
     ylabel = L"C_L",
     title  = "Drag Polar",
     ls     = :solid)

# Let's also take a look at the variations of all the coefficients.

## Concatenate results into one array
data = permutedims(reduce(hcat, [α; c] for (α, c) in zip(αs, coeffs)))

## Plot
plot(data[:,1], round.(data[:,2:end], digits = 4),
     layout = (3,2),
     xlabel = L"\alpha",
     ylabel = [L"C_{D_i}" L"C_Y" L"C_L" L"C_\ell" L"C_m" L"C_n" ],
     labels = "",
     size   = (800, 600)
    )

# > **Tip:** You can convert this into a DataFrame for convenient reference.
# > ```julia
# > using DataFrames, StatsPlots
# > data = DataFrame([ xs for xs in zip(αs, coeffs) ])
# > rename!(data, [:α, :CD, :CY, :CL, :Cl, :Cm, :Cn])
# > @df data plot()
# > ```

# ### Spanwise Loading

# You can compute the aerodynamic coefficients on the panels from the system.
CFs, CMs = surface_coefficients(system)

## Get panels along the chord-lines of the wing.
wing_panels = chord_panels(wing_mesh)

## Compute spanwise loads
span_loads  = spanwise_loading(wing_panels, CFs.wing, projected_area(wing))
CL_loads    = vec(sum(system.circulations.wing, dims = 1)) / (0.5 * refs.speed * refs.chord);

## Plot spanwise loadings
plot_CD = plot(span_loads[:,1], span_loads[:,2], label = :none, ylabel = L"C_{D_i}")
plot_CY = plot(span_loads[:,1], span_loads[:,3], label = :none, ylabel = L"C_Y")
plot_CL = begin
            plot(span_loads[:,1], span_loads[:,4], label = :none, xlabel = L"y", ylabel = L"C_L")
            plot!(span_loads[:,1], CL_loads, label = "Normalized", xlabel = L"y")
          end
plot(plot_CD, plot_CY, plot_CL, size = (800, 700), layout = (3,1))


text:
module test_bukdu_plugs_static

using Test
using Bukdu

routes(:a) do
    plug(Plug.Static, at="/hello", from=normpath(@__DIR__, "."))
end
result = Router.call(get, "/hello/static.jl")
@test startswith(String(result.resp.body), "module test_bukdu_plugs_static")
Routing.empty!()

routes(:b) do
    plug(Plug.Static, at="/", from=normpath(@__DIR__, "."))
end
result = Router.call(get, "/static.jl")
@test startswith(String(result.resp.body), "module test_bukdu_plugs_static")
Routing.empty!()

routes(:c) do
    plug(Plug.Static, at="/", from=normpath(@__DIR__, "."), only=["static.jl"])
end
result = Router.call(get, "/static.jl")
@test startswith(String(result.resp.body), "module test_bukdu_plugs_static")
@test Router.call(get, "/csrf_protection.jl").resp.status == 404
Routing.empty!()

routes(:d) do
    plug(Plug.Static, at="/", from=normpath(@__DIR__, "public"))
end
@test Router.call(get, "/a.html").resp.status == 200
@test Router.call(get, "/b.wasm").resp.status == 200
Routing.empty!()

end # module test_bukdu_plugs_static


text:
using Plots
using DifferentialEquations
using DiffEqBiological

seirmodel = @reaction_network SEIR begin
    β, S + I --> E + I
    δ, E --> I
    γ, I --> R
end β δ γ

function solveSEIR(u0, β, γ, δ, time_span)

    dprob = DiscreteProblem(seirmodel, u0, time_span, [β, δ, γ])
    jprob = JumpProblem(dprob, Direct(), seirmodel)

    sol = solve(jprob, SSAStepper())

    return sol

end

R0=2.0
N=10000
γ=0.1
β=γ*R0/N
δ=0.25

sol = solveSEIR([N-1,0,1,0], β, γ, δ, (0.0,360.0))

plot_graph = plot(sol, vars=(0,1), title="SEIR model/Gillespie R0=$R0 γ=$γ δ=$δ", label="Suscepible",
                  color=:blue, seriestype=:line, legend=:left, size=(1200,900))
plot!(plot_graph, sol, vars=(0,2), label="Infectious", color=:red)
plot!(plot_graph, sol, vars=(0,3), label="Exposed", color=:darkmagenta)
plot!(plot_graph, sol, vars=(0,4), label="Removed", color=:green)

png(plot_graph, "seir_gillespie.png")

max_stars_repo_name: seisyuu-hantatsushi/julia

max_issues_repo_name: seisyuu-hantatsushi/julia

max_forks_repo_name: seisyuu-hantatsushi/julia


text:
#=

  Test of uniform draw in Turing.jl

  What I can see Turing.jl don't have a function to randomly draw
  an element from a list, e.g.
     uniformDraw([1,10,32,100])
  It use have DiscreteUniform() and Categorical()

  So I'm trying to simulating uniformDraw....

  Asked about this at Discourse:
  # https://discourse.julialang.org/t/turing-jl-unformdraw-distribution/65123
  https://discourse.julialang.org/t/turing-jl-uniformdraw-distribution/65123

  Ah, it's there as DiscreteNonParametric()
  https://juliastats.org/Distributions.jl/stable/univariate/#Discrete-Distributions

  I was looking in an old documentation of Distributions.jl!

=#

using Turing
include("jl_utils.jl")

# Defined in jl_utils.jl
# UniformDraw(xs) = DiscreteNonParametric(xs, ones(length(xs)) ./ length(xs))

@model function uniformDrawTest(x,pcts)
    #=
    function uniformDraw(x)
        n = length(x)
        ix1 ~ DiscreteUniform(1,n)
        return x[ix1]
    end
    function uniformDraw(x,pcts)
        n = length(x)
        ix2 ~ Categorical(simplex(pcts))
        return x[ix2]
    end
    val1 ~ Dirac(uniformDraw(x))
    val2 ~ Dirac(uniformDraw(x,pcts))
    val3 ~ Dirac(uniformDraw(x))
    =#
    val1 ~ UniformDraw(x)
    val2 ~ DiscreteNonParametric(x,simplex(pcts))
    val3 ~ UniformDraw(x)
    println([val1,val2,val3])
end

x = [1,10,32,100]
pcts = [1,2,3,4] # ones(length(x))
model = uniformDrawTest(x,pcts)

# chns = sample(model, Prior(), 100_000)
# chns = sample(model, MH(), 100_000)
# chns = sample(model, PG(15), 10_000)
chns = sample(model, SMC(), 10_000)
# chns = sample(model, IS(), 100_000)

display(chns)
show_var_dist_pct(chns, :ix)
show_var_dist_pct(chns, :val1)
show_var_dist_pct(chns, :val2)
show_var_dist_pct(chns, :val3)

max_stars_repo_name: tias/hakank

max_issues_repo_name: tias/hakank

max_forks_repo_name: tias/hakank


text:
using SDE
using Cubature
import SDE.b, SDE.sigma, SDE.a
#srand(7)
if !isdefined(:Model)

type Model <: UvPro
    B
    beta
    Sigma
    A
    d::Int
end
end

b(t,x, P::Model) =   exp(-0.2*t)*P.B*x + P.beta
sigma(t,x, P::Model) = exp(-0.1*(t))*P.Sigma
a(t,x,  P::Model) = exp(-0.2*(t))*P.A

let d = 1

Q95 = sqrt(2.)*erfinv(0.95)
function mc(M)
  m = mean(M)
  ste = std(M)/sqrt(length(M))
  round([m, Q95*ste], floor(Int,2-log(10,Q95*ste)))
end

tmax = 0.6
tmin = 0.3
T = tmax - tmin

B0 = -2.0
beta0 = 0.0
sigma0 = .75
ph0(t,s ) =  5.*exp(-0.2*s)-5.*exp(-0.2*t)

u = 0.3
v = 0*0.5

B = exp(-0.2*tmax)*B0

N = 1000

P = Model(B0, beta0,sigma0, sigma0^2, 1)
Pt = UvLinPro(B,  beta0, sigma(tmax, v, P))
#Pt = UvLinPro(-1E-6, 0.0, sigma(tmax, v, P))
#Pt = UvAffPro(0.0, sigma(tmax, v, P))

tt = linspace(tmin, tmax, N)
dt = (tt[N]-tt[1])/(N-1)

ss = linspace(0.,T, N)
ds = (ss[N]-ss[1])/(N-1)

ttofss = map(s -> tofs(s, tmin, T), ss)

M = 10000

Yll = zeros(M)
UYll = zeros(M)

Y2ll = zeros(M)
UY2ll = zeros(M)

Ull = zeros(M)
YUll = zeros(M)

Yt0 = zeros(M)
Y2t0 = zeros(M)
YUt0 = zeros(M)
UYt0 = zeros(M)
Us0 = zeros(M)

nt = floor(Int,5N/10)

t0 =  tmin + dt*(nt-1)
W = SDE.sample(tt, Wiener())

@time for i in 1:M
	resample!(W, Wiener())
	Y = guidedeuler(u, W, tmax, v, Pt, P)
	UY = UofX(Y, tmin, T, v, Pt)
	ll = llikeliXcirc(Y, Pt, P)
	ll2 = llikeliU(UY, tmin, T, v, Pt, P)
	Yt0[i] = Y.yy[nt]
#	println(U.tt[ns], s0)
    s0 = UY.tt[nt]
	UYt0[i] = xofu(UY.tt[nt], UY.yy[nt], T, v, Pt)
	Yll[i] = ll
	UYll[i] = ll2
end

#       Y               UY                               U                       YU
println("\ntesttc0.jl:")
println("X° - proposal, U(X°) - timechanged X° proposal, U - proposal in U-time, X°(U) - undone timechange, X°° - X° at same times as Us")

println("X° at ", round(t0,3), "($nt): ""[", repr(mc(Yt0)),"]")
println("U(X°) at ", round(tofs(s0, tmin, T),3), "($nt): ""[", repr(mc(UYt0)),"]")

s0 = soft(t0, tmin, T)
ns = 1 + floor(Int,s0/ds)
print(s0)
s0 = ds*(ns-1)
println(" ", s0)

@Test.test abs(1.-SDE.J(T-0.001, T, Pt)*a(tmax, 0., Pt)) < 0.001

u0 = uofx(0., u,  T, v, Pt)
W = SDE.sample(ss, Wiener())
U = eulerU(u0, W, tmin, T, v, Pt, P)
@time for i in 1:M
 	resample!(W, Wiener())
	U = eulerU(u0, W, tmin, T, v, Pt, P)
	YU = XofU(U, tmin, T, v, Pt)
	llu = llikeliU(U, tmin, T, v, Pt, P)
	llyu = llikeliXcirc(YU, Pt, P)
	Us0[i] = U.yy[ns]
	YUt0[i] = xofu(s0, U.yy[ns],  T, v, Pt)
	Ull[i] = llu
	YUll[i] = llyu
end

println("X°(U) at ", round(tofs(s0,tmin, T),3), "($ns): ",  "[", repr(mc(YUt0[:])),"]")

W = SDE.sample(ttofss, Wiener())
@time for i in 1:M
	resample!(W, Wiener())
	Y2 = guidedeuler(u, W, tmax, v, Pt, P)
	Y2ll[i]  = llikeliXcirc(Y2, Pt, P)
	Y2t0[i] = Y2.yy[ns]
	U2 = UofX(Y2, tmin, T, v, Pt)
	UY2ll[i] = llikeliU(U2, tmin, T, v, Pt, P)

end

println("X°° at ", round(ttofss[ns],3), "($ns): ", "[", repr(mc(Y2t0[:])),  "]"	)

    pt = exp(lp(tmin, u, tmax, v, Pt))
	p = exp(SDE.varlp(tmin, u, tmax, v, ph0, B0, beta0, s->a(s, u, P)))
	println("p ", round(p,5), " ", repr(mc(exp(Yll)*pt)), repr(mc(exp(Ull)*pt)) , repr(mc(exp(Y2ll)*pt)))
	println("~p ", round(pt,5))
	w1 = mc(pt/p*exp(Yll))
	w1b = mc(pt/p*exp(UYll))

	w2 = mc(pt/p*exp(Ull))
	w2b = mc(pt/p*exp(YUll))
	w3 = mc(pt/p*exp(Y2ll))
    w3b = mc(pt/p*exp(UY2ll))

	println(" Σ ~p/p*psi(X°) = ", repr(w1), " ≈ 1\n",
	        " Σ ~p/p*psi(UX°) = ", repr(w1b), " ≈ 1\n",
            " Σ ~p/p*psi(U) = ", repr(w2), " ≈ 1\n",
            " Σ ~p/p*psi(YU) = ", repr(w2b), " ≈ 1\n",
            " Σ ~p/p*psi(Xs)= ", repr(w3), " ≈ 1\n",
            " Σ ~p/p*psi(UXs)= ", repr(w3b), " ≈ 1"
            )
	println("lmax ", maximum(exp(Yll)), " ", maximum(exp(Ull)), " ", maximum(exp(Y2ll)))

    Test.@test abs(w1[1] - 1.) < 1.96w1[2]
    Test.@test abs(w2[1] - 1.) < 1.96w2[2]
    Test.@test abs(w3[1] - 1.) < 1.96w3[2]

end


text:
"""
Based on:
https://medium.com/vooban-ai/hyperopt-tutorial-for-optimizing-neural-networks-hyperparameters-e3102814b919
"""
module TestVoobanBasic

using Test
using TreeParzen

objective(params) = params[:x]^2 - params[:x] + 1
space = Dict(:x => HP.Uniform(:x, -5.0, 5.0))
best = fmin(objective, space, 100)
@test isapprox(best[:x], 0.5366692707330428, rtol=1e1)

end
true


text:
addprocs(2)
@everywhere import MultipleShootingPEM
@everywhere include("ex3_base.jl")
@everywhere import Example3
@everywhere using JLD2
@everywhere using JSON

@everywhere N=1024
@everywhere function run_and_save(options_dict)
    println("Create directory")
    if ~isdir("solutions")
        mkdir("solutions")
    end
    time = Dates.format(Dates.now(), "yyyy-mm-ddTHH:MM:SS-sss")
    root_dir = "solutions/sol_"*time*"_"*string(rand(1:100000))
    mkdir(root_dir)
    for sim_len in options_dict["sim_len"]
        println("")
        println("**************************")
        println("sim_len = "*string(sim_len))
        options_dict["pem"] = merge(options_dict["pem"], Dict(:sim_len=>sim_len))
        results = Example3.runner(options_dict)
        println("Save results...")
        dir = root_dir*"/sim_len_"*string(sim_len)
        mkdir(dir)
        # Save all data
        JLD2.@save dir*"/results.jld2" results
        # Save config file separately to be easy to check it
        json_string = JSON.json(results["options"])
        open(dir*"/config.json","w") do f
            write(f, json_string)
        end
    end
end

#sim_len = [2^i for i in 0:10]
sim_len = [32, 1024]
options_dicts = []
# Near stable region
d = Dict("data_generator" => Dict(:t=>"pendulum", :N=>N,
                                  :σw=>0., :σv=>0.03,
                                  :ampl=>10, :rep=>16,
                                  :seed=>1),
         "pem" => Dict(:model=>"output_error"),
         "grid_cost_funtion" => Dict(:gl=>(20, 50), :ka=>(0.5, 6),
                                     :npoints => (50, 50)),
         "solve_grid" => Dict(:gl=>(20, 50), :ka=>(0.5, 6),
                              :npoints => (5, 5)),
         "sim_len" => sim_len)
push!(options_dicts, d)
# Full turns around center
d = Dict("data_generator" => Dict(:t=>"pendulum", :N=>N,
                                  :σw=>0., :σv=>0.03,
                                  :ampl=>50, :rep=>16,
                                  :seed=>1),
         "pem" => Dict(:model=>"output_error"),
         "grid_cost_funtion" => Dict(:gl=>(20, 50), :ka=>(0.5, 6),
                                     :npoints => (50, 50)),
         "solve_grid" => Dict(:gl=>(20, 50), :ka=>(0.5, 6),
                              :npoints => (5, 5)),
         "sim_len" => sim_len)
push!(options_dicts, d)
# Near unstable region
d = Dict("data_generator" => Dict(:t=>"inverted_pendulum",
                                  :N=>N, :ampl=>0.2, :rep=>16,
                                  :σv=>0, :seed=>1),
         "pem" => Dict(:model=>"output_error"),
         "grid_cost_funtion" => Dict(:gl=>(20, 50), :ka=>(0.5, 6),
                                     :npoints => (50, 50)),
         "solve_grid" => Dict(:gl=>(20, 50), :ka=>(0.5, 6),
                              :npoints => (5, 5)),
         "sim_len" => sim_len)
push!(options_dicts, d)

pmap(run_and_save, options_dicts)


text:
using Unicode

mutable struct Classification
    type::Symbol
    name::Symbol
    bio::String
    children::Vector{Classification}
    parent::Classification

    function Classification(classif::Dict{String, Any})
        children = [Classification(d) for d in get(classif, "children", [])]
        type = Symbol(Unicode.normalize(classif["type"], casefold=true, stripmark=true))
        name = Symbol(Unicode.normalize(classif["name"], casefold=true, stripmark=true))
        classif = new(type, name, get(classif, "bio", ""), children)
        for child in children
            child.parent = classif
        end
        classif
    end
end

function Base.show(io::IO, clf::Classification)
    if length(clf.children) < 2
        childrentext = " with $(length(clf.children)) child"
    else
        childrentext = " with $(length(clf.children)) children"
    end
    biotext = ""
    if clf.bio != ""
        biotext = " ($(clf.bio))"
    end
    print("Classification(", clf.type, " ", clf.name, biotext, childrentext, ")")
end

function getfirstparent(name::Symbol, classification::Classification)
    if classification.name == name
        parent = classification
        while parent.parent.name != :god
            parent = parent.parent
        end
        return parent
    else
        for child in classification.children
            parent = getfirstparent(name, child)
            if !isnothing(parent)
                return parent
            end
        end
    end
end

max_stars_repo_name: dlozeve/GardenOptim

max_issues_repo_name: dlozeve/GardenOptim

max_forks_repo_name: dlozeve/GardenOptim


text:
using HDF5  # to load HDF5 code via Requires
using PencilArrays
using Documenter

DocMeta.setdocmeta!(
    PencilArrays, :DocTestSetup,
    quote
        using PencilArrays
        using MPI
        MPI.Initialized() || MPI.Init()
    end;
    recursive=true,
)

function main()
    makedocs(;
        modules = [PencilArrays],
        authors = "Juan Ignacio Polanco <jipolanc@gmail.com> and contributors",
        repo = "https://github.com/jipolanco/PencilArrays.jl/blob/{commit}{path}#L{line}",
        sitename = "PencilArrays.jl",
        format = Documenter.HTML(;
            prettyurls = true,
            canonical = "https://jipolanco.github.io/PencilArrays.jl",
            assets = [
                "assets/custom.css",
                "assets/tomate.js",
            ],
        ),
        pages = [
            "Home" => "index.md",
            "Library" => [
                "MPITopology.md",
                "Pencils.md",
                "PencilArrays.md",
                "Transpositions.md",
                "PencilIO.md",
                "PencilArrays_timers.md",
            ],
        ],
        linkcheck = false,
    )

    deploydocs(;
        repo = "github.com/jipolanco/PencilArrays.jl",
        forcepush = true,
    )

    nothing
end

main()


text:
module TestAqua

import Aqua
import FoldsKernelAbstractions
using Test

Aqua.test_all(FoldsKernelAbstractions; ambiguities = false, project_extras = false)

@testset "Method ambiguity" begin
    Aqua.test_ambiguities(FoldsKernelAbstractions)
end

end  # module


text:
### from RosettaCode
### http://rosettacode.org/wiki/Factors_of_an_integer#Julia
function factors(n)
    f = [one(n)]
    for (p,e) in factor(n)
        f = reduce(vcat, f, [f*p^j for j in 1:e])
    end
    return length(f) == 1 ? [one(n), n] : sort!(f)
end

for x in 2:24
	println(x, " ", 10*sum(factors(x)))
end

count = 100000
x = 0
while x < 34000000
	count += 1
	x = 10*sum(factors(count))
	if count % 10000 == 0
		println(count, " ", x)
	end
end
println(count, " ", x)

### second way
### allocate M houses and add a loop over elves adding presents to each house

# allocate the houses
houses = 11*ones(Int64, 3400000)
for elf in 2:length(houses)
	houses[elf:elf:min(50*elf, 3400000)] += 11*elf
end

for (idx, h) in enumerate(houses)
	if h > 34000000
		println(idx)
		break
	end
end

max_stars_repo_name: jstrube/adventofcode

max_issues_repo_name: jstrube/adventofcode

max_forks_repo_name: jstrube/adventofcode


text:
using Printf
using TimerOutputs
using Oceananigans
using Oceananigans.Utils

include("benchmark_utils.jl")

#####
##### Benchmark setup and parameters
#####

const timer = TimerOutput()

Nt = 10  # Number of iterations to use for benchmarking time stepping.

threads = Threads.nthreads()

if threads == 1
    Ns = [(16, 16, 16), (32, 32, 32), (64, 64, 64), (128, 128, 128), (256, 256, 256)]
else
    Ns = [(256, 256, 256)]
end

   float_types = [Float32, Float64]
         archs = [CPU()]
@hascuda archs = [CPU(), GPU()]

#####
##### Run benchmarks
#####

for arch in archs, FT in float_types, N in Ns
    grid = RegularCartesianGrid(size=N, extent=(1, 1, 1))
    model = IncompressibleModel(architecture=arch, float_type=FT, grid=grid)

    time_step!(model, 1)  # precompile

    bname =  benchmark_name(N, "", arch, FT)
    @printf("Running static ocean benchmark: %s...\n", bname)
    for i in 1:Nt
        @timeit timer bname time_step!(model, 1)
    end
end

#####
##### Print benchmark results
#####

println()
println(oceananigans_versioninfo())
println(versioninfo_with_gpu())

title = "Static ocean benchmarks"
title *= threads > 1 ? " ($threads threads)" : ""

print_timer(timer, title=title, sortby=:name)

println("\n\nCPU Float64 -> Float32 speedup:")
for N in Ns
    bn32 = benchmark_name(N, "", CPU(), Float32)
    bn64 = benchmark_name(N, "", CPU(), Float64)
    t32  = TimerOutputs.time(timer[bn32])
    t64  = TimerOutputs.time(timer[bn64])
    @printf("%s: %.3f\n", benchmark_name(N), t64/t32)
end

@hascuda begin
    println("\nGPU Float64 -> Float32 speedup:")
    for N in Ns
        bn32 = benchmark_name(N, "", GPU(), Float32)
        bn64 = benchmark_name(N, "", GPU(), Float64)
        t32  = TimerOutputs.time(timer[bn32])
        t64  = TimerOutputs.time(timer[bn64])
        @printf("%s: %.3f\n", benchmark_name(N), t64/t32)
    end

    println("\nCPU -> GPU speedup:")
    for N in Ns, ft in float_types
        bn_cpu = benchmark_name(N, "", CPU(), ft)
        bn_gpu = benchmark_name(N, "", GPU(), ft)
        t_cpu  = TimerOutputs.time(timer[bn_cpu])
        t_gpu  = TimerOutputs.time(timer[bn_gpu])
        @printf("%s: %.3f\n", benchmark_name(N, ft), t_cpu/t_gpu)
    end
end

println()


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:4] <= 1)

                     @variable(m, -6.563131467197746 <= q <= 9.310824610097802)

                     add_NL_constraint(m, :(softplus(0.5323461867533106 + 0.6233251355511138*softplus(0.9117705078314118 + -0.4325489455874667*$(x[1]) + 0.44461795780922087*$(x[2]) + -0.310674968881143*$(x[3]) + 0.3874148238299093*$(x[4])) + 0.13135733952437967*softplus(0.4793544889478012 + 0.21125743039643652*$(x[1]) + -0.625324840825729*$(x[2]) + -0.9496988785997882*$(x[3]) + 0.8662818947925528*$(x[4])) + -0.0038770043009219712*softplus(0.7417071748063861 + 0.06375566706279434*$(x[1]) + -0.03899151888275032*$(x[2]) + 0.7226457302550271*$(x[3]) + 0.006005128865761655*$(x[4]))) + softplus(0.48577545639109676 + -0.6684827900810446*softplus(0.9117705078314118 + -0.4325489455874667*$(x[1]) + 0.44461795780922087*$(x[2]) + -0.310674968881143*$(x[3]) + 0.3874148238299093*$(x[4])) + 0.9262921195438665*softplus(0.4793544889478012 + 0.21125743039643652*$(x[1]) + -0.625324840825729*$(x[2]) + -0.9496988785997882*$(x[3]) + 0.8662818947925528*$(x[4])) + 0.29789654203123295*softplus(0.7417071748063861 + 0.06375566706279434*$(x[1]) + -0.03899151888275032*$(x[2]) + 0.7226457302550271*$(x[3]) + 0.006005128865761655*$(x[4]))) + softplus(0.2863540742777313 + -0.41164742912319063*softplus(0.9117705078314118 + -0.4325489455874667*$(x[1]) + 0.44461795780922087*$(x[2]) + -0.310674968881143*$(x[3]) + 0.3874148238299093*$(x[4])) + 0.6047572744817185*softplus(0.4793544889478012 + 0.21125743039643652*$(x[1]) + -0.625324840825729*$(x[2]) + -0.9496988785997882*$(x[3]) + 0.8662818947925528*$(x[4])) + -0.7133357903136108*softplus(0.7417071748063861 + 0.06375566706279434*$(x[1]) + -0.03899151888275032*$(x[2]) + 0.7226457302550271*$(x[3]) + 0.006005128865761655*$(x[4]))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
using DocOpt

include("toolkit.jl")
include("load_data.jl")
include("solve.jl")
include("save_output.jl")

doc =
"""Shadow Selector - Choosing your destiny

Usage:
  main.jl [options]

Options:
  -h --help                      Show this screen
  -l=<level> --loglevel=<level>  Log level: [default: info]
  -v --version                   Show version
"""

function main()
    args = docopt(doc)
    initialise_logger(args["--loglevel"])

    env = load_data(args)

    solution = solve(env)

    save_output(env, solution)

    exit(0)
end

Base.exit(main())