text:
"""
    MeshImportModule

Module for mesh import  functions.
"""
module MeshImportModule

using FinEtools.FTypesModule: FInt, FFlt, FCplxFlt, FFltVec, FIntVec, FFltMat, FIntMat, FMat, FVec, FDataDict
import FinEtools.FENodeSetModule: FENodeSet
import FinEtools.FESetModule: FESet, FESetT4, FESetT10, FESetH8, FESetH20, setlabel!
import FinEtools.MeshModificationModule: renumberconn!
import Unicode: uppercase, isdigit
import LinearAlgebra: norm

"""
!!! note
The arrays are reallocated as the data is read from files. The size of the
arrays is increased by this much. If the number of entities to be read  is
large, the chunk should be probably increased so that only a few reallocations
are needed.
"""
const chunk = 1000

"""
    fixupdecimal(s)

Fix up an old style floating-point number without the exponent letter.
"""
function fixupdecimal(s)
    os = ""
    for i = length(s):-1:1
        os = s[i] * os
        if (s[i] == '-') && (i > 1) && (uppercase(s[i-1]) != "E") && isdigit(s[i-1])
            os = "E" * os
        end
        if (s[i] == '+') && (i > 1) && (uppercase(s[i-1]) != "E") && isdigit(s[i-1])
            os = "E" * os
        end
    end
    return os
end

"""
    import_NASTRAN(filename)

Import tetrahedral (4- and 10-node) NASTRAN mesh (.nas file).

    Limitations:
    1. only the GRID and CTETRA  sections are read.
    2. Only 4-node and 10-node tetrahedra  are handled.
    3. The file needs to be free-form (data separated by commas).

# Return
Data dictionary, with `fens`, `fesets`.
"""
function import_NASTRAN(filename; allocationchunk=chunk)
    lines = readlines(filename)

    nnode = 0
    node = zeros(allocationchunk, 4)
    maxnodel = 10
    nelem = 0
    elem = zeros(FInt, allocationchunk, maxnodel + 3)

    current_line = 1
    while true
        if current_line >= length(lines)
            break
        end
        temp  = lines[current_line]
        current_line = current_line + 1
        if (length(temp) >= 4) && (uppercase(temp[1:4]) == "GRID")
            nnode = nnode + 1
            if size(node, 1) < nnode
                node = vcat(node, zeros(allocationchunk, 4))
            end
            fixedformat = (length(temp) == 72) # Is this fixed-format record? This is a guess based on the length of the line.
            if fixedformat
                # $------1-------2-------3-------4-------5-------6-------7-------8-------9-------0
                # GRID*                  5               0-1.66618812195+1-3.85740337853+0
                # *       1.546691269367+1               0
                node[nnode, 1] = parse(Float64, fixupdecimal(temp[9:24]))
                node[nnode, 2] = parse(Float64, fixupdecimal(temp[41:56]))
                node[nnode, 3] = parse(Float64, fixupdecimal(temp[57:72]))
                temp  = lines[current_line]
                current_line = current_line + 1
                node[nnode, 4] = parse(Float64, fixupdecimal(temp[9:24]))
            else
                # Template:
                #   GRID,1,,-1.32846E-017,3.25378E-033,0.216954
                A = split(replace(temp, "," => " "))
                for  six = 1:4
                    node[nnode, six] = parse(Float64, A[six+1])
                end
            end
        end # GRID
        if (length(temp) >= 6) && (uppercase(temp[1:6]) == "CTETRA")
            # Template:
            #   CTETRA,1,3,15,14,12,16,8971,4853,8972,4850,8973,4848
            nelem = nelem + 1
            if size(elem, 1) < nelem
                elem = vcat(elem, zeros(FInt, allocationchunk, maxnodel + 3))
            end
            A = split(replace(temp, "," => " "))
            elem[nelem, 1] = parse(FInt, A[2])
            elem[nelem, 2] = parse(FInt, A[3])
            if length(A) == 7  #  nodes per element  equals  4
                nperel = 4
            else
                nperel = 10
                if length(A) < 13 # the line is continued: read the next line
                    temp  = lines[current_line]
                    current_line = current_line + 1
                    temp = strip(temp)
                    Acont = split(replace(temp, "," => " "))
                    A = vcat(A, Acont)
                end
            end
            elem[nelem, 3] = nperel
            for  six = 1:nperel
                elem[nelem, six+3] = parse(FInt, A[six+3])
            end
        end # CTETRA

    end # while

    node=node[1:nnode,:]
    elem=elem[1:nelem,:]
    # The nodes need to be in serial order:  if they are not,  the element
    # connectivities  will not point at the right nodes
    @assert  norm(collect(1:nnode)-node[:,1]) == 0 "Nodes are not in serial order"

    # Process output arguments
    # Extract coordinates
    xyz=node[:,2:4]
    # Cleanup element connectivities
    ennod = unique(elem[:,3])
    @assert length(ennod) == 1 "Cannot handle mixture of element types"

    @assert ((ennod[1] == 4) || (ennod[1] == 10)) "Unknown element type"
    conn = elem[:,4:3+convert(FInt, ennod[1])]

    # Create output arguments. First the nodes
    fens = FENodeSet(xyz)
    if ennod[1] == 4
        fes = FESetT4(conn)
    else
        fes = FESetT10(conn)
    end
    setlabel!(fes, elem[:,2])

    output = FDataDict("fens"=>fens, "fesets"=>[fes])
    return output
end

mutable struct AbaqusElementSection
    ElementLine::AbstractString
    nelem::FInt
    elem::Array{FInt,2}
end

"""
    import_ABAQUS(filename)

Import tetrahedral (4- and 10-node) or hexahedral (8- and 20-node) Abaqus mesh
(.inp file).

    Limitations:
    1. Only the `*NODE` and `*ELEMENT`  sections are read
    2. Only 4-node and 10-node tetrahedra and 8-node or 20-node  hexahedra
      are handled.

"""
function import_ABAQUS(filename; allocationchunk=chunk)
    lines = readlines(filename)

    maxelnodes = 20

    warnings = String[]
    nnode = 0
    node = zeros(allocationchunk, 4)
    Reading_nodes = false
    next_line = 1
    while true
        if next_line > length(lines)
            break
        end
        temp = uppercase(strip(lines[next_line]))
        next_line = next_line + 1
        if (length(temp) >= 5) && (temp[1:5] == "*NODE")
            Reading_nodes = true
            nnode = 0
            node = zeros(allocationchunk, 4)
            temp = uppercase(strip(lines[next_line]))
            next_line = next_line + 1
        end
        if Reading_nodes
            if temp[1:1] == "*" # another section started
                Reading_nodes = false
                break
            end
            nnode = nnode + 1
            if size(node, 1) < nnode # if needed, allocate more space
                node = vcat(node, zeros(allocationchunk, 4))
            end
            A = split(replace(temp, "," => " "))
            for  six = 1:length(A)
                node[nnode, six] = parse(Float64, A[six])
            end
        end
    end # while

    nelemset = 0
    elemset = AbaqusElementSection[]
    Reading_elements = false
    next_line = 1
    while true
        if next_line > length(lines)
            break
        end
        temp = uppercase(strip(lines[next_line]))
        next_line = next_line + 1
        if (length(temp) >= 8) && (temp[1:8] == "*ELEMENT")
            Reading_elements = true
            nelemset = nelemset + 1
            nelem = 0
            a = AbaqusElementSection(temp, nelem, zeros(FInt, allocationchunk, maxelnodes+1))
            push!(elemset, a)
            temp = uppercase(strip(lines[next_line]))
            next_line = next_line + 1
        end
        if Reading_elements
            if temp[1:1] == "*" # another section started
                Reading_elements = false
                break
            end
            elemset[nelemset].nelem = elemset[nelemset].nelem + 1
            if size(elemset[nelemset].elem, 1) < elemset[nelemset].nelem
                elemset[nelemset].elem = vcat(elemset[nelemset].elem,
                zeros(FInt, allocationchunk, maxelnodes+1))
            end
            A = split(temp, ",")
            if (A[end] == "") # the present line is continued on the next one
                temp = uppercase(strip(lines[next_line]))
                next_line = next_line + 1
                Acont = split(temp, ",")
                A = vcat(A[1:end-1], Acont)
            end
            for ixxxx = 1:length(A)
                elemset[nelemset].elem[elemset[nelemset].nelem, ixxxx] = parse(FInt, A[ixxxx])
            end
        end
    end # while

    node = node[1:nnode, :] # truncate the array to just the lines read
    # The nodes need to be in serial order:  if they are not,  the element
    # connectivities  will not point at the right nodes. So,  if that's the case we
    # will figure out the sequential numbering of the nodes  and then we will
    # renumbered the connectivvities of the elements.
    newnumbering = collect(1:nnode)
    if norm(collect(1:nnode)-node[:,1]) != 0
        newnumbering = zeros(FInt, convert(FInt, maximum(node[:,1])))
        jn = 1
        for ixxxx = 1:size(node, 1)
            if node[ixxxx,1] != 0
                on = convert(FInt, node[ixxxx,1])
                newnumbering[on] = jn
                jn = jn + 1
            end
        end
    end

    # Process output arguments
    # Nodes
    xyz = node[:,2:4]
    fens = FENodeSet(xyz)

    # Element sets
    fesarray = FESet[]

    function feset_construct(elemset1)
        temp = uppercase(strip(elemset1.ElementLine))
        b  = split(temp, ",")
        for ixxx = 1:length(b)
            c = split(b[ixxx], "=")
            if (uppercase(strip(c[1])) == "TYPE") && (length(c) > 1)
                TYPE = uppercase(strip(c[2]))
                if (length(TYPE) >= 4) && (TYPE[1:4] == "C3D8")
                    return FESetH8(elemset1.elem[:, 2:9])
                elseif (length(TYPE) >= 5) && (TYPE[1:5] == "C3D20")
                    return FESetH20(elemset1.elem[:, 2:21])
                elseif (length(TYPE) >= 4) && (TYPE[1:4] == "C3D4")
                    return FESetT4(elemset1.elem[:, 2:5])
                elseif (length(TYPE) >= 5) && (TYPE[1:5] == "C3D10")
                    return FESetT10(elemset1.elem[:, 2:11])
                else
                    return nothing
                end
            end
        end
    end

    for ixxxx = 1:length(elemset)
        elemset[ixxxx].elem = elemset[ixxxx].elem[1:elemset[ixxxx].nelem, :]
        fes = feset_construct(elemset[ixxxx])
        if (fes === nothing)
            push!(warnings, "Don't know how to handle " * elemset[ixxxx].ElementLine)
        else
            fes = renumberconn!(fes, newnumbering)
            push!(fesarray, fes)
        end
    end

    output = FDataDict("fens"=>fens, "fesets"=>fesarray, "warnings"=>warnings)
    return output
end

end #Module


text:
#EasyData base types & core functions
#-------------------------------------------------------------------------------

