text:
"""
    sample_poissondisk(shape::Tuple{Int64},redFac;calsize::Int64=0,seed::Int64=1234,kargs...)

generates a Poisson disk sampling pattern for an Vector of size `shape` with a subsampling factor `redFac`.
The arguments are the same as in the 2d case with the exception that shape is of type `Tuple{Int64}`
"""
function sample_poissondisk(shape::Tuple{Int64},redFac;calsize::Int64=0,seed::Int64=1234,kargs...)
  sample_poissondisk((shape[1],1),redFac,calsize=calsize,seed=seed;kargs...)
end

function sample_poissondisk(shape::Tuple{Int64,Int64,Int64},redFac;calsize::Int64=0,seed::Int64=1234,kargs...)
  error("Not implemented")
end

"""
    sample_poissondisk(shape::Tuple{Int64,Int64},redFac::Float64;calsize::Int64=0, seed::Int64=1234,kargs...)

generates a Poisson disk sampling pattern for an Array of size `shape` with a subsampling factor `redFac`.

# Arguments
* `shape::NTuple{2,Int64}` - size of the Array to be sampled
* `redFac::Float64`        - subsampling factor
* (`calsize::Int64=0`)     - size of the fully sampled calibration area
* (`seed=1234`)            - seed for the random number generator
"""
function sample_poissondisk(shape::Tuple{Int64,Int64},redFac::Float64;calsize::Int64=0, seed::Int64=1234,kargs...)
  M,N = shape
  A = zeros(Int64,shape)
  ChosenSamples = 0
  NumberSamples = floor(Int64,M*N/redFac)
  A, ChosenSamples = setcalibrationarea(A,M,N,redFac,calsize)
  chosen = (LinearIndices(A))[findall(x->x!=0, A)]
  selection = (LinearIndices(abs.(A .- 1)))[findall(x->x!=0, abs.(A .- 1))]

  cal_x, cal_y = min(calsize,M), min(calsize,N)
  # forbiddenradius = floor(Int64,sqrt((M*N-calsize^2)/(NumberSamples-ChosenSamples)/pi))
  forbiddenradius = floor(Int64,sqrt((M*N-cal_x*cal_y)/(NumberSamples-ChosenSamples)/pi))
  if forbiddenradius <= 1
    forbiddenradius = 2
  end

  Random.seed!(seed)

  while ChosenSamples < NumberSamples
    if length(selection)<1
      A = reshape(A,M*N,1)
      A[chosen] .= 1
      A = reshape(A,M,N)
      selection = (LinearIndices(abs.(A .- 1)))[findall(x->x!=0, abs.(A .- 1))]
    end
    randnum = rand(1:length(selection))
    push!(chosen,selection[randnum])
    ChosenSamples += 1

    selection = deleteinsideforbiddenradius(chosen[end],selection,forbiddenradius,M,N)
  end
  A = reshape(A,M*N,1)
  A[chosen] .= 1

  A = reshape(A,M,N)

  return chosen
end

function deleteinsideforbiddenradius(chosen::Int64,selection::Array{Int64},rad::Int64,M::Int64,N::Int64)
  x,y=Tuple(CartesianIndices((M,N))[chosen])

  for xi = x-rad:x+rad
      for yi = y-rad:y+rad
        if (xi > 0 && xi<= M && yi > 0 && yi<= N)
        index = (LinearIndices((M,N)))[xi,yi]
        deleteindex = 0
        for (indexi,valuei) in enumerate(selection)
           if valuei == index
              deleteindex = indexi
           end
        end
        if deleteindex > 0
          deleteat!(selection,deleteindex)
        end
      end
      end
  end
  return selection
end


text:
function CCLTrack(Depth,ccl;DepthFrom=minimum(Depth),DepthTo=maximum(Depth),Dtick=false)

    cclax=gca()
    cclax.plot(ccl,Depth, color="black",linewidth=0.5)
    cclax.set_ylim([DepthTo,DepthFrom])
    cclax.set_xlim([-50,50])
    cclax.set_xlabel("CCL")
    cclax.set_yticks(range(DepthFrom, stop=DepthTo, length=51),minor=true)
    cclax.set_yticks(range(DepthFrom, stop=DepthTo, length=11))
    cclax.xaxis.tick_top()
    cclax.xaxis.set_label_position("top")
    cclax.tick_params("both",labelsize=8)
    setp(cclax.get_yticklabels(),visible=Dtick)
end

ext: jl


text:
@testset "714.best-time-to-buy-and-sell-stock-with-transaction-fee.jl" begin
    @test max_profit714([1, 3, 2, 8, 4, 9], 2) == 8
end


text:
using SatelliteToolbox
using LinearAlgebra

"""
`dif((q,ω)::Tuple{SatelliteToolbox.Quaternion,Vector})`
クォータニオンと角速度ベクトルを微分する関数
## Argument
- `(q,ω)::Tuple{SatelliteToolbox.Quaternion,Vector}` :時刻`t`における姿勢を表すクォータニオンと角速度ベクトルの組
- `(T,I)::Tuple{Vector,Matrix}` :時刻`t`におけるトルクベクトルと慣性テンソルの組
## Returns
- `(dq,dω)::Tuple{SatelliteToolbox.Quaternion,Vector}`時刻`t`における姿勢を表すクォータニオンと角速度ベクトルを時間微分したものの組
"""
function dif((q,ω)::Tuple{SatelliteToolbox.Quaternion,Vector},(T,I)::Tuple{Vector,Matrix})
    dq = 0.5q*ω
    dω = inv(I)*(T-cross(ω,(I*ω)))
    return (dq,dω)
end

max_stars_repo_name: yui-project/ACSim

max_issues_repo_name: yui-project/ACSim

max_forks_repo_name: yui-project/ACSim


text:
# This file is part of EndemicModel project, which is licensed under BDS-3-Clause.
# See file LICENSE.md for more information.

function database_path(
    ext::Union{Nothing,AbstractString} = data_extension(option(:database_data_type));
    database_directory = option(:database_directory),
    database_filename = option(:database_filename),
    kwargs...,
)
    joinpath(Path(database_directory), Path(database_filename * "." * ext))
end

function database_path(sourcesym::Symbol; kwargs...)
    source = DATA_SOURCES[sourcesym]
    database_path(data_extension(source); kwargs...)
end

function import_data(
    database::AbstractDatabase;
    database_data_type = option(:database_data_type),
    database_directory = option(:database_directory),
    database_filename = name(database),
    model_data_type = option(:model_data_type),
    model_directory = option(:model_directory),
    model_filename = name(database),
    simple::Bool = true,
    force_update::Bool = false,
    kwargs...,
)
    @debug "Creating database."
    imported = false
    if !force_update
        db_input = database_path(
            database_data_type;
            database_directory = database_directory,
            database_filename = database_filename,
        )
        model_input = database_path(
            model_data_type;
            database_directory = model_directory,
            database_filename = database_filename,
        )
        if (
            exists(db_input) &&
            exists(model_input) &&
            modified(db_input) >= today() &&
            modified(model_input) >= today()
        )
            @debug "Importing data from cache." db_input model_input
            data =
                import_data(database_data_type; path = db_input, simple = simple, kwargs...)
            modeldata = import_data(
                database_data_type;
                path = model_input,
                simple = simple,
                kwargs...,
            )
            model = SEIRModel(data; modeldata = modeldata, kwargs...)
            imported = true
            @debug "Data imported from cache."
        end
    end
    if !imported
        @debug "Importing data from sources."
        imp_kwargs = merge(default_kwargs(database), kwargs)
        data = import_data(sources(database); imp_kwargs...)
        model = nothing
        funcs = computing_functions(database)

        @debug "Data imported from sources." _debuginfo(data)
        @debug "Computing database."
        while any(func(data) for func ∈ funcs)
        end
    end
    @debug "Database created."
    (data, model)
end

function import_data!(database::AbstractDatabase; kwargs...)
    (data, model) = import_data(database; kwargs...)
    datadict!(database, data)
    !isnothing(model) && modeldict!(database, model)
    (data, model)
end

function export_data(source::AbstractDataSource, database::AbstractDatabase; kwargs...)
    export_data(source, datadict(database); kwargs...)
end

function export_data(
    database::AbstractDatabase;
    database_data_type = option(:database_data_type),
    database_directory = option(:database_directory),
    database_filename = name(database),
    model_data_type = option(:model_data_type),
    model_directory = option(:model_directory),
    model_filename = name(database),
    pretty::Bool = true,
    kwargs...,
)
    db_output = database_path(
        database_data_type;
        database_directory = database_directory,
        database_filename = database_filename,
    )
    model_output = database_path(
        model_data_type;
        database_directory = model_directory,
        database_filename = database_filename,
    )
    data = datadict(database)
    @info "Exporting database." path = db_output _debuginfo(data)
    dbout = export_data(
        database_data_type,
        data;
        pretty = pretty,
        output = db_output,
        kwargs...,
    )
    data = modeldict(database)
    @info "Exporting database models." path = model_output _debuginfo(data)
    modelout = export_data(
        model_data_type,
        data;
        pretty = pretty,
        output = model_output,
        kwargs...,
    )
    (dbout, modelout)
end


text:
using MarketData

clstamp = convert(TimestampArray, cl)

facts("timestamp conversion") do

    context("array of Timestamp from TimeArray") do
        @fact clstamp[1].value       --> 111.94
        @fact clstamp[500].value     --> 21.90
        @fact clstamp[1].timestamp   --> Date(2000,1,3)
        @fact clstamp[500].timestamp --> Date(2001,12,31)
    end
end


text:
using Printf

abstract type AbstractTransferOperator end

#########################
# Indexing
#########################

ATO = AbstractTransferOperator

Base.size(to::AbstractTransferOperator) = size(to.transfermatrix)
Base.length(to::AbstractTransferOperator) = prod(size(to))
Base.sum(to::AbstractTransferOperator, i::Int) = sum(to.transfermatrix, i)

Base.getindex(to::ATO, i) = to.transfermatrix[i]
Base.getindex(to::ATO, i, j) = to.transfermatrix[i, j]

