text:
include("../SimpleTasks.jl")

module AWSScheduler

using SimpleTasks.Types
using SimpleTasks.Services.AWSQueue
using SimpleTasks.Services.CLIBucket
using SimpleTasks.Services.AWSCLIProvider
using SimpleTasks.Examples.NoOpTask

import AWS
import JSON
import SimpleTasks.Services.Bucket
import SimpleTasks.Services.Queue
import SimpleTasks.Tasks.BasicTask

const LOCAL_PREFIX = "/var/tmp/taskdaemon"
const BASE_DIRECTORY = "datasets/noop_dataset"

type ScheduleConfig
    task_queue_name::ASCIIString
    bucket_name::ASCIIString
end

const KEY_FOLDER = "0_input"
# datasets/noop_dataset/0_input
const FULL_PATH = "$BASE_DIRECTORY/$KEY_FOLDER"
# /var/tmp/datasets/noop_dataset/0_input
const FULL_LOCAL_PATH = "$LOCAL_PREFIX/$FULL_PATH"

function to_name(index::Int64)
    return "$index.dat"
end

function to_key(index::Int64)
    return "$KEY_FOLDER/$(to_name(index))"
end

function to_full_path(index::Int64)
    return "$FULL_PATH/$(to_name(index))"
end

function to_full_local_path(index::Int64)
    return "$FULL_LOCAL_PATH/$(to_name(index))"
end

function create_input_file(index::Int64)
    filename = to_full_local_path(index)
    file = open(filename, "w")
    for value in index*1000000:(index + 1)*1000000
        write(file, "$value\n")
    end
    close(file)
    return filename
end

function create_input_files(indices::UnitRange{Int64})
    mkpath("$FULL_LOCAL_PATH")
    input_filenames = map(create_input_file, indices)
    bucket_paths = map(to_full_path, indices)

    return zip(input_filenames, bucket_paths)
end

function create_task(index::Int64)
    task_indices = index:index+1
    basic_info = BasicTask.Info(index, NoOpTask.NAME, BASE_DIRECTORY,
        map(to_key, task_indices))
    task = NoOpTaskDetails(basic_info, "NoOp Task for $task_indices")
    return task
end

function schedule(queue_name, bucket_name)
    env = AWS.AWSEnv()
    queue = AWSQueueService(env, queue_name)
    bucket = CLIBucketService(AWSCLIProvider.Details(env), bucket_name)

    # create data and upload it to the bucket service
    indices = 0:9
    inouts = create_input_files(indices)
    map((inout) -> Bucket.upload(bucket, inout[1], inout[2]), inouts)

    # create tasks from the inputs and add them to the queue
    tasks = map(create_task, indices[1:end-1])
    map((task) -> Queue.push_message(queue; message_body = JSON.json(task)),
        tasks)
end