#==Version info:
===============================================================================#
function _get_CMDimData_versionstr()
	#Adds to load up time... Maybe a more efficient way??
	try
		deps = Pkg.dependencies()
		uuid = Base.UUID("70385e83-f223-47f4-874b-539892411e49") #CMDimData
		vinfo = deps[uuid].version
		return "Source: CMDimData.EasyData (v$vinfo)"
	catch
		vinfo = v"0.2.0"
		@warn("Old version of Julia. Package version number written to file might be inexact.")
		return "Source: CMDimData.EasyData (> v$vinfo)???"
	end
end

#==Useful constants
===============================================================================#
const hdf5plotcollroot = "plots"
const hdf5dataroot = "data"
const _versionstr = _get_CMDimData_versionstr()

#==Main data structures
===============================================================================#

mutable struct EasyDataReader
	reader::HDF5.File
end

mutable struct EasyDataWriter
	writer::HDF5.File
end

#==Helper functions
===============================================================================#

#Create/open HDF5 groups:
creategrp(w::EasyDataWriter, path::String) = HDF5.create_group(w.writer, path)
creategrp(grp::HDF5.Group, sub::String) = HDF5.create_group(grp, sub)
opengrp(w::EasyDataWriter, path::String) = HDF5.open_group(w.writer, path)
opengrp(r::EasyDataReader, path::String) = HDF5.open_group(r.reader, path)
opengrp(grp::HDF5.Group, sub::String) = HDF5.open_group(grp, sub)

function _write_length_attr(grp::HDF5.Group, v::Vector)
	HDF5.attributes(grp)["LENGTH"] = length(v)
end
_read_length_attr(::Type{Vector}, grp::HDF5.Group) = HDF5.read(HDF5.attributes(grp)["LENGTH"])

#==User-level interface:
===============================================================================#
function openwriter(path::String)
	w = EasyDataWriter(HDF5.h5open(path, "w"))
	creategrp(w, hdf5dataroot)
	creategrp(w, hdf5plotcollroot)
	HDF5.write_dataset(w.writer, "VERSION_INFO", _versionstr)
	return w
end
Base.close(w::EasyDataWriter) = close(w.writer)
function openwriter(fn::Function, path::String)
	w = openwriter(path)
	try
		fn(w)
	finally
		close(w)
	end
end

openreader(path::String) = EasyDataReader(HDF5.h5open(path, "r"))
Base.close(r::EasyDataReader) = close(r.reader)
function openreader(fn::Function, path::String)
	w = openreader(path)
	try
		fn(w)
	finally
		close(w)
	end
end

#Last line

ext: jl


text:
() -> begin
Flax.h1("Bill's Gates top $( length(@vars(:books)) ) recommended books")
Flax.ul(
   @foreach(@vars(:books)) do book
      partial("app/resources/books/views/book.jl.html", book = book)
   end
)
end

max_stars_repo_name: tetsugps/julia

max_issues_repo_name: tetsugps/julia

max_forks_repo_name: tetsugps/julia


text:
function map_memspec_funcs(obuf)
    # The op dictionaries map an operation name
    # to a tuple of (is_mutator, default_memspec)
    const signal_prefix = "hsa_signal_"
    const signal_op = Dict(
    "load" => (false, :Acquire),
    "store" => (true, :Release),
    "exchange" => (true, :AcquRel),
    "cas" => (true, :AcquRel),
    "add" => (true, :AcquRel),
    "subtract" => (true, :AcquRel),
    "and" => (true, :AcquRel),
    "or" => (true, :AcquRel),
    "xor" => (true, :AcquRel),
    "wait" => (false, :Acquire)
    )

    const queue_prefix = "hsa_queue_"
    const queue_op = Dict(
    "load" => (false, :Acquire),
    "store" => (true, :Release),
    "cas" => ( true, :AcquRel),
    "add" => ( true, :AcquRel),
    )

    const prefix_ops = Dict(
    signal_prefix => signal_op,
    queue_prefix => queue_op
    )

    const memspec_suffixes = Dict(
    "acquire" => :Acquire,
    "acq_rel" => :AcquRel,
    "relaxed" => :Relaxed,
    "release" => :Release
    )

    # maps each prefix to the ops that have been
    # found for it so far
    const prefix_found_ops = Dict{AbstractString,Set{AbstractString}}()

    for exu in obuf
        if isa(exu, Expr) && exu.head == :function
            sig = exu.args[1]
            name = string(sig.args[1])

            for prefix in keys(prefix_ops)
                if startswith(name, prefix)
                    ops = get(prefix_ops, prefix, [])
                    found_methods = get!(prefix_found_ops, prefix, Set{AbstractString}())
                    suffixes = filter((x) -> endswith(name, x), keys(memspec_suffixes))

                    if isempty(suffixes) || isempty(ops)
                        continue
                    end

                    suffix = first(suffixes)

                    rest = replace(name, prefix, "")
                    rest = replace(rest, suffix, "")

                    op_erand = split(rest, "_", limit = 2)

                    op = op_erand[1]
                    operand = (length(op_erand) == 2) ? strip(op_erand[2],'_') : ""

                    if haskey(ops, op)
                        is_mutator, default_memspec = ops[op]

                        method_name = op

                        if operand != ""
                            method_name *= "_" * operand
                        end

                        if is_mutator
                            method_name *= "!"
                        end

                        # println("$name -> $prefix / $op / $operand / $suffix -> $method_name") # debug

                        # update method name
                        sig.args[1] = symbol(method_name)

                        if !in(method_name, found_methods)
                            # upon encountering the first method of an op,
                            # emit overload with default mem consistency
                            union!(found_methods, [method_name])

                            arg_specs = sig.args[2:end]

                            default_impl = copy(exu)

                            default_impl.args[2] =
                            Expr(:block,
                            Expr(:call, symbol(method_name), [a.args[1] for a in arg_specs]..., :(Val{$default_memspec}))
                            )
                            println(default_impl) #debug

                            push!(obuf, default_impl)
                        end

                        # add memspec argument as the last one
                        memspec_constant = memspec_suffixes[suffix]
                        memspec_arg = :(::Type{Val{$memspec_constant}})

                        push!(sig.args, memspec_arg)
                    end
                end
            end
        end
    end
end


text:
module PLaplacianTestsSeq
using PartitionedArrays
include("../PLaplacianTests.jl")
prun(PLaplacianTests.main,sequential,(2,2))
end # module


text:
export apply1DAcquisition

function apply1DAcquisition(ip, numSamplesPerPeriod=100, numPeriods=100)
  socket = connect(ip,7777)
  write(socket,UInt32(numSamplesPerPeriod))
  write(socket,UInt32(numPeriods))

  uMeas = zeros(Int16,numSamplesPerPeriod,numPeriods)
  uControl = zeros(Int16,numSamplesPerPeriod,numPeriods)
  u = zeros(Int16,numSamplesPerPeriod,numPeriods,2)
  data_send = 0
  packet_size = 10000
  buff_size = numSamplesPerPeriod * numPeriods
  while data_send < buff_size
    local_packet_size = (data_send + packet_size > buff_size) ?
                             (buff_size-data_send) : packet_size
    uMeas[data_send+1:(data_send+local_packet_size)] = read(socket,Int16, local_packet_size)
    uControl[data_send+1:(data_send+local_packet_size)] = read(socket,Int16, local_packet_size)
    write(socket,"OK")
    data_send += local_packet_size
  end
  close(socket)
  u[:,:,1] = uMeas
  u[:,:,2] = uControl
  u = reshape(u,numSamplesPerPeriod*numPeriods,2)
  return u
end


text:
using FluxGAN
using FileIO
using Flux
using CUDA

n = 25

# FIXME: loading errs here
model = load("models/cifar10_goodfellow_MLP_n_$n.jld2")["model"]

layout = (4, 3)

output_dir = "images/CIFAR10"

info = ["loaded", "n", n]

save_image_grid(model, output_dir, layout=layout, file_info=info)

max_stars_repo_name: aarontrowbridge/GAN

max_issues_repo_name: aarontrowbridge/GAN

max_forks_repo_name: aarontrowbridge/GAN


text:
#########################################################################
# https://github.com/chkwon/PATHSolver.jl/issues/16
#########################################################################

using Complementarity, Printf

@testset "hhoeschle mcp 1" begin

    model = MCPModel()
    scenarios = [@sprintf "s%03d" s for s=1:3]
    INDEX = Dict("s001" => 1., "s002" => 0., "s003" => 0.5)
    COST = Dict("s001" => 10., "s002" => 2., "s003" => 5)
    COST_INDEX = Dict("s001" => 2., "s002" => 1., "s003" => 3.)

    @variable(model, xname[s in scenarios] >= 0)
    @variable(model, ynoname[s in scenarios; INDEX[s] >0] >= 0)
    @variable(model, lambda1 >= 0)
    @variable(model, lambda2 >= 0)
    @NLexpression(model, lambda, lambda1 - lambda2)

    @mapping(model, market_lambda1,
        + sum(xname[s] for s in scenarios)
        + sum(ynoname[s] for s in scenarios if INDEX[s] > 0)
        - 10)
    @complementarity(model, market_lambda1, lambda1)

    @mapping(model, market_lambda2,
        - sum(xname[s] for s in scenarios)
        - sum(ynoname[s] for s in scenarios if INDEX[s] > 0)
        + 10)
    @complementarity(model, market_lambda2, lambda2)

    @mapping(model, KKT_xname[s in scenarios],
        - lambda
        + COST[s])
    @complementarity(model, KKT_xname, xname)

    @mapping(model, KKT_ynoname[s in scenarios; INDEX[s] >0],
        - lambda
        + COST_INDEX[s])
    # @complementarity(model, KKT_ynoname, ynoname)
    for s in scenarios
        if INDEX[s] > 0
            @complementarity(model, KKT_ynoname[s], ynoname[s])
        end
    end

    stat = solveMCP(
        model;
        convergence_tolerance=1e-6,
        output="yes",
        time_limit=3600*12,
        # time_limit=0.1,
        minor_iteration_limit=1000,
        cumulative_iteration_limit=1000000000
    )

    stat = solveMCP(
        model;
        convergence_tolerance=1e-6,
        output="yes",
        time_limit=3600*12,
        # time_limit=0.1,
        minor_iteration_limit=1000,
        cumulative_iteration_limit=1000000000
    ) # solve twice to see if model is reusable

    stat = solveMCP(
        model;
        convergence_tolerance=1e-6,
        output="yes",
        time_limit=3600*12,
        # time_limit=0.1,
        minor_iteration_limit=1000,
        cumulative_iteration_limit=1000000000
    ) # solve three times to see if model is reusable
end


text:
function style_css(w::Gtk.GtkWidget, provider::GtkCssProvider)
    sc = Gtk.G_.style_context(w)
    push!(sc, provider, 600)
end
style_css(w::Gtk.GtkWidget, css::String) = style_css(w, GtkCssProvider(data=css))

index(notebook::Gtk.GtkNotebook) = Gtk.GAccessor.current_page(notebook) + 1
index(notebook::Gtk.GtkNotebook, i::Integer) = Gtk.GAccessor.current_page(notebook, i-1)
index(notebook::Gtk.GtkNotebook, child::Gtk.GtkWidget) = pagenumber(notebook, child) + 1