#########################
# Pretty printing
#########################
function Base.summary(to::T) where T<:AbstractTransferOperator
    s = size(to)
    l = length(to)
    percent_nonzero = @sprintf("%.4f", count(to.transfermatrix .> 0.0)/length(to) * 100)

    transferoperatortype = typeof(to)
    return "$transferoperatortype of size $s with $percent_nonzero% nonzero entries"
end

function matstring(to::T) where T<:AbstractTransferOperator
    return summary(to)
end

Base.show(io::IO, to::T) where {T<:AbstractTransferOperator} =
    println(io, matstring(to))

export AbstractTransferOperator


text:
module TestCascadeModel
  using Test
  using EcologicalNetworks

  @test typeof(cascademodel(10, 0.1)) <: UnipartiteNetwork

  @test richness(cascademodel(10, 0.1)) == 10
  @test richness(cascademodel(10, 0.2)) == 10
  @test richness(cascademodel(20, 0.1)) == 20

  @test richness(cascademodel((10, 0.1))) == 10
  @test richness(cascademodel((10, 10))) == 10

  @test_throws ArgumentError cascademodel(10, 0.9)
  @test_throws ArgumentError cascademodel(10, 0.7)
  @test_throws ArgumentError cascademodel(-10, 0.1)

  empirical_foodweb = EcologicalNetworks.nz_stream_foodweb()[1]
  @test typeof(cascademodel(empirical_foodweb)) <: UnipartiteNetwork

end


text:
@testset "utils" begin

    @testset "update_with_cpmodel!()" begin
        trailer = SeaPearl.Trailer()
        model = SeaPearl.CPModel(trailer)

        x = SeaPearl.IntVar(2, 3, "x", trailer)
        y = SeaPearl.IntVar(3, 4, "y", trailer)
        z = SeaPearl.IntVar(4, 5, "z", trailer)
        SeaPearl.addVariable!(model, x)
        SeaPearl.addVariable!(model, y)
        SeaPearl.addVariable!(model, z; branchable=false)
        SeaPearl.addConstraint!(model, SeaPearl.Equal(x, y, trailer))
        SeaPearl.addConstraint!(model, SeaPearl.NotEqual(x, y, trailer))

        lh = SeaPearl.LearnedHeuristic(agent)

        SeaPearl.update_with_cpmodel!(lh, model)

        @test typeof(lh.action_space) == Array{Int64,1}
        @test lh.action_space == [2, 3, 4]
        @test typeof(lh.current_state) == SeaPearl.DefaultStateRepresentation{SeaPearl.DefaultFeaturization, SeaPearl.DefaultTrajectoryState}
        @test lh.reward.value == 0
        @test isa(lh.search_metrics, SeaPearl.SearchMetrics)
    end

    @testset "sync_state!()" begin
        trailer = SeaPearl.Trailer()
        model = SeaPearl.CPModel(trailer)

        x = SeaPearl.IntVar(2, 3, "x", trailer)
        y = SeaPearl.IntVar(2, 3, "y", trailer)
        SeaPearl.addVariable!(model, x)
        SeaPearl.addVariable!(model, y)
        SeaPearl.addConstraint!(model, SeaPearl.Equal(x, y, trailer))
        SeaPearl.addConstraint!(model, SeaPearl.NotEqual(x, y, trailer))

        lh = SeaPearl.LearnedHeuristic(agent)
        SeaPearl.update_with_cpmodel!(lh, model)

        SeaPearl.sync_state!(lh, model, x)

        @test Matrix(LightGraphs.LinAlg.adjacency_matrix(lh.current_state.cplayergraph)) == [0 0 1 1 0 0
                                                        0 0 1 1 0 0
                                                        1 1 0 0 1 1
                                                        1 1 0 0 1 1
                                                        0 0 1 1 0 0
                                                        0 0 1 1 0 0]

        @test lh.current_state.nodeFeatures == Float32[ 1 1 0 0 0 0
                                                            0 0 1 1 0 0
                                                            0 0 0 0 1 1]

        @test lh.current_state.variableIdx == 3

        SeaPearl.assign!(x, 2)
        SeaPearl.sync_state!(lh, model, y)

        @test Matrix(LightGraphs.LinAlg.adjacency_matrix(lh.current_state.cplayergraph)) == [0 0 1 1 0 0
                                                        0 0 1 1 0 0
                                                        1 1 0 0 1 0
                                                        1 1 0 0 1 1
                                                        0 0 1 1 0 0
                                                        0 0 0 1 0 0]

        @test lh.current_state.nodeFeatures == Float32[ 1 1 0 0 0 0
                                                            0 0 1 1 0 0
                                                            0 0 0 0 1 1]

        @test lh.current_state.variableIdx == 4
    end

    @testset "get_observation!()" begin
        trailer = SeaPearl.Trailer()
        model = SeaPearl.CPModel(trailer)

        x = SeaPearl.IntVar(2, 4, "x", trailer)
        y = SeaPearl.IntVar(6, 8, "y", trailer)
        SeaPearl.addVariable!(model, x)
        SeaPearl.addVariable!(model, y)
        SeaPearl.addConstraint!(model, SeaPearl.Equal(x, y, trailer))
        SeaPearl.addConstraint!(model, SeaPearl.NotEqual(x, y, trailer))

        lh = SeaPearl.LearnedHeuristic(agent)
        SeaPearl.update_with_cpmodel!(lh, model)

        obs = SeaPearl.get_observation!(lh, model, x)

        @test obs.reward == 0
        @test obs.terminal == false
        @test obs.actions_index==[1, 2, 3, 4, 5, 6]  #correspond to the index of branchable values [2, 3, 4, 6, 7, 8] for ALL variables
        @test obs.legal_actions == [2, 3, 4]
        @test obs.legal_actions_mask == [true, true, true, false, false, false]

        SeaPearl.remove!(x.domain, 2)

        obs = SeaPearl.get_observation!(lh, model, x)

        @test obs.reward == 0
        @test obs.terminal == false
        @test obs.actions_index==[1, 2, 3, 4, 5, 6]  #correspond to the index of branchable values [2, 3, 4, 6, 7, 8] for ALL variables
        @test obs.legal_actions == [3, 4]
        @test obs.legal_actions_mask == [false, true, true, false, false, false]

        SeaPearl.remove!(y.domain, 7)

        obs = SeaPearl.get_observation!(lh, model, y)

        @test obs.reward == 0
        @test obs.terminal == false
        @test obs.actions_index==[1, 2, 3, 4, 5, 6]  #correspond to the index of branchable values [2, 3, 4, 6, 7, 8] for ALL variables
        @test obs.legal_actions == [6, 8]
        @test obs.legal_actions_mask == [false, false, false, true, false, true]

    end

    @testset "action_to_value(::FixedOutput)" begin
        trailer = SeaPearl.Trailer()
        model = SeaPearl.CPModel(trailer)

        x = SeaPearl.IntVar(2, 3, "x", trailer)
        y = SeaPearl.IntVar(2, 3, "y", trailer)
        SeaPearl.addVariable!(model, x)
        SeaPearl.addVariable!(model, y)

        lh = SeaPearl.LearnedHeuristic{SeaPearl.DefaultStateRepresentation{SeaPearl.DefaultFeaturization,SeaPearl.DefaultTrajectoryState}, SeaPearl.DefaultReward, SeaPearl.FixedOutput}(agent)
        SeaPearl.update_with_cpmodel!(lh, model)

        obs = SeaPearl.get_observation!(lh, model, x)

        @test SeaPearl.action_to_value(lh, 1, obs.state, model) == 2
        @test SeaPearl.action_to_value(lh, 2, obs.state, model) == 3
        @test_throws BoundsError SeaPearl.action_to_value(lh, 3, obs.state, model)
    end

    #TODO repair TSPTW testset
    """
    @testset "action_to_value(::VariableOutput)" begin
        trailer = SeaPearl.Trailer()
        model = SeaPearl.CPModel(trailer)

        x = SeaPearl.IntVar(2, 3, "x", trailer)
        y = SeaPearl.IntVar(2, 3, "y", trailer)
        SeaPearl.addVariable!(model, x)
        SeaPearl.addVariable!(model, y)

        lh = SeaPearl.LearnedHeuristic{SeaPearl.DefaultStateRepresentation{SeaPearl.DefaultFeaturization,SeaPearl.DefaultTrajectoryState}, SeaPearl.DefaultReward, SeaPearl.VariableOutput}(agent)
        SeaPearl.update_with_cpmodel!(lh, model)

        obs = SeaPearl.get_observation!(lh, model, y)
        @test SeaPearl.action_to_value(lh, 1, obs.state, model) == 4
        @test SeaPearl.action_to_value(lh, 2, obs.state, model) == 2
        @test SeaPearl.action_to_value(lh, 3, obs.state, model) == 3
        @test_throws BoundsError SeaPearl.action_to_value(lh, 4, obs.state, model)

        SeaPearl.remove!(y.domain, 3)
        SeaPearl.update_with_cpmodel!(lh, model)

        obs = SeaPearl.get_observation!(lh, model, y)
        @test SeaPearl.action_to_value(lh, 1, obs.state, model) == 4
        @test SeaPearl.action_to_value(lh, 2, obs.state, model) == 2
        @test_throws BoundsError SeaPearl.action_to_value(lh, 3, obs.state, model)

        obs = SeaPearl.get_observation!(lh, model, x)
        @test SeaPearl.action_to_value(lh, 1, obs.state, model) == 2
        @test SeaPearl.action_to_value(lh, 2, obs.state, model) == 3
        @test_throws BoundsError SeaPearl.action_to_value(lh, 4, obs.state, model)
    end
    """

    @testset "branchable_values()" begin
        trailer = SeaPearl.Trailer()
        model = SeaPearl.CPModel(trailer)

        x = SeaPearl.IntVar(2, 3, "x", trailer)
        y = SeaPearl.IntVar(3, 4, "y", trailer)
        z = SeaPearl.IntSetVar(4, 5, "z", trailer)
        SeaPearl.addVariable!(model, x)
        SeaPearl.addVariable!(model, y; branchable=false)
        SeaPearl.addVariable!(model, z; branchable=false)

        @test SeaPearl.branchable_values(model) == [2, 3]
    end
end