"""
    parse_args()
Parse ARGS into scheduler configuration.
Return ScheduleConfig
"""
function parse_args()
    if length(ARGS) < 2
        error("Not enough arguments given, (given $ARGS) sample usage:
            -- julia awsscheduler.jl task_queue_name bucket_name")
    end

    schedule_config = ScheduleConfig(
        ASCIIString(ARGS[1]),
        ASCIIString(ARGS[2])
    )
    return schedule_config
end

function __init__()
    schedule_config = parse_args()
    #=schedule_config = ScheduleConfig("task-queue-TEST", "seunglab-test")=#
    schedule(schedule_config.task_queue_name, schedule_config.bucket_name)
end

end # module AWSScheduler

max_forks_repo_name: seung-lab/SimpleTasks


text:
using MatrixNetworks
using SparseArrays

# Adding a tolerance parameter to the max-flow code to be more careful with
# rounding errors

mutable struct stFlow
    flowvalue::Float64 # gives you the max-flow value
    cutvalue::Float64 # gives min-cut value, which should equal flowvalue,
                      # but may differ by a small tolerance value.
    source_nodes::Vector{Int64} # give the indices of the nodes attached to the source
    C::SparseMatrixCSC # gives the original capacity matrix
    F::SparseMatrixCSC # gives the values of the flows on each edge
    s::Int64  # index of source node
    t::Int64 # index of sink node
end

"""
maxflow

Given a sparse matrix A representing a weighted and possibly directed graph,
a source node s, and a sink node t, return the maximum s-t flow.

flowtol = tolerance parameter for whether there is still capacity available on
            an edge. Helps avoid rounding errors. Default is 1e-6.

Returns F, which is of type stFlow.
"""
function maxflow(B::Union{SparseMatrixCSC,MatrixNetwork},s::Int,t::Int, flowtol::Union{Float64,Int}= 1e-6)

    if flowtol >= .1
        println("flowtol is a tolerance parameter for rounding small residual capacity edges to zero, and should be much smaller than $flowtol. Changing it to default value 1e-6")
        flowtol = 1e-6
    end

    # The code actually assumes a SparseMatrixCSC input
    if typeof(B) <: SparseMatrixCSC
    else
        B = sparse(B)
    end

    N = size(B,1)

    # Extract weights from source s to non-terminal nodes,
    # and from non-terminal nodes to sink node t
    sWeights = Array(B[s,:])
    tWeights = Array(B[:,t])
    NonTerminal = setdiff(collect(1:N),[s t])

    sWeights = sWeights[NonTerminal]
    tWeights = tWeights[NonTerminal]

    # Extract the edges between non-terminal nodes
    A = B[NonTerminal,NonTerminal]

    # A = the matrix of capacities for all nodes EXCEPT the source and sink
    # sWeights = a vector of weights for edges from source to non-terminal nodes
    # tWeights = vector of weights from non-terminal nodes to the sink node t.

    # This is the map from the original node indices to the rearranged
    # version in which the source is the first node and the sink is the last
    Map = [s; NonTerminal; t]

    # Directly set up the flow matrix
    C = [spzeros(1,1) sparse(sWeights') spzeros(1,1);
         sparse(sWeights) A sparse(tWeights);
         spzeros(1,1) sparse(sWeights') spzeros(1,1)]

    # Allocate space for the flow we will calculate
    # In a flow problem, we will eventually need to send flow the reverse
    # direction, so it's important to allocate space for F[i,j] if C[j,i] is an
    # edge, even if C[i,j] is not directed
    Cundir = C+C'
    F = SparseMatrixCSC(N,N,Cundir.colptr,Cundir.rowval,zeros(length(Cundir.rowval)))
    ExcessNodes = vec(round.(Int64,findall(x->x!=0,sWeights).+1))

    # Initialize the Preflow and the excess vector
    for v = ExcessNodes
        F[1,v] = C[1,v]
        F[v,1] = -C[1,v]
    end
    excess = [0;sWeights;0]
    source_nodes, FlowMat, value = Main_Push_Relabel(C,F,ExcessNodes,excess,flowtol)

    smap = sortperm(Map)
    F = stFlow(value, value, sort(Map[source_nodes]),C[smap,smap],FlowMat[smap,smap],s,t)
    return F
end

"""
This maxflow code assumes that A represents the adjacencies between
non-terminal nodes. Edges adjecent to source node s and sink node t
are given by vectors svec and tvec.

This code sets s as the first node, and t as the last node.
"""
function maxflow(A::Union{SparseMatrixCSC,MatrixNetwork},svec::Vector{Float64},tvec::Vector{Float64}, flowtol::Union{Float64,Int}= 1e-6)

    if flowtol >= .1
        println("flowtol is a tolerance parameter for rounding small residual capacity edges to zero, and should be much smaller than $flowtol. Changing it to default value 1e-6")
        flowtol = 1e-6
    end
    if typeof(A) <: SparseMatrixCSC
    else
        A = sparse(A)
    end

    # Directly set up the flow matrix
    C = [spzeros(1,1) sparse(sWeights') spzeros(1,1);
         sparse(sWeights) A sparse(tWeights);
         spzeros(1,1) sparse(sWeights') spzeros(1,1)]

    # Allocate space for the flow we will calculate
    # In a flow problem, we will eventually need to send flow the reverse
    # direction, so it's important to allocate space for F[i,j] if C[j,i] is an
    # edge, even if C[i,j] is not directed.
    Cundir = C+C'
    F = SparseMatrixCSC(N,N,Cundir.colptr,Cundir.rowval,zeros(length(Cundir.rowval)))
    ExcessNodes = vec(round.(Int64,findall(x->x!=0,sWeights).+1))

    # Initialize the Preflow and the excess vector
    for v = ExcessNodes
        F[1,v] = C[1,v]
        F[v,1] = -C[1,v]
    end
    excess = [0;sWeights;0]
    source_nodes, FlowMat, value = Main_Push_Relabel(C,F,ExcessNodes,excess,flowtol)

    F = stFlow(value,value,source_nodes,FlowMat,s,t)
end

maxflow(A::Union{SparseMatrixCSC,MatrixNetwork},svec::Vector{Int64},tvec::Vector{Int64},flowtol::Union{Float64,Int}= 1e-6) =
    maxflow(A,float(svec),float(tvec),flowtol)

flow(F::stFlow) =
    F.flowvalue

"""
Given a flow, stored in an stFlow object, return the set of nodes attached to
the source
"""
function source_nodes(F::stFlow,flowtol::Union{Float64,Int}= 1e-6)
    # Run a bfs from the sink node. Anything with distance
    # n is disconnected from the sink. Thus it's part of the minimium cut set
    n = size(F.C,2)
    finalHeight = relabeling_bfs(F.C,F.F,flowtol, F.t)
    S = Vector{Int64}()
    for i = 1:n
        if finalHeight[i] == n
            push!(S,i)
        end
    end

    # Sanity checks: source node is on source side, sink node is on sink side
    @assert(~in(F.t,S))
    @assert(in(F.s,S))

    return S
end

"""
Given a flow, stored in an stFlow object, return the set of nodes attached to
the sink
"""
function sink_nodes(F::stFlow,flowtol::Union{Float64,Int}= 1e-6)
    # Run a bfs from the sink node. Anything with distance < n is sink-attached.
    n = size(F.C,2)
    finalHeight = relabeling_bfs(F.C,F.F,flowtol,F.t)
    T = Vector{Int64}()
    for i = 2:n
        if finalHeight[i] < n
            push!(T,i)
        end
    end

    # Sanity checks
    @assert(in(F.t,T))
    @assert(~in(F.s,T))

    return T
end

"""
Gives the cut as a list of edges.
"""
function cut_edges(F::stFlow,flowtol::Union{Float64,Int}= 1e-6)
    # Run a bfs from the sink node to get source and sink sets
    n = size(F.C,2)
    finalHeight = relabeling_bfs(F.C,F.F,flowtol,F.t)
    T = Vector{Int64}()
    S = Vector{Int64}()
    for i = 1:n
        if finalHeight[i] < n
            push!(T,i)
        else
            push!(S,i)
        end
    end

    I,J,V = findnz(F.C[S,T])
    return [S[I] T[J]]

end

# Main_Push_Relabel returns a maximum flow F and the min s-t cut set S for the
# flow graph C.
#
# C = the capacity matrix for the flow problem.
#   This code assumes node 1 is the source, and node n is the sink.
#   the preflow immediately pushes all flow from the source to create an
#   excess on nodes in the graph.
#
# F = an initial flow. It can be initialize to zero.
#
# excess = the vector of excess values at the start of the algorithm. If F = 0,
#   this is the vector of edge capacities from the implicit source to the graph.
#   If F != 0, then it's the excess from a previous run of the algorithm
function Main_Push_Relabel(C::SparseMatrixCSC,
    F::SparseMatrixCSC,ExcessNodes::Array{Int64},excess::Array{Float64},flowtol::Union{Float64,Int}= 1e-6)

    # here, n includes only one terminal node, the sink
    n = size(C,1)

    height = zeros(Int64,n)      # label/height of each node
    inQ = zeros(Bool,n)          # list whether or not nodes are in the queue

    # Store adjacency list. Because flow can be sent either direction on an
    # arc during the course of the algorithm, it's important to list all neighbors
    # or each node, counting both incoming and outgoing edges
    Neighbs,d = ConstructAdj(C+C',n)

    # We will maintain a queue of active nodes.
    #   An actual queue implementation is available in the DataStructures.jl
    #   Julia package. The performane is nearly identical (and in some cases
    #   slightly slower), thus to minimize dependency on outside packages, we
    #   just use a Vector, rather than an actual implemented Queue
    Queue = Vector{Int64}()

    # Start by saturating edges from source to its neighbors
    # All nodes with nonzero excess are the first to be processed
    for v = ExcessNodes
        push!(Queue,v)
    end
    inQ[ExcessNodes] .= true

    # count the number of nodes that have been relabeled
    relabelings::Int64 = 0

    height = relabeling_bfs(C,F,flowtol,n)  # compute initial distance from sink
    # In the code and comments, height = distance from sink = label of node

    # Continue until the queue no longer contains any active nodes.
    while length(Queue) > 0

        u = pop!(Queue)     # Select a new active node

        inQ[u] = false      # Take it out of the queue

        # discharge flow through node u
        relabelings += discharge!(C,F,Queue,u,Neighbs[u],height,excess,n,d[u],inQ,flowtol)

        # if u is still active, put it back into the queue
        if excess[u] > flowtol
            prepend!(Queue,u)
            inQ[u] = true
        end

        # Global relabeling heuristic for push-relabel algorithm.
        # This periodically recomputes distances between nodes and the sink
        if relabelings == n
            relabelings = 0
            dist = relabeling_bfs(C,F,flowtol)
            height = dist
        end

    end

    # Compute final distances from sink using BFS. Anything with distance
    # n is disconnected from the sink. Thus it's part of the minimium cut set
    finalHeight = relabeling_bfs(C,F,flowtol,n)
    S = Vector{Int64}()
    push!(S,1)          # Include the source node
    for i = 2:n
        if finalHeight[i] == n
            push!(S,i)
        end
    end

    mflow = excess[n]     # the excess at the sink equals the maximum flow value

    return S, F, mflow

end

# Discharege operation: pushes flow away from node u across admissible edges.
# If excess[u] > 0 but no admissible edges exist, we relabel u.
function discharge!(C::SparseMatrixCSC,F::SparseMatrixCSC,
    Queue::Vector{Int64},u::Int64,uNeighbs::Array{Int64},height::Array{Int64},
    excess::Array{Float64},n::Int64,du::Int64,inQ::Array{Bool},
    flowtol::Union{Float64,Int}= 1e-6)

    vLocal::Int64 = 1           # Start at the first neighbor of node u
    hu = height[u]
    relabeled = 0

    # As long as there is excess at node u and there is another neighbor to explore...
    while excess[u] > flowtol && vLocal <= du

            # ...grab the next neighbor of node u
            v = uNeighbs[vLocal]

            # ... if edge (u,v) is admissible, push more flow.
            # Otherwise, move to the next neighbor of u
            if hu > height[v] && C[u,v] - F[u,v] > flowtol
                pushflow!(C,F,Queue,u,v,excess,height,inQ,n)
                vLocal += 1
            else
                vLocal += 1
            end
    end

    # if we needed to visit every neighbor of u, we must relabel u,
    # so that at least one admissible edge is created
    if vLocal > du
        relabeled = 1
        relabel!(C,F,Queue,u,uNeighbs,height,du,n,flowtol)
    end

    return relabeled
end

# Relabel sets the label/height of node u to be equal to the minimum label
# such that an admissible edge exists. An edge (u,v) is admissible if
# height[u] = height[v] + 1
function relabel!(C::SparseMatrixCSC,F::SparseMatrixCSC,
    Queue::Vector{Int64},u::Int64,uNeighbs::Array{Int64},height::Array{Int64},
    du::Int64,n::Int64,flowtol::Union{Float64,Int}= 1e-6)
   # find smallest new height making a push possible, if such a push is possible

   min_height = Inf
   # search through the neighbors of u
   # and relabel so that height[u] = height[v] + 1 for some v in the neighborhood
   for vLocal = 1:du
       v = uNeighbs[vLocal]
       if C[u,v] - F[u,v] > flowtol
           min_height = min(min_height, height[v])
           height[u] = min_height + 1
       end
   end

end

# Push flow from an active node u to a node v via an admissible edge (u,v)
function pushflow!(C::SparseMatrixCSC,F::SparseMatrixCSC,
    Queue::Vector{Int},u::Int64,v::Int64,excess::Array{Float64},height::Array{Int64},
    inQ::Array{Bool},n::Int64)

    send = min(excess[u], C[u,v] - F[u,v])
    F[u,v] += send
    F[v,u] -= send
    excess[u] -= send
    excess[v] += send

    # If v isn't in the queue, isn't the sink, isn't the source,
    # and is active, then add it to the Queue
    if ~inQ[v] && v < n && v > 1
        prepend!(Queue,v)
        inQ[v] = true
    end
end

# From the adjacency matrix, build an adjacency list for the graph
function ConstructAdj(C::SparseMatrixCSC,n::Int64)
    rp = C.rowval
    ci = C.colptr
    Neighbs = Vector{Vector{Int64}}()
    d = zeros(Int64,n)
    for i = 1:n
        # chop up the rp vector and put it in Neighbs
        push!(Neighbs,rp[ci[i]:ci[i+1]-1])
        d[i] = ci[i+1]-ci[i]
    end

    # d is the number of neighbors. This is the unweighted degree,
    # but note importantly that if the original graph is weighted this is
    # not the same as the degree vector d we will sometimes use
    return Neighbs, d

end

# Given initial capacity matrix C and flow matrix F, compute the distance
# from each node to the specified "start" node.
# Start defaults to node n, which is assumed to be the sink node
function relabeling_bfs(C::SparseMatrixCSC,F::SparseMatrixCSC,flowtol::Union{Float64,Int}=1e-6,start::Int64=0)

    if flowtol >= .1
        println("flowtol is a tolerance parameter for rounding small residual capacity edges to zero, and should be much smaller than $flowtol. Changing it to default value 1e-6")
        flowtol = 1e-6
    end

    # To avoid subtraction cancellation errors that may have ocurred when pushing
    # flow, when computing a bfs, round edges to zero if they are under
    # a certain tolerance
    Cf = C-F
    Cf = Cf.*(Cf.>flowtol)
    n = size(Cf,1)

    if start == 0
        start = n
    end

    rp = Cf.colptr
    ci = Cf.rowval

    N=length(rp)-1

    d = n*ones(Int64,N)
    sq=zeros(Int64,N)
    sqt=0
    sqh=0 # search queue and search queue tail/head

    # start bfs at the node "start"
    u = start
    sqt=sqt+1
    sq[sqt]=u
    d[u]=0
    while sqt-sqh>0
        sqh=sqh+1
        v=sq[sqh] # pop v off the head of the queue
        for ri=rp[v]:rp[v+1]-1
            w=ci[ri]
            if d[w] > n-1
                sqt=sqt+1
                sq[sqt]=w
                d[w]= d[v]+1
            end
        end
    end

    return d
end

ext: jl

max_stars_repo_name: luotuoqingshan/Sparsest-Cut

max_issues_repo_name: luotuoqingshan/Sparsest-Cut

max_forks_repo_name: luotuoqingshan/Sparsest-Cut


text:
#=
- point http://jsxgraph.org/docs/symbols/Point.html
- line http://jsxgraph.org/docs/symbols/Line.html
- circle http://jsxgraph.org/docs/symbols/Circle.html
- ellipse http://jsxgraph.org/docs/symbols/Ellipse.html
- arrow http://jsxgraph.org/docs/symbols/Arrow.html
=#


text:
using LinearAlgebra;
using SparseArrays;
using IterativeSolvers;
using MKLSparse; #<! Impportant for the Iterative Solver (Much faster sparseMat * denseVec)

# using Parameters #<! Might help with packing / unpacking of parameters

# https://docs.julialang.org/en/v1/manual/unicode-input/

@enum LinearSolverMode modeAuto = 1 modeItertaive modeDirect
@enum ConvergenceFlag convNumItr = 1 convAdmm convPrimDual

function SolveQuadraticProgram!(vX, mP, vQ, mA, vL, vU, LinSysSolInit, LinSysSol!;
    numIterations = 5000, ϵAbs = 1e-6, ϵRel = 1e-6,
    ρ = 1, σ = 1e-6, α = 1.6, δ = 1e-6, adptΡ::Bool = false,
    fctrΡ = 5, numItrConv = 25, numItrPolish = 10, ϵMinres = 1e-6, numItrMinres = 500)

    numElementsX            = size(vX, 1);
    numRowsP, numColsP      = size(mP);
    numElementsQ            = size(vQ, 1);
    numRowsA, numColsA      = size(mA);
    numElementsL            = size(vL, 1);
    numElementsU            = size(vU, 1);

    # TODO: Numbers should be optimized
    MAX_NUM_ROWS_L  = 5000;
    MAX_DENSITY     = 0.4;

    ρ¹ = 1 / ρ;
    α¹ = 1 - α;

    convFlag    = convNumItr;
    ϵAdmm       = min(ϵAbs, ϵRel) * 1e-2;

    vXX, vZZ, tuSolver = LinSysSolInit(vX, mP, vQ, mA, ρ, ρ¹, σ, numElementsX, numRowsA);

    vXP = zeros(numElementsX); #<! Previous iteration of vX
    vZ  = zeros(numRowsA);
    vY  = zeros(numRowsA);
    vZP = zeros(numRowsA); #<! Previous iteration of vZ

    ρρ = ρ;

    for ii in 1:numIterations
        changedΡ = false;
        if (adptΡ && ((ρρ * fctrΡ < ρ) || (ρρ > fctrΡ * ρ)))
            ρ   = ρρ;
            ρ¹  = 1 / ρ;

            changedΡ = true;
        end

        LinSysSol!(tuSolver, vXX, vZZ, vX, mP, vQ, mA, vZ, vY, ρ, ρ¹, σ, numElementsX, numRowsA, changedΡ);

        copyto!(vXP, vX);
        @. vX = α * vXX + α¹ * vX;

        copyto!(vZP, vZ);
        @. vZ = clamp(α * vZZ + α¹ * vZ + ρ¹ * vY, vL, vU); #<! Projection
        @. vY = vY + ρ * (α * vZZ + α¹ * vZP - vZ);

        if (mod(ii, numItrConv) == 0)
            ρρ, convFlag = CheckConvergence(vX, mP, vQ, mA, vZ, vY, vXP, vZP, ρ, ρρ, adptΡ, ϵAbs, ϵRel, ϵAdmm, convFlag);

            if(convFlag ≠ convNumItr)
                break;
            end
        end

    end

    return convFlag;

end

function CheckConvergence(vX, mP, vQ, mA, vZ, vY, vXP, vZP, ρ, ρρ, adptΡ, ϵAbs, ϵRel, ϵAdmm, convFlag)
    #TODO: Use buffers for the intermediate allocations (mP * vX, mA * vX, ...)
    MIN_VAL_Ρ = 1e-3;
    MAX_VAL_Ρ = 1e6;

    # Pre Computation
    normResPrim = norm(mA * vX - vZ, Inf);
    normResDual = norm(mP * vX + vQ + mA' * vY, Inf);

    maxNormPrim = max(norm(mA * vX, Inf), norm(vZ, Inf));
    maxNormDual = max(norm(mP * vX, Inf), norm(mA' * vY, Inf), norm(vQ, Inf));

    # Adaptive Rho
    if (adptΡ)
        numeratorVal    = normResPrim * maxNormDual;
        denominatorVal  = normResDual * maxNormPrim;
        ρρ              = clamp(ρ * sqrt(numeratorVal / denominatorVal), MIN_VAL_Ρ, MAX_VAL_Ρ);
    end

    # Termination
    epsPrim = ϵAbs + ϵRel * maxNormPrim;
    epsDual = ϵAbs + ϵRel * maxNormDual;

    if ((normResPrim < epsPrim) && (normResDual < epsDual))
        convFlag = convPrimDual;
    end
    if ((norm(vX - vXP, Inf) <= ϵAdmm) && (norm(vZ - vZP, Inf) <= ϵAdmm))
        convFlag = convAdmm;
    end

    return ρρ, convFlag;

end

# Left for reference
function SolveQuadraticProgramRef!(vX, mP, vQ, mA, vL, vU;
    numIterations = 5000, ϵAbs = 1e-6, ϵRel = 1e-6,
    ρ = 1e6, σ = 1e-6, α = 1.6, δ = 1e-6, adptΡ::Bool = false,
    fctrΡ = 5, numItrPolish = 10, linSolverMode::LinearSolverMode = modeAuto,
    ϵPcg = 1e-9, numItrPcg = 15000, ϵMinres = 1e-6, numItrMinres = 500, numItrConv = 25)

    numElementsX            = size(vX, 1);
    numRowsP, numColsP      = size(mP);
    numElementsQ            = size(vQ, 1);
    numRowsA, numColsA      = size(mA);
    numElementsL            = size(vL, 1);
    numElementsU            = size(vU, 1);

    # TODO: Numbers should be optimized
    MAX_NUM_ROWS_L  = 5000;
    MAX_DENSITY     = 0.4;

    MIN_VAL_Ρ = 1e-3;
    MAX_VAL_Ρ = 1e6;

    ρ¹ = 1 / ρ;
    α¹ = 1 - α;

    if (linSolverMode == modeItertaive)
        directSol = false;
    elseif (linSolverMode == modeDirect)
        directSol = true;
    else
        numRowsL    = numRowsP + numRowsA;
        numNonZeros = nnz(mP) + nnz(mA);
        nnzDensity  = numNonZeros / (numRowsL * numRowsL);
        if ((numRowsL <= MAX_NUM_ROWS_L) && (nnzDensity <= MAX_DENSITY))
            directSol = true;
        else
            directSol = false;
        end
    end

    convFlag    = convNumItr;
    ϵAdmm       = min(ϵAbs, ϵRel) * 1e-2;

    vXX = copy(vX);
    vXP = zeros(numElementsX); #<! Previous iteration of vX
    vZ  = zeros(numRowsA);
    vY  = zeros(numRowsA);
    vZZ = zeros(numRowsA);
    vZP = zeros(numRowsA); #<! Previous iteration of vZ

    vV  = zeros(numElementsX + numRowsA);
    vT1 = @view vV[1:numElementsX];
    vT2 = @view vV[(numElementsX + 1):end];

    if (adptΡ)
        # ̂ρ = ρ; #<! Won't work
        ρρ = ρ;

        mAA = mA' * mA;
        mPI = mP + sparse(σ * I, numElementsX, numElementsX);
    end

    if (directSol)
        hDL = ldlt([mP + sparse(σ * I, numElementsX, numElementsX) mA'; mA sparse(-ρ¹ * I, numRowsA, numRowsA)]);
    else
        mL = mP + sparse(σ * I, numElementsX, numElementsX) + (ρ * (mA' * mA));
        # sCgSolver = Krylov.CgSolver(numElementsX, numElementsX, typeof(vX)); #<! For Krylov based
        # mL = LinearOperator(Float64, numElements, numElements, true, true, (vU, vW, α, β) -> begin
        #         mul!(vU, mAA, vW);
        #         mul!(vU, mPI, vW, one(Float64), ρ);
        #     end);
    end

    for ii in 1:numIterations
        if (adptΡ && ((ρρ * fctrΡ < ρ) || (ρρ > fctrΡ * ρ)))
            ρ   = ρρ;
            ρ¹  = 1 / ρ;
            if (directSol)
                hDL = ldlt([mP + sparse(σ * I, numElementsX, numElementsX) mA'; mA sparse(-ρ¹ * I, numRowsA, numRowsA)]);
            else
                mL = mPI + (ρ * mAA);
                #     mL = LinearOperator(Float64, numElements, numElements, true, true, (vU, vW, α, β) -> begin
                #     mul!(vU, mAA, vW);
                #     mul!(vU, mPI, vW, one(Float64), ρ);
                # end);
            end
        end
        if (directSol)
            # vV = hDL \ [σ * vX - vQ; vZ - ρ¹ * vY];
            # @. vXX = vV[1:numElementsX];
            # @. vZZ = vZ + ρ¹ * (vV[(numElementsX + 1):end] - vY);
            @. vT1 = σ * vX - vQ;
            @. vT2 = vZ - ρ¹ * vY;
            # ldiv!(hDL, vV); #<! No support in SuiteSparse
            vV .= hDL \ vV; #<! Like copy!() / copyto!()
            @. vXX = vV[1:numElementsX];
            @. vZZ = vZ + ρ¹ * (vT2 - vY);
        else
            @. vT2 = ρ * vZ - vY;
            mul!(vT1, mA', vT2);
            @. vT1 = σ * vX - vQ + vT1;
            IterativeSolvers.cg!(vXX, mL, vT1, abstol = ϵPcg, maxiter = numItrPcg);
            # cg!(vXX, mL, σ * vX - vQ + mA' * (ρ * vZ - vY), abstol = ϵPcg, maxiter = numItrPcg);
            mul!(vZZ, mA, vXX);
        end

        copyto!(vXP, vX);
        @. vX = α * vXX + α¹ * vX;

        copyto!(vZP, vZ);
        @. vZ = clamp(α * vZZ + α¹ * vZ + ρ¹ * vY, vL, vU); #<! Projection
        @. vY = vY + ρ * (α * vZZ + α¹ * vZP - vZ);

        if (mod(ii, numItrConv) == 0)
            # Pre Computation
            normResPrim = norm(mA * vX - vZ, Inf);
            normResDual = norm(mP * vX + vQ + mA' * vY, Inf);

            maxNormPrim = max(norm(mA * vX, Inf), norm(vZ, Inf));
            maxNormDual = max(norm(mP * vX, Inf), norm(mA' * vY, Inf), norm(vQ, Inf));

            # Adaptive Rho
            if (adptΡ)
                numeratorVal    = normResPrim * maxNormDual;
                denominatorVal  = normResDual * maxNormPrim;
                ρρ              = clamp(ρ * sqrt(numeratorVal / denominatorVal), MIN_VAL_Ρ, MAX_VAL_Ρ);
            end

            # Termination
            epsPrim = ϵAbs + ϵRel * maxNormPrim;
            epsDual = ϵAbs + ϵRel * maxNormDual;

            if ((normResPrim < epsPrim) && (normResDual < epsDual))
                convFlag = convPrimDual;
                break;
            end
            if ((norm(vX - vXP, Inf) <= ϵAdmm) && (norm(vZ - vZP, Inf) <= ϵAdmm))
                convFlag = convAdmm;
                break;
            end
        end

    end

    return convFlag;

end

max_stars_repo_name: RoyiAvital/QuadraticProgramSolver

max_issues_repo_name: RoyiAvital/QuadraticProgramSolver

max_forks_repo_name: RoyiAvital/QuadraticProgramSolver


text:
using Plots
using DataFrames
using XLSX
using LsqFit
using LaTeXStrings

gr()

e = 1.60217662e-19
k = 1.38064852e-23
T = 298.15

reverse = DataFrame(XLSX.readtable("Reverse saturation current and material constant.xlsx", "Sheet1"))
reverse = DataFrame(Voltage = reverse[1, 1], Current = reverse[2, 1])
reverse[!, "ln(I)"] = log.(exp(1), (reverse.Current .* 1e-3))

linear_model(x, params) = params[1] .* x .+ params[2]

fit = curve_fit(linear_model, (reverse.Voltage)[3:end],
    (reverse."ln(I)")[3:end], [0.5, 0.5])

params = fit.param
m, c = params
Δm, Δc = standard_errors(fit)

scatter(reverse[!, "Voltage"], reverse[!, "ln(I)"], markersize = 2,
    label = "Data")
x = LinRange(0.45, 0.75, 1000)
plot!(x, linear_model(x, params), label = "Best Fit",
    color = "lawngreen", legend = :topleft, show = true)
title!(L"log_e(I)\quad  v/s\quad Voltage")
ylabel!(L"log_e(I)")
xlabel!(L"Voltage (V)")

I0 = exp(c) ##in A
I0 = I0 * 10^(9)

η = e/(m*k*T)

Δη = sqrt((Δm/m)^2)

println("Material Constant η = $η")
println("Standard Deviation = $Δη")
println("Reverse Saturation Current = $I0 nA")

TvsV = DataFrame(XLSX.readtable("Energy band gap and Temperature coefficient.xlsx", "Sheet1"))
TvsV = DataFrame(Temperature = TvsV[1, 1], Voltage = TvsV[2, 1])

linear_model(x, params) = params[1] .* x .+ params[2]

fit = curve_fit(linear_model, TvsV.Voltage, TvsV.Temperature, [0.5, 0.5])

params = fit.param
m, c = params
Δm, Δc = standard_errors(fit)

scatter(TvsV[!, "Voltage"], TvsV[!, "Temperature"], label = "Data", color = "blue", markersize = 2)
x = LinRange(0.59, 0.673, 1000)
plot!(x, linear_model(x, params), label = "Best Fit", color = "lawngreen", show = true)
title!("Voltage v/s Temperature")
ylabel!(L"Temperature (K)")
xlabel!(L"Voltage (V)")

Eg = 6.242e+18 * -(c/m)*e
ΔEg = sqrt((Δm/m)^2 + (Δc/c)^2)

println("Band gap value = $Eg eV")
println("Standard Deviation = $ΔEg eV")

forward = DataFrame(XLSX.readtable("Forward characteristics of junction diode.xlsx", "Sheet1"))
forward = DataFrame(Voltage = forward[1, 1], Current = forward[2, 1])

exp_model(x, params) = params[1] .* exp.(params[2] .* x) .+ params[3]

fit = curve_fit(exp_model, forward.Voltage, forward.Current, [0.5, 0.5, 0.5])

params = fit.param
I0, r, c = params
ΔI0, Δr, Δc = standard_errors(fit)

scatter(forward[!, "Voltage"], forward[!, "Current"] , legend = :topleft, label = "Given Data")
x = LinRange(0.0, 0.65, 1000)
plot!(x, exp_model(x, params), label = "Best Fit", color = "lawngreen", legend = :topleft)
plot!( [0.55, 0.4], [6, 16], arrow = :closed, label = "", color = :black)
title!("Current v/s Voltage \n Forward Bias")
ylabel!(L"Current (I)")
xlabel!(L"Voltage (V)")
annotate!((0.4, 17, L"8.44 \times e^{19.37 V} - 0.19"), show = true)

max_stars_repo_path: PHY212/P-N Junction/Estimating material constant and bang gap energy.jl

max_stars_repo_name: dev-aditya/Mathematical-Python

max_issues_repo_name: dev-aditya/Mathematical-Python

max_forks_repo_name: dev-aditya/Mathematical-Python


text:
# The Dates module provides two types for working with dates: Date and DateTime, representing day and millisecond precision.
using Dates
println(DateTime(2018))
println(DateTime(2018, 11))
println(DateTime(2018, 11, 11))

t = Date(2014, 1, 31)
println(Dates.month(t))
println(Dates.dayname(t))
println(Dates.isleapyear(t))

# Arithmetic
println((Date(2018, 11, 11)+Dates.Day(1)) + Dates.Month(1))

# Aduster Function
println(Dates.lastdayofmonth(Date(2018,11,11)))

# Period Type: Periods are a human view of discrete, sometimes irregular durations of time.
println(Dates.Year(10))

max_stars_repo_name: startprogress/Hello-Julia

max_issues_repo_name: startprogress/Hello-Julia

max_forks_repo_name: startprogress/Hello-Julia


text:
using Base: _to_linear_index
using GaussianBasis
using Molecules
using HDF5
using Test

@testset "GaussianBasis" begin
    include("test_misc.jl")
    include("test_integrals.jl")
    include("test_gradients.jl")
end


text:
const basic_config = (
    doom_scenario_path = get_scenario_path("deadly_corridor.wad"),
    doom_map = "map01",
    screen_resolution = RES_640X480,
    screen_format = RGB24,
    depth_buffer_enabled = true,
    labels_buffer_enabled = true,
    automap_buffer_enabled = true,
    render_hud = false,
    render_minimal_hud = false,
    render_crosshair = false,
    render_weapon = true,
    render_decals = false,
    render_particles = false,
    render_effects_sprites = false,
    render_messages = false,
    render_corpses = false,
    render_screen_flashes = true,
    episode_timeout = 200,
    episode_start_time = 10,
    window_visible = true,
    sound_enabled = true,
    living_reward = -1,
    mode = PLAYER,

    available_game_variable = AMMO2,
    available_buttons = [MOVE_LEFT, MOVE_RIGHT, ATTACK]
)

function basic_game(;kw...)
    config = merge(basic_config, kw)
    @debug config
    game = DoomGame()
    set_game(game; config...)
end


text:
@assert d==2
xobs0comp1 = extractcomp(xobs0,1)
xobs0comp2 = extractcomp(xobs0,2)
xobsTcomp1 = extractcomp(xobsT[1],1)
xobsTcomp2 = extractcomp(xobsT[1],2)
pp1 = plotshapes(xobs0comp1,xobs0comp2,xobsTcomp1, xobsTcomp2)

anim = @animate for i in 1:ITER
    drawpath(ITER, i, P.n,x,X,objvals,parsave,(xobs0comp1,xobs0comp2,xobsTcomp1, xobsTcomp2),pb)
end

if make_animation
    fn = string(model)
    gif(anim, outdir*"anim.gif", fps = 50)
    mp4(anim, outdir*"anim.mp4", fps = 50)
end

# plotting
#Pdeterm = MarslandShardlow(0.1, 0.1, 0.0, 0.0, P.n)
#plotlandmarkpositions[](initSamplePath(0:0.01:0.1,x0),Pdeterm,x0.q,deepvec2state(xᵒ).q;db=.5)


text:
Pkg.init()
Pkg.update()

for pkg in [# JuliaPro
            "DataStructures",
            "Calculus",
            "DataFrames",
            "StatsBase",
            "Distributions",
            "HypothesisTests",
            "GLM",
            "JuMP",
            "Optim",
            "Roots",
#            "ODBC",
#            "JDBC",

# no interactive stuff
#            "Gadfly",
#            "PyPlot",
#            "Interact",

#            "PyCall",
            "JSON",
#            "HDF5",
#            "JLD",
            # Other Packages
            "Iterators",
#            "BenchmarkTools",
            ]
  println("Installing ", pkg)
  Pkg.add(pkg)
  pkgsym = Symbol(pkg)
  eval(:(using $pkgsym))
end

max_stars_repo_name: mikea/dockerfiles

max_issues_repo_name: mikea/dockerfiles

max_forks_repo_name: mikea/dockerfiles


text:
include("power_balance_equation.jl")

include("beta_equation.jl")
include("heat_equation.jl")
include("kink_equation.jl")
include("pcap_equation.jl")
include("wall_equation.jl")

include("r_0_equation.jl")
include("b_0_equation.jl")
include("i_p_equation.jl")
include("n_bar_equation.jl")
include("t_bar_equation.jl")

include("p_f_equation.jl")
include("w_m_equation.jl")
include("cost_equation.jl")
include("f_bs_equation.jl")
include("p_bar_equation.jl")


text:
module PolynomialAmoebas

    using StaticArrays
    using RecipesBase
    using LinearAlgebra

    import MultivariatePolynomials
    const MP = MultivariatePolynomials
    import StaticPolynomials
    const SP = StaticPolynomials
    import CDDLib, Polyhedra

    import DynamicPolynomials: @polyvar

    export @polyvar

    import Colors
    import PlotUtils
    import Contour
    import DataStructures: PriorityQueue, enqueue!, dequeue!, peek, dequeue_pair!
    import Statistics: mean

    include("types.jl")
    include("utilities.jl")
    include("show.jl")

    include("fibers/fiber_helpers.jl")
    include("fibers/amoeba_fiber_2d.jl")
    include("fibers/amoeba_fiber_3d.jl")
    include("fibers/coamoeba_fiber_2d.jl")
    include("fibers/coamoeba_fiber_3d.jl")
    include("fibers/contour_fiber_2d.jl")
    include("fibers/imaginary_fiber_2d.jl")
    include("fibers/imaginary_fiber_3d.jl")

    include("newton.jl")

    include("membership_test_startvalues.jl")
    include("membership_test.jl")

    include("newtonpolygon.jl")

    include("grid_2d.jl")
    include("grid_3d.jl")
    include("bitmap_2d.jl")
    include("bitmap_3d.jl")
    include("bitmap.jl")

    include("tropical.jl")
    include("tropicalcurve.jl")
    include("archtrop.jl")

    include("simple_grid.jl")
    include("greedy_grid.jl")

    include("contour_2d.jl")
    include("contour.jl")

    include("amoeba.jl")
    include("coamoeba.jl")
    include("imaginary.jl")

    include("spine/components_complement.jl")
    include("spine/ronkin.jl")
    include("spine.jl")

    include("polygonal_amoeba/covering.jl")
    include("polygonal_amoeba/covering_fitter.jl")
    include("polygonal_amoeba.jl")
end


text:
const _pkg_root = dirname(dirname(@__FILE__))
const _pkg_deps = joinpath(_pkg_root,"deps")
const _pkg_assets = joinpath(_pkg_root,"assets")

!isdir(_pkg_assets) && mkdir(_pkg_assets)

deps = [
    "https://use.fontawesome.com/releases/v5.0.7/js/all.js",
    "https://cdn.jsdelivr.net/gh/piever/InteractResources@0.1.0/highlight/prism.css",
    "https://cdn.jsdelivr.net/gh/piever/InteractResources@0.1.0/highlight/prism.js",
    "https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/11.1.0/nouislider.min.js",
    "https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/11.1.0/nouislider.min.css",
    "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.js",
    "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.css"
]

for dep in deps
    download(dep, joinpath(_pkg_assets, splitdir(dep)[2]))
end


text:
function mslicer(g, dim, x0, xargs; N=1000, w=0.5, m=10)
    #=VERSION FOR VECTOR FIXES=#
    #= multi-D slice sampler, g: log of distribution function,
    dim number of dimensions
    x0: start (or next) point, values of distribution parameters. x1: next point.
    xargs: extra arguments for distribution, Nm samples to return,
        w: \"out step\" distance, m: max number of outward steps.
    Returns N x dim array.
    Steps successively in each direction in the sample space, so it produces
    dim*N samples as currently written.

    Note that you only have to worry about log scaling in 'vertical' comparisons
    in these Monte Carlo chain calculations.

    NOTE: this needs to be checked for the whole julia
    vector vs matrix thing: what is  [1 2 3] vs [1,2,3]
    =#
    xs = zeros(N, dim)  # array that will be returned
    xs[1,:] = x0  #x0 should be array 1,dim; needs [1.0 1.0] syntax for this version.
    #print(x0)
    x1 = zeros(1,dim)
    L = zeros(1,dim)
    R = zeros(1,dim)
    way = zeros(1,dim)  # which axis to go along in space
    i = 2    # assumed start values for chain are recorded at xs[1,1]
    while i <= N
        for d in 1:dim       # go one step in each dimensional direction.
            way = 0.0 * way #clear it
            way[d] = 1.0 #set nonzero in direction we go for slicing on this step
            y0 = g(x0,xargs)  #height of distribution at x0
            y = y0 + log(rand()) # height for slice (using log scaled distribution)
            #start stepping out
            U = rand()   # between 0 and 1
            L = x0 - (w * way * U)
            R = L .+ w .* way

            V = rand()
            J = floor(m*V)
            K = (m - 1) - J
            while J > 0 && y < g(L,xargs)
                L = L .- w .* way
                J = J - 1
            end
            while K > 0 && y < g(R,xargs)
                R = R .+ w .* way
                K = K - 1
            end
            #now should be stepped out beyond distribution at slice level
            # work back in if no value found:
            Lbar, Rbar = L, R
            while true
                U = rand()
                x1 = Lbar .+ U .* (Rbar .- Lbar)  # vector subtraction should be correct dir
                if y < g(x1,xargs)
                    break # exit while loop
                end
                if x1[d] < x0[d]
                    Lbar = x1
                    else
                    Rbar = x1
                end
            end
            xs[i,:] = x1 # found an acceptable point, record in chain (a row)
            x0 = x1 # set initial to new point for next round.
            i += 1
            if i > N
                break # catch case where we reach N in the middle of set of dimensions
            end
        end # for d
        end  #while i
    return xs
end

max_stars_repo_name: davidwcraig/mslicer

max_issues_repo_name: davidwcraig/mslicer

max_forks_repo_name: davidwcraig/mslicer


text:
# Autogenerated wrapper script for Singular_jll for x86_64-apple-darwin
export Singular, libfactory, libomalloc, libparse, libpolys, libsingular, libsingular_resources

using cddlib_jll
using FLINT_jll
using GMP_jll
using MPFR_jll
JLLWrappers.@generate_wrapper_header("Singular")
JLLWrappers.@declare_library_product(libfactory, "@rpath/libfactory-4.2.1.dylib")
JLLWrappers.@declare_library_product(libomalloc, "@rpath/libomalloc-0.9.6.dylib")
JLLWrappers.@declare_library_product(libpolys, "@rpath/libpolys-4.2.1.dylib")
JLLWrappers.@declare_library_product(libsingular, "@rpath/libSingular-4.2.1.dylib")
JLLWrappers.@declare_library_product(libsingular_resources, "@rpath/libsingular_resources-4.2.1.dylib")
JLLWrappers.@declare_executable_product(Singular)
JLLWrappers.@declare_executable_product(libparse)
function __init__()
    JLLWrappers.@generate_init_header(cddlib_jll, FLINT_jll, GMP_jll, MPFR_jll)
    JLLWrappers.@init_library_product(
        libfactory,
        "lib/libfactory.dylib",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libomalloc,
        "lib/libomalloc.dylib",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpolys,
        "lib/libpolys.dylib",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libsingular,
        "lib/libSingular.dylib",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libsingular_resources,
        "lib/libsingular_resources.dylib",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_executable_product(
        Singular,
        "bin/Singular",
    )

    JLLWrappers.@init_executable_product(
        libparse,
        "bin/libparse",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
### DC power flow results
@inbounds function results_flowdc(system, num, settings, results, slack, algtime)
    dheader = dcpfheader(); pheader = psheader(system)
    header = merge(dheader, pheader)

    ########## DC main display ##########
    println(string("Execution time: ", (@sprintf "%.4f" algtime * 1000), " (ms)"))
    if settings.main
        h1 = Highlighter((data, i, j) -> (i == slack),  background = :blue)
        println("\n Main Data Display")
        pretty_table(results.main, header[:main], screen_size = (-1,-1), alignment = [:r,:r,:r,:r,:r,:r],
            highlighters = h1, columns_width = [7, 18, 18, 18, 18, 18],
            formatters = ft_printf(["%1.0f","%1.4f","%1.2f","%1.2f","%1.2f","%1.2f"], collect(1:6)))

        pretty_table(["Sum" sum(results.main[:, 3:6], dims = 1)], noheader = true, screen_size = (-1,-1), columns_width = [28, 18, 18, 18, 18],
            alignment = [:l,:r,:r,:r,:r], formatters = ft_printf(["%-s","%15.2f","%11.2f","%11.2f","%13.2f"], collect(1:5)))
    end

    ########## DC flow display ##########
        if settings.flow
        println("\n Flow Data Display")
        pretty_table(results.flow, header[:flow], screen_size = (-1,-1), columns_width = [7, 8, 8, 18, 18],
            alignment = [:r,:r,:r,:r,:r], formatters = ft_printf(["%1.0f","%1.0f","%1.0f","%1.2f","%1.2f"], collect(1:5)))
    end

    ########## DC generation display ##########
    gen = 0; gent = 0
    if num.Ngen != 0
        gen = 2; gent = 1
    end
    cost = 0
    if num.Ncost != 0
        cost = 2
    end

    if settings.generation
        println("\n Generation Data Display")
        pretty_table(results.generation, header[:generation], screen_size = (-1,-1), alignment=[:r,:r],
            formatters = ft_printf(["%1.0f","%1.4f"], collect(1:2)))
    end

    group = (main = 1, flow = 1, generation = gent, bus = 2, branch = 2, generator = gen, generatorcost = cost, basePower = 2)

    return header, group
end

### AC power flow results
@inbounds function results_flowac(system, num, settings, results, slack, limit, algtime)
    println(string("Execution time: ", (@sprintf "%.4f" algtime * 1000), " (ms)"))
    aheader = acpfheader(); pheader = psheader(system)
    header = merge(aheader, pheader)

    ########## AC limit display ##########
    if settings.reactive[1]
        min = findall(x -> x == 2, limit)
        max = findall(x -> x == 3, limit)
        if !isempty(min)
            println("\n Generators that Violate Lower Reactive Power Limits")
            Nl = length(min)
            pretty_table(["Bus" system.generator[min, 1]'; "Generator" min'],
                noheader = true, alignment = repeat([Symbol(:r)], outer = Nl + 1),
                formatters = ft_printf(vcat("%s", repeat(["%1.0f"], outer = Nl)), collect(1:1 + Nl)))
        end
        if !isempty(max)
            println("\n Generators that Violate Uppert Reactive Power Limits")
            Nl = length(max)
            pretty_table(["Bus" system.generator[max, 1]'; "Generator" max'],
                noheader = true, alignment = repeat([Symbol(:r)], outer = Nl + 1),
                formatters = ft_printf(vcat("%s", repeat(["%1.0f"], outer = Nl)), collect(1:1 + Nl)))
        end
    end

    ########## AC main display ##########
    if settings.main
        h1 = Highlighter((data, i, j)-> (i == slack), background = :red)
        println("\n Main Data Display")
        pretty_table(results.main, header[:main],
            screen_size = (-1,-1), highlighters = h1, columns_width = [7, 16, 12, 17, 21, 17, 21, 17, 21, 17, 21],
            alignment = repeat([Symbol(:r)], outer = 11),
            formatters = ft_printf(["%1.0f", "%1.4f","%1.4f","%1.2f" ,"%1.2f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f"], collect(1:11)))
        sum_data = Any["Sum" sum(results.main[:, 4:11], dims = 1)]
        pretty_table(sum_data, noheader = true, screen_size = (-1,-1),
            alignment=[:l,:r,:r,:r,:r,:r,:r,:r,:r], columns_width = [41, 17, 21, 17, 21, 17, 21, 17, 21],
            formatters = ft_printf(["%-s","%15.2f","%15.2f","%11.2f","%15.2f","%11.2f","%15.2f","%13.2f","%15.2f"], collect(1:9)))
    end

    ########## AC flow display ##########
    if settings.flow
        println("\n Flow Data Display")
        pretty_table(results.flow[:,1:10], header[:flow][:,1:10],
            screen_size = (-1,-1), columns_width = [6, 8, 8, 17, 21, 17, 21, 21, 17, 21],
            alignment=[:r,:r,:r,:r,:r,:r,:r,:r,:r,:r],
            formatters = ft_printf(["%1.0f","%1.0f","%1.0f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f"], collect(1:10)))
        sum_data = Any["Sum" sum(results.flow[:, 8:10], dims = 1)]
        pretty_table(sum_data, noheader = true, screen_size = (-1,-1), alignment=[:l,:r,:r,:r], columns_width = [116, 21, 17, 21],
            formatters = ft_printf(["%-s","%15.2f","%11.2f","%15.2f"], collect(1:4)))
    end

    ########## AC generation display ##########
    gen = 0; gent = 0
    if num.Ngen != 0
        gen = 2; gent = 1
    end
    cost = 0
    if num.Ncost != 0
        cost = 2
    end

    if settings.generation
        println("\n Generation Data Display")
        pretty_table(results.generation, header[:generation],
            screen_size = (-1,-1), alignment=[:r,:r,:r],
            formatters = ft_printf(["%1.0f", "%1.4f", "%1.4f"], collect(1:3)))
    end

    group = (main = 1, flow = 1, generation = gent, bus = 2, branch = 2, generator = gen, generatorcost = cost, basePower = 2)

    return header, group
end

### Power system info data
@inbounds function infogrid(bus, branch, generator, info, dataname, Nbranch, Nbus, Ngen)
    reference = "unknown"; grid = "unknown"
    for (k, i) in enumerate(info[:, 1])
        if occursin("Reference", i)
            reference = info[k, 2]
        end
        if occursin("Grid", i)
            grid = info[k, 2]
        end
    end

    Ntrain = 0; Ntra = 0; pv = 0
    for i = 1:Nbranch
        if branch[i, 12] == 1 && (branch[i, 10] != 0 || branch[i, 11] != 0)
            Ntrain += 1
        end
        if branch[i, 10] != 0 || branch[i, 11] != 0
            Ntra += 1
        end
    end
    if Ngen != 0
        pv = length(unique(generator[:, 1]))
    end

    info = [["Reference" string(reference) ""]
            ["Data" string(dataname) ""]
            ["Grid" string(grid) ""]
            ["" "" ""]
            ["Bus" string(Nbus) ""]
            ["PV bus" string(pv) ""]
            ["PQ bus" string(Nbus - pv - 1) ""]
            ["Shunt element" string(count(x->x != 0, abs.(bus[:, 5]) + abs.(bus[:, 6]))) ""]
            ["Generator" string(Ngen) "$(trunc(Int, sum(generator[:, 8]))) in-service"]
            ["Branch" string(Nbranch) "$(trunc(Int, sum(branch[:, 12]))) in-service"]
            ["Transformer" string(Ntra) "$Ntrain in-service"]]

    return info
end

### Measurements info data
@inbounds function infogenerator(system, measurements, settings, info, names)
    setkeys = keys(settings.set)
    varkeys = keys(settings.variance)

    ########## PMU set ##########
    info = [info; ["" "" ""]]
    if :pmucomplete in setkeys
        info = [info; ["PMU set setting" "complete measurement set in-service" ""]]
    elseif :pmuredundancy in setkeys
        info = [info; ["PMU set setting" "redundancy" string(settings.set[:pmuredundancy])]]
    elseif :pmudevice in setkeys
        info = [info; ["PMU set setting" "devices in-services" string(settings.set[:pmudevice])]]
    elseif :pmuoptimal in setkeys
        info = [info; ["PMU set setting" "optimal placement" ""]]
    elseif :pmuVoltage in setkeys || :pmuCurrent in setkeys
        info = [info; ["PMU set setting" "measurements by type adjust in-service" ""]]
    else
        info = [info; ["PMU set setting" "" ""]]
    end
    readps = (pmuVoltage = [4, 7], pmuCurrent = [6, 9])
    titleps = (pmuVoltage = ["Bus voltage magnitude", "Bus voltage angle"], pmuCurrent = ["Branch current magnitude", "Branch current angle"])

    for i in names[:pmu]
        cnt = 1
        for k in readps[i]
            on = trunc(Int, sum(getfield(measurements, i)[:, k]))
            info = [info; [titleps[i][cnt] "$on in-service" "$(size(getfield(measurements, i), 1) - on) out-service"]]
            cnt += 1
        end
    end

    ########## Legacy set ##########
    info = [info; ["" "" ""]]
    if :legacycomplete in setkeys
        info = [info; ["Legacy set setting" "complete measurement set in-service" ""]]
    elseif :legacyredundancy in setkeys
        info = [info; ["Legacy set setting" "redundancy" string(settings.set[:legacyredundancy])]]
    elseif :legacyFlow in setkeys || :legacyCurrent in setkeys || :legacyInjection in setkeys || :legacyVoltage in setkeys
        info = [info; ["Legacy set setting" "measurements by type adjust in-service" ""]]
    else
        info = [info; ["Legacy set setting" "" ""]]
    end
    readls = (legacyFlow = [6, 9], legacyCurrent = [6], legacyInjection = [4, 7], legacyVoltage = [4])
    titlels = (legacyFlow = ["Active power flow", "Reactive power flow"], legacyCurrent = ["Branch current magnitude"],
            legacyInjection = ["Active power injection", "Reactive power injection"], legacyVoltage = ["Bus voltage magnitude"])
    for i in names[:legacy]
        cnt = 1
        for k in readls[i]
            on = trunc(Int, sum(getfield(measurements, i)[:, k]))
            info = [info; [titlels[i][cnt] "$on in-service" "$(size(getfield(measurements, i), 1) - on) out-service"]]
            cnt += 1
        end
    end

    ########## PMU variance ##########
    info = [info; ["" "" ""]]
    if :pmucomplete in varkeys
        info = [info; ["PMU variance setting" "fixed-value variance over all measurements" string(settings.variance[:pmucomplete])]]
    elseif :pmurandom in varkeys
        info = [info; ["PMU variance setting" "randomized variances within limits" "$(settings.variance[:pmurandom][1]), $(settings.variance[:pmurandom][2])"]]
    elseif :pmuVoltage in varkeys || :pmuCurrent in varkeys
        info = [info; ["PMU variance setting" "variances by measurement type" ""]]
    else
        info = [info; ["PMU variance set setting" "" ""]]
    end
    readpv = (pmuVoltage = [3, 6], pmuCurrent = [5, 8])
    titlepv = (pmuVoltage = ["Bus voltage magnitude", "Bus voltage angle"], pmuCurrent = ["Branch current magnitude", "Branch current angle"])
    for i in names[:pmu]
        cnt = 1
        for k in readpv[i]
            on = extrema(getfield(measurements, i)[:, k])
            info = [info; [titlepv[i][cnt] "$(on[1]) minimum" "$(on[2]) maximum"]]
            cnt += 1
        end
    end

    ########## Legacy variance ##########
    info = [info; ["" "" ""]]
    if :legacycomplete in varkeys
        info = [info; ["Legacy variance setting" "fixed-value variance over all measurements" string(settings.variance[:legacycomplete])]]
    elseif :legacyrandom in varkeys
        info = [info; ["Legacy variance setting" "randomized variances within limits" string(settings.variance[:legacyrandom][1], ", ", settings.variance[:legacyrandom][2])]]
    elseif :legacyFlow in varkeys || :legacyCurrent in varkeys || :legacyInjection in varkeys || :legacyVoltage in varkeys
        info = [info; ["Legacy variance setting" "variances by measurement type" ""]]
    else
        info = [info; ["Legacy variance set setting" "" ""]]
    end
    readlv = (legacyFlow = [5, 8], legacyCurrent = [5], legacyInjection = [3, 6], legacyVoltage = [3])
    titlelv = (legacyFlow = ["Active power flow", "Reactive power flow"], legacyCurrent = ["Branch current magnitude"],
               legacyInjection = ["Active power injection", "Reactive power injection"], legacyVoltage = ["Bus voltage magnitude"])
    for i in names[:legacy]
        cnt = 1
        for k in readlv[i]
            on = extrema(getfield(measurements, i)[:, k])
            info = [info; [titlelv[i][cnt] "$(on[1]) minimum" "$(on[2]) maximum"]]
            cnt += 1
        end
    end

    return info
end

### DC state estimation results
function results_estimatedc(system, numsys, measurements, num, settings, results, idxbad, Npseudo, algtime, slack)
    println(string("Execution time: ", (@sprintf "%.4f" algtime * 1000), " (ms)"))
    header = dcseheader()

    ########## DC estimate and error results ##########
    label = Array{String}(undef, size(results.estimate, 1), 3)
    idex = 1
    for (k, i) in enumerate(results.estimate[:, 2])
        if i == 1.0
            label[k, 1] = "in-service"
        elseif i == 2.0
            label[k, 1] = "bad-measurement"
        elseif i == 3.0
            label[k, 1] = "pseudo-measurement"
        end
        if results.estimate[k, 3] == 1.0
            label[k, 2] = "Legacy"
        else
            label[k, 2] = "PMU"
        end
        j = convert(Int, results.estimate[k, 5])
        if results.estimate[k, 4] == 1.0
            label[k, 3] = "P$(trunc(Int, measurements.legacyFlow[j, 2])),$(trunc(Int, measurements.legacyFlow[j, 3])) [MW]"
        elseif results.estimate[k, 4] == 3.0
            label[k, 3] = "P$(trunc(Int, measurements.legacyInjection[j, 1])) [MW]"
        elseif results.estimate[k, 4] == 8.0
            label[k, 3] = "T$(trunc(Int, measurements.pmuVoltage[j, 1])) [deg]"
        end
    end

    ########## Observability display ##########
    idxp = findall(x->x==3, results.estimate[:, 2])
    pseudo = [label[idxp, 2:3] results.estimate[idxp, 5:7]]
    if settings.observe[:observe] == 1 && Npseudo != 0
        Nisland = size(results.observability, 1)
        numer = collect(1:Nisland)
        islanddisp = copy(results.observability)
        if Nisland > Npseudo
            pseudo = [pseudo; repeat([""], Nisland - Npseudo, 5)]
        elseif Nisland < Npseudo
            islanddisp = [islanddisp; repeat([[""]], Npseudo - Nisland, 1)]
            numer = [numer; repeat([""], Npseudo - Nisland)]
        end
        println("\n Observability Analysis Display")
        pretty_table([numer islanddisp pseudo], header[:observe], alignment=[:l,:l,:l,:l,:r,:r,:r],
            columns_width = [11, 40, 10, 20, 11, 11, 11],
            formatters = ft_printf(["%1.0f", "%-s", "%-s", "%-s", "%1.0f", "%1.2f", "%1.2e"], collect(1:7)))
    end

    ########## DC bad data display ##########
    if settings.bad[:bad] == 1 && !isempty(results.baddata)
        println("\n Bad Data Analysis Display")
        pretty_table([results.baddata[:,1] label[idxbad, 2:3] results.estimate[idxbad, 5] results.baddata[:,5] label[idxbad, 1]],
            header[:bad], screen_size = (-1,-1),
            columns_width = [10, 10, 18, 13, 20, 18], alignment=[:l,:l,:l,:r,:r,:r],
            formatters = ft_printf(["%1.0f", "%-s","%-s","%1.0f","%1.4e","%-s"], collect(1:6)))
    end

    ########## DC main display ##########
    if settings.main
        h1 = Highlighter((data, i, j) -> (i == slack),  background = :blue)
        println("\n Main Data Display")
        pretty_table(results.main, header[:main], screen_size = (-1,-1), alignment = [:r,:r,:r],
            highlighters = h1, columns_width = [8, 18, 18],
            formatters = ft_printf(["%1.0f","%1.4f","%1.2f"], collect(1:3)))

        sum_data = Any["Sum" sum(results.main[:, 3], dims = 1)]
        pretty_table(sum_data, noheader = true, screen_size = (-1,-1), columns_width = [29, 18],
            alignment = [:l,:r], formatters = ft_printf(["%-s","%15.2f"], [1, 2]))
    end

    ########## DC flow display ##########
    if settings.flow
        println("\n Flow Data Display")
        pretty_table(results.flow, header[:flow], screen_size = (-1,-1), columns_width = [8, 8, 8, 18, 18],
            alignment=[:r,:r,:r,:r,:r], formatters = ft_printf(["%1.0f","%1.0f","%1.0f","%1.2f","%1.2f"], collect(1:5)))
    end

    ########## DC Estimate display ##########
    if settings.estimate
        println("\n Estimate Data Display")
        columns_width = [18, 12, 15, 12, 12, 12, 12, 19, 12, 19]
        alignment = [:l, :l, :l, :r, :r, :r, :r, :r, :r, :r]
        formatters = ["%s", "%s", "%s", "%1.0f", "%1.2f", "%1.2e", "%1.2f", "%1.2e", "%1.2f", "%1.2e"]
        many = collect(1:10)
        head = header[:estimatedisplay]
        if size(results.estimate, 2) == 9
            columns_width = columns_width[1:8]
            alignment = alignment[1:8]
            formatters = formatters[1:8]
            many = many[1:8]
            head = head[:, 1:8]
        end
        pretty_table([label results.estimate[:, 5:end]], head, screen_size = (-1,-1), columns_width = columns_width,
            show_row_number = true, alignment = alignment, formatters = ft_printf((formatters), many))
    end

    ########## DC error display ##########
    if settings.error
        println("\n Error Data Display\n")
        if size(results.estimate, 2) == 11
            head = header[:errordisplay]
            err = [""; results.error[1:3]; ""; ""; results.error[4:6]]
        else
            head = header[:errordisplay][1:4, :]
            err = [""; results.error[1:3]]
        end
        pretty_table([head err], screen_size = (-1,-1), tf = borderless,
            noheader = true, alignment = [:l, :l, :r], formatters = ft_printf("%1.4e", 3),
            highlighters = (hl_cell( [(1,1);(6,1)], crayon"bold"), hl_col(2, crayon"dark_gray")),
            body_hlines = [1,6], body_hlines_format = Tuple('─' for _ = 1:4))
    end

    ########## Export results ##########
    pmuv = 2; pmuc = 2; legf = 2; legc = 2; legi = 2; legv = 2; gen = 3; cost = 3;
    if num.pmuNv == 0 pmuv = 0  end
    if num.pmuNc == 0 pmuc = 0 end
    if num.legacyNf == 0 legf = 0 end
    if num.legacyNc == 0 legc = 0 end
    if num.legacyNi == 0 legi = 0 end
    if num.legacyNv == 0 legv = 0 end
    if numsys.Ngen == 0 gen = 0 end
    if numsys.Ncost == 0 cost = 0 end

    group = (main = 1, flow = 1, estimate = 1, error = 1,
        pmuVoltage = pmuv, pmuCurrent = pmuc, legacyFlow = legf, legacyCurrent = legc, legacyInjection = legi, legacyVoltage = legv,
        bus = 3, branch = 3, generator = gen, generatorcost = cost, basePower = 3)

    mheader = measureheader(); pheader = psheader(system); headernew = merge(mheader, pheader, header)

    return headernew, group
end

### PMU state estimation results
@inbounds function results_estimatepmu(system, numsys, measurements, num, settings, results, idxbad, Npseudo, algtime)
    println(string("Execution time: ", (@sprintf "%.4f" algtime * 1000), " (ms)"))
    aheader = pmuseheader(); pheader = psheader(system)
    header = merge(aheader, pheader)

    ########## PMU estimate and error results ##########
    label = Array{String}(undef, size(results.estimate, 1), 3)
    idex = 1
    for (k, i) in enumerate(results.estimate[:, 2])
        if i == 1.0
            label[k, 1] = "in-service"
        elseif i == 2.0
            label[k, 1] = "bad-measurement"
        elseif i == 3.0
            label[k, 1] = "pseudo-measurement"
        end
        label[k, 2] = "PMU"
        j = convert(Int, results.estimate[k, 5])
        if results.estimate[k, 4] == 9.0
            label[k, 3] = "Ir$(trunc(Int, measurements.pmuCurrent[j, 2])),$(trunc(Int, measurements.pmuCurrent[j, 3])) [p.u.]"
        elseif results.estimate[k, 4] == 10.0
            label[k, 3] = "Ii$(trunc(Int, measurements.pmuCurrent[j, 2])),$(trunc(Int, measurements.pmuCurrent[j, 3])) [p.u.]"
        elseif results.estimate[k, 4] == 11.0
            label[k, 3] = "Vr$(trunc(Int, measurements.pmuVoltage[j, 1])) [p.u.]"
        elseif results.estimate[k, 4] == 12.0
            label[k, 3] = "Vi$(trunc(Int, measurements.pmuVoltage[j, 1])) [p.u.]"
        end
    end

    ########## PMU bad data display ##########
    if settings.bad[:bad] == 1 && !isempty(results.baddata)
        println("\n Bad Data Analysis Display")
        pretty_table([results.baddata[:,1] label[idxbad, 2:3] results.estimate[idxbad, 5] results.baddata[:,5] label[idxbad, 1]],
            header[:bad], screen_size = (-1,-1),
            columns_width = [10, 10, 18, 13, 20, 18], alignment=[:l,:l,:l,:r,:r,:r],
            formatters = ft_printf(["%1.0f", "%-s","%-s","%1.0f","%1.4e","%-s"], collect(1:6)))
    end

    ########## PMU main results ##########
    if settings.main
        println("\n Main Data Display")
        pretty_table(results.main, header[:main],
            screen_size = (-1,-1), columns_width = [7, 16, 12, 17, 21, 17, 21],
            alignment = repeat([Symbol(:r)], outer = 7),
            formatters = ft_printf(["%1.0f", "%1.4f","%1.4f","%1.2f" ,"%1.2f","%1.2f","%1.2f"], collect(1:7)))
        sum_data = Any["Sum" sum(results.main[:, 4:7], dims = 1)]
        pretty_table(sum_data, noheader = true, screen_size = (-1,-1),
            alignment=[:l,:r,:r,:r,:r], columns_width = [41, 17, 21, 17, 21],
            formatters = ft_printf(["%-s","%15.2f","%15.2f","%11.2f","%15.2f"], collect(1:5)))
    end

    ########## PMU flow results ##########
    if settings.flow
        println("\n Flow Data Display")
        pretty_table(results.flow[:,1:10], header[:flow][:,1:10],
            screen_size = (-1,-1), columns_width = [6, 8, 8, 17, 21, 17, 21, 21, 17, 21],
            alignment=[:r,:r,:r,:r,:r,:r,:r,:r,:r,:r],
            formatters = ft_printf(["%1.0f","%1.0f","%1.0f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f"], collect(1:10)))
        sum_data = Any["Sum" sum(results.flow[:, 8:10], dims = 1)]
        pretty_table(sum_data, noheader = true, screen_size = (-1,-1), alignment=[:l,:r,:r,:r], columns_width = [116, 21, 17, 21],
            formatters = ft_printf(["%-s","%15.2f","%11.2f","%15.2f"], collect(1:4)))
    end

    ########## PMU Estimate display ##########
    if settings.estimate
        println("\n Estimate Data Display")
        columns_width = [18, 12, 15, 12, 12, 12, 12, 19, 12, 19]
        alignment = [:l, :l, :l, :r, :r, :r, :r, :r, :r, :r]
        formatters = ["%s", "%s", "%s", "%1.0f", "%1.2f", "%1.2e", "%1.2f", "%1.2e", "%1.2f", "%1.2e"]
        many = collect(1:10)
        head = header[:estimatedisplay]
        if size(results.estimate, 2) == 9
            columns_width = columns_width[1:8]
            alignment = alignment[1:8]
            formatters = formatters[1:8]
            many = many[1:8]
            head = head[:, 1:8]
        end
        pretty_table([label results.estimate[:, 5:end]], head, screen_size = (-1,-1), columns_width = columns_width,
            show_row_number = true, alignment = alignment, formatters = ft_printf((formatters), many))
    end

    ########## DC error display ##########
    if settings.error
        println("\n Error Data Display\n")
        if size(results.estimate, 2) == 11
            head = header[:errordisplay]
            err = [""; results.error[1:3]; ""; ""; results.error[4:6]]
        else
            head = header[:errordisplay][1:4, :]
            err = [""; results.error[1:3]]
        end
        pretty_table([head err], screen_size = (-1,-1), tf = borderless,
            noheader = true, alignment = [:l, :l, :r], formatters = ft_printf("%1.4e", 3),
            highlighters = (hl_cell( [(1,1);(6,1)], crayon"bold"), hl_col(2, crayon"dark_gray")),
            body_hlines = [1,6], body_hlines_format = Tuple('─' for _ = 1:4))
    end

    ########## Export results ##########
    pmuv = 2; pmuc = 2; legf = 2; legc = 2; legi = 2; legv = 2; gen = 3; cost = 3
    if num.pmuNv == 0 pmuv = 0  end
    if num.pmuNc == 0 pmuc = 0 end
    if num.legacyNf == 0 legf = 0 end
    if num.legacyNc == 0 legc = 0 end
    if num.legacyNi == 0 legi = 0 end
    if num.legacyNv == 0 legv = 0 end
    if numsys.Ngen == 0 gen = 0 end
    if numsys.Ncost == 0 cost = 0 end

    group = (main = 1, flow = 1, estimate = 1, error = 1,
        pmuVoltage = pmuv, pmuCurrent = pmuc, legacyFlow = legf, legacyCurrent = legc, legacyInjection = legi, legacyVoltage = legv,
        bus = 3, branch = 3, generator = gen, generatorcost = cost, basePower = 3)

    mheader = measureheader(); pheader = psheader(system); headernew = merge(mheader, pheader, header)

    return headernew, group
end

### Nonlinear state estimation results
@inbounds function results_estimateac(system, numsys, measurements, num, settings, results, slack, algtime)
    println(string("Execution time: ", (@sprintf "%.4f" algtime * 1000), " (ms)"))
    aheader = acseheader(); pheader = psheader(system)
    header = merge(aheader, pheader)

    ########## Nonlinear main display ##########
    if settings.main
        h1 = Highlighter((data, i, j)-> (i == slack), background = :red)
        println("\n Main Data Display")
        pretty_table(results.main, header[:main],
            screen_size = (-1,-1), highlighters = h1, columns_width = [7, 16, 12, 17, 21, 17, 21],
            alignment = repeat([Symbol(:r)], outer = 7),
            formatters = ft_printf(["%1.0f", "%1.4f","%1.4f","%1.2f","%1.2f","%1.2f","%1.2f"], collect(1:7)))
        sum_data = Any["Sum" sum(results.main[:, 4:7], dims = 1)]
        pretty_table(sum_data, noheader = true, screen_size = (-1,-1),
            alignment=[:l,:r,:r,:r,:r], columns_width = [41, 17, 21, 17, 21],
            formatters = ft_printf(["%-s","%15.2f","%15.2f","%13.2f","%15.2f"], collect(1:5)))
    end

    ########## Nonlinear flow display ##########
    if settings.flow
        println("\n Flow Data Display")
        pretty_table(results.flow[:,1:10], header[:flow][:,1:10],
            screen_size = (-1,-1), columns_width = [6, 8, 8, 17, 21, 17, 21, 21, 17, 21],
            alignment=[:r,:r,:r,:r,:r,:r,:r,:r,:r,:r],
            formatters = ft_printf(["%1.0f","%1.0f","%1.0f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f","%1.2f"], collect(1:10)))
        sum_data = Any["Sum" sum(results.flow[:, 8:10], dims = 1)]
        pretty_table(sum_data, noheader = true, screen_size = (-1,-1), alignment=[:l,:r,:r,:r], columns_width = [116, 21, 17, 21],
            formatters = ft_printf(["%-s","%15.2f","%11.2f","%15.2f"], collect(1:4)))
    end

    ########## Nonlinear estimate and error results ##########
    label = Array{String}(undef, size(results.estimate, 1), 3)
    idex = 1
    for (k, i) in enumerate(results.estimate[:, 2])
        if i == 1.0
            label[k, 1] = "in-service"
        elseif i == 2.0
            label[k, 1] = "bad-measurement"
        elseif i == 3.0
            label[k, 1] = "pseudo-measurement"
        end
        if results.estimate[k, 3] == 1.0
            label[k, 2] = "Legacy"
        else
            label[k, 2] = "PMU"
        end
        j = convert(Int, results.estimate[k, 5])
        if results.estimate[k, 4] == 1.0
            label[k, 3] = "P$(trunc(Int, measurements.legacyFlow[j, 2])),$(trunc(Int, measurements.legacyFlow[j, 3])) [MW]"
        elseif results.estimate[k, 4] == 2.0
            label[k, 3] = "Q$(trunc(Int, measurements.legacyFlow[j, 2])),$(trunc(Int, measurements.legacyFlow[j, 3])) [MVAr]"
        elseif results.estimate[k, 4] == 3.0
            label[k, 3] = "P$(trunc(Int, measurements.legacyInjection[j, 1])) [MW]"
        elseif results.estimate[k, 4] == 4.0
            label[k, 3] = "Q$(trunc(Int, measurements.legacyInjection[j, 1])) [MVAr]"
        elseif results.estimate[k, 4] == 5.0 && results.estimate[k, 3] == 1.0
            label[k, 3] = "I$(trunc(Int, measurements.legacyCurrent[j, 2])),$(trunc(Int, measurements.legacyCurrent[j, 3])) [p.u.]"
        elseif results.estimate[k, 4] == 5.0 && results.estimate[k, 3] == 2.0
            label[k, 3] = "I$(trunc(Int, measurements.pmuCurrent[j, 2])),$(trunc(Int, measurements.pmuCurrent[j, 3])) [p.u.]"
        elseif results.estimate[k, 4] == 6.0
            label[k, 3] = "D$(trunc(Int, measurements.pmuCurrent[j, 2])),$(trunc(Int, measurements.pmuCurrent[j, 3])) [deg]"
        elseif results.estimate[k, 4] == 7.0 && results.estimate[k, 3] == 1.0
            label[k, 3] = "V$(trunc(Int, measurements.legacyVoltage[j, 1])) [p.u.]"
        elseif results.estimate[k, 4] == 7.0 && results.estimate[k, 3] == 2.0
            label[k, 3] = "V$(trunc(Int, measurements.pmuVoltage[j, 1])) [p.u.]"
        elseif results.estimate[k, 4] == 8.0
            label[k, 3] = "T$(trunc(Int, measurements.pmuVoltage[j, 1])) [deg]"
        end
    end

    ########## Nonlinear Estimate display ##########
    if settings.estimate
        println("\n Estimate Data Display")
        columns_width = [18, 12, 15, 12, 12, 12, 12, 19, 12, 19]
        alignment = [:l, :l, :l, :r, :r, :r, :r, :r, :r, :r]
        formatters = ["%s", "%s", "%s", "%1.0f", "%1.2f", "%1.2e", "%1.2f", "%1.2e", "%1.2f", "%1.2e"]
        many = collect(1:10)
        head = header[:estimatedisplay]
        if size(results.estimate, 2) == 9
            columns_width = columns_width[1:8]
            alignment = alignment[1:8]
            formatters = formatters[1:8]
            many = many[1:8]
            head = head[:, 1:8]
        end
        pretty_table([label results.estimate[:, 5:end]], head, screen_size = (-1,-1), columns_width = columns_width,
            show_row_number = true, alignment = alignment, formatters = ft_printf((formatters), many))
    end

    ########## Nonlinear error display ##########
    if settings.error
        println("\n Error Data Display\n")
        if size(results.estimate, 2) == 11
            head = header[:errordisplay]
            err = [""; results.error[1:3]; ""; ""; results.error[4:6]]
        else
            head = header[:errordisplay][1:4, :]
            err = [""; results.error[1:3]]
        end
        pretty_table([head err], screen_size = (-1,-1), tf = borderless,
            noheader = true, alignment = [:l, :l, :r], formatters = ft_printf("%1.4e", 3),
            highlighters = (hl_cell( [(1,1);(6,1)], crayon"bold"), hl_col(2, crayon"dark_gray")),
            body_hlines = [1,6], body_hlines_format = Tuple('─' for _ = 1:4))
    end

    ########## Export results ##########
    pmuv = 2; pmuc = 2; legf = 2; legc = 2; legi = 2; legv = 2; gen = 3; cost = 3
    if num.pmuNv == 0 pmuv = 0  end
    if num.pmuNc == 0 pmuc = 0 end
    if num.legacyNf == 0 legf = 0 end
    if num.legacyNc == 0 legc = 0 end
    if num.legacyNi == 0 legi = 0 end
    if num.legacyNv == 0 legv = 0 end
    if numsys.Ngen == 0 gen = 0 end
    if numsys.Ncost == 0 cost = 0 end

    group = (main = 1, flow = 1, estimate = 1, error = 1,
        pmuVoltage = pmuv, pmuCurrent = pmuc, legacyFlow = legf, legacyCurrent = legc, legacyInjection = legi, legacyVoltage = legv,
        bus = 3, branch = 3, generator = gen, generatorcost = cost, basePower = 3)

    mheader = measureheader(); pheader = psheader(system); headernew = merge(mheader, pheader, header)

    return headernew, group
end

max_stars_repo_name: mcosovic/JuliaGrid

max_issues_repo_name: mcosovic/JuliaGrid

max_forks_repo_name: mcosovic/JuliaGrid


text:
using GeoPhyInv

medium_true=Medium(:pizza)

pa=SeisInvExpt(Fdtd(), LS(), :pizza);

update!(pa,solver=:ipopt);


text:
using AlphaStructures
using Test

#include("deWall.jl")
include("delaunay.jl")
include("alpha_complex.jl")
include("geometry.jl")


text:
# test memory allocation

using MicrochipRTDM
using FTD2XX

projectdirectory = "c:/Users/Chris/MPLABXProjects/lbcmcp/PWM_RTDM.x"
mapdict = microchip_parsemap(projectdirectory,"production")
uartconfig1 = UARTConfiguration(921600,8,1,"n",readtimeout = 1000,writetimeout = 1000)
io = open(FT_DeviceIndex(0),uartconfig1)
ft_setlatencytimer(io.ft_handle,2); #Should speed things up a little
rtdminterface = RTDMInterface(mapdict,io)

f() = for i in 1:100
  isrtdmok(rtdminterface)
end
@time f()

Profile.clear_malloc_data()
f()

close(io)
quit()


text:
include("brush.jl")

const loadedTools = joinpath.(abs"tools", readdir(abs"tools"))
loadModule.(loadedTools)
currentTool = nothing

function getToolName(tool::String)
    if hasModuleField(tool, "displayName")
        return getModuleField(tool, "displayName")

    elseif haskey(loadedModules, tool)
        return repr(loadedModules[tool])
    end
end

function getToolGroup(tool::String)
    if hasModuleField(tool, "group")
        return getModuleField(tool, "group")

    elseif haskey(loadedModules, tool)
        return "Unknown"
    end
end

toolDisplayNames = Dict{String, String}()
function updateToolDisplayNames!(tools::Array{String, 1})
    global toolDisplayNames = Dict{String, String}(
        getToolName(tool) => tool for tool in loadedTools if haskey(loadedModules, tool)
    )
end

subtoolList = generateTreeView("Mode", Tuple{String}[], sortable=false)
connectChanged(subtoolList) do list::ListContainer, selected::String
    eventToModule(currentTool, "subToolSelected", list, selected)
end

layersList = generateTreeView(("Layer",), Tuple{String}[], sortable=false)
connectChanged(layersList) do list::ListContainer, selected::String
    eventToModule(currentTool, "layerSelected", list, selected)
    eventToModule(currentTool, "layerSelected", list, selected)
    eventToModule(currentTool, "layerSelected", list, materialList, selected)
    eventToModule(currentTool, "layerSelected", list, materialList, selected)

    updateMaterialFilter!(selected)
end

materialList = generateTreeView("Material", Tuple{String}[], sortable=false)
connectChanged(materialList) do list::ListContainer, selected::String
    eventToModule(currentTool, "materialSelected", list, selected)
end

function updateMaterialFilter!(layer::String)
    if get(config, "keep_search_text_per_layer", true)
        # Force event to trigger by first changing the text to blank
        searchText = get(persistence, "material_search_$layer", "")
        Gtk.GLib.@sigatom GAccessor.text(materialFilterEntry, "")
        Gtk.GLib.@sigatom GAccessor.text(materialFilterEntry, searchText)

    else
        Gtk.GLib.@sigatom GAccessor.text(materialFilterEntry, "")
    end
end

function changeTool!(tool::String)
    if loadedState.map !== nothing && loadedState.room !== nothing
        dr = getDrawableRoom(loadedState.map, loadedState.room)

        if currentTool !== nothing
            eventToModule(currentTool, "cleanup")
        end

        if tool in loadedTools
            global currentTool = tool

        elseif haskey(toolDisplayNames, tool)
            global currentTool = toolDisplayNames[tool]
        end

        # Clear the subtool and material list
        # Tools need to set up this themselves
        updateTreeView!(subtoolList, [])
        updateTreeView!(materialList, [])

        eventToModule(currentTool, "layersChanged", dr.layers)
        eventToModule(currentTool, "toolSelected")
        eventToModule(currentTool, "toolSelected", subtoolList, layersList, materialList)
    end
end

function getSortedToolNames(tools::Array{String, 1})
    res = Tuple{String, String}[]
    for tool in tools
        group, name = getToolGroup(tool), getToolName(tool)

        if group !== nothing && name !== nothing
            push!(res, (group, name))
        end
    end

    sort!(res)

    return String[r[2] for r in res]
end

toolList = generateTreeView("Tool", Tuple{String}[], sortable=false)
connectChanged(toolList) do list::ListContainer, selected::String
    debug.log("Selected $selected", "TOOLS_SELECTED")
    changeTool!(selected)
end

function updateToolList!(list::ListContainer)
    updateTreeView!(list, getSortedToolNames(loadedTools), 1)
end

function selectionRectangle(x1::Number, y1::Number, x2::Number, y2::Number)
    drawX = min(x1, x2)
    drawW = abs(x1 - x2) + 1

    drawY = min(y1, y2)
    drawH = abs(y1 - y2) + 1

    return Rectangle(drawX, drawY, drawW, drawH)
end

function updateSelectionByCoords!(map::Map, ax::Number, ay::Number)
    room = Maple.getRoomByCoords(map, ax, ay)

    if room != false && room.name != loadedState.roomName
        selectRow!(roomList, row -> row[1] == room.name)
        handleRoomChanged(Ahorn.loadedState.map, Ahorn.loadedState.room)

        return true
    end

    return false
end

function notifyMaterialsFiltered(text::String)
    eventToModule(currentTool, "materialFiltered", materialList)
    eventToModule(currentTool, "materialFiltered", materialList, text)
end

function selectMaterialList!(m::String)
    selectRow!(materialList, row -> row[1] == m)
end

function setMaterialList!(materials::Array{String, 1}, selector::listViewSelectUnion=nothing)
    if selector !== nothing
        updateTreeView!(materialList, materials, selector)

    else
        updateTreeView!(materialList, materials)
    end
end

function selectLayer!(layers::Array{Layer, 1}, layer::String, default::String="")
    newLayer = getLayerByName(layers, layer, default)
    selectRow!(layersList, row -> row[1] == newLayer.name)

    return newLayer
end

selectLayer!(layers::Array{Layer, 1}, layer::Union{Layer, Nothing}, default::String="") = selectLayer!(layers, layerName(layer), default)

function updateLayerList!(names::Array{String, 1}, selector::listViewSelectUnion=getSelected(layersList))
    if selector !== nothing
        updateTreeView!(layersList, names, selector)

    else
        updateTreeView!(layersList, names)
    end
end

function handleSelectionMotion(start::eventMouse, startCamera::Camera, current::eventMouse)
    room = loadedState.room

    mx1, my1 = getMapCoordinates(startCamera, start.x, start.y)
    mx2, my2 = getMapCoordinates(camera, current.x, current.y)

    max1, may1 = getMapCoordinatesAbs(startCamera, start.x, start.y)
    max2, may2 = getMapCoordinatesAbs(camera, current.x, current.y)

    x1, y1 = mapToRoomCoordinates(mx1, my1, room)
    x2, y2 = mapToRoomCoordinates(mx2, my2, room)

    ax1, ay1 = mapToRoomCoordinatesAbs(max1, may1, room)
    ax2, ay2 = mapToRoomCoordinatesAbs(max2, may2, room)

    # Grid Based coordinates
    eventToModule(currentTool, "selectionMotion", selectionRectangle(x1, y1, x2, y2))
    eventToModule(currentTool, "selectionMotion", x1, y1, x2, y2)

    # Absolute coordinates
    eventToModule(currentTool, "selectionMotionAbs", selectionRectangle(ax1, ay1, ax2, ay2))
    eventToModule(currentTool, "selectionMotionAbs", ax1, ay1, ax2, ay2)
end

function handleSelectionFinish(start::eventMouse, startCamera::Camera, current::eventMouse, currentCamera::Camera)
    room = loadedState.room

    mx1, my1 = getMapCoordinates(startCamera, start.x, start.y)
    mx2, my2 = getMapCoordinates(currentCamera, current.x, current.y)

    max1, may1 = getMapCoordinatesAbs(startCamera, start.x, start.y)
    max2, may2 = getMapCoordinatesAbs(currentCamera, current.x, current.y)

    x1, y1 = mapToRoomCoordinates(mx1, my1, room)
    x2, y2 = mapToRoomCoordinates(mx2, my2, room)

    ax1, ay1 = mapToRoomCoordinatesAbs(max1, may1, room)
    ax2, ay2 = mapToRoomCoordinatesAbs(max2, may2, room)

    # Grid Based coordinates
    eventToModule(currentTool, "selectionFinish", selectionRectangle(x1, y1, x2, y2))
    eventToModule(currentTool, "selectionFinish", x1, y1, x2, y2)

    # Absolute coordinates
    eventToModule(currentTool, "selectionFinishAbs", selectionRectangle(ax1, ay1, ax2, ay2))
    eventToModule(currentTool, "selectionFinishAbs", ax1, ay1, ax2, ay2)
end

function getMouseEventName(event::eventMouse, downEvent::eventMouse)
    prefix = get(mouseTypePrefix, downEvent.event_type, "")
    handle = mouseHandlers[event.button]

    if !isempty(prefix)
        return prefix * uppercasefirst(handle)

    else
        return handle
    end
end

function handleClicks(event::eventMouse, camera::Camera, downEvent::eventMouse)
    if haskey(mouseHandlers, event.button)
        handle = getMouseEventName(event, downEvent)
        room = loadedState.room

        mx, my = getMapCoordinates(camera, event.x, event.y)
        max, may = getMapCoordinatesAbs(camera, event.x, event.y)

        x, y = mapToRoomCoordinates(mx, my, room)
        ax, ay = mapToRoomCoordinatesAbs(max, may, room)

        lock!(camera)
        if !updateSelectionByCoords!(loadedState.map, max, may)
            # Teleport to cursor
            if EverestRcon.loaded && event.button == 0x1 && modifierControl() && modifierAlt()
                url = get(config, "everest_rcon", "http://localhost:32270")
                room = loadedState.roomName
                EverestRcon.reload(url, room)
                EverestRcon.teleportToRoom(url, room, ax, ay)

            else
                eventToModule(currentTool, handle)
                eventToModule(currentTool, handle, event, camera)
                eventToModule(currentTool, handle, x, y)
                eventToModule(currentTool, handle * "Abs", ax, ay)
            end
        end
        unlock!(camera)
    end
end

function handleMotion(event::eventMouse, camera::Camera)
    room = loadedState.room

    mx, my = getMapCoordinates(camera, event.x, event.y)
    max, may = getMapCoordinatesAbs(camera, event.x, event.y)

    x, y = mapToRoomCoordinates(mx, my, room)
    ax, ay = mapToRoomCoordinatesAbs(max, may, room)

    eventToModule(currentTool, "mouseMotion", event, camera)
    eventToModule(currentTool, "mouseMotion", x, y)
    eventToModule(currentTool, "mouseMotionAbs", event, camera)
    eventToModule(currentTool, "mouseMotionAbs", ax, ay)
end

function toolChangeCallback(index)
    sortedToolNames = getSortedToolNames(loadedTools)
    if length(sortedToolNames) >= index
        changeTool!(sortedToolNames[index])
        selectRow!(toolList, index)

        return true
    end

    return false
end

function roomMoveCallback(direction::String)
    keyval = getfield(Gtk.GdkKeySyms, Symbol(direction))
    History.addSnapshot!(History.RoomSnapshot("Room Movement", loadedState.room))

    ox, oy = moveDirections[keyval] .* 8
    loadedState.room.position = loadedState.room.position .+ (ox, oy)
    updateTreeView!(roomList, getTreeData(loadedState.map), row -> row[1] == loadedState.room.name, updateByReplacement=true)

    draw(canvas)

    return true
end

function deleteRoomCallback(widget=nothing)
    index = findfirst(isequal(loadedState.room), loadedState.map.rooms)

    if index !== nothing && ask_dialog("Are you sure you want to delete this room? '$(loadedState.room.name)'", window)
        History.addSnapshot!(History.MapSnapshot("Room Deletion", loadedState.map))

        deleteat!(loadedState.map.rooms, index)
        updateTreeView!(roomList, getTreeData(loadedState.map))
        draw(canvas)

        return true
    end

    return false
end

debugHotkeys = Tuple{Hotkey, String}[
    (Hotkey("F1", debug.reloadTools!), "Reloading tools"),
    (Hotkey("F2", () -> debug.reloadEntities!() && debug.reloadTriggers!()), "Reloading entities and triggers"),
    (Hotkey("F3", debug.clearMapDrawingCache!), "Deleting room render caches"),
]

# 10 is ctrl + 0
toolChangeHotkeys = Hotkey[
    Hotkey("ctrl + $(i % 10)", () -> toolChangeCallback(i)) for i in 1:10
]

roomModificationHotkeys = vcat(
    Hotkey[Hotkey("alt + $key", () -> roomMoveCallback(key)) for key in String["Left", "Up", "Right", "Down"]],
    Hotkey[Hotkey("alt + Delete", deleteRoomCallback)]
)

function handleDebugKeys(event::eventKey)
    if get(debug.config, "ENABLE_HOTSWAP_HOTKEYS", false)
        for (hotkey, desc) in debugHotkeys
            if active(hotkey, event)
                println("! $desc")

                callback(hotkey)

                return true
            end
        end
    end

    return false
end

function handleHotkeyToolChange(event::eventKey)
    return callbackFirstActive(toolChangeHotkeys, event)
end

function handleRoomModifications(event::eventKey)
    if loadedState.room !== nothing && loadedState.map !== nothing
        return callbackFirstActive(roomModificationHotkeys, event)
    end

    return false
end

function handleKeyPressed(event::eventKey, sendToToolModules::Bool=true)
    # Handle in this order, until one of them consumes the event
    return handleDebugKeys(event) ||
        handleRoomModifications(event) ||
        handleHotkeyToolChange(event) ||
        sendToToolModules && eventToModule(currentTool, "keyboard", event)
end

function handleKeyReleased(event::eventKey)

end

function handleRoomChanged(map::Map, room::Union{Nothing, Room}, previousRoom::Union{Nothing, Room}=nothing)
    # Clean up tools layer before notifying about room change
    eventToModule(currentTool, "cleanup")

    if isa(room, Room)
        dr = getDrawableRoom(map, room)

        eventToModule(currentTool, "roomChanged", room)
        eventToModule(currentTool, "roomChanged", map, room)
        eventToModule(currentTool, "layersChanged", dr.layers)
    end

    if isa(previousRoom, Room)
        dr = getDrawableRoom(map, previousRoom)
        layer = getLayerByName(dr.layers, "tools")

        clearSurface(layer.surface)
        layer.redraw = true

        redrawLayer!(dr.rendering)
    end
end


text:
# Copyright 2019 Tobias Frilling
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

module Umatrix

macro todo()
    :(error("not implemented"))
end

using DataIO
using CalculatedABC
using Distances
using Distributions
using JuliennedArrays
using Plots
using Random

const EsomWeights{T} = AbstractArray{T,3}

export esomTrain, esomTrainOnline, projection, bestMatch
export umatrix, pmatrix, ustarmatrix

include("settings.jl")

include("coolDowns.jl")
include("esom.jl")
include("initMethod.jl")
include("matrices.jl")
include("neighbourhood.jl")
include("plotting.jl")
include("utils.jl")

end # module


text:
# ---
# title: 110. Balanced Binary Tree
# id: problem110
# author: Tian Jun
# date: 2020-10-31
# difficulty: Easy
# categories: Tree, Depth-first Search
# link: <https://leetcode.com/problems/balanced-binary-tree/description/>
# hidden: true
# ---
#
# Given a binary tree, determine if it is height-balanced.
#
# For this problem, a height-balanced binary tree is defined as:
#
# > a binary tree in which the left and right subtrees of _every_ node differ in
# > height by no more than 1.
#
#
#
# **Example 1:**
#
# ![](https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg)
#
#
#
#     Input: root = [3,9,20,null,null,15,7]
#     Output: true
#
#
# **Example 2:**
#
# ![](https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg)
#
#
#
#     Input: root = [1,2,2,3,3,null,null,4,4]
#     Output: false
#
#
# **Example 3:**
#
#
#
#     Input: root = []
#     Output: true
#
#
#
#
# **Constraints:**
#
#   * The number of nodes in the tree is in the range `[0, 5000]`.
#   * `-104 <= Node.val <= 104`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
using .Links
using .ProductDistributions
BayesianTools.Links.link(p::ProductDistribution, x::Vector) = map(BayesianTools.Links.link, p, x)
BayesianTools.Links.invlink(p::ProductDistribution, x::Vector) = map(BayesianTools.Links.invlink, p, x)
BayesianTools.Links.logjacobian(p::ProductDistribution, x::Vector) = map(BayesianTools.Links.logjacobian, p, x)

max_stars_repo_name: gragusa/ProductDistributions

max_issues_repo_name: gragusa/ProductDistributions

max_forks_repo_name: gragusa/ProductDistributions


text:
# example for loading robot description to database

using Caesar, GraffSDK

rovconf = Dict()
rovconf["robot"] = "hovering-rov"
rovconf["bTc"] = "[0.0;0.0;0.0; 1.0; 0.0; 0.0; 0.0]"
rovconf["bTc_format"] = "xyzqwqxqyqz"
rovconf["pointcloud_description_name"] = "BSONpointcloud"
rovconf["pointcloud_color_description_name"] = "BSONcolors"

# Actually modify the databases
updateRobotConfig(graffConfig, robotId, rovconf)

## Obsolete usege below

#
# addrdict = nothing
# include(joinpath(dirname(@__FILE__),"..","database","blandauthremote.jl"))
# # prepare the factor graph with just one node
# # (will prompt on stdin for db credentials)
# cloudGraph, addrdict = standardcloudgraphsetup(addrdict=addrdict)
#
#
#
# # Turtlebot robot
# turtlebot = Dict()
# turtlebot["robot"] = "mrg-turtlebot"
# turtlebot["CAMK"] = [ 570.34222412 0.0 319.5;
#                       0.0 570.34222412 239.5;
#                       0.0 0.0 1.0]
# #
# turtlebot["imshape"]=[480,640]
# turtlebot["bTc"] = [0.0;0.0;0.6; 0.5; -0.5; 0.5; -0.5]
# turtlebot["bTc_format"] = "xyzqwqxqyqz"
#
# # robotdata = json(turtlebot).data
# # resp = JSON.parse(String(take!(IOBuffer(robotdata))))
# # tryunpackalltypes!(resp)
# # resp
#
# # Actually modify the database
# insertrobotdatafirstpose!(cloudGraph, "SESSTURT21", turtlebot)
# frd = fetchrobotdatafirstpose(cloudGraph, "SESSTURT21")
#
#
#
#
# # A different robot
#
# hauv = Dict()
# hauv["robot"] = "hauv"
# hauv["bTc"] = [0.0;0.0;0.0; 1.0; 0.0; 0.0; 0.0]
# hauv["bTc_format"] = "xyzqwqxqyqz"
# hauv["depth_pointcloud_description"] = "BSONpointcloud"
# hauv["depth_color_description"] = ["BSONcolor"]
#
# # robotdata = json(hauv).data
# hauv
#
#
# # Actually modify the databases
# insertrobotdatafirstpose!(cloudGraph, "SESSHAUVDEV", hauv)
# frd = fetchrobotdatafirstpose(cloudGraph, "SESSHAUVDEV")
#
#

#


text:
function clean(phone_number)

end


text:
using ITensors
using ChainRulesCore: ZeroTangent

# Write a custom `rrule` for this.
function inner_circuit(ϕ::ITensor, U::Vector{ITensor}, ψ::ITensor)
  Uψ = ψ
  for u in U
    s = commoninds(u, Uψ)
    s′ = s'
    Uψ = replaceinds(u * Uψ, s′ => s)
  end
  return (ϕ * Uψ)[]
end

# Write a custom `rrule` for this.
function rayleigh_quotient(H::ITensor, Uψ::Tuple{Vector{ITensor},ITensor})
  U, ψ = Uψ
  Uψ = ψ
  for u in U
    s = commoninds(u, Uψ)
    s′ = s'
    Uψ = replaceinds(u * Uψ, s′ => s)
  end
  return (dag(Uψ)' * H * Uψ)[]
end

name(g::Tuple{String,Vararg}) = g[1]
sites(g::Tuple{<:Any,Tuple{Vararg{Int}},Vararg}) = g[2]
params(g::Tuple{<:Any,<:Any,<:NamedTuple}) = g[3]
params(g::Tuple{<:Any,<:Any}) = (;)

function gate(g::Tuple, s::Vector{<:Index})
  return gate(name(g), params(g), s[collect(sites(g))])
end

function gate(gn::String, params::NamedTuple, s::Vector{<:Index})
  return gate(gate(gn, params), s)
end

function gate(gn, params::NamedTuple)
  return gate(gn; params...)
end

function gate(gn::String, params::NamedTuple)
  return gate(Val{Symbol(gn)}(), params)
end

function gate(g::Matrix, s::Vector{<:Index})
  s = reverse(s)
  return itensor(g, s'..., dag(s)...)
end

function buildcircuit(gates::Vector, s::Vector{<:Index})
  return [gate(g, s) for g in gates]
end

# Gate definitions
function gate(gn::Val; params...)
  return error("Gate $gn not defined")
end

# XXX: For some reason Zygote needs these definitions?
Base.reverse(z::ZeroTangent) = z
Base.adjoint(::Tuple{Nothing}) = nothing
Base.adjoint(::Tuple{Nothing,Nothing}) = nothing


text:
using AlgebraOfGraphics
const AOG = AlgebraOfGraphics

function mcmc_recover_hist(posterior, true_parameters; kwargs...)
end

function mcmc_hist(x; kwargs...)
end

# https://github.com/TuringLang/MCMCChains.jl/issues/306#issuecomment-860698289
function mcmc_trace(chain; kwargs...)
    # exclude additional information such as log probability
    params = names(chain, :parameters)
    chain_mapping = mapping(params .=> "sample value") *
        mapping(; color=:chain => nonnumeric, row=dims(1) => renamer(params))
    plt1 = data(chain) * mapping(:iteration) * chain_mapping * visual(Lines)
    plt2 = data(chain) * chain_mapping * AOG.density()
    fig = Figure(; resolution=(800, 600))
    draw!(fig[1, 1], plt1)
    draw!(fig[1, 2], plt2; axis=(ylabel="density",))

    return fig
end

function mcmc_scatter(x; kwargs...)
end

function mcmc_parcoord(x; kwargs...)
    series!(nondiverging, solid_color=(:grey, 0.3))
    series!(diverging, solid_color=(:blue, 0.3))
end

function mcmc_areas(x; kwargs...)
end

max_stars_repo_name: kskyten/BayesPlot

max_issues_repo_name: kskyten/BayesPlot

max_forks_repo_name: kskyten/BayesPlot


text:
# MIT License
#
# Copyright (c) 2020 Joshua E Gentry

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
using Test

# -------------------------------------------------------------------------------------------------
# Test tess_image()
@testset "tess_image" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @test tess_init(inst, "eng", datadir) == true
    @test_nowarn tess_image(inst, pix)

    local err  = "Instance has been freed."
    tess_delete!(inst)
    @test_logs (:error, err) tess_image(inst, pix)

    local err  = "Pix object has been freed."
    local inst = TessInst("eng", datadir)
    pix_delete!(pix)
    @test_logs (:error, err) tess_image(inst, pix)
end

# -------------------------------------------------------------------------------------------------
# Test tess_resolution()
@testset "tess_resolution" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @test tess_init(inst, "eng", datadir) == true
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)

    local err  = "Instance has been freed."
    tess_delete!(inst)
    @test_logs (:error, err) tess_resolution(inst, 72)
end


text:
function _flush()
    Base.flush(stdout)
    Base.flush(stderr)
    Base.Libc.flush_cstdio()
end

max_stars_repo_name: josePereiro/GitWorkers

max_issues_repo_name: josePereiro/GitWorkers

max_forks_repo_name: josePereiro/GitWorkers