## TODO this could be in Gtk.jl

nonmutable(buffer::GtkTextBuffer, it::Gtk.GLib.MutableTypes.Mutable{GtkTextIter}) =
    GtkTextIter(buffer, char_offset(it))

nonmutable(buffer::GtkTextBuffer, it::GtkTextIter) = it

get_tab(notebook::Gtk.GtkNotebook, page_num::Int) = Gtk.GAccessor.nth_page(notebook, page_num-1)

#get_tab(notebook::Gtk.GtkNotebook, page_num::Int) = convert(Gtk.GtkWidget, ccall((:gtk_notebook_get_nth_page,Gtk.libgtk), Ptr{Gtk.GObject},
#    (Ptr{Gtk.GObject}, Cint),notebook, page_num-1))


text:
"""
calculated this by hand so may not be right,
all kernels (both smoothing and base process) in EQ form, see eqn 2
"""
function threeEQs(t::AbstractFloat, tp::AbstractFloat,
				  Gp1::AbstractArray, Gp2::AbstractArray, bp::AbstractArray)::AbstractFloat
	a, b, c = Gp1[1], Gp2[1], bp[1]
	coeff = 1 / (sqrt(2 * π) * sqrt(abs(a^2 + b^2 + c^2)))
	ans =  exp(-0.5 * (1 / (a^2 + b^2 + c^2)) * (t - tp)^2) * coeff
	ans
end

function threeEQs(ts::AbstractVector, # like ϕ[i, j] := scaledEQs(ts[i], ts[j], Gs[i, :], Gs[j, :], u[:])
	Gs::AbstractMatrix, bp::AbstractVector)
    @tullio phi[i,j] := exp(-0.5 * (inv(Gs[i,1]^2 + Gs[j,1]^2 + bp[1]^2) * (ts[i] - ts[j])^2)) * 1 / (sqrt(2 * π * (Gs[i,1]^2 + Gs[j,1]^2 + bp[1]^2)))
end

function scaledEQs(t::Real, tp::Real,
				   Gp1::AbstractArray, Gp2::AbstractArray, bp::AbstractArray)::Real
	sq = Gp1[1]^2 + Gp2[1]^2 + bp[1]^2
	exp(-0.5 * (1 / (sq) * (t - tp)^2)) * (Gp1[2] * Gp2[2]) / (sqrt(2 * π * sq))
end

function scaledEQs(ts::AbstractVector, # like ϕ[i, j] := scaledEQs(ts[i], ts[j], Gs[i, :], Gs[j, :], u[:])
	Gs::AbstractMatrix, bp::AbstractVector)
    @tullio phi[i,j] := exp(-0.5 * (inv(Gs[i,1]^2 + Gs[j,1]^2 + bp[1]^2) * (ts[i] - ts[j])^2)) * (Gs[i,2] * Gs[j,2]) / (sqrt(2 * π * (Gs[i,1]^2 + Gs[j,1]^2 + bp[1]^2)))
end

function scaledEQs_adj(t::AbstractFloat, tp::AbstractFloat,
					   Gp1::AbstractArray, Gp2::AbstractArray, bp::AbstractArray)
	sq = Gp1[1]^2 + Gp2[1]^2 + bp[1]^2
	f_val = scaledEQs(t, tp, Gp1, Gp2, bp)
	∇sq =  (t - tp)^2 / (2 * sq^2) * f_val - 0.5 * (1 / sq) * f_val
	(nothing, nothing, [2 * Gp1[1] * ∇sq, f_val / Gp1[2]], [2 * Gp2[1] * ∇sq, f_val / Gp2[2]], [2 * bp[1] * ∇sq])
end

@adjoint function scaledEQs(t::AbstractFloat, tp::AbstractFloat,
	Gp1::AbstractArray, Gp2::AbstractArray, bp::AbstractArray)
	scaledEQs(t, tp, Gp1, Gp2, bp), _ -> scaledEQs_adj(t, tp, Gp1, Gp2, bp)
end


text:
### A Pluto.jl notebook ###
# v0.12.4

using Markdown
using InteractiveUtils

# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
    quote
        local el = $(esc(element))
        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
        el
    end
end

# ╔═╡ a0f0ae42-9ad8-11ea-2475-a735df64aa28
begin
	# Pkg.add(["Images", "ImageIO", "ImageMagick"])
	using Images
end

# ╔═╡ baeb2820-1645-11eb-3e15-0fe5abc28118
using PlutoUI

# ╔═╡ 7b93882c-9ad8-11ea-0288-0941e163f9d5
md"""
# Image processing in Julia
"""

# ╔═╡ 2b356cb0-1648-11eb-3a0a-6b810440efc9

# ╔═╡ d889e13e-f0ff-11ea-3306-57491904d83f
md"_First, we set up a clean package environment:_"

# ╔═╡ aefb6004-f0ff-11ea-10c9-c504c7aa9fe5
# begin
#	import Pkg
#   Pkg.activate(mktempdir())
# end

# ╔═╡ e48a0e78-f0ff-11ea-2852-2f4eee1a7d2d
md"_Next, we add the `Images` package to our environment, and we import it._"

# ╔═╡ 5ae65950-9ad9-11ea-2e14-35119d369acd
md"""
## The basics
Now we can get started. Let's load an image and explore its properties.
"""

# ╔═╡ aaa805d4-9ad8-11ea-21c2-3b20580fea0e
url = "https://eskipaper.com/images/shihtzu-1.jpg"

# ╔═╡ 2ac9f6c0-15f2-11eb-249d-77733d9b3fd5
puppy_file = download(url, "puppy.jpg")

# ╔═╡ 5e9abc00-15f2-11eb-08b8-31eef538d1eb
puppy = load(puppy_file)

# ╔═╡ ea52b590-15f2-11eb-2f93-1319c9d9c0e4
typeof(puppy)

# ╔═╡ f50693d0-15f2-11eb-14e8-ffcada6c1bd1
RGBX(0.4, 0.4, 0.6)

# ╔═╡ 0bcc80c0-15f3-11eb-254b-d744f1b6f701
size(puppy)

# ╔═╡ 285caad0-15f3-11eb-1dd2-496a616913f7
begin
	(h, w) = size(puppy)
	eye = puppy[(h ÷ 3): (h ÷ 2), (w ÷ 3): (w ÷ 2)]
end

# ╔═╡ 43f11a50-15f4-11eb-34f5-8b2b836cf772
size(eye)

# ╔═╡ 4b812350-15f4-11eb-1095-6f1ea5754557
[
	eye                   reverse(eye, dims=2)
]

# ╔═╡ ed5d72a0-15f4-11eb-319b-85235c633494
new_puppy = copy(puppy);

# ╔═╡ bfea3460-15f5-11eb-235f-cb0abc6406d0
red = RGB(1, 0, 0)

# ╔═╡ e01ed560-15f5-11eb-3154-9f6cc9722dee
for i in 1:100
	for j in 1:300
		new_puppy[i, j] = red
	end
end

# ╔═╡ 0406ba60-15f6-11eb-1c26-bbfe9bd0ee3d
new_puppy

# ╔═╡ 21251ab0-15f6-11eb-3561-1fa3e9f7de1b
begin
	new_puppy2 = copy(new_puppy)
	new_puppy2[100:200, 1:100] .= RGB(0, 1, 0)
	new_puppy2
end

# ╔═╡ 8baf4632-15f6-11eb-23a9-d7afc60ae64f
function redify(color)
	return RGB(color.r, 0, 0)
end

# ╔═╡ b77fb470-15f6-11eb-10ef-fb0c8a53747b
begin
	color = RGB(0.8, 0.5, 0.2)
	[color, redify(color)]
end

# ╔═╡ dec73f32-15f6-11eb-1617-11cad6e316bf
redify.(puppy)

# ╔═╡ ea558d60-1642-11eb-0d64-9ff0b0223125
decimate(image, ratio=5) = image[1:ratio:end, 1:ratio:end]

# ╔═╡ 13bf4660-15f7-11eb-0bac-676621168238
begin
	poor_puppy = decimate(puppy, 20)
	size(poor_puppy)
	poor_puppy
end

# ╔═╡ 145bea00-1643-11eb-2a19-fbfb2f2e6072
# convolve(puppy, blur(2))

# ╔═╡ 4464d1d0-1643-11eb-1f61-a51dfd39197e

# ╔═╡ 7e2f48a0-1643-11eb-2e90-131b0e9580f5
md"""
## Experiments
"""

# ╔═╡ c8088c4e-1645-11eb-164f-e5e814cbb6ff
@bind repeat_count Slider(1:10, show_value=true)

# ╔═╡ 0eb90b00-1643-11eb-28b9-9f6f753d8861
repeat(poor_puppy, repeat_count, repeat_count)

# ╔═╡ 4f0e04e0-1647-11eb-0d85-fd2fc760b466

# ╔═╡ 911299a0-1642-11eb-218c-8f6840b887ab

# ╔═╡ fc23af62-15f5-11eb-0299-9bf620ca0ff1

# ╔═╡ b85681e0-15f5-11eb-14ab-c3cfbe62b4ad

# ╔═╡ e73dc280-15f4-11eb-195e-713a69ac9fbc

# ╔═╡ 3ef8fa40-15f4-11eb-1c95-672b781ada4a

# ╔═╡ 3b9d2510-15f4-11eb-1770-8d398ff60073

# ╔═╡ 2f0f7dc0-15f4-11eb-2518-59bef4e15fe2

# ╔═╡ 260530d0-15f4-11eb-2693-85f048f60c3f

# ╔═╡ 1818bcce-15f4-11eb-23bf-2b737bb9c447

# ╔═╡ 13fdb652-15f4-11eb-311f-b190620c8bd3

# ╔═╡ 10170640-15f4-11eb-294b-2740fb779cd3

# ╔═╡ 07d9310e-15f4-11eb-06d4-9141cb006dc1

# ╔═╡ e3ec42fe-15f3-11eb-1994-d9690c0e2b80

# ╔═╡ dc306f10-15f3-11eb-3799-e7eb265a5c55

# ╔═╡ d76d8fd0-15f3-11eb-21fe-bffcf0020255

# ╔═╡ d20a2ad2-15f3-11eb-370d-d56acfe3ca54

# ╔═╡ c6228780-15f3-11eb-0025-f30f5d3e89f7

# ╔═╡ b88a7510-15f3-11eb-13c0-0db9ee1d5769

# ╔═╡ 8fc4aec0-15f3-11eb-236f-0fc69d96e2ac

# ╔═╡ 8453c210-15f3-11eb-006e-c37bbd9a96e0

# ╔═╡ 7d9030d0-15f3-11eb-08fd-eda5b3de05fb

# ╔═╡ e9e32ade-15f2-11eb-23e6-8f4b9cc624da