text:
## Source: https://stackoverflow.com/questions/2997004/using-map-reduce-for-mapping-the-properties-in-a-collection
## ## It's a little mess.
## ## This way of finding the key names is not nice but it works.
## ## TODO: Find a better way to do this
"""
    computefeatureskeys(collection::Mongoc.Collection)

Compute the features keys of a collection with a max depth of 2 (I couldn't get the expected results for a depth > 3).
The keys are stored in another collection named `\$(collection.name)_keys`.
"""
function computefeatureskeys(collection::Mongoc.Collection)
        mapper = Mongoc.BSONCode("""
            function(){
              for(var key in this["features"]) {
                if(typeof this["features"][key] == 'object'){
                    for(var subkey in this["features"][key]) {
                        if(!(['exactValueString', 'floatApprox', 'tojson', 'top', 'bottom'].includes(subkey))) {
                            emit(key + "." + subkey, null);
                        }
                    }
                }
                else {
                    emit(key, null);
                }
              }
            }
        """)
    reducer = Mongoc.BSONCode("""function(key, stuff) { return null; }""")
    map_reduce_command = Mongoc.BSON()
    map_reduce_command["mapReduce"] = collection.name
    map_reduce_command["map"] = mapper
    map_reduce_command["reduce"] = reducer
    map_reduce_command["out"] = "$(collection.name)_keys"
    result = Mongoc.read_command(collection.database, map_reduce_command)
    return result
end

"""
    getfeaturesdf(collection::Mongoc.Collection; collection_keys=collection.database["\$(collection.name)_keys"], collectiontype::Symbol=:name)

Build a dataframe from the "features" field in `collection`.
"""
function getfeaturesdf(collection::Mongoc.Collection; collection_keys=collection.database["$(collection.name)_keys"], collectiontype::Symbol=:name)
    isempty(collection_keys) && computefeatureskeys(collection)
    collectiontype == :name && (collectiontype = getcollectiontype(collection_keys))
    features_name = [feature["_id"] for feature in collection_keys]
    colnames = getcolnamesdict(collection_keys, features_name, collectiontype=collectiontype)
    df = DataFrame(colnames)
    allowmissing!(df)
    fill!(df, collect(collection), features_name, collectiontype)
    types = eltype.(eachcol(df))
    parsecolumns!(Float64, df)
    return df
end

max_stars_repo_name: charlyalizadeh/OPFdecgen

max_issues_repo_name: charlyalizadeh/OPFdecgen

max_forks_repo_name: charlyalizadeh/OPFdecgen


text:
"""
    PositionEmbedding(size::Int, max_len::Int = 1024; trainable::Bool = false)

The position embedding layer. `size` is the number of neuron. `max_len` is the maximum acceptable length of input.
If is not `trainable`, `max_len` will dynamically adjust to the longest input length. If `trainable`, use a random init
embedding value, otherwise use a sin/cos position encoding.
"""
mutable struct PositionEmbedding{F, W <: AbstractArray{F}} <: AbstractBroadcastEmbed{F}
    trainable::Bool
    embedding::W
end

Flux.functor(pe::PositionEmbedding) = (pe.embedding,), m -> PositionEmbedding(pe.trainable, m...)

get_value(e::PositionEmbedding, name::Symbol, xs::NamedTuple) = e(first(xs))

function PE(size, pos, i::Int)
    if rem(i, 2) == 0
        sin(pos/1e4^(i/size))
    else
        cos(pos/1e4^((i-1)/size))
    end
end

function PositionEmbedding(size::Int, max_len::Int = 1024; trainable::Bool = false)
    if trainable
        embedding = randn(Float32, size, max_len)
    else
        embedding = Matrix{Float32}(undef, size, max_len)
        for l = 1:max_len
            map!(i->PE(size, l, i), selectdim(embedding, 2, l), 1:size)
        end
    end
    PositionEmbedding(trainable, embedding)
end

using ZygoteRules: @adjoint, AContext, pullback
import ZygoteRules: _pullback

function resize_pe!(pe::PositionEmbedding, len::Int)
    max_len = size(pe.embedding, 2)

    if len > max_len
        if pe.trainable
            error("position embedding length exceeded")
        else
            over = similar(pe.embedding, size(pe.embedding, 1), len)
            copyto!(over, 1, pe.embedding, 1, length(pe.embedding))

            for l = size(pe.embedding, 2)+1:len
                map!(i->PE(size(pe.embedding, 1), l, i), selectdim(over, 2, l), 1:size(pe.embedding, 1))
            end

            pe.embedding = over
        end
    end
    return nothing
end

(pe::PositionEmbedding)(x::AbstractArray{Int}) = pe(size(x, 1))
(pe::PositionEmbedding{F})(x::AbstractArray{F}) where F = pe(size(x, 2))
function (pe::PositionEmbedding)(len::Int)
    resize_pe!(pe, len)
    idx = cumsum(fill!(similar(pe.embedding, Int, len), one(Int)))
    gather(pe.embedding, idx)
end

function _pullback(cx::AContext, pe::PositionEmbedding, len::Int)
    resize_pe!(pe, len)
    idx = cumsum(fill!(similar(pe.embedding, Int, len), one(Int)))
    y, back = _pullback(cx, gather, pe.embedding, idx)
    return y, Δ -> ((trainable=nothing, embedding=back(Δ)[2]), nothing)
end

function Base.show(io::IO, pe::PositionEmbedding)
    s, max_len = size(pe.embedding)
    if pe.trainable
        print(io, "PositionEmbedding($(s), max_len=$(max_len))")
    else
        print(io, "PositionEmbedding($(s))")
    end
end


text:
using Test
using MechGlueModelingToolkit
import MechGlueModelingToolkit.Unitfu
using Unitfu:s, @u_str
using ModelingToolkit
using ModelingToolkit: Symbolic, Variable, Differential, @syms, @variables

t = Variable{typeof(1.0s)}(:t)()
x = Variable{u"kg"}(:x)(t)
y = Variable{u"kg"}(:y)(t)
D = Differential(t)

eq1 = x ~ y*t
eq2 = x*10u"s" ~ y*t

@test ModelingToolkit.instantiate(t) == 1u"s"
@test ModelingToolkit.instantiate(x) == 1u"kg"
@test ModelingToolkit.instantiate(y) == 1u"kg"

@test !ModelingToolkit.validate(eq1)
@test ModelingToolkit.validate(eq2)

eqs = [
        D(x) ~ y/t
        D(y) ~ (x*y)/(t*10u"kg")
]

sys = ODESystem(eqs,t,[x,y],[])
@test ModelingToolkit.validate(sys)

@testset "MechGlueModelingToolkit.jl" begin
    # Write your tests here.
end


text:
import AllenNeuropixels as AN
using WGLMakie
using DataFrames
using Statistics
using FileIO

session_table = AN.getsessiontable()

function numprobes(sessionid)
	session_table[session_table[!, :id].==sessionid, :probe_count][1]
end

function targetintersections(sessionid)
	s = session_table[session_table.id.==sessionid, :ecephys_structure_acronyms][1]
	targets = ["VISp", "VISl", "VISrl", "VISal", "VISpm", "VISam", "CA1", "CA3", "DG", "SUB", "ProS", "LGd", "LP", "APN"];
	structures = eachmatch(r"'(.*?)'", s)
	structures = [replace(x.match, r"'"=>s"") for x ∈ structures]
	targetsintersected = [x ∈ structures for x ∈ targets]
	return mean(targetsintersected)
end;

metrics = AN.getunitanalysismetricsbysessiontype("brain_observatory_1.1")

session_metrics = combine(groupby(metrics, :ecephys_session_id),
		:ecephys_session_id => numprobes∘unique => :num_probes,
		:ecephys_session_id => targetintersections∘unique => :target_intersections,
		:has_lfp_data=>all,
		:genotype => (x->all(isequal.(x, ("wt/wt",)))) => :is_wt,
		:max_drift=>median∘skipmissing,
		:d_prime=>median∘skipmissing,
		:isolation_distance=>median∘skipmissing,
		:silhouette_score=>median∘skipmissing,
		:snr=>median∘skipmissing)

oursession = subset(session_metrics,
						:num_probes => ByRow(==(6)),
						:target_intersections => ByRow(>(0.9)),
						:is_wt => ByRow(==(true)),
						:has_lfp_data_all => ByRow(==(true)),
						:max_drift_median_skipmissing => ByRow(<(25.0)))

session = AN.Session(oursession.ecephys_session_id[1])

session = AN.Session(757216464)
probeid = 769322749

# --------------------- Do the plots and save to dropbox --------------------- #
AN.Plots.formattedreferencevolume(session, "C:\\Users\\Brendan\\Dropbox (Sydney Uni Student)\\AllenNeuropixels\\probelocations.html")

data = AN.getdownsampledlfp(session, probeid);
fig = AN.Plots.neuroslidingcarpet(data; resolution=(800, 800));
AN.Plots.htmlexport(fig)


text:
################################################################################
#
#   DEFINITION OF CONCRETE HAMILTONIAN <: AbstractHamiltonian
#   - label type L (of bond labels)
#   - unitcell type U<:AbstractUnitcell{S,B} where {S, B<:AbstractBond{L,N} where {N}},
#   - bond hamiltonian type HB<:AbstractBondHamiltonian{L,NS} where {NS}
#
################################################################################

################################################################################
#
#   ABSTRACT TYPE DEFINITION
#
################################################################################
struct Hamiltonian{L,UC,HB} <: AbstractHamiltonian{L,UC,HB}

    # the unitcell
    unitcell :: UC

    # the bond hamiltonian
    h_bond   :: HB

end

# export the type
export Hamiltonian

################################################################################
#
#	INTERFACING / ACCESSING HAMILTONIANS
#	(functions have to be overwritten by concrete types)
#
################################################################################

# Function to obtain the unitcell
function unitcell(
            h :: Hamiltonian{L,UC,HB}
        ) :: UC where {L,S,N,B<:AbstractBond{L,N},UC<:AbstractUnitcell{S,B},NS,HB<:AbstractBondHamiltonian{L,NS}}

    # return the unitcell
    return h.unitcell
end

# Function to obtain the bond hamiltonian
function bondHamiltonian(
            h :: Hamiltonian{L,UC,HB}
        ) :: HB where {L,S,N,B<:AbstractBond{L,N},UC<:AbstractUnitcell{S,B},NS,HB<:AbstractBondHamiltonian{L,NS}}

    # return the bond hamiltonian
    return h.h_bond