# ╔═╡ Cell order:
# ╟─7b93882c-9ad8-11ea-0288-0941e163f9d5
# ╠═2b356cb0-1648-11eb-3a0a-6b810440efc9
# ╟─d889e13e-f0ff-11ea-3306-57491904d83f
# ╠═aefb6004-f0ff-11ea-10c9-c504c7aa9fe5
# ╟─e48a0e78-f0ff-11ea-2852-2f4eee1a7d2d
# ╠═a0f0ae42-9ad8-11ea-2475-a735df64aa28
# ╟─5ae65950-9ad9-11ea-2e14-35119d369acd
# ╠═aaa805d4-9ad8-11ea-21c2-3b20580fea0e
# ╠═2ac9f6c0-15f2-11eb-249d-77733d9b3fd5
# ╠═5e9abc00-15f2-11eb-08b8-31eef538d1eb
# ╠═ea52b590-15f2-11eb-2f93-1319c9d9c0e4
# ╠═f50693d0-15f2-11eb-14e8-ffcada6c1bd1
# ╠═0bcc80c0-15f3-11eb-254b-d744f1b6f701
# ╠═285caad0-15f3-11eb-1dd2-496a616913f7
# ╠═43f11a50-15f4-11eb-34f5-8b2b836cf772
# ╠═4b812350-15f4-11eb-1095-6f1ea5754557
# ╠═ed5d72a0-15f4-11eb-319b-85235c633494
# ╠═bfea3460-15f5-11eb-235f-cb0abc6406d0
# ╠═e01ed560-15f5-11eb-3154-9f6cc9722dee
# ╠═0406ba60-15f6-11eb-1c26-bbfe9bd0ee3d
# ╠═21251ab0-15f6-11eb-3561-1fa3e9f7de1b
# ╠═8baf4632-15f6-11eb-23a9-d7afc60ae64f
# ╠═b77fb470-15f6-11eb-10ef-fb0c8a53747b
# ╠═dec73f32-15f6-11eb-1617-11cad6e316bf
# ╠═ea558d60-1642-11eb-0d64-9ff0b0223125
# ╠═13bf4660-15f7-11eb-0bac-676621168238
# ╠═145bea00-1643-11eb-2a19-fbfb2f2e6072
# ╠═4464d1d0-1643-11eb-1f61-a51dfd39197e
# ╟─7e2f48a0-1643-11eb-2e90-131b0e9580f5
# ╠═baeb2820-1645-11eb-3e15-0fe5abc28118
# ╠═c8088c4e-1645-11eb-164f-e5e814cbb6ff
# ╠═0eb90b00-1643-11eb-28b9-9f6f753d8861
# ╠═4f0e04e0-1647-11eb-0d85-fd2fc760b466
# ╠═911299a0-1642-11eb-218c-8f6840b887ab
# ╠═fc23af62-15f5-11eb-0299-9bf620ca0ff1
# ╠═b85681e0-15f5-11eb-14ab-c3cfbe62b4ad
# ╠═e73dc280-15f4-11eb-195e-713a69ac9fbc
# ╠═3ef8fa40-15f4-11eb-1c95-672b781ada4a
# ╠═3b9d2510-15f4-11eb-1770-8d398ff60073
# ╠═2f0f7dc0-15f4-11eb-2518-59bef4e15fe2
# ╠═260530d0-15f4-11eb-2693-85f048f60c3f
# ╠═1818bcce-15f4-11eb-23bf-2b737bb9c447
# ╠═13fdb652-15f4-11eb-311f-b190620c8bd3
# ╠═10170640-15f4-11eb-294b-2740fb779cd3
# ╠═07d9310e-15f4-11eb-06d4-9141cb006dc1
# ╠═e3ec42fe-15f3-11eb-1994-d9690c0e2b80
# ╠═dc306f10-15f3-11eb-3799-e7eb265a5c55
# ╠═d76d8fd0-15f3-11eb-21fe-bffcf0020255
# ╠═d20a2ad2-15f3-11eb-370d-d56acfe3ca54
# ╠═c6228780-15f3-11eb-0025-f30f5d3e89f7
# ╠═b88a7510-15f3-11eb-13c0-0db9ee1d5769
# ╠═8fc4aec0-15f3-11eb-236f-0fc69d96e2ac
# ╠═8453c210-15f3-11eb-006e-c37bbd9a96e0
# ╠═7d9030d0-15f3-11eb-08fd-eda5b3de05fb
# ╠═e9e32ade-15f2-11eb-23e6-8f4b9cc624da

max_stars_repo_name: martin-fabbri/colab-notebooks

max_issues_repo_name: martin-fabbri/colab-notebooks

max_forks_repo_name: martin-fabbri/colab-notebooks


text:
# ---
# name: simulations.jl
# author: Jhelum Chakravorty, Jayakumar Subramanian, Aditya Mahajan
# date: 1 Feb, 2017
# license: BSD 3 clause
# ---
#

@everywhere begin
    include("algorithms.jl")
end

# Traces from multiple runs
# =========================
#
# To visualize how well the stochastic approximation algorithms (implemented
# in `algorithms.jl`) work, we run them multiple times for any particular
# choice of parameters. Since this task is an embarrassingly parallel one, we run
# each trace on a separate core and then combine all the traces.
# This is implemented in the `generateTraces` function below. The inputs to this
# function are:
#
# * `sa` : the stochastic approximation algorithm to be run. The function
#   must have the signature:
#
#     `sa(param, discount, dropProb; iterations=iterations)`
#
#     `param` corresponds to `cost` for costly communication
#     and `rate` for constrained communication.
# * `param` : A parameter used by the `sa` function, corresponding to
#   communication cost or rate.
# * `discount`: The discount factor
# * `dropProb`: The packet drop probability.
# * `iterations`: Number of iterations
#
# It also accepts the following optional argument
#
# * `numRuns` : The number of runs.
#
# The output is a 2D array of size `iterations * numRuns`, where column
# corresponds to a different traces.

function generateTraces(sa, param, discount, dropProb, iterations; numRuns = 100)
    tuples = pmap(_ -> sa(param, discount, dropProb; iterations=iterations), 1:numRuns)
    traces = zeros(iterations, numRuns)

    for run in 1:numRuns
        traces[:, run] = tuples[run]
    end

    return traces
end

# Generating and saving results
# =============================
#
# The function `generateOutput` takes the same parameters as `generateTraces`
# plus an additional optional parameter: `saveRawData`, which defaults to
# `false`. It returns a data frame with three columns: mean
# value, mean + 2(standard deviation), mean - 2(standard deviation). These are
# shown in the plots included in the paper. This data is saved to a tab
# separated file (in the `output/` directory). The filename includes the name
# of stochastic approximation algorithm, and values of parameter, discount,
# and dropProb.
#
# When `saveRawData` is set to `true`, the traces are saved to a
# `.jld` file.

using JLD, DataFrames

function generateOutput(sa, param, discount, dropProb, iterations;
    numRuns  = 100, saveSummaryData = true, saveRawData = false)

    traces = generateTraces(sa, param, discount, dropProb, iterations; numRuns = 100)
    meanValue, std = mean_and_std(traces, 2)

    meanValue = vec(meanValue)
    std       = vec(std)

    # Generate summary statistics.
    stats = DataFrame(mean=meanValue,
                      upper=meanValue + 2std, lower=meanValue - 2std)

    filename = string("output/", sa,             "__parameter_", param,
                      "__discount_" , discount,  "__dropProb_" , dropProb)

    if saveSummaryData
      writetable("$filename.tsv", stats, separator='\t', header = true)
    end

    if saveRawData
        save("$filename.jld",         "param", param,
            "discount", discount,     "dropProb", dropProb,
            "iterations", iterations, "numRuns",  numRuns,
            "traces", traces,         "meanValue", meanValue,
            "std", std)
    end

    return stats
end

max_stars_repo_name: adityam/remote-estimation-packet-drops

max_issues_repo_name: adityam/remote-estimation-packet-drops

max_forks_repo_name: adityam/remote-estimation-packet-drops


text:
function run!(model, game, gui=nothing)
    while !game_over!(game)
        model.real_time ? sleep(.5) : nothing
        decide!(model, game, gui)
    end
end

decide!(model::TwoDotsModel, game, gui) = throw("must implement decide! for model <: TwoDotsModel")

import TwoDots: is_adjecent

function search_all(game)
    moves = Vector{Vector{Dot}}()
    return mapreduce(x->search(game.dots, x), vcat, game.dots)
end

function search(dots, dot)
    sub_list = [dot]
    list = Vector{Vector{Dot}}()
    return search(dots, list, sub_list, dot.row, dot.col)
end

function search(dots, list, sub_list, r, c)
    branch = connected_dots(dots, sub_list, r, c)
    for dot in branch
        _sub_list = copy(sub_list)
        push!(_sub_list, dot)
        search(dots, list, _sub_list, dot.row, dot.col)
        push!(list, _sub_list)
    end
    return list
end

function connected_dots(dots, list, r, c)
    new_dots = Dot[]
    for i in -1:1
        for j in -1:1
            if can_connect(dots, list, r+j, c+i)
                push!(new_dots, dots[r+j,c+i])
            end
        end
    end
    return new_dots
end

function can_connect(dots, list, r, c)
    if !is_in_bounds(dots, r, c)
        return false
    elseif dots[r,c] ∈ list
        return false
    elseif !is_adjecent(list[end], dots[r,c])
        return false
    elseif color_matches(dots[r,c], list[1])
        return true
    end
    return false
end

function is_in_bounds(dots, r, c)
    n_rows, n_cols = size(dots)
    return r > 0 && r ≤ n_rows && c > 0 && c ≤ n_cols
end

color_matches(dot1, dot2) = dot1.color == dot2.color


text:
using Dash
using DashHtmlComponents
using DashCoreComponents

app = dash(meta_tags = [Dict(["name"=>"description", "content" => "some content"])])

app.layout = html_div(children = "Hello world!", id = "hello-div")

run_server(app)


text:
# policy file better sanity fewer contacts

socialmaxyyt = socialmaxyy_o # max no. people met outside firm young_young
socialmaxoot = socialmaxoo_o # max no. people met outside firm old_old
socialmaxoyt = socialmaxoy_o
socialmaxyot = socialmaxyo_o

genhomeoffice = false

ptravel = ptravel_o

pshopt = [[1,1,1],[1,1,1]]

tauadj = 0.05

shorttimeprogram = false

pinf = 0
pinft = 0


text:
# This piece of code defines the main macro of this package

"""
    @exception(macro_name::Symbol, args::Union{Symbol, Expr}...; context::Expr=:()) -> Expr

Create a macro to create exceptions. Optionally inject context before defining
the structure.

# Arguments
- `macro_name::Symbol`: name of the macro
- `args::Tuple{Vararg{Union{Symbol, Expr}}}`: a set of fields to be defined in the
  exception structure

# Keywords
- `context::Expr=:()`: expression evaluated before defining the exception structure

# Returns
- `Expr`: new macro definition

# Throws
- [`OnlyOneEquation`](@ref): more than one equation has been passed

# Example
```jldoctest; output = false
using Exceptions
using Suppressor
using SyntaxTree

macro_name = :name
args = (:(arg1::String), :(arg2))
context = :()

EXCEPTIONS = Dict{Symbol, Any}()
EXCEPTIONS[:DocstringIsNotAString] = Exceptions.Internal.DocstringIsNotAString
EXCEPTIONS[:ErrorMessageIsNotAString] = Exceptions.Internal.ErrorMessageIsNotAString

d1 = @capture_out(
    @macroexpand(@exception(name, arg1::String, arg2)) |> linefilter! |> dump
)

d2 = @capture_out quote
    macro \$(macro_name)(
        exception_name::Symbol,
        docstring::Union{Expr, String},
        error_message_bits::Union{Expr, String, Char}...,
    )
        args = \$(args)

        error_header = "\$(__module__).\$(exception_name):"
        error_message_bits = ("\\n\\n\$(error_header)\\n", error_message_bits..., '\\n')

        \$(context)

        EX = \$(EXCEPTIONS)
        error_message_bits_filtered = filter(
            e -> typeof(e) == String || e.head ≠ :(.) && e.args[1] ≠ :(e),
            error_message_bits,
        )

        return esc(
            quote
                # Checks
                if !(\$(docstring) isa String)
                    throw(\$(EX[:DocstringIsNotAString])())
                end
                if !(string(\$(error_message_bits_filtered...)) isa String)
                    throw(\$(EX[:ErrorMessageIsNotAString])())
                end

                @doc \$(docstring)
                mutable struct \$(exception_name) <: Exception
                    \$(args...)
                end

                Base.showerror(io::IO, e::\$(exception_name)) =
                print(io, \$(error_message_bits...))
            end
        )
    end
end |> linefilter! |> dump

d1 == d2

# output

true
```
"""
macro exception(
    macro_name::Symbol,
    args::Union{Symbol, Expr}...,
)
    context = :()

    for (index, arg) in pairs(args)
        if typeof(arg) == Expr
            if arg.head == :(=)
                if arg.args[1] == :context
                    context = args[index]
                    args = args[1:end .≠ index]
                else
                    throw(OnlyOneEquation())
                end
            elseif arg.head ≠ :(::) || length(arg.args) ≠ 2
                throw(FieldsOnly())
            end
        end
    end

    return esc(
        quote
            macro $(macro_name)(
                exception_name::Symbol,
                docstring::Union{Expr, String},
                error_message_bits::Union{Expr, String, Char}...,
            )
                args = $(args)

                error_header = "$(__module__).$(exception_name):"
                error_message_bits = ("\n\n$(error_header)\n", error_message_bits..., '\n')

                $(context)

                EX = $(EXCEPTIONS)
                error_message_bits_filtered = filter(
                    e -> e isa Union{String, Char} || e.head ≠ :(.) && e.args[1] ≠ :(e),
                    error_message_bits,
                )

                return esc(
                    quote
                        # Checks
                        if !($(docstring) isa String)
                            throw($(EX[:DocstringIsNotAString])())
                        end
                        if !(string($(error_message_bits_filtered...)) isa String)
                            throw($(EX[:ErrorMessageIsNotAString])())
                        end

                        @doc $(docstring)
                        mutable struct $(exception_name) <: Exception
                            $(args...)
                        end

                        Base.showerror(io::IO, e::$(exception_name)) =
                        print(io, $(error_message_bits...))
                    end
                )
            end
        end
    )
end


text:
using LinearAlgebra

struct ValueOne; end
ValueOne()

# Compute X <- a X + b I.
function matfun_axpby!(X,a,b,Y::UniformScaling)
    m,n=size(X)
    if ~(a isa ValueOne)
        rmul!(X,a)
    end
    @inbounds for i=1:n
        X[i,i]+=(b isa ValueOne) ? 1 : b
    end
end

@inline function exp_mono_m7_opt_rho6_0(A)
    T=promote_type(eltype(A),Float64)
    A_copy=similar(A,T); A_copy .= A;
    return exp_mono_m7_opt_rho6_0!(A_copy)
end

@inline function exp_mono_m7_opt_rho6_0!(A)
    T=promote_type(eltype(A),Float64) # Make it work for many 'bigger' types (matrices and scalars)
    # max_memslots=10
    n=size(A,1)
    # The first slots are precomputed nodes [:A]
    memslots2 = similar(A,T)
    memslots3 = similar(A,T)
    memslots4 = similar(A,T)
    memslots5 = similar(A,T)
    memslots6 = similar(A,T)
    memslots7 = similar(A,T)
    memslots8 = similar(A,T)
    memslots9 = similar(A,T)
    memslots10 = similar(A,T)
    # Assign precomputed nodes memslots
    memslots1=A # overwrite A
    # Uniform scaling is exploited.
    # No matrix I explicitly allocated.
    # Computation order: Bb2 Ba2 B2 Ba3 Bb3 B3 Ba4 Bb4 B4 Ba5 Bb5 B5 Ba6 Bb6 B6 Ba7 Bb7 B7 Ba8 Bb8 B8 T2k10
    # Computing Bb2 = x*I+x*A
    coeff1=0.19853207576158147
    coeff2=0.4568156227748025
    memslots2 .= coeff2.*memslots1
    mul!(memslots2,true,I*coeff1,true,true)
    # Computing Ba2 = x*I+x*A
    coeff1=0.19853207576158147
    coeff2=0.4568156227748025
    memslots3 .= coeff2.*memslots1
    mul!(memslots3,true,I*coeff1,true,true)
    # Computing B2 with operation: mult
    mul!(memslots4,memslots3,memslots2)
    # Deallocating Ba2 in slot 3
    # Deallocating Bb2 in slot 2
    # Computing Ba3 = x*I+x*A+x*B2
    coeff1=-0.03985250441225717
    coeff2=0.1604494657928954
    coeff3=0.9304976822330905
    memslots2 .= coeff2.*memslots1 .+ coeff3.*memslots4
    mul!(memslots2,true,I*coeff1,true,true)
    # Computing Bb3 = x*I+x*A+x*B2
    coeff1=0.3044412670842123
    coeff2=0.4680830251883016
    coeff3=0.029166175784732254
    memslots3 .= coeff2.*memslots1 .+ coeff3.*memslots4
    mul!(memslots3,true,I*coeff1,true,true)
    # Computing B3 with operation: mult
    mul!(memslots5,memslots2,memslots3)
    # Deallocating Ba3 in slot 2
    # Deallocating Bb3 in slot 3
    # Computing Ba4 = x*I+x*A+x*B2+x*B3
    coeff1=-0.01206538482409284
    coeff2=-0.007524875465546422
    coeff3=0.32310560219905493
    coeff4=0.9639420128969182
    memslots2 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5
    mul!(memslots2,true,I*coeff1,true,true)
    # Computing Bb4 = x*I+x*A+x*B2+x*B3
    coeff1=-0.011223283513386698
    coeff2=0.5004951105037614
    coeff3=0.0587301450366299
    coeff4=0.0020530677449521447
    memslots3 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5
    mul!(memslots3,true,I*coeff1,true,true)
    # Computing B4 with operation: mult
    mul!(memslots6,memslots2,memslots3)
    # Deallocating Ba4 in slot 2
    # Deallocating Bb4 in slot 3
    # Computing Ba5 = x*I+x*A+x*B2+x*B3+x*B4
    coeff1=-0.0014350882470920096
    coeff2=-0.0029204003557249366
    coeff3=0.004322247579028231
    coeff4=0.013953282030764238
    coeff5=0.8220608344548307
    memslots2 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5 .+ coeff5.*memslots6
    mul!(memslots2,true,I*coeff1,true,true)
    # Computing Bb5 = x*I+x*A+x*B2+x*B3+x*B4
    coeff1=0.8268548885673269
    coeff2=0.32692355515774696
    coeff3=0.05385438234818326
    coeff4=0.003348134917199928
    coeff5=4.728916919898747e-5
    memslots3 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5 .+ coeff5.*memslots6
    mul!(memslots3,true,I*coeff1,true,true)
    # Computing B5 with operation: mult
    mul!(memslots7,memslots2,memslots3)
    # Deallocating Ba5 in slot 2
    # Deallocating Bb5 in slot 3
    # Computing Ba6 = x*I+x*A+x*B2+x*B3+x*B4+x*B5
    coeff1=-0.00011974681141880265
    coeff2=-9.609608204465964e-5
    coeff3=0.004160420231960609
    coeff4=-0.13025928619739066
    coeff5=0.8471750409761895
    coeff6=0.8150363087806349
    memslots2 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5 .+ coeff5.*memslots6 .+ coeff6.*memslots7
    mul!(memslots2,true,I*coeff1,true,true)
    # Computing Bb6 = x*I+x*A+x*B2+x*B3+x*B4+x*B5
    coeff1=-0.10687141220929966
    coeff2=0.49573353466641706
    coeff3=0.09669233528231447
    coeff4=0.008584243736221898
    coeff5=0.0002579652548561839
    coeff6=-6.616194274488254e-8
    memslots3 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5 .+ coeff5.*memslots6 .+ coeff6.*memslots7
    mul!(memslots3,true,I*coeff1,true,true)
    # Computing B6 with operation: mult
    mul!(memslots8,memslots2,memslots3)
    # Deallocating Ba6 in slot 2
    # Deallocating Bb6 in slot 3
    # Computing Ba7 = x*I+x*A+x*B2+x*B3+x*B4+x*B5+x*B6
    coeff1=-4.539313763978297e-6
    coeff2=2.446796588580378e-6
    coeff3=4.215986081751763e-5
    coeff4=-0.0061270230013822065
    coeff5=0.06884543294512852
    coeff6=-0.1203307382956932
    coeff7=0.9948104309724103
    memslots2 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5 .+ coeff5.*memslots6 .+ coeff6.*memslots7 .+ coeff7.*memslots8
    mul!(memslots2,true,I*coeff1,true,true)
    # Computing Bb7 = x*I+x*A+x*B2+x*B3+x*B4+x*B5+x*B6
    coeff1=-8.127184169897754e-8
    coeff2=0.5009422778394859
    coeff3=0.10725741908100991
    coeff4=0.011203185515508135
    coeff5=0.0005125194848333935
    coeff6=1.4968901291255363e-5
    coeff7=1.941362084939232e-8
    memslots3 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5 .+ coeff5.*memslots6 .+ coeff6.*memslots7 .+ coeff7.*memslots8
    mul!(memslots3,true,I*coeff1,true,true)
    # Computing B7 with operation: mult
    mul!(memslots9,memslots2,memslots3)
    # Deallocating Ba7 in slot 2
    # Deallocating Bb7 in slot 3
    # Computing Ba8 = x*I+x*A+x*B2+x*B3+x*B4+x*B5+x*B6+x*B7
    coeff1=0.9834849370950302
    coeff2=0.40790543324377204
    coeff3=0.4202712650569836
    coeff4=0.15990304681757225
    coeff5=0.033732264254459236
    coeff6=0.008536371457893934
    coeff7=0.0010322498247622353
    coeff8=4.413245234287325e-5
    memslots2 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5 .+ coeff5.*memslots6 .+ coeff6.*memslots7 .+ coeff7.*memslots8 .+ coeff8.*memslots9
    mul!(memslots2,true,I*coeff1,true,true)
    # Computing Bb8 = x*I+x*A+x*B2+x*B3+x*B4+x*B5+x*B6+x*B7
    coeff1=0.9834849370950302
    coeff2=0.40790543324377204
    coeff3=0.4202712650569836
    coeff4=0.15990304681757225
    coeff5=0.033732264254459236
    coeff6=0.008536371457893934
    coeff7=0.0010322498247622353
    coeff8=4.413245234287325e-5
    memslots3 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5 .+ coeff5.*memslots6 .+ coeff6.*memslots7 .+ coeff7.*memslots8 .+ coeff8.*memslots9
    mul!(memslots3,true,I*coeff1,true,true)
    # Computing B8 with operation: mult
    mul!(memslots10,memslots2,memslots3)
    # Deallocating Ba8 in slot 2
    # Deallocating Bb8 in slot 3
    # Computing T2k10 = x*I+x*A+x*B2+x*B3+x*B4+x*B5+x*B6+x*B7+x*B8
    coeff1=-0.00018687382272586462
    coeff2=-0.00010155826657765157
    coeff3=-0.0001809250904584009
    coeff4=-0.00011452178091543187
    coeff5=-3.544767352137871e-5
    coeff6=-1.1868405154805229e-5
    coeff7=-1.9506111159992416e-6
    coeff8=-1.0864858600469639e-7
    coeff9=1.0004223592531323
    # Smart lincomb recycle A
    memslots1 .= coeff2.*memslots1 .+ coeff3.*memslots4 .+ coeff4.*memslots5 .+ coeff5.*memslots6 .+ coeff6.*memslots7 .+ coeff7.*memslots8 .+ coeff8.*memslots9 .+ coeff9.*memslots10
    mul!(memslots1,true,I*coeff1,true,true)
    # Deallocating B2 in slot 4
    # Deallocating B3 in slot 5
    # Deallocating B4 in slot 6
    # Deallocating B5 in slot 7
    # Deallocating B6 in slot 8
    # Deallocating B7 in slot 9
    # Deallocating B8 in slot 10
    return memslots1 # Returning T2k10