end

# easy constructor
function Hamiltonian(
            unitcell :: UC,
            h_bond   :: HB
        ) :: Hamiltonian{L,UC,HB} where {L,S,N,B<:AbstractBond{L,N},UC<:AbstractUnitcell{S,B},NS,HB<:AbstractBondHamiltonian{L,NS}}

    # return a newly created hamiltonian
    return Hamiltonian{L,UC,HB}(unitcell, h_bond)
end


text:
# Taken from https://github.com/kostya/benchmarks/blob/master/base64/test.jl

using Codecs
using MD5

function main(tries)
  str_size = 1_000_000
  str = repeat("a", str_size)
  println(bytes2hex(md5(str)))

  for i in range(0, tries)
    str = String(encode(Base64, str))
  end
  println(bytes2hex(md5(str)))

  for i in range(0, tries)
    str = String(decode(Base64, str))
  end
  println(bytes2hex(md5(str)))
end

main(20)

max_stars_repo_name: davidkellis/benchmarks

max_issues_repo_name: davidkellis/benchmarks

max_forks_repo_name: davidkellis/benchmarks


text:
printstyled("SeisIO.Nodal submodule\n", color=:light_green)

function pop_nodal_dict!(info:: Dict{String, Any}; n::Int64=12, kmax::Int64=32)
  for i in 1:n
    k = randstring(rand(1:kmax))
    t = rand([0x00000001,
              0x00000002,
              0x00000003,
              0x00000004,
              0x00000005,
              0x00000006,
              0x00000007,
              0x00000008,
              0x00000009,
              0x0000000a,
              0x00000020])
    T = get(SeisIO.Nodal.tdms_codes, t, UInt8)
    v = T == Char ? randstring(rand(1:256)) : rand(T)
    info[k] = v
  end
  return nothing
end

fstr = path*"/SampleFiles/Nodal/Node1_UTC_20200307_170738.006.tdms"
fref = path*"/SampleFiles/Nodal/silixa_vals.dat"
io = open(fref, "r")
YY = Array{UInt8, 1}(undef, 39518815)
readbytes!(io, YY)
XX = reshape(decompress(Int16, YY), 60000, :)


text:
# Section 6.4.2
# Boyd & Vandenberghe "Convex Optimization"
# Original by Lieven Vandenberghe
# Adapted for Convex by Joelle Skaf - 10/03/05
#
# Adapted for Convex.jl by Karanveer Mohan and David Zeng - 26/05/14
# Original cvx code and plots here:
# http://web.cvxr.com/cvx/examples/cvxbook/Ch06_approx_fitting/html/fig6_15.html
#
# Consider the least-squares problem:
#       minimize ||(A + tB)x - b||_2
# where t is an uncertain parameter in [-1,1]
# Three approximate solutions are found:
#   1- nominal optimal (i.e. letting t=0)
#   2- stochastic robust approximation:
#           minimize E||(A+tB)x - b||_2
#      assuming u is uniformly distributed on [-1,1] )
#      (reduces to minimizing E ||(A+tB)x-b||^2 = ||A*x-b||^2  + x^TPx
#        where P = E(t^2) B^TB = (1/3) B^TB )
#   3- worst-case robust approximation:
#           minimize sup{-1<=u<=1} ||(A+tB)x - b||_2)
#      (reduces to minimizing max{||(A-B)x - b||_2, ||(A+B)x - b||_2} )

using Convex

# Input Data
m = 20;
n = 10;
A = randn(m,n);
(U,S,V) = svd(A);
S = diagm(logspace(-1, 1, n));
A = U[:, 1:n] * S * V';

B = randn(m, n);
B = B / Base.norm(B);

b = randn(m, 1);
x = Variable(n)

# Case 1: Nominal optimal solution
p = minimize(norm(A * x - b, 2))
solve!(p)
x_nom = x.evaluate()

# Case 2: Stochastic robust approximation
P = 1 / 3 * B' * B;
p = minimize(square_pos(norm(A * x - b)) + quadform(x, P))
solve!(p)
x_stoch = x.evaluate()

# Case 3: Worst-case robust approximation
p = minimize(max(norm((A - B) * x - b), norm((A + B) * x - b)))
solve!(p)
x_wc = x.evaluate()

# plot residuals
novals = 100;
parvals = linspace(-2, 2, novals);

errvals_ls = [];
errvals_stoch = [];
errvals_wc = [];

for k=1:novals
  errvals_ls = [errvals_ls, Base.norm((A + parvals[k] * B) * x_nom - b)];
  errvals_stoch = [errvals_stoch, Base.norm((A + parvals[k] * B) * x_stoch - b)];
  errvals_wc = [errvals_wc, Base.norm((A + parvals[k] * B) * x_wc - b)];
end

# Plots. You'll need Gaston and gnuplot installed.
# For other plotting libraries, you probably have to change the next few lines.
using Gaston
Gaston.set_terminal("x11")
plot(parvals, errvals_ls, "color","blue", "legend", "Nominal problem",
     parvals, errvals_stoch, "color", "black", "legend", "Stochastic Robust Approximation",
     parvals, errvals_wc, "color", "red", "legend", "Worst-Case Robust Approximation",
     "title", "Residual r(u) vs a parameter u for three approximate solutions",
     "xlabel", "u", "ylabel", "r(u) = ||A(u)x-b||_2")


text:
#=
  Copyright (c) 2021
  https://github.com/Ismael-VC/Varvara.jl/blob/main/CONTRIBUTORS.md

  Permission to use, copy, modify, and distribute this software for any
  purpose with or without fee is hereby granted, provided that the above
  copyright notice and this permission notice appear in all copies.

  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE.
=#

module UxnCLI

import Base: show

using Dates: year, dayofyear, month, dayofmonth, hour, minute, second, dayofweek, now
using Printf: @sprintf

import Match

using Match: @match

using ..Uxn: CPU, Stack, Memory, Device
using ..VarvaraOS: uxn_boot, run!

#! format: off

export dev_console, dev_system, dev_datetime, dev_file,
       inspect, system_talk, nil_talk, datetime_talk,
       console_talk

show(io::IO, s::Stack)::Nothing = print(io, """
Stack:\tptr: $(@sprintf("%04x", s.ptr))\tkptr: $(@sprintf("%04x", s.kptr))\terror: $(@sprintf("%04x", s.error))
$(join([@sprintf("%02x", i) for i ∈ s.dat[0:15]], ' '))
$(join([@sprintf("%02x", i) for i ∈ s.dat[16:31]], ' '))
$(join([@sprintf("%02x", i) for i ∈ s.dat[32:47]], ' '))
$(join([@sprintf("%02x", i) for i ∈ s.dat[48:63]], ' '))
""")

show(io::IO, m::Memory)::Nothing = print(io, """
Memory:\tptr: $(@sprintf("%04x", m.ptr))
$(join([@sprintf("%02x", i) for i ∈ m.dat[0:15]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[16:31]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[32:47]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[48:63]], ' '))

$(join([@sprintf("%02x", i) for i ∈ m.dat[64:79]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[78:95]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[94:111]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[112:127]], ' '))

$(join([@sprintf("%02x", i) for i ∈ m.dat[128:143]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[142:159]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[158:175]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[174:191]], ' '))

$(join([@sprintf("%02x", i) for i ∈ m.dat[190:207]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[206:223]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[224:239]], ' '))
$(join([@sprintf("%02x", i) for i ∈ m.dat[240:255]], ' '))
""")

show(io::IO, d::Device)::Nothing = print(io, """
$(startswith(string(d.talk), '#') ? "Empty" : titlecase(split(string(d.talk), '_')[1]))\tDevice:\t$(@sprintf("%02x", d.id))
""")

show(io::IO, c::CPU)::Nothing = print(io, """
CPU: $(c.uuid)
ram.ptr: $(@sprintf("%04x", c.ram.ptr))\tdevs: $(sum(isassigned(c.dev, i) for i ∈ 0:15))

$(join(Device[c.dev[i] for i ∈ 0:15 if isassigned(c.dev, i)], ""))
wst:
ptr: $(@sprintf("%04x", c.wst.ptr))\tkptr: $(@sprintf("%04x", c.wst.kptr))\terror: $(@sprintf("%04x", c.wst.error))
$(join([@sprintf("%02x", i) for i ∈ c.wst.dat[0:15]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.wst.dat[16:31]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.wst.dat[32:47]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.wst.dat[48:63]], ' '))

rst:
ptr: $(@sprintf("%04x", c.rst.ptr))\tkptr: $(@sprintf("%04x", c.rst.kptr))\terror: $(@sprintf("%04x", c.rst.error))
$(join([@sprintf("%02x", i) for i ∈ c.rst.dat[0:15]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.rst.dat[16:31]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.rst.dat[32:47]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.rst.dat[48:63]], ' '))

src:
ptr: $(@sprintf("%04x", c.src.ptr))\tkptr: $(@sprintf("%04x", c.src.kptr))\terror: $(@sprintf("%04x", c.src.error))
$(join([@sprintf("%02x", i) for i ∈ c.src.dat[0:15]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.src.dat[16:31]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.src.dat[32:47]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.src.dat[48:63]], ' '))

dst:
ptr: $(@sprintf("%04x", c.dst.ptr))\tkptr: $(@sprintf("%04x", c.dst.kptr))\terror: $(@sprintf("%04x", c.dst.error))
$(join([@sprintf("%02x", i) for i ∈ c.dst.dat[0:15]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.dst.dat[16:31]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.dst.dat[32:47]], ' '))
$(join([@sprintf("%02x", i) for i ∈ c.dst.dat[48:63]], ' '))
""")

#! format: on

function uxn_halt(c::CPU, err::UInt8, name::AbstractString, id::Int)::Int
  @error "Halted"
  throw(UXN_ERRORS[error](@sprintf("%s#%04x, at 0x%04x", id, c.ram.ptr)))
end

end  # module

if abspath(PROGRAM_FILE) == @__FILE__
  using .UxnCLI: main

  main()
end


text:
using Documenter, GMT, GMT.Drawing, GMT.Gdal