end

max_stars_repo_name: matrixfunctions/GraphMatFunData

max_issues_repo_name: matrixfunctions/GraphMatFunData

max_forks_repo_name: matrixfunctions/GraphMatFunData


text:
using DelayEmbeddings
using Test
using DynamicalSystemsBase

println("\nTesting traditional optimal embedding dimension...")
test_value = (val, vmin, vmax) -> @test vmin <= val <= vmax

@testset "Embedding dimension estimation" begin
diffeq = (atol = 1e-9, rtol = 1e-9, maxiters = typemax(Int))
s_sin = sin.(0:0.1:1000)
ro = Systems.roessler(ones(3));
data = trajectory(ro,1000;Δt=0.1,diffeq)
s_roessler = data[:,1]
lo = Systems.lorenz96(4, [0.1, 0.2, 0.5, 0.1]; F = 16.0);
data = trajectory(lo,5000.0;Δt=0.05, Ttr = 100.0, diffeq)
s_lorenz = data[:,1]

@testset "Caos method" begin
    𝒟, τ, x = optimal_traditional_de(s_roessler, "afnn")
    @test 3 ≤ size(𝒟, 2) ≤ 5

    E2s = DelayEmbeddings.stochastic_indicator(s_roessler, τ, 1:6)
    @test minimum(E2s) < 0.3

    𝒟, τ, x = optimal_traditional_de(s_roessler, "afnn"; metric = Chebyshev())
    @test 3 ≤ size(𝒟, 2) ≤ 5

    𝒟, τ, x = optimal_traditional_de(s_lorenz, "afnn")
    @test 4 ≤ size(𝒟, 2) ≤ 8

    #Test against random signal
    E2s = DelayEmbeddings.stochastic_indicator(rand(10000), 1, 1:5)
    @test minimum(E2s) > 0.9
end

@testset "fnn method" begin
    𝒟, τ, x = optimal_traditional_de(s_sin, "fnn")
    @test 1 ≤ size(𝒟, 2) ≤ 3

    𝒟, τ, x = optimal_traditional_de(s_roessler, "fnn")
    @test 3 ≤ size(𝒟, 2) ≤ 5

    𝒟, τ, x = optimal_traditional_de(s_lorenz, "fnn")
    @test 4 ≤ size(𝒟, 2) ≤ 8
end

@testset "ifnn method" begin
    𝒟, τ, x = optimal_traditional_de(s_sin, "ifnn")
    @test 1 ≤ size(𝒟, 2) ≤ 4

    𝒟, τ, x = optimal_traditional_de(s_roessler, "ifnn")
    @test 3 ≤ size(𝒟, 2) ≤ 5

    𝒟, τ, x = optimal_traditional_de(s_roessler, "ifnn"; metric = Chebyshev())
    @test 3 ≤ size(𝒟, 2) ≤ 5

    𝒟, τ, x = optimal_traditional_de(s_lorenz, "ifnn")
    @test 4 ≤ size(𝒟, 2) ≤ 8
end

end


text:
using LightGraphs
using NetworkEpidemics
using Plots
using ColorSchemes

N = 1000
M = 10
β = 0.05
γ = 0.5

h = erdos_renyi(M, 0.5)
g = static_scale_free(N, 50*N, 2)
g = erdos_renyi(N, 0.2)
mp = Metapopulation(h,0.1, SI(β))
mp2 = ContactProcess(g, SI(β))
mp3 = Metaplex(g, h, 0.1, SI(β))

x0 = Array{Int64,2}(undef, M, 2)
x0[1,:] .= [90, 10]
x0[2:M,:] .= [100 0]

x02 = fill(1, N)
x02[1:10] .= 2
x0_μ = [div(i-1,div(N,M))+1 for i in 1:N]

nmax = 5000
tmax = 15.0

t, output = gillespie(mp, x0, nmax=nmax, tmax=tmax)
t2, output2 = gillespie(mp2, [x02,x0_μ], nmax=nmax, tmax=tmax)

t_av, out_av = average(mp, x0, nsims=1000, nbins=200, tmax=tmax, nmax=nmax)
t_av2, out_av2 = average(mp2, x02, nsims=500, nbins=200, tmax=tmax, nmax=nmax)
t_av3, out_av3 = average(mp3, [x02,x0_μ], nsims=500, nbins=200, tmax=tmax, nmax=nmax)

t_mf, out_mf = meanfield(mp, x0, tmax=tmax, saveat=t_av)
t_mf2, out_mf2 = meanfield(mp2, x02, tmax=tmax, saveat=t_av2)
t_mf3, out_mf3 = meanfield(mp3, [x02,x0_μ], tmax=tmax, saveat=t_av2)

colours = ColorSchemes.tab10;

plot(t_mf, sum(out_mf[2], dims=2)/N,
    label="Metapopulation",
    fontfamily="Deja Vu Sans",
    xlabel="Temps",
    ylabel="Fraction d'individus infectes",
    legend=:bottomright,
    color=colours[1]
    )
    plot!(t_mf2, sum(out_mf2, dims=2)/N,
    label="Contact Process",
    color=colours[2])
    plot!(t_mf3, sum(out_mf3[2], dims=2)/N,
    label="Metaplex",
    color=colours[3]
    )
    plot!(t_av, sum(out_av[2], dims=2)/N,
    label="",
    linestyle=:dash,
    color=colours[1]
    )
    plot!(t_av2, out_av2[2]/N,
    label="",
    linestyle=:dash,
    color=colours[2])
    plot!(t_av3, sum(out_av3[2], dims=2)/N,
    label="",
    linestyle=:dash,
    color=colours[3]
    )

savefig("metaplex-si.pdf")

max_stars_repo_name: csimal/metaplex-networks

max_issues_repo_name: csimal/metaplex-networks

max_forks_repo_name: csimal/metaplex-networks


text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: grafana
using AWS.Compat
using AWS.UUIDs