makedocs(
	modules = [GMT],
	sitename = "GMT",
	format = Documenter.HTML(assets = ["assets/custom.css"]),
	pages = Any[
		"Introduction"             => "usage.md",
		"Quick Learn"              => "quick_learn.md",
		"Some examples"            => "examples.md",
		"Draw rectangles examples" => "rectangles.md",
		"Draw frames examples"     => "frames.md",
		"Map projections"          => "proj_examples.md",
		"Gallery"                  => [
			"Advanced ISC example"  => "gallery/isc.md",
			"AGU"                   => "gallery/tables.md",
			"Bar plots"             => "gallery/bars/bars.md",
			"Color lines"           => "gallery/color_lines/color_lines.md",
			"Choropleth maps"       => [
										"Coutries (DCW)"    => "gallery/choropleths/choropleth_DCW.md",
										"Covid in Portugal" => "gallery/choropleths/choropleth_cv19.md"
										],
			"Contourf"              => "gallery/contourf/contourf.md",
			"GADM Countries"        => "gallery/GADM/gadm.md",
			"Geodesic buffers"      => "gallery/buffergeo/buffer.md",
			"Historical collection" => "gallery/historic.md",
			"Landsat 8"             => "gallery/Landsat8/histogram_stretch.md",
			"Map projections"       => "gallery/mapprojs.md",
			"Plotting functions"    => "gallery/plot_funs/plot_funs.md",
			"Plotyy"                => "gallery/plotyy/plotyy.md",
			"Spirals"               => "gallery/spirals/spirals.md",
			"Ternary"               => "gallery/ternary/ternary.md",
			"UTM and Geog axes"     => "gallery/UTM_Geog_annot/ex28.md",
		],
		hide("gallery/scripts_agu/arrows_I.md"),
		hide("gallery/scripts_agu/arrows_II.md"),
		hide("gallery/scripts_agu/arrows_III.md"),
		hide("gallery/scripts_agu/bars_3D.md"),
		hide("gallery/scripts_agu/bars3_peaks.md"),
		hide("gallery/scripts_agu/bezier.md"),
		hide("gallery/scripts_agu/colored_bars.md"),
		hide("gallery/scripts_agu/compass.md"),
		hide("gallery/scripts_agu/decorated_I.md"),
		hide("gallery/scripts_agu/decorated_II.md"),
		hide("gallery/scripts_agu/error_bars.md"),
		hide("gallery/scripts_agu/flower.md"),
		hide("gallery/scripts_agu/histo_step.md"),
		hide("gallery/scripts_agu/matangles.md"),
		hide("gallery/scripts_agu/hello_I.md"),
		hide("gallery/scripts_agu/spiders.md"),
		hide("gallery/scripts_agu/snake.md"),
		hide("gallery/scripts_agu/solar.md"),
		hide("gallery/scripts_agu/scatter_cart.md"),
		hide("gallery/scripts_agu/scatter_polar.md"),
		hide("gallery/historic/ex01.md"),
		hide("gallery/historic/ex02.md"),
		hide("gallery/historic/ex03.md"),
		hide("gallery/historic/ex04.md"),
		hide("gallery/historic/ex05.md"),
		hide("gallery/historic/ex06.md"),
		hide("gallery/historic/ex07.md"),
		hide("gallery/historic/ex08.md"),
		hide("gallery/historic/ex09.md"),
		hide("gallery/historic/ex10.md"),
		hide("gallery/historic/ex11.md"),
		hide("gallery/historic/ex12.md"),
		hide("gallery/historic/ex13.md"),
		hide("gallery/historic/ex14.md"),
		hide("gallery/historic/ex15.md"),
		hide("gallery/historic/ex16.md"),
		hide("gallery/historic/ex17.md"),
		hide("gallery/historic/ex18.md"),
		hide("gallery/historic/ex19.md"),
		hide("gallery/historic/ex20.md"),
		hide("gallery/historic/ex21.md"),
		hide("gallery/historic/ex22.md"),
		hide("gallery/historic/ex23.md"),
		hide("gallery/historic/ex24.md"),
		hide("gallery/historic/ex25.md"),
		hide("gallery/historic/ex26.md"),
		hide("gallery/historic/ex27.md"),
		hide("gallery/historic/ex28.md"),
		hide("gallery/historic/ex29.md"),
		hide("gallery/historic/ex30.md"),
		hide("gallery/historic/ex32.md"),
		hide("gallery/historic/ex33.md"),
		hide("gallery/historic/ex34.md"),
		hide("gallery/historic/ex35.md"),
		hide("gallery/historic/ex36.md"),
		hide("gallery/historic/ex40.md"),
		hide("gallery/historic/ex41.md"),
		hide("gallery/historic/ex42.md"),
		hide("gallery/historic/ex43.md"),
		hide("gallery/historic/ex44.md"),
		hide("gallery/historic/ex45.md"),
		hide("gallery/historic/ex46.md"),
		hide("gallery/historic/ex48.md"),
		hide("pens.md"),
		hide("grdhisteq.md"),
		"Manual" => [
			"monolitic.md",
			"modules.md",
			"Common options"   => "common_opts.md",
			"General features" => [
				"arrows_control.md",
				"color.md",
				"decorated.md",
				"symbols.md",
				"themes.md",
			],
		],
		"Modules manuals" => [
			"arrows.md",
			"bar.md",
			"bar3.md",
			"coast.md",
			"colorbar.md",
			"contourf.md",
			"grdcontour.md",
			"grdimage.md",
			"grdgradient.md",
			"grdview.md",
			"histogram.md",
			"lines.md",
			"makecpt.md",
			"movie.md",
			"plot.md",
			"scatter.md",
			"scatter3.md",
			"solar.md",
			"subplot.md",
			"text.md",
		],
		"The GMT types"            => "types.md",
		"Index"                    => "index.md",
	],
)

deploydocs(
	repo   = "github.com/GenericMappingTools/GMT.jl.git",
	target  = "build",
	push_preview = true,
)


text:
export Model, @model
using MLStyle

using SimpleGraphs
using SimplePosets

abstract type AbstractModel end

struct Model <: AbstractModel
    args :: Vector{Symbol}
    body :: Vector{Statement}
end

function Model(vs :: Vector{Symbol}, expr :: Expr)
    body = [Statement(x) for x in expr.args]
    Model(vs, body)
end

macro model(vs::Expr,expr::Expr)
    @assert vs.head == :tuple
    @assert expr.head == :block
    Model(Vector{Symbol}(vs.args), expr)
end

macro model(v::Symbol, expr::Expr)
    Model([v], expr)
end

macro model(expr :: Expr)
    Model(Vector{Symbol}(), expr)
end

(m::Model)(vs...) = begin
    vs = collect(vs)
    vars = variables(m)
    args = m.args ∪ vs

    po = poset(m)
    g = digraph(m)

    function proc(m, st::Let)
        st.x ∈ vs && return nothing
        return st
    end
    function proc(m, st::Follows)
        if st.x ∈ vs && isempty(vars ∩ variables(st.rhs))
            return nothing
        end
        return st
    end
    proc(m, st) = st
    newbody = buildSource(m, proc)
    Model(args,newbody) |> toposort
end

(m::Model)(;kwargs...) = begin
    po = poset(m)
    g = digraph(m)

    vs = keys(kwargs)
    # Make v ∈ vs no longer depend on other variables
    for v ∈ vs
        for x in below(po, v)
            delete!(g, x, v)
        end
    end

    # Find connected components of what's left after removing parents
    partition = SimpleGraphs.simplify(g) |> SimpleGraphs.components |> collect

    keep = Symbol[]
    for v ∈ vs
        v_component = partition[in.(v, partition)][1]
        union!(keep, v_component)
    end

    function proc(m, st::Let)
        st.x ∈ vs && return nothing
        st.x ∈ keep && return st
        return nothing
    end
    function proc(m, st::Follows)
        st.x ∈ vs && return nothing
        st.x ∈ keep && return st
        return nothing
    end
    proc(m, st) = st
    newargs = keep ∩ setdiff(m.args, vs)
    newbody = buildSource(m, proc)
    for k in keys(kwargs)
        push!(newbody.args, Let(k, kwargs[k]))
    end
    Model(newargs,newbody) |> toposort
end

function Base.show(io::IO, m::Model)
    print(io, convert(Expr, m))
end

function Base.convert(::Type{Expr}, m::Model)
    numArgs = length(m.args)
    args = if numArgs == 1
       m.args[1]
    elseif numArgs > 1
        Expr(:tuple, [x for x in m.args]...)
    end
    q = if numArgs == 0
        @q begin
            @model $(convert(Expr, m.body))
        end
    else
        @q begin
            @model $(args) $(convert(Expr, m.body))
        end
    end
    striplines(q).args[1]
end

dropLines(l::Let)        = [l]
dropLines(l::Follows)    = [l]
dropLines(l::Return)     = [l]
dropLines(l::LineNumber) = []

export dropLines
dropLines(m::Model) = begin
    newbody = cat(dropLines.(m.body)..., dims=1)
    Model(m.args, newbody)
end


text:
#
# Self - Water
#

using PDBTools
include("../../src/MDDF.jl")

atoms = PDBTools.readPDB("./structure.pdb")
water_atoms = PDBTools.select(atoms,"water")
water = MDDF.Selection( water_atoms, natomspermol=3)

# Input options for the calcualtion
options = MDDF.Options(binstep=0.2)

trajectory = MDDF.Trajectory("./trajectory.dcd",water)
@time R = MDDF.mddf(trajectory,options)


text:
# jim.jl

import MIRT # jim
using Test: @test, @test_throws

@test MIRT.jim(:defs) isa Dict


text:
function init_2!(champu   :: Array{ComplexF64,2},
                 champv   :: Array{ComplexF64,2},
                 m        :: MicMac,
                 t        :: Float64,
                 fft_ubar :: Vector{ComplexF64},
                 fft_vbar :: Vector{ComplexF64},
                 fft_ug   :: Vector{ComplexF64},
                 fft_vg   :: Vector{ComplexF64})

    ftau!(champu, champv, m, t, fft_ubar, fft_vbar)

    fft!(champu, 1)
    fft!(champv, 1)

    champu[1, :] .= 0
    champv[1, :] .= 0

    champu ./= (1im * m.ktau)
    champv ./= (1im * m.ktau)

    ifft!(champu, 1)
    ifft!(champv, 1)

    fft_ubar .-= m.epsilon * champu[1, :]
    fft_vbar .-= m.epsilon * champv[1, :]

    C1!(champu, champv, m, t, fft_ubar, fft_vbar)

    fft_ug .-= champu[1, :]
    fft_vg .-= champv[1, :]

end


text:
#Function for quickly determining the energy of a state
#25/07/2017

function envalfunc(atom,nn,ll,jj)
  ZZ, spin, eneigval, params = GetAtomParams(atom,nn,ll,jj)
  return eneigval
end

max_stars_repo_name: CSChisholm/Rydberg

max_issues_repo_name: CSChisholm/Rydberg

max_forks_repo_name: CSChisholm/Rydberg


text:
"""
    logbin(x,P)

calculate a log-binned distribution from an evenly space distribution `P(x)`
where bins that start with `bin_width_start` (keyword argument) increase with
`inrement_factor` (keyword argument)

# Remarks
* `P` has to be a probability density
* `x` has to be equi-distant
"""
function logbin(x, P; increment_factor=sqrt(2), bin_width_start=1)
    @assert length(x)==length(P)

    dx = x[2]-x[1]

    index     = 1
    x_bin = zeros(1)
    P_bin = zeros(1)
    w_bin = ones(1)*floor(Int, bin_width_start)

    bin_counter = 0
    bin_width::Float64 = w_bin[end]
    for (i,p) in enumerate(P)
        # bin_counter counts the number of bins that are merged currently; if
        # this coincides with the target size, then create new bin and reset
        # counter.
        if bin_counter == w_bin[end]
            index += 1
            bin_counter = 0
            bin_width *= increment_factor
            push!(x_bin, 0)
            push!(P_bin, 0)
            push!(w_bin, floor(Int, bin_width))
        end
        bin_counter += 1

        # estimate expectation value of x in log bin
        x_bin[index] += x[i]*P[i]
        # estimate probability weight of bin (sum of equally spaced
        # probabilities)
        P_bin[index] += P[i]
    end

    # normalize x bins (end of expectation value)
    x_bin ./= P_bin

    # transform P into proper probability DENSITY such that <x>=\sum xP(x)dx/sum P(x)dx
    P_bin ./= w_bin

    return x_bin, P_bin, w_bin.*dx
end
logbin(dist; increment_factor=sqrt(2), bin_width_start=1) = logbin(collect(dist.edges[1])[1:end-1], dist.weights, increment_factor=increment_factor, bin_width_start=bin_width_start)

function pbc_index(x,y,Lx,Ly)
    _index = (y-1)*Lx + x
    #implement periodic boundary
    while x<1
        _index += Lx
        x += Lx
    end
    while x>Lx
        _index -= Lx
        x -= Lx
    end
    while y<1
        _index += Lx*Ly
        y += Ly
    end
    while y>Ly
        _index -= Lx*Ly
        y -= Ly
    end
    return _index
end

# correlation function for d-dimensional state but only along x-axis
function correlation_x!(C,state,lags)
    Ls = size(state)
    C .= 0
    mean_state = mean(state)
    L_x   = CartesianIndex(Ls[1],zeros(Int,length(Ls)-1)...)
    for (l,lag) in enumerate(lags)
        lag_x = CartesianIndex(lag,zeros(Int,length(Ls)-1)...)
        for r in CartesianIndices(Ls)
            r_ = r + lag_x
            if r_[1] > Ls[1]
                r_ -= L_x
            end
            C[l] += (state[r]-mean_state)*(state[r_]-mean_state)
        end
    end
    C./=length(state)
end
function correlation_x(state,lags)
    C = zeros(Float64, length(lags))
    correlation_x!(C, state,lags)
    return C
end


text:
using BandedMatrices, LinearAlgebra, UnicodePlots
using KernelAbstractions, StaticArrays
using CUDA, CUDAKernels
using KernelAbstractions: get_device
using KernelAbstractions.Extras: @unroll
using Test

@kernel function bandedlu_kernel!(
        LU::AbstractArray,
        ::Val{Nqh},
        ::Val{n},
        ::Val{ku},
        ::Val{kl},
        ::Val{Neh},
    ) where{Nqh, n, ku, kl, Neh}

    eh = @index(Group, Linear)

    ij = @index(Local, Linear)

    @inbounds for v = 1:n
        invUvv = 1/LU[ij, ku + 1, v, eh]

        for p = 1:kl
            LU[ij, ku + 1 + p, v, eh] *= invUvv
        end

        for q = 1:ku
            u = v + q
            if u ≤ n
                Uvu = LU[ij, ku + 1 - q, u, eh]
                for p = 1:kl
                    LU[ij, ku + 1 + p - q, u, eh] -=
                        LU[ij, ku + 1 + p, v, eh] * Uvu
                end
            end
        end
    end
end

@kernel function banded_forward_kernel!(
        x::AbstractArray{T, 3},
        LU::AbstractArray{T, 4},
        b::AbstractArray{T, 3},
        ::Val{Nqh},
        ::Val{n},
        ::Val{ku},
        ::Val{kl},
        ::Val{Neh},
    ) where{Nqh, n, ku, kl, Neh, T}

    # private storage for the part of b we are working on
    p_b = @private T (kl + 1)

    # horizonal element number
    eh = @index(Group, Linear)

    # horizontal degree of freedom
    ij = @index(Local, Linear)

    # Fill the private storage of b
    @inbounds for v = 1:kl+1
        p_b[v] = v ≤ n ? b[ij, v, eh] : -zero(T)
    end

    # Loop over the columns
    @inbounds for v = 1:n
        # Loop over the rows
        @unroll for p = 1:kl
            # Update element
            Luv = LU[ij, ku + 1 + p, v, eh]
            p_b[p + 1] -= Luv * p_b[1]
        end

        # Pull out the b associated with v
        x[ij, v, eh] = p_b[1]

        # Loop over the rows
        @unroll for p = 1:kl
            # shift the private array back one
            p_b[p] = p_b[p + 1]
        end

        # If we have more elements, get the next value
        if v + kl < n
            p_b[kl + 1] = b[ij, v + kl + 1, eh]
        end
    end
end

@kernel function banded_backward_kernel!(
        x::AbstractArray{T, 3},
        LU::AbstractArray{T, 4},
        b::AbstractArray{T, 3},
        ::Val{Nqh},
        ::Val{n},
        ::Val{ku},
        ::Val{kl},
        ::Val{Neh},
    ) where{Nqh, n, ku, kl, Neh, T}

    # private storage for the part of b we are working on
    p_b = @private T (ku + 1)

    # horizonal element number
    eh = @index(Group, Linear)

    # horizontal degree of freedom
    ij = @index(Local, Linear)

    # Fill the private storage of b
    @inbounds for q = 1:ku + 1
        v = n + 1 - q
        p_b[q] = v > 0 ? b[ij, v, eh] : -zero(T)
    end

    # Loop over the columns
    @inbounds for v = n:-1:1
        # Scale and store the first element of b
        Uvv = LU[ij, ku + 1, v, eh]
        p_b[1] /= Uvv

        # Loop over the rows
        @unroll for q = 1:ku
            # Update element
            Uuv = LU[ij, ku + 1 - q, v, eh]
            p_b[q + 1] -= Uuv * p_b[1]
        end

        x[ij, v, eh] = p_b[1]

        # Loop over the rows
        @unroll for q = 1:ku
            # shift the private array back one
            p_b[q] = p_b[q + 1]
        end

        # If we have more elements, get the next value
        if v - ku > 1
            p_b[ku + 1] = b[ij, v - ku - 1, eh]
        end
    end
end

function extract_banded!(B::AbstractMatrix, A::AbstractMatrix, p, q)
  @assert p ≥ 0
  @assert q ≥ 0

  m, n = size(A)

  for j = 1:n, i = max(1, j - q):min(j + p, n)
    B[q + i - j + 1, j] = A[i, j]
  end

  return B
end

function extract_banded(A::AbstractMatrix, p, q)
  B = similar(A, p + q + 1, size(A, 2))
  fill!(B, 0)
  extract_banded!(B, A, p, q)
end

let
  Nfields = 5
  Nq = (4, 4, 4)

  Nqh = prod(Nq[1:end-1])
  Nqv = Nq[end]

  Neh = 1350
  #Neh = 10
  Nev = 15

  kl = Nqv * Nfields
  ku = Nqv * Nfields

  n = Nfields * Nev * Nqv

  # T, AT = (Float64,  Array)
  T, AT = (Float64, CuArray)

  sA = Array(brand(T, n, n, kl, ku)) + 10I
  sF = lu(sA, Val(false))

  # display(spy(sA))
  # display(spy(sF.L))
  # display(spy(sF.U))

  bA = extract_banded(sA, kl, ku)
  bL = extract_banded(sF.L, kl, 0)
  bU = extract_banded(sF.U, 0, ku)

  A = AT(repeat(reshape(repeat(bA, inner=(Nqh, 1)), Nqh, kl+ku+1, n), outer=(1, 1, 1, Neh)))

  CUDA.@profile begin
      event = Event(get_device(A))
      kernel! = bandedlu_kernel!(get_device(A), (Nqh,))
      event = kernel!(A, Val(Nqh), Val(n), Val(ku), Val(kl), Val(Neh);
                      ndrange = (Nqh * Neh,), dependencies = (event,))
      wait(event)
  end

  L = repeat(reshape(repeat(bL, inner=(Nqh, 1)), Nqh, kl+1,    n), outer=(1, 1, 1, Neh))
  U = repeat(reshape(repeat(bU, inner=(Nqh, 1)), Nqh, ku+1,    n), outer=(1, 1, 1, Neh))
  LL = Array(A[:, ku+1:end, :, :])
  LL[:, 1,:, :] .= one(eltype(LL))
  UU = Array(A[:, 1:ku+1, :, :])
  @test U ≈ UU
  @test L ≈ LL

  bb = rand(T, Nq..., Nfields, Nev, Neh)
  xx = similar(bb)
  perm = (3, 4, 5, 1, 2, 6)
  xp = reshape(PermutedDimsArray(xx, perm), Nfields*Nqv*Nev, Nqh*Neh)
  bp = reshape(PermutedDimsArray(bb, perm), Nfields*Nqv*Nev, Nqh*Neh)
  xp .= sF \ bp

  bb = reshape(bb, Nqh, n, Neh)
  xx = reshape(xx, Nqh, n, Neh)

  b = AT(bb)
  x = similar(b)

  CUDA.@profile begin
      event = Event(get_device(A))
      kernel! = banded_forward_kernel!(get_device(A), (Nqh,))
      event = kernel!(x, A, b, Val(Nqh), Val(n), Val(ku), Val(kl), Val(Neh);
                      ndrange = (Nqh * Neh,), dependencies = (event,))
      kernel! = banded_backward_kernel!(get_device(A), (Nqh,))
      event = kernel!(x, A, x, Val(Nqh), Val(n), Val(ku), Val(kl), Val(Neh);
                      ndrange = (Nqh * Neh,), dependencies = (event,))
      wait(event)
  end

  @test xx ≈ Array(x)