"""
    associate_license(license_type, workspace_id)
    associate_license(license_type, workspace_id, params::Dict{String,<:Any})

Assigns a Grafana Enterprise license to a workspace. Upgrading to Grafana Enterprise incurs
additional fees. For more information, see Upgrade a workspace to Grafana Enterprise.

# Arguments
- `license_type`: The type of license to associate with the workspace.
- `workspace_id`: The ID of the workspace to associate the license with.

"""
function associate_license(
    licenseType, workspaceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return grafana(
        "POST",
        "/workspaces/$(workspaceId)/licenses/$(licenseType)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function associate_license(
    licenseType,
    workspaceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "POST",
        "/workspaces/$(workspaceId)/licenses/$(licenseType)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_workspace(account_access_type, authentication_providers, permission_type)
    create_workspace(account_access_type, authentication_providers, permission_type, params::Dict{String,<:Any})

Creates a workspace. In a workspace, you can create Grafana dashboards and visualizations
to analyze your metrics, logs, and traces. You don't have to build, package, or deploy any
hardware to run the Grafana server. Don't use CreateWorkspace to modify an existing
workspace. Instead, use UpdateWorkspace.

# Arguments
- `account_access_type`: Specifies whether the workspace can access Amazon Web Services
  resources in this Amazon Web Services account only, or whether it can also access Amazon
  Web Services resources in other accounts in the same organization. If you specify
  ORGANIZATION, you must specify which organizational units the workspace can access in the
  workspaceOrganizationalUnits parameter.
- `authentication_providers`: Specifies whether this workspace uses SAML 2.0, Amazon Web
  Services Single Sign On, or both to authenticate users for using the Grafana console within
  a workspace. For more information, see User authentication in Amazon Managed Grafana.
- `permission_type`: If you specify Service Managed, Amazon Managed Grafana automatically
  creates the IAM roles and provisions the permissions that the workspace needs to use Amazon
  Web Services data sources and notification channels. If you specify CUSTOMER_MANAGED, you
  will manage those roles and permissions yourself. If you are creating this workspace in a
  member account of an organization that is not a delegated administrator account, and you
  want the workspace to access data sources in other Amazon Web Services accounts in the
  organization, you must choose CUSTOMER_MANAGED. For more information, see Amazon Managed
  Grafana permissions and policies for Amazon Web Services data sources and notification
  channels

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"clientToken"`: A unique, case-sensitive, user-provided identifier to ensure the
  idempotency of the request.
- `"organizationRoleName"`: The name of an IAM role that already exists to use with
  Organizations to access Amazon Web Services data sources and notification channels in other
  accounts in an organization.
- `"stackSetName"`: The name of the CloudFormation stack set to use to generate IAM roles
  to be used for this workspace.
- `"workspaceDataSources"`: Specify the Amazon Web Services data sources that you want to
  be queried in this workspace. Specifying these data sources here enables Amazon Managed
  Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data
  from these sources. You must still add them as data sources in the Grafana console in the
  workspace. If you don't specify a data source here, you can still add it as a data source
  in the workspace console later. However, you will then have to manually configure
  permissions for it.
- `"workspaceDescription"`: A description for the workspace. This is used only to help you
  identify this workspace.
- `"workspaceName"`: The name for the workspace. It does not have to be unique.
- `"workspaceNotificationDestinations"`: Specify the Amazon Web Services notification
  channels that you plan to use in this workspace. Specifying these data sources here enables
  Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed
  Grafana to use these channels.
- `"workspaceOrganizationalUnits"`: Specifies the organizational units that this workspace
  is allowed to use data sources from, if this workspace is in an account that is part of an
  organization.
- `"workspaceRoleArn"`: The workspace needs an IAM role that grants permissions to the
  Amazon Web Services resources that the workspace will view data from. If you already have a
  role that you want to use, specify it here. If you omit this field and you specify some
  Amazon Web Services resources in workspaceDataSources or workspaceNotificationDestinations,
  a new IAM role with the necessary permissions is automatically created.
"""
function create_workspace(
    accountAccessType,
    authenticationProviders,
    permissionType;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "POST",
        "/workspaces",
        Dict{String,Any}(
            "accountAccessType" => accountAccessType,
            "authenticationProviders" => authenticationProviders,
            "permissionType" => permissionType,
            "clientToken" => string(uuid4()),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_workspace(
    accountAccessType,
    authenticationProviders,
    permissionType,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "POST",
        "/workspaces",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "accountAccessType" => accountAccessType,
                    "authenticationProviders" => authenticationProviders,
                    "permissionType" => permissionType,
                    "clientToken" => string(uuid4()),
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_workspace(workspace_id)
    delete_workspace(workspace_id, params::Dict{String,<:Any})

Deletes an Amazon Managed Grafana workspace.

# Arguments
- `workspace_id`: The ID of the workspace to delete.

"""
function delete_workspace(workspaceId; aws_config::AbstractAWSConfig=global_aws_config())
    return grafana(
        "DELETE",
        "/workspaces/$(workspaceId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_workspace(
    workspaceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "DELETE",
        "/workspaces/$(workspaceId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_workspace(workspace_id)
    describe_workspace(workspace_id, params::Dict{String,<:Any})

Displays information about one Amazon Managed Grafana workspace.

# Arguments
- `workspace_id`: The ID of the workspace to display information about.

"""
function describe_workspace(workspaceId; aws_config::AbstractAWSConfig=global_aws_config())
    return grafana(
        "GET",
        "/workspaces/$(workspaceId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_workspace(
    workspaceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "GET",
        "/workspaces/$(workspaceId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_workspace_authentication(workspace_id)
    describe_workspace_authentication(workspace_id, params::Dict{String,<:Any})

Displays information about the authentication methods used in one Amazon Managed Grafana
workspace.

# Arguments
- `workspace_id`: The ID of the workspace to return authentication information about.

"""
function describe_workspace_authentication(
    workspaceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return grafana(
        "GET",
        "/workspaces/$(workspaceId)/authentication";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_workspace_authentication(
    workspaceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "GET",
        "/workspaces/$(workspaceId)/authentication",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    disassociate_license(license_type, workspace_id)
    disassociate_license(license_type, workspace_id, params::Dict{String,<:Any})

Removes the Grafana Enterprise license from a workspace.

# Arguments
- `license_type`: The type of license to remove from the workspace.
- `workspace_id`: The ID of the workspace to remove the Grafana Enterprise license from.

"""
function disassociate_license(
    licenseType, workspaceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return grafana(
        "DELETE",
        "/workspaces/$(workspaceId)/licenses/$(licenseType)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function disassociate_license(
    licenseType,
    workspaceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "DELETE",
        "/workspaces/$(workspaceId)/licenses/$(licenseType)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_permissions(workspace_id)
    list_permissions(workspace_id, params::Dict{String,<:Any})

Lists the users and groups who have the Grafana Admin and Editor roles in this workspace.
If you use this operation without specifying userId or groupId, the operation returns the
roles of all users and groups. If you specify a userId or a groupId, only the roles for
that user or group are returned. If you do this, you can specify only one userId or one
groupId.

# Arguments
- `workspace_id`: The ID of the workspace to list permissions for. This parameter is
  required.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"groupId"`: (Optional) Limits the results to only the group that matches this ID.
- `"maxResults"`: The maximum number of results to include in the response.
- `"nextToken"`: The token to use when requesting the next set of results. You received
  this token from a previous ListPermissions operation.
- `"userId"`: (Optional) Limits the results to only the user that matches this ID.
- `"userType"`: (Optional) If you specify SSO_USER, then only the permissions of Amazon Web
  Services SSO users are returned. If you specify SSO_GROUP, only the permissions of Amazon
  Web Services SSO groups are returned.
"""
function list_permissions(workspaceId; aws_config::AbstractAWSConfig=global_aws_config())
    return grafana(
        "GET",
        "/workspaces/$(workspaceId)/permissions";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_permissions(
    workspaceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "GET",
        "/workspaces/$(workspaceId)/permissions",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_workspaces()
    list_workspaces(params::Dict{String,<:Any})

Returns a list of Amazon Managed Grafana workspaces in the account, with some information
about each workspace. For more complete information about one workspace, use
DescribeWorkspace.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of workspaces to include in the results.
- `"nextToken"`: The token for the next set of workspaces to return. (You receive this
  token from a previous ListWorkspaces operation.)
"""
function list_workspaces(; aws_config::AbstractAWSConfig=global_aws_config())
    return grafana(
        "GET", "/workspaces"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_workspaces(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return grafana(
        "GET", "/workspaces", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    update_permissions(update_instruction_batch, workspace_id)
    update_permissions(update_instruction_batch, workspace_id, params::Dict{String,<:Any})

Updates which users in a workspace have the Grafana Admin or Editor roles.

# Arguments
- `update_instruction_batch`: An array of structures that contain the permission updates to
  make.
- `workspace_id`: The ID of the workspace to update.

"""
function update_permissions(
    updateInstructionBatch, workspaceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return grafana(
        "PATCH",
        "/workspaces/$(workspaceId)/permissions",
        Dict{String,Any}("updateInstructionBatch" => updateInstructionBatch);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_permissions(
    updateInstructionBatch,
    workspaceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "PATCH",
        "/workspaces/$(workspaceId)/permissions",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("updateInstructionBatch" => updateInstructionBatch),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_workspace(workspace_id)
    update_workspace(workspace_id, params::Dict{String,<:Any})

Modifies an existing Amazon Managed Grafana workspace. If you use this operation and omit
any optional parameters, the existing values of those parameters are not changed. To modify
the user authentication methods that the workspace uses, such as SAML or Amazon Web
Services SSO, use UpdateWorkspaceAuthentication. To modify which users in the workspace
have the Admin and Editor Grafana roles, use UpdatePermissions.

# Arguments
- `workspace_id`: The ID of the workspace to update.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"accountAccessType"`: Specifies whether the workspace can access Amazon Web Services
  resources in this Amazon Web Services account only, or whether it can also access Amazon
  Web Services resources in other accounts in the same organization. If you specify
  ORGANIZATION, you must specify which organizational units the workspace can access in the
  workspaceOrganizationalUnits parameter.
- `"organizationRoleName"`: The name of an IAM role that already exists to use to access
  resources through Organizations.
- `"permissionType"`: If you specify Service Managed, Amazon Managed Grafana automatically
  creates the IAM roles and provisions the permissions that the workspace needs to use Amazon
  Web Services data sources and notification channels. If you specify CUSTOMER_MANAGED, you
  will manage those roles and permissions yourself. If you are creating this workspace in a
  member account of an organization and that account is not a delegated administrator
  account, and you want the workspace to access data sources in other Amazon Web Services
  accounts in the organization, you must choose CUSTOMER_MANAGED. For more information, see
  Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and
  notification channels
- `"stackSetName"`: The name of the CloudFormation stack set to use to generate IAM roles
  to be used for this workspace.
- `"workspaceDataSources"`: Specify the Amazon Web Services data sources that you want to
  be queried in this workspace. Specifying these data sources here enables Amazon Managed
  Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data
  from these sources. You must still add them as data sources in the Grafana console in the
  workspace. If you don't specify a data source here, you can still add it as a data source
  later in the workspace console. However, you will then have to manually configure
  permissions for it.
- `"workspaceDescription"`: A description for the workspace. This is used only to help you
  identify this workspace.
- `"workspaceName"`: A new name for the workspace to update.
- `"workspaceNotificationDestinations"`: Specify the Amazon Web Services notification
  channels that you plan to use in this workspace. Specifying these data sources here enables
  Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed
  Grafana to use these channels.
- `"workspaceOrganizationalUnits"`: Specifies the organizational units that this workspace
  is allowed to use data sources from, if this workspace is in an account that is part of an
  organization.
- `"workspaceRoleArn"`: The workspace needs an IAM role that grants permissions to the
  Amazon Web Services resources that the workspace will view data from. If you already have a
  role that you want to use, specify it here. If you omit this field and you specify some
  Amazon Web Services resources in workspaceDataSources or workspaceNotificationDestinations,
  a new IAM role with the necessary permissions is automatically created.
"""
function update_workspace(workspaceId; aws_config::AbstractAWSConfig=global_aws_config())
    return grafana(
        "PUT",
        "/workspaces/$(workspaceId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_workspace(
    workspaceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "PUT",
        "/workspaces/$(workspaceId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_workspace_authentication(authentication_providers, workspace_id)
    update_workspace_authentication(authentication_providers, workspace_id, params::Dict{String,<:Any})

Use this operation to define the identity provider (IdP) that this workspace authenticates
users from, using SAML. You can also map SAML assertion attributes to workspace user
information and define which groups in the assertion attribute are to have the Admin and
Editor roles in the workspace.

# Arguments
- `authentication_providers`: Specifies whether this workspace uses SAML 2.0, Amazon Web
  Services Single Sign On, or both to authenticate users for using the Grafana console within
  a workspace. For more information, see User authentication in Amazon Managed Grafana.
- `workspace_id`: The ID of the workspace to update the authentication for.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"samlConfiguration"`: If the workspace uses SAML, use this structure to map SAML
  assertion attributes to workspace user information and define which groups in the assertion
  attribute are to have the Admin and Editor roles in the workspace.
"""
function update_workspace_authentication(
    authenticationProviders, workspaceId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return grafana(
        "POST",
        "/workspaces/$(workspaceId)/authentication",
        Dict{String,Any}("authenticationProviders" => authenticationProviders);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_workspace_authentication(
    authenticationProviders,
    workspaceId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return grafana(
        "POST",
        "/workspaces/$(workspaceId)/authentication",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("authenticationProviders" => authenticationProviders),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end


text:
#=
This file is auto-generated. Do not edit.
=#
"""
    mutable struct OpenPipe <: Pipe
        name::String
        arc::Arc
        available::Bool
        diameter::Float64
        length::Float64
        roughness::Float64
        flowlimits::NamedTuple{(:min, :max), Tuple{Float64, Float64}}
        flow::Union{Nothing,Float64}
        headloss::Union{Nothing,Float64}
        internal::InfrastructureSystemsInternal
    end

An always open, bidirectional-flow pipe.

# Arguments
- `name::String`
- `arc::Arc`
- `available::Bool`
- `diameter::Float64`
- `length::Float64`
- `roughness::Float64`
- `flowlimits::NamedTuple{(:min, :max), Tuple{Float64, Float64}}`
- `flow::Union{Nothing,Float64}`
- `headloss::Union{Nothing,Float64}`
- `internal::InfrastructureSystemsInternal`: internal reference, do not modify
"""
mutable struct OpenPipe <: Pipe
    name::String
    arc::Arc
    available::Bool
    diameter::Float64
    length::Float64
    roughness::Float64
    flowlimits::NamedTuple{(:min, :max), Tuple{Float64, Float64}}
    flow::Union{Nothing,Float64}
    headloss::Union{Nothing,Float64}
    "internal reference, do not modify"
    internal::InfrastructureSystemsInternal
end

function OpenPipe(name, arc, available, diameter, length, roughness, flowlimits, flow, headloss, )
    OpenPipe(name, arc, available, diameter, length, roughness, flowlimits, flow, headloss, InfrastructureSystemsInternal(), )
end

function OpenPipe(; name, arc, available, diameter, length, roughness, flowlimits, flow, headloss, )
    OpenPipe(name, arc, available, diameter, length, roughness, flowlimits, flow, headloss, )
end

# Constructor for demo purposes; non-functional.
function OpenPipe(::Nothing)
    OpenPipe(;
        name="init",
        arc=Arc(nothing),
        available=true,
        diameter=0.0,
        length=0.0,
        roughness=0.0,
        flowlimits=(min=-10.0, max=10.0),
        flow=nothing,
        headloss=nothing,
    )
end

"""Get OpenPipe name."""
get_name(value::OpenPipe) = value.name
"""Get OpenPipe arc."""
get_arc(value::OpenPipe) = value.arc
"""Get OpenPipe available."""
get_available(value::OpenPipe) = value.available
"""Get OpenPipe diameter."""
get_diameter(value::OpenPipe) = value.diameter
"""Get OpenPipe length."""
get_length(value::OpenPipe) = value.length
"""Get OpenPipe roughness."""
get_roughness(value::OpenPipe) = value.roughness
"""Get OpenPipe flowlimits."""
get_flowlimits(value::OpenPipe) = value.flowlimits
"""Get OpenPipe flow."""
get_flow(value::OpenPipe) = value.flow
"""Get OpenPipe headloss."""
get_headloss(value::OpenPipe) = value.headloss
"""Get OpenPipe internal."""
get_internal(value::OpenPipe) = value.internal


text:
# Julia executable to populate UMLS Semantic Network Database
# Example of how to use from terminal (inside this file directory):
# ```
#     julia populate_net.jl --clean_db mysql --host "localhost" --username "root --password "" --dbname "umls_sn"
# ```

using ArgParse
using BioMedQuery.UMLS

function parse_commandline()
    s = ArgParseSettings()

    @add_arg_table s begin
        "--clean_db"
            help = "Flag indicating wether to empty database"
            action = :store_true
        "mysql"
             help = "Use MySQL backend"
             action = :command
    end
    @add_arg_table s["mysql"] begin
        "--host"
             help = "Host where you database lives"
             arg_type = ASCIIString
             default = "localhost"
        "--dbname"
             help = "Database name"
             arg_type = ASCIIString
             required = true
        "--username"
             help = "MySQL username"
             arg_type = ASCIIString
             default = "root"
        "--password"
             help = "MySQL password"
             arg_type = ASCIIString
             default = ""
    end
    return parse_args(s)
end

function main()
    parsed_args = parse_commandline()
    println("Parsed args:")
    for (arg,val) in parsed_args
        println("  $arg  =>  $val")
    end

    if haskey(parsed_args, "mysql")
        db_config = Dict(:host=>parsed_args["mysql"]["host"],
        :dbname=>parsed_args["mysql"]["dbname"],
        :username=>parsed_args["mysql"]["username"],
        :pswd=>parsed_args["mysql"]["password"],
        :overwrite=>parsed_args["clean_db"])
    else
        error("Unsupported database backend")
    end

    populate_net_mysql(db_config)

end

main()


text:
module BasicStatisticsController
using DataFrames, Statistics, Query, Combinatorics
using ..Stats, ..Histogram
using JSON

export call

"""
call(message)

Computes mean, std, max, min and row count from records.

# Arguments
- `message::Dict`: the arguments dict
  - `"records"`: Array of array of rows

# Return
the json string of result object

# Examples
```jldoctest
julia> BasicStatisticsController.call(Dict("records" => [[1.0, 2.0, 3.0, 4.0], [2.0, 4.0, 6.0, 8.0]]))
"{\"means\":[1.5,3.0,4.5,6.0],\"row_count\":2,\"maxs\":[2.0,4.0,6.0,8.0],\"stds\":[0.7071067811865476,1.4142135623730951,2.1213203435596424,2.8284271247461903],\"mins\":[1.0,2.0,3.0,4.0]}"
```
"""
function call(message)
  records = hcat(convert.(Array{Any,1}, message["records"])...)

  row_count = Stats.count(records[1, :])
  means, stds, maxs, mins = [], [], [], []
  for i = 1:size(records, 1)
    means = vcat(means, Statistics.mean(records[i, :]))
    stds = vcat(stds, Statistics.stdm(records[i, :], means[i]))
    maxs = vcat(maxs, Stats.max(records[i, :]))
    mins = vcat(mins, Stats.min(records[i, :]))
  end

  Dict(
   :means => means,
   :stds => stds,
   :maxs => maxs,
   :mins => mins,
   :row_count => row_count
  ) |> JSON.json
end
end


text:
sbmlfile = joinpath("data", "ecoli_core.xml")
download_data_file(
    "http://systemsbiology.ucsd.edu/sites/systemsbiology.ucsd.edu/files/Attachments/Images/downloads/Ecoli_core/ecoli_core_model.xml",
    sbmlfile,
    "78692f8509fb36534f4f9b6ade23b23552044f3ecd8b48d84d484636922ae907",
)

@testset "SBML import and conversion" begin
    sbmlm = load_sbml_model(sbmlfile)
    m = convert(CoreModel, sbmlm)

    @test size(stoichiometry(sbmlm)) == (92, 95)
    @test size(stoichiometry(m)) == (n_metabolites(sbmlm), n_reactions(sbmlm))
    @test length(m.S.nzval) == 380
    @test length.(bounds(sbmlm)) == (95, 95)
    @test length.(bounds(m)) == (95, 95)
    @test all([length(m.xl), length(m.xu), length(m.c)] .== 95)

    @test metabolites(m)[1:3] == ["M_succoa_c", "M_ac_c", "M_fru_b"]
    @test reactions(m)[1:3] == ["R_EX_fum_e", "R_ACONTb", "R_GLNS"]

    cm = convert(CoreModelCoupled, sbmlm)
    @test n_coupling_constraints(cm) == 0
end


text:
using Documenter
include("src/example.jl")

makedocs(sitename="My Documentation")

max_stars_repo_name: SergioGmezM/GeneticJulia

max_issues_repo_name: SergioGmezM/GeneticJulia

max_forks_repo_name: SergioGmezM/GeneticJulia


text:
@enum ColumnType SPECIALIZED VALUES
struct ColumnOrSpecialized
    type::ColumnType
    val::Union{Any,Vector}
end
function _unspecialized_columns(relation::PhysicalRelation)
    col = 0
    ColumnOrSpecialized[
        if startswith(v, ':')
            ColumnOrSpecialized(SPECIALIZED, v)
        else
            col += 1
            ColumnOrSpecialized(VALUES, relation.columns[col])
        end
        for v in relation.relpath
    ]
end

# TODO: haha oh shit, i've got to change this back to iterating over tuples, so that we can
# handle the end of the prefix. 🙄
# We need to do the binary search on the tuples() object directly
struct PhysicalRelationIterator
    relpath::Vector{String}
    maybe_columns::Vector{ColumnOrSpecialized}
    relation::PhysicalRelation

    row_idx::Int # Current row offset into the relation
end

function PhysicalRelationIterator(r::PhysicalRelation)
    return PhysicalRelationIterator(r.relpath, _unspecialized_columns(r), r, 1)
end
function seek_to(iter::PhysicalRelationIterator, i::Int)
    return PhysicalRelationIterator(iter.relpath, iter.maybe_columns, iter.relation, i)
end

struct TrieWalker
    relations::Vector{PhysicalRelationIterator}
    # relations::Vector{PhysicalRelation}
    # element_getters::Vector{Any}
    # slots::Vector{Vector{Int}}
    # column_getters::Vector{Vector{Int}}
    # TODO: Should this be a dynamically sized collection instead, like a vector? I think probably.
    prefix::Tuple
end

function TrieWalker(relations::Vector{PhysicalRelation})
    return TrieWalker([PhysicalRelationIterator(r) for r in relations], ())
end

function Base.keys(t::TrieWalker)
    e = length(t.prefix) + 1

    keyset = sizehint!(OrderedSet{Any}(), length(t.relations))
    for iter in sort(t.relations, by=r->r.relpath)
        if e <= length(iter.maybe_columns)
            maybe_col = iter.maybe_columns[e]
            if maybe_col.type == SPECIALIZED
                push!(keyset, maybe_col.val)
            else
                col = maybe_col.val::AbstractVector
                sizehint!(keyset, length(keyset) + length(col))
                for v in col
                    push!(keyset, v)
                end
            end
        end
    end
    return keyset
end

function Base.getindex(t::TrieWalker, v)
    e = length(t.prefix) + 1

    new_iters = sizehint!(empty(t.relations), length(t.relations))
    for iter in t.relations
        new_idx = _seek_match(iter, iter.row_idx, e, v)
        if new_idx !== NotFound()
            iter = seek_to(iter, new_idx)
            push!(new_iters, iter)
        else
            # drop the iterator
        end
    end

    TrieWalker(new_iters, (t.prefix..., v))
end

struct NotFound end

function _seek_match(iter, start_idx::Int, elt_idx::Int, v)
    if elt_idx > length(iter.maybe_columns)
        return NotFound()
    end
    maybe_col = iter.maybe_columns[elt_idx]
    if maybe_col.type == SPECIALIZED
        return maybe_col.val == v ? start_idx : NotFound()
    end
    # Otherwise, it's a normal column
    col = maybe_col.val::AbstractVector

    # Do a binary search from start_idx to end until you find `v` in column elt_idx
    new_idx = binary_search_from(col, start_idx, v)

    if new_idx <= length(col) && col[new_idx] == v
        return new_idx
    else
        return NotFound()
    end
end

binary_search_from(col, start, v) = searchsortedfirst(@view(col[start:end]), v) + start-1

function _make_element_getter(relation::PhysicalRelation, elt)
    # TODO: don't need to do all of this.
    row_getter = RAI._make_getrow(r.relpath, r.columns)

    return idx->row_getter[idx][elt]
end