end


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

MyGame.Example.eval(quote

FlatBuffers.@STRUCT struct Test
    a::Int16
    b::Int8
end
FlatBuffers.@ALIGN(Test, 2)

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

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

import ToStruct.tostruct

struct S1
    i::Int
    s::String
end

struct S2
    s1::S1
end

struct S3
    si::Union{String,Int}
    ni::Union{Nothing,Int}
    mi::Union{Missing,Int}
end

@testset "Any" begin
    @test tostruct(Any, 1) == 1.
    @test tostruct(Any, 1.) == 1.
    @test tostruct(Any, "foo") == "foo"
    @test tostruct(Any, [1, 2, 3]) == [1, 2, 3]
    @test tostruct(Any, Dict("a" => 1)) == Dict("a" => 1)
end

@testset "Primitive" begin
    @test tostruct(Int, 1) == 1
    @test tostruct(Float64, 1.) == 1.
    @test tostruct(String, "foo") == "foo"
    @test tostruct(Float64, 1) == 1.
end

@testset "Union" begin
    @test tostruct(Union{Nothing,Int}, 1) == 1
    @test tostruct(Union{Nothing,Int}, nothing) == nothing
    # Left type will be given priority
    @test tostruct(Union{Float64,Int}, 1.) == 1
    # Union{Int,Float64} will be automatically reordered to Union{Float64,Int} by julia compiler
    @test tostruct(Union{Int,Float64}, 1.) == 1
end

@testset "Vector" begin
    @test tostruct(Vector{S1}, [
        Dict("i" => 1, "s" => "foo"),
        Dict("i" => 2, "s" => "bar"),
    ]) == [
        S1(1, "foo"),
        S1(2, "bar"),
    ]
end

@testset "Dict" begin
    @test tostruct(Dict{String,S1}, Dict(
        "a" => Dict("i" => 1, "s" => "foo"),
        "b" => Dict("i" => 2, "s" => "bar"),
    )) == Dict(
        "a" => S1(1, "foo"),
        "b" => S1(2, "bar"),
    )
end

@testset "type" begin
    @test tostruct(S2, Dict(
        "s1" => Dict("i" => 1, "s" => "foo")
    )) == S2(
        S1(1, "foo")
    )
    @test tostruct(S2, Dict{Any,Any}(
        "s1" => Dict{Any,Any}("i" => 1, "s" => "foo")
    )) == S2(
        S1(1, "foo")
    )
    @test tostruct(S3, Dict("si" => "foo", "ni" => 1, "mi" => 1)) == S3("foo", 1, 1)
    @test tostruct(S3, Dict("si" => 1, "mi" => 1)).ni == nothing
    @test ismissing(tostruct(S3, Dict("si" => 1, "ni" => 1)).mi)
    @test_throws KeyError tostruct(S3, Dict("ni" => 1, "mi" => 1))
end


text:
# ## Run forward model
# ####################
# priority_cutoff = 1
# for gl in instances(I2Gls.ITMIX2Glaciers)
#     if getpriority(tab, gl)>priority_cutoff
#         continue
#     end
#     gid = ITMIX2Glacier(gl)
#     for (_, exp, radar) in experiments(tab, gl)
#         # note that the radar-lines do not matter here as we don't fit the model
#         @time gl,gb,pp,pm,pn,pl = BM.init_forward(gid, verbose;
#                                                   update_cache=update_cache,
#                                                   use_glogem=use_glogem,
#                                                   radarlines=getradar(radar))
#         @time out = BM.fwdm(gb, pp, pm, pn, gb.bdot-gb.dhdt, gb.fsl, gb.temp)
#         save_itmix2(gl, exp, out)
#     end
# end

##########################################
## Fitting
using Parameters
include("itmix-setup.jl")

######
# Choose glacier & options
######
plotyes = false
itmixversion = 2
itmix_exp = 10

glacier = :Unteraar
gid = BM.ITMIXGlacier(glacier, 2)
gl,gb,pp,pm,pn,pl = BM.init_forward(gid)

####################
# Do it
####################
runtyp = [:test,:mid,:prodlow,:prodmid,:prod][3]
fit_target = [BM.FitTarget.h, BM.FitTarget.iv, BM.FitTarget.h_iv, BM.FitTarget.length][3]
n_1d_btilde = 3
n_1d_fsl = 3
n_1d_temp = 1
rm_iv = false

(gln, gbn, th0d,
 theta0, logposterior, logposterior1d,
 logprior, logprior_debug, loglikelihood, loglikelihood1d,
 fwdm_fn, fwdm1d_fn, pmcmc_defaults, fit_target) =
     setup_one_exp(itmix_exp, gl, gb, pp, pm, pn,
                   n_1d_btilde, n_1d_fsl, n_1d_temp,
                   runtyp, fit_target, rm_iv)

# some tests:
print("Time to run forward model:")
@time fwdsol = fwdm_fn(theta0.th0);
# display(BM.plot_run(fwdsol, reuse=false, plot2d=[:h,:iv,:ivlog][1]))
print("Prior value:")
@show logprior(theta0.th0)[1]
#logprior_debug(theta0.th0)[1]
print("Posterior value:")
@show logposterior(theta0.th0)[1]
print("Time to calculate posterior:")
@time logposterior(theta0.th0)[1]

########
# max posterior estimation
#######
if false
    using Optim
    println("Optimizing for maximum posterior...")
    theta_max2 = optimize(theta_vec -> -logposterior(theta_vec)[1], float(theta0.th0), iterations=200, f_tol=1.0)
    # these don't work so well:
    #   theta_max2 = optimize(theta_vec -> -logposterior(theta_vec)[1], float(theta0.th0), GradientDescent())
    #theta_max2 = optimize(theta_vec -> -logposterior(theta_vec)[1], float(theta0.th0),  LBFGS())

    @show theta_max2
    error("asdf")
    theta0.th0[:] = theta_max2.minimizer
end

###############
## MCMC fitting
###############
println("Starting MCMC...")
pmcmc = BM.MCMCNum(;pmcmc_defaults...)

# sample posterior
sol = BM.mcmc(logposterior, theta0, pmcmc; verbose=true);
varnames = BM.get_varnames(theta0)
using KissMCMC
print_results(sol.thetas, sol.solverstats[:accept_ratio], sol.solverstats[:effective_sample_sizes], names=varnames)

# sample the prior to get that distribution too:
println("\n\nStarting MCMC of the prior to get that distribution too...")

pmcmc_prior = BM.MCMCNum(pmcmc, niter=10^5,
                         nthin = 50,
                         nburnin = 5*10^4,
                         nchains=100)

sol_prior = BM.mcmc(logprior, theta0, pmcmc_prior; verbose=true)
print_results(sol_prior.thetas, sol_prior.solverstats[:accept_ratio], sol_prior.solverstats[:effective_sample_sizes], names=varnames)

# BM.savemcmc(thetas, blobs, gb,
#                   pp, pm, pn, pmcmc,
#                   theta0, run, sigmas, error_on_dirty=false)

#end
# ### plots

if plotyes
    display(BM.plotinv1d(sol, reuse=false))
    display(BM.plotinv1d_err(sol, reuse=false))

    display(BM.plotinv2d(sol, reuse=false))
    display(BM.plotinv2d_h(sol, reuse=false))
    display(BM.plotinv2d_iverr(sol, reuse=false))
    @unpack thetas, theta0 = sol
    display(BM.plottheta(thetas, theta0))
    display(BM.plottheta(thetas, theta0, toplot=:btilde, reuse=false))
    display(BM.plottheta(thetas, theta0, toplot=:fsl, reuse=false))
    display(BM.plottheta(thetas, theta0, toplot=:temp, reuse=false))

    display(BM.plottheta_violin((thetas, sol_prior.thetas), theta0, :btilde, reuse=false, width=1))
    display(BM.plottheta_violin((thetas, sol_prior.thetas), theta0, :fsl, reuse=false, width=1))
    display(BM.plottheta_violin((thetas, sol_prior.thetas), theta0, :temp, reuse=false, width=1))
end


text:
EmptyWorkbook() = Workbook(EmptyMSOfficePackage(), Vector{Worksheet}(), false, Vector{Relationship}(), SharedStrings(), EzXML.XMLDocument(), Dict{Int, Bool}(), Dict{Int, Bool}())

"""
Lists internal files from the XLSX package.
"""
filenames(xl::XLSXFile) = keys(xl.data)

"""
Lists Worksheet names for this Workbook.
"""
sheetnames(wb::Workbook) = [ s.name for s in wb.sheets ]
sheetnames(xl::XLSXFile) = sheetnames(xl.workbook)

"""
Counts the number of sheets in the Workbook.
"""
sheetcount(wb::Workbook) = length(wb.sheets)
sheetcount(xl::XLSXFile) = sheetcount(xl.workbook)

"""
    isdate1904(wb) :: Bool

Returns true if workbook follows date1904 convention.
"""
isdate1904(wb::Workbook) :: Bool = wb.date1904
isdate1904(xf::XLSXFile) :: Bool = isdate1904(xf.workbook)

"""
    xmldocument(xl::XLSXFile, filename::String) :: EzXML.Document

Utility method to find the XMLDocument associated with a given package filename.
Returns xl.data[filename] if it exists. Throws an error if it doesn't.
"""
function xmldocument(xl::XLSXFile, filename::String) :: EzXML.Document
    @assert in(filename, filenames(xl)) "$filename not found in XLSX package."
    return xl.data[filename]
end

"""
    xmlroot(xl::XLSXFile, filename::String) :: EzXML.Node

Utility method to return the root element of a given XMLDocument from the package.
Returns EzXML.root(xl.data[filename]) if it exists.
"""
xmlroot(xl::XLSXFile, filename::String) :: EzXML.Node = EzXML.root(xmldocument(xl, filename))

function getsheet(xl::XLSXFile, sheetname::String) :: Worksheet
    for ws in xl.workbook.sheets
        if ws.name == sheetname
            return ws
        end
    end
    error("$(xl.filepath) does not have a Worksheet named $sheetname.")
end

getsheet(xl::XLSXFile, sheet_index::Int) :: Worksheet = xl.workbook.sheets[sheet_index]
getsheet(filepath::AbstractString, s) = getsheet(read(filepath), s)

Base.getindex(xl::XLSXFile, s) = getsheet(xl, s)

Base.show(io::IO, xf::XLSXFile) = print(io, "XLSXFile(\"$(xf.filepath)\")")


text:
#Pkg.add("GZip")
#Pkg.add("Glob")
#Pkg.add("JSON")

import GZip
import JSON

function iterlines(fun, filename)
    if endswith(filename, ".gz")
        f = GZip.open(filename)
        while !eof(f)
            line = readline(f)
            if length(line) == 0
                continue
            end
            fun(line)
        end
        close(f)
    else
        open(filename) do f
            while !eof(f)
                line = readline(f)
                fun(line)
            end
        end
    end
end

function parsetweet(line)
    if line[1] == '{'
        tweet = JSON.parse(line)
    else
        key, value = split(line, '\t', limit=2)
        tweet = JSON.parse(value)
        tweet["key"] = key
    end

    tweet
end

function itertweets(fun, filename::String)
    iterlines(filename) do line
        tweet = parsetweet(line)
        fun(tweet)
    end
end

function itertweets(fun, file)
    while !eof(file)
        line = readline(file)
        try
            tweet = parsetweet(line)
            fun(tweet)
        catch
            continue
        end
    end
end

function getkeypath(dict, key)
    if contains(key, ".")
        v = dict
        for k in split(key, '.')
            v = v[k]
        end

        return v
    else
        return dict[key]
    end
end

max_stars_repo_name: INGEOTEC/PatternAnalysisTools

max_issues_repo_name: INGEOTEC/PatternAnalysisTools

max_forks_repo_name: INGEOTEC/PatternAnalysisTools


text:
type T
  f::Function
  inF::Function
  t::Task
  T(f) = new(f)
end

function main()
	amount = 2
	tasks  = T[]
	for i = 1:amount
	  t     = T(function(t) function() while true produce(); t.inF() end end end)
	  t.inF = function() produce(); produce(); produce() end
	  t.t   = Task(t.f(t))
	  push!(tasks, t)
	end

	while true
	  for i = 1:amount
	    t = tasks[i]
		if rand(1:5) == 3
		  t.inF = eval(:(function() produce(); produce(); produce() end))
		end
		consume(t.t)
	  end
	end
end

@profile main()

#g:\my\projects\jevo>julia tmp\\consume.jl
#failed to get context from main thread. aborting profiling.

max_stars_repo_name: tmptrash/jevo

max_issues_repo_name: tmptrash/jevo

max_forks_repo_name: tmptrash/jevo


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

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

                     @variable(m, -65.76627584345755 <= q <= 59.26265199263469)

                     add_NL_constraint(m, :(swish(-0.4079491356153899 + -0.18134844314194787*swish(0.2817697329190594 + 0.989386077401103*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.6068435500303653*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.8530798012021474*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + 0.8376755183348754*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.6594644406874322*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.2976334456396539*swish(-0.4984715860832294 + -0.6460783499544172*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.0952691245496573*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + -0.5434919689873383*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.2400778955734424*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.904210133814042*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.11940205422195982*swish(-0.9402956128299329 + 0.19522910845028774*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + -0.5236489579886725*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + -0.09802794343243137*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.5359271533353085*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.5362141752531211*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.6350558501595733*swish(-0.842982128122256 + 0.6833459994096582*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.15560340828874075*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.5368387122163134*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.6086259049043772*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + -0.5403730914454505*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + 0.4683577877900529*swish(0.6067063734003204 + 0.8661978259504042*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + -0.06088102390312189*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.9836506901320718*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + 0.7952476421961925*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + -0.6703006410599177*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3])))) + swish(0.9379679817528435 + -0.4660824895766815*swish(0.2817697329190594 + 0.989386077401103*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.6068435500303653*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.8530798012021474*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + 0.8376755183348754*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.6594644406874322*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + 0.32761179552569075*swish(-0.4984715860832294 + -0.6460783499544172*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.0952691245496573*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + -0.5434919689873383*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.2400778955734424*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.904210133814042*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + 0.6880683972685175*swish(-0.9402956128299329 + 0.19522910845028774*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + -0.5236489579886725*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + -0.09802794343243137*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.5359271533353085*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.5362141752531211*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + 0.5888723964207281*swish(-0.842982128122256 + 0.6833459994096582*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.15560340828874075*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.5368387122163134*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.6086259049043772*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + -0.5403730914454505*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.05595383404471299*swish(0.6067063734003204 + 0.8661978259504042*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + -0.06088102390312189*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.9836506901320718*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + 0.7952476421961925*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + -0.6703006410599177*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3])))) + swish(-0.3048668135843893 + -0.3680078347752045*swish(0.2817697329190594 + 0.989386077401103*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.6068435500303653*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.8530798012021474*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + 0.8376755183348754*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.6594644406874322*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.09989706667818732*swish(-0.4984715860832294 + -0.6460783499544172*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.0952691245496573*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + -0.5434919689873383*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.2400778955734424*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.904210133814042*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.6733365176188579*swish(-0.9402956128299329 + 0.19522910845028774*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + -0.5236489579886725*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + -0.09802794343243137*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.5359271533353085*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.5362141752531211*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.7967060490111804*swish(-0.842982128122256 + 0.6833459994096582*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.15560340828874075*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.5368387122163134*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.6086259049043772*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + -0.5403730914454505*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + 0.8483184805894783*swish(0.6067063734003204 + 0.8661978259504042*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + -0.06088102390312189*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.9836506901320718*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + 0.7952476421961925*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + -0.6703006410599177*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3])))) + swish(-0.8260325513973243 + 0.9282935832138137*swish(0.2817697329190594 + 0.989386077401103*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.6068435500303653*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.8530798012021474*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + 0.8376755183348754*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.6594644406874322*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.5968467249691596*swish(-0.4984715860832294 + -0.6460783499544172*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.0952691245496573*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + -0.5434919689873383*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.2400778955734424*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.904210133814042*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.003449906971975558*swish(-0.9402956128299329 + 0.19522910845028774*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + -0.5236489579886725*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + -0.09802794343243137*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.5359271533353085*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.5362141752531211*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + 0.5427745947324003*swish(-0.842982128122256 + 0.6833459994096582*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.15560340828874075*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.5368387122163134*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.6086259049043772*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + -0.5403730914454505*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + 0.4794292841893828*swish(0.6067063734003204 + 0.8661978259504042*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + -0.06088102390312189*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.9836506901320718*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + 0.7952476421961925*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + -0.6703006410599177*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3])))) + swish(-0.3442450542855955 + 0.3679171232252214*swish(0.2817697329190594 + 0.989386077401103*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.6068435500303653*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.8530798012021474*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + 0.8376755183348754*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.6594644406874322*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + 0.4969759600474797*swish(-0.4984715860832294 + -0.6460783499544172*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.0952691245496573*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + -0.5434919689873383*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.2400778955734424*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.904210133814042*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.17345395101703964*swish(-0.9402956128299329 + 0.19522910845028774*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + -0.5236489579886725*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + -0.09802794343243137*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.5359271533353085*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + 0.5362141752531211*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + -0.24637355767613478*swish(-0.842982128122256 + 0.6833459994096582*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + 0.15560340828874075*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.5368387122163134*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + -0.6086259049043772*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + -0.5403730914454505*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))) + 0.4183638306902213*swish(0.6067063734003204 + 0.8661978259504042*swish(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3])) + -0.06088102390312189*swish(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3])) + 0.9836506901320718*swish(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3])) + 0.7952476421961925*swish(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3])) + -0.6703006410599177*swish(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3])))) - $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:
module iLQGames
    using DocStringExtensions
    using Reexport
    using Parameters
    using ForwardDiff
    using DiffResults
    @reexport using StaticArrays
    using LinearAlgebra
    using Parameters
    using Colors, ColorSchemes
    using LaTeXStrings
    using Plots
    gr()

    import Base:
        getindex,
        setindex!,
        zero,
        copy

    # game setup
    export ControlSystem, LTISystem, LTVSystem
    export PlayerCost, QuadraticPlayerCost, FunctionPlayerCost
    export AffineStrategy
    # games solution
    export GeneralGame
    export iLQSolver, solve, solve!, cost
    # visualization
    export plot_traj, plot_states, plot_inputs, @animated

    # some macro sugar to make life easier
    include("sugar.jl")
    include("performance.jl")

    # game utils
    include("strategy.jl")
    include("system_trajectory.jl")
    include("player_cost.jl")

    # interface for feedback linearizable system
    include("flat.jl")
    # dynamics abstraction
    include("control_system.jl")
    include("linear_system.jl")
    include("product_system.jl")
    # game abstraction
    include("game.jl")
    include("prealloc.jl")
    include("game_impl.jl")
    # ad quadraticization
    include("quadraticize.jl")

    # the solver implementations
    include("solve_lq_game.jl")
    include("ilq_solver.jl")

    # simulation
    include("sim.jl")

    # some handy tools for problem description
    include("cost_design_utils.jl")

    # some dynamical systems to work with
    include("lorenz.jl")
    include("unicycle_4D.jl")
    include("n_player_navigation_game.jl")
    include("n_player_unicycle_game.jl")
    include("n_player_2Ddoubleintegrator_cost.jl")

    # some helpful tooling
    include("plot_utils.jl")
    include("test_utils.jl")

end # module