text:
export SquaredUpSystem

"""
    SquaredUpSystem(F, A, degrees) <: AbstractSystem

Square up a system `F(x)`. Assume `m, n = size(F)`. Then this computes with with the system
``(f_1,...,f_n) + A(f_m+1,...,f_n)``  where ``A`` is a random ``n × (m - n)`` matrix.
"""
struct SquaredUpSystem{S<:AbstractSystem,T} <: AbstractSystem
    F::S
    A::Matrix{T}
    degrees::Vector{Int}
end

function SquaredUpSystem(F::AbstractSystem, A::Matrix)
    SquaredUpSystem(F, A, zeros(Int, sum(size(A))))
end

struct SquaredUpSystemCache{SC<:AbstractSystemCache,T} <: AbstractSystemCache
    u::Vector{T}
    U::Matrix{T}
    cache::SC
    degree_diffs::Matrix{Int}
end

function cache(F::SquaredUpSystem, x)
    c = cache(F.F, x)
    u = Vector(evaluate(F.F, x, c))
    U = similar(u, size(F.F))
    n = size(F.A, 1)
    degree_diffs = [F.degrees[i] - F.degrees[n+j] for i = 1:n, j = 1:size(F.A, 2)]
    SquaredUpSystemCache(u, U, c, degree_diffs)
end

Base.size(F::SquaredUpSystem) = (size(F.A, 1), size(F.F)[2])

function evaluate!(u, F::SquaredUpSystem, x, c::SquaredUpSystemCache)
    evaluate!(c.u, F.F, x, c.cache)
    n, m = size(F.A, 1), size(F.F)[1]
    for i = 1:n
        u[i] = c.u[i]
        for j = 1:(m-n)
            u[i] += F.A[i, j] * c.u[n+j]
        end
    end
    u
end

function evaluate!(u, F::SquaredUpSystem, x::PVector{<:Number,1}, c::SquaredUpSystemCache)
    evaluate!(c.u, F.F, x, c.cache)
    n, m = size(F.A, 1), size(F.F)[1]
    for i = 1:n
        u[i] = c.u[i]
    end
    for j = 1:(m-n), i = 1:n
        u[i] += F.A[i, j] * c.u[n+j] * x[end]^c.degree_diffs[i, j]
    end
    u
end

function jacobian!(U, F::SquaredUpSystem, x, c::SquaredUpSystemCache)
    jacobian!(c.U, F.F, x, c.cache)
    n, m = size(F.A, 1), size(F.F)[1]
    for j = 1:n, i = 1:n
        U[i, j] = c.U[i, j]
        # + A * F̂
        for k = 1:(m-n)
            U[i, j] += F.A[i, k] * c.U[n+k, j]
        end
    end
    U
end

function jacobian!(U, F::SquaredUpSystem, x::PVector{<:Number,1}, c::SquaredUpSystemCache)
    evaluate_and_jacobian!(c.u, c.U, F.F, x, c.cache)
    n, m = size(F.A, 1), size(F.F)[1]
    for j = 1:n+1, i = 1:n
        U[i, j] = c.U[i, j]
        # + A * F̂
        for k = 1:(m-n)
            U[i, j] += F.A[i, k] * c.U[n+k, j] * x[end]^c.degree_diffs[i, k]
        end
    end

    # we have to take care of the product rule in the derivative wrt x[n+1]
    for i = 1:n, k = 1:(m-n)
        if c.degree_diffs[i, k] == 1
            U[i, n+1] += F.A[i, k] * c.u[n+k]
        elseif c.degree_diffs[i, k] > 1
            U[i, n+1] += c.degree_diffs[i, k] *
                F.A[i, k] *
                c.u[n+k] *
                x[n+1]^(c.degree_diffs[i, k] - 1)
        end
    end
    U
end

function evaluate_and_jacobian!(u, U, F::SquaredUpSystem, x, c::SquaredUpSystemCache)
    evaluate_and_jacobian!(c.u, c.U, F.F, x, c.cache)
    n, m = size(F.A, 1), size(F.F)[1]

    for i = 1:n
        u[i] = c.u[i]
        for j = 1:(m-n)
            u[i] += F.A[i, j] * c.u[n+j]
        end
    end
    for j = 1:n, i = 1:n
        U[i, j] = c.U[i, j]
        # + A * F̂
        for k = 1:(m-n)
            U[i, j] += F.A[i, k] * c.U[n+k, j]
        end
    end
    nothing
end

function evaluate_and_jacobian!(
    u,
    U,
    F::SquaredUpSystem,
    x::PVector{<:Number,1},
    c::SquaredUpSystemCache,
)
    evaluate_and_jacobian!(c.u, c.U, F.F, x, c.cache)
    n, m = size(F.A, 1), size(F.F)[1]

    for i = 1:n
        u[i] = c.u[i]
    end
    for j = 1:(m-n), i = 1:n
        u[i] += F.A[i, j] * c.u[n+j] * x[end]^c.degree_diffs[i, j]
    end

    for j = 1:n+1, i = 1:n
        U[i, j] = c.U[i, j]
        # + A * F̂
        for k = 1:(m-n)
            U[i, j] += F.A[i, k] * c.U[n+k, j] * x[end]^c.degree_diffs[i, k]
        end
    end

    # we have to take care of the product rule in the derivative wrt x[n+1]
    for i = 1:n, k = 1:(m-n)
        if c.degree_diffs[i, k] == 1
            U[i, n+1] += F.A[i, k] * c.u[n+k]
        elseif c.degree_diffs[i, k] > 1
            U[i, n+1] += c.degree_diffs[i, k] *
                F.A[i, k] *
                c.u[n+k] *
                x[n+1]^(c.degree_diffs[i, k] - 1)
        end
    end

    nothing
end

function evaluate(F::SquaredUpSystem, x, c::SquaredUpSystemCache)
    u = Vector{_return_type(F, c)}(undef, size(F.A, 1))
    evaluate!(u, F, x, c)
end
function jacobian(F::SquaredUpSystem, x, c::SquaredUpSystemCache)
    U = Matrix{_return_type(F, c)}(undef, size(F.A, 1), size(F.F)[2])
    jacobian!(U, F, x, c)
end

function evaluate_and_jacobian(F::SquaredUpSystem, x, c::SquaredUpSystemCache)
    T = _return_type(F, c)
    u = Vector{T}(undef, size(F.A, 1))
    U = Matrix{T}(undef, size(F.A, 1), size(F.F)[2])
    evaluate_and_jacobian!(u, U, F, x, c)
    u, U
end

_return_type(F::SquaredUpSystem, c::SquaredUpSystemCache) = typeof(F.A[1, 1] * c.u[1])


text:
# add Mux    # pkg mode

using Interact, Mux

ddn = dropdown(["Getting groceries",
                "Visiting my therapist",
                "Getting a haircut",
                "Paying the energy bill",
                "Blog about workspace management"])

ui = dom"div"(ddn)
WebIO.webio_serve(page("/", req -> ui), 8080) # serve on port 8080

ext: jl


text:
#
# The query input/output types.
#

include("type/domain.jl")
include("type/output.jl")
include("type/input.jl")
include("type/bound.jl")

max_stars_repo_name: rbt-lang/rbt-proto

max_issues_repo_name: rbt-lang/rbt-proto

max_forks_repo_name: rbt-lang/rbt-proto


text:
# Julia wrapper for header: /Volumes/BOOTCAMP/programs/compa_libs/iup/include/iupweb.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function IupWebBrowserOpen()
  ccall( (:IupWebBrowserOpen, iup), Cint, (), )
end

function IupWebBrowser()
  ccall( (:IupWebBrowser, iup), Ptr{Cint}, (), )
end


text:
# Autogenerated wrapper script for Word2Vec_jll for x86_64-apple-darwin
export word2phrase, word2vec

JLLWrappers.@generate_wrapper_header("Word2Vec")
JLLWrappers.@declare_executable_product(word2phrase)
JLLWrappers.@declare_executable_product(word2vec)
function __init__()
    JLLWrappers.@generate_init_header()
    JLLWrappers.@init_executable_product(
        word2phrase,
        "bin/word2phrase",
    )

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

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
using DelimitedFiles
using Random

Random.seed!(42)

n_types = 2
n_draws = 30000

initial_locations = rand(n_types, n_draws)

writedlm("out/data/initial_locations.csv", initial_locations, ",")

max_stars_repo_name: roecla/econ-project-templates

max_issues_repo_name: roecla/econ-project-templates

max_forks_repo_name: roecla/econ-project-templates


text:
#include("square.jl")
include("dparse.jl")
include("validate.jl") #for pre-existing functions types
include("board.jl")

#==== TO DO LIST ===#
#1. unit functions
#2. edge cases
#3. review each unit functions see if the function parameters matches and if the logic makes sense

import validateMod
using ST #square.jl module
using SQLite

board = ST.loadBoard()
database = ARGS[1] #path/to/databasefile {string}
db = SQLite.DB(database) #opens database gamefile

#returns True if move is valid in Tenjiku Shogi
function tenjikuMoveValidate(unit, moveType, team, sourcex, sourcey, targetx, targety, targetx2, targety2, targetx2, targetx3)

  #edge 1: no dropping
  if (moveType == "drop")
    return false
  end

  #case 1
  if (unit == "jeweledgeneral")
    return validateMod.kingValidate(team, sourcex, sourcey, targetx, targety)

  #case 2
  elseif (unit == "prince")
    return validateMod.kingValidate(team, sourcex, sourcey, targetx, targety)

  #case 3
  elseif (unit == "kinggeneral")
    return validateMod.kingValidate(team, sourcex, sourcey, targetx, targety)

  #case 4
  elseif (unit == "drunkelephant")
    return validateMod.drunkElephantValidate(team, sourcex, sourcey, targetx, targety)

      #case 5
  elseif (unit == "vicegeneral")
    return viceGeneralValidate(team, sourcex, sourcey, targetx, targety, targetx2, targety2, targetx3, targety3)

      #case 6
  elseif (unit == "greatgeneral")
    return greatGeneralValidate(team, sourcex, sourcey, targetx, targety)

      #case 7
  elseif (unit == "bishopgeneral")
    return bishopGeneralValidate(team, sourcex, sourcey, targetx, targety)

      #case 8
  elseif (unit == "rookgeneral")
    return rookGeneralValidate(team, sourcex, sourcey, targetx, targety)

      #case 9
  elseif (unit == "hornedfalcon")
    return validateMod.hornedFalconValidate(team, sourcex, sourcey, targetx, targety)

      #case 10
  elseif (unit == "soaringeagle")
    return validateMod.soaringEagleValidate(team, sourcex, sourcey, targetx, targety)

      #case 11
  elseif (unit == "dragonhorse")
    return validateMod.dragonHorseValidate(team, sourcex, sourcey, targetx, targety)

      #case 12
  elseif (unit == "dragonking")
    return validateMod.dragonKingValidate(team, sourcex, sourcey, targetx, targety)

      #case 13
  elseif (unit == "bishop")
    return validateMod.bishopValidate(team, sourcex, sourcey, targetx, targety)

      #case 14
  elseif (unit == "rook")
    return validateMod.rookValidate(team, sourcex, sourcey, targetx, targety)

      #case 15
  elseif (unit == "ferociousleopard")
    return validateMod.ferociousLeopardValidate(team, sourcex, sourcey, targetx, targety)

      #case 16
  elseif (unit == "goldgeneral")
    return validateMod.goldGeneralValidate(team, sourcex, sourcey, targetx, targety)

      #case 17
  elseif (unit == "pawn")
    return validateMod.pawnValidate(team, sourcex, sourcey, targetx, targety)

      #case 18
  elseif (un18t == "firedemon")
    return fireDemonValidate(team, sourcex, sourcey, targetx, targety)

      #case 19
  elseif (unit == "heavenlytetrarch")
    return heavenlyTetrarchValidate(team, sourcex, sourcey, targetx, targety)

      #case 20
  elseif (unit == "waterbuffalo")
    return waterBuffaloValidate(team, sourcex, sourcey, targetx, targety)

      #case 21
  elseif (unit == "chariotSoldier")
    return chariotSoldierValidate(team, sourcex, sourcey, targetx, targety)

      #case 22
  elseif (unit == "sidesoldier")
    return sideSoldierValidate(team, sourcex, sourcey, targetx, targety)

      #case 23
  elseif (unit == "verticalsoldier")
    return verticalSoldierValidate(team, sourcex, sourcey, targetx, targety)

      #case 24
  elseif (unit == "knight")
    return validateMod.knightValidate(team, sourcex, sourcey, targetx, targety)

      #case 25
  elseif (unit == "irongeneral")
    return ironGeneralValidate(team, sourcex, sourcey, targetx, targety)

      #case 26
  elseif (unit == "freeeagle")
    return freeEagleValidate(team, sourcex, sourcey, targetx, targety)

      #case 27
  elseif (unit == "lionhawk")
    return lionHawkValidate(team, sourcex, sourcey, targetx, targety)

      #case 28
  elseif (unit == "queen")
    return validateMod.queenValidate(team, sourcex, sourcey, targetx, targety)

      #case 29
  elseif (unit == "lion")
    return validateMod.lionValidate(team, sourcex, sourcey, targetx, targety)

      #case 30
  elseif (unit == "phoenix")
    return validateMod.phoenixValidate(team, sourcex, sourcey, targetx, targety)

      #case 31
  elseif (unit == "kirin")
    return validateMod.kirinValidate(team, sourcex, sourcey, targetx, targety)

      #case 32
  elseif (unit == "freeboar")
    return validateMod.freeBoarValidate(team, sourcex, sourcey, targetx, targety)

      #case 33
  elseif (unit == "flyingox")
    return validateMod.flyingOxValidate(team, sourcex, sourcey, targetx, targety)

      #case 34
  elseif (unit == "sidemover")
    return validateMod.sideMoverValidate(team, sourcex, sourcey, targetx, targety)

      #case 35
  elseif (unit == "verticalmover")
    return validateMod.verticalMoverValidate(team, sourcex, sourcey, targetx, targety)

      #case 36
  elseif (unit == "coppergeneral")
    return validateMod.copperGeneralValidate(team, sourcex, sourcey, targetx, targety)

      #case 37
  elseif (unit == "silvergeneral")
    return validateMod.silverGeneralValidate(team, sourcex, sourcey, targetx, targety)

      #case 38
  elseif (unit == "multigeneral")
    return multiGeneralValidate(team, sourcex, sourcey, targetx, targety)

      #case 39
  elseif (unit == "flyingstag")
    return validateMod.flyingStagValidate(team, sourcex, sourcey, targetx, targety)

      #case 40
  elseif (unit == "dog")
    return dogValidate(team, sourcex, sourcey, targetx, targety)

      #case 41
  elseif (unit == "blindtiger")
    return validateMod.blindTigerValidate(team, sourcex, sourcey, targetx, targety)

      #case 42
  elseif (unit == "whitehorse")
    return validateMod.whiteHorseValidate(team, sourcex, sourcey, targetx, targety)

      #case 43
  elseif (unit == "whale")
    return validateMod.whaleValidate(team, sourcex, sourcey, targetx, targety)

      #case 44
  elseif (unit == "lance")
    return validateMod.lanceValidate(team, sourcex, sourcey, targetx, targety)

      #case 45
  elseif (unit == "reversechariot")
    return validateMod.reverseChariotValidate(team, sourcex, sourcey, targetx, targety)

  else
    return false #invalid unitType

end #tenjikuMoveValidate

#if lower rank can capture
function lowerRank(unit, targetUnit)

  if unit == "vicegeneral"
    if targetUnit == "king" || targetUnit == "prince" || targetUnit == "greatgeneral" || targetUnit == "vicegeneral"
      return false #cannot jump
    else
      return true #jump
    end

  elseif unit == "greatgeneral"
    if targetUnit == "king" || targetUnit == "prince" || targetUnit == "greatgeneral"
      return false
    else
      return true
    end

  elseif unit == "bishopgeneral" || unit == "rookgeneral"
    if targetUnit == "king" || targetUnit == "prince" || targetUnit == "greatgeneral" || targetUnit == "vicegeneral" || targetUnit == "rookgeneral"
      return false
    else
      return true
    end
  end

  return false
end #lowerRank

#checks if the captured piece can be captured by jumping
function jumpCapture(unit , targetUnit)

  if unit == "vicegeneral" || unit == "greatgeneral" || unit == "bishopgeneral" || unit == "rookgeneral"
    if targetUnit == "king" || targetUnit == "prince"
      return false #cannot jumpCapture
    else
      return true
    end
  end

  return false
end #jumpCapture

#moveUpValidate <=== Return true if unit can move veritcally upwards to target ===>
function rangeUpValidate(sourcex, sourcey, targetx, targety, unit)
  if (sourcey != targety)
    return false
  end

  unitCheck = abs(sourcex - targetx) - 1
  x = sourcex - 1
  jumpFlag = false

  for unit in 1:unitCheck
    if !((x,targety) in keys(board))
      x = x - 1
    elseif lowerRank(unit, board[(x,targety)][1]) == true #tagetUnit is lower rank
      jumpFlag = true
      x = x - 1
    else
      return false
    end
  end

  if jumpFlag == true
    if (jumpCapture(unit, board[targetx,targety][1]) == false) #jump capturing something that is higher rank
      return false
    end
  end

  return true
end #moveUpValidate

#moveDownValidate <=== Return true if unit can move veritcally downwards to target ===>
function rangeDownValidate(sourcex, sourcey, targetx, targety, unit)
  if (sourcey != targety)
    return false
  end

  unitCheck = abs(sourcex - targetx) - 1
  x = sourcex + 1
  jumpFlag = false

  for unit in 1:unitCheck
    if !((x,targety) in keys(board))
      x = x + 1
    elseif lowerRank(unit, board[(x,targety)][1]) == true
      jumpFlag = true
      x = x + 1
    else
      return false
    end
  end

  if jumpFlag == true
    if (jumpCapture(unit, board[targetx,targety][1]) == false) #jump capturing something that is higher rank
      return false
    end
  end

  return true
end #moveDownValidate

#moveLeftValidate <=== Return true if unit can move horizontally left to target ===>
function rangeLeftValidate(sourcex, sourcey, targetx, targety, unit)
  if (sourcex != targetx)
    return false
  end

  unitCheck = abs(sourcey - targety) - 1
  y = sourcey - 1
  jumpFlag = false;

  for unit in 1:unitCheck
    if !((targetx,y) in keys(board))
      y = y - 1
    elseif lowerRank(unit, board[(sourcex,y)][1]) == true
      jumpFlag = true;
      y = y - 1
    else
      return false
    end
  end

  if jumpFlag == true
    if (jumpCapture(unit, board[targetx,targety][1]) == false) #jump capturing something that is higher rank
      return false
    end
  end

  return true
end #moveLeftValidate

#moveRightValidate <=== Return true if unit can move horizontally Right to target ===>
function rangeRightValidate(sourcex, sourcey, targetx, targety, unit)
  if (sourcex != targetx)
    return false
  end

  unitCheck = abs(sourcey - targety) - 1
  y = sourcey + 1
  jumpFlag = false

  for unit in 1:unitCheck
    if !((targetx,y) in keys(board))
      y = y + 1
    elseif lowerRank(unit, board[(sourcex,y)][1]) == true
      jumpFlag = true;
      y = y + 1
    else
      return false
    end
  end

  if jumpFlag == true
    if (jumpCapture(unit, board[targetx,targety][1]) == false) #jump capturing something that is higher rank
      return false
    end
  end

  return true
end #moveLeftValidate

#diagonalUpLeft <=== Return true if unit can move diagonally upleft to target ===>
function rangeUpLeftValidate(sourcex, sourcey, targetx, targety, unit)
  if (sourcex - targetx) == (sourcey - targety)
    if (sourcex > targetx) #moving diagonal up left
      unitCheck == abs(sourcex - targetx) - 1
      x = sourcex - 1
      y = sourcey - 1
      jumpFlag = false

      for unit in 1:unitCheck
        if !((x,y) in keys(board))
          x = x - 1
          y = y - 1
        elseif lowerRank(unit, board[(x,y)][1]) == true
          jumpFlag = true
          x = x - 1
          y = y - 1
        else
          return false
        end
      end

      if jumpFlag == true
        if (jumpCapture(unit, board[targetx,targety][1]) == false) #jump capturing something that is higher rank
          return false
        end
      end

      return true
    end
  end

  return false
end #diagonalUpLeftValidate

#digonalUpRight <=== Return true if unit can move diagonally upleft to target ===>
function rangeUpRightValidate(sourcex, sourcey, targetx, targety, unit)
  if (sourcex - targetx) == (targety - sourcey)
    if (sourcex > targetx) #moving diagonal up right
      unitCheck == abs(sourcex - targetx) - 1
      x = sourcex - 1
      y = sourcey + 1
      jumpFlag = false

      for unit in 1:unitCheck
        if !((x,y) in keys(board))
          x = x - 1
          y = y + 1
        elseif lowerRank(unit, board[(x,y)][1]) == true
          jumpFlag = true
          x = x - 1
          y = y + 1
        else
          return false
        end
      end

      if jumpFlag == true
        if (jumpCapture(unit, board[targetx,targety][1]) == false) #jump capturing something that is higher rank
          return false
        end
      end

      return true
    end
  end

  return false
end #diagonalUpRightValidate

#diagonalDownLeft <=== Return true if unit can move diagonally downleft to target ===>
function rangeDownLeftValidate(sourcex, sourcey, targetx, targety, unit)
  if (sourcex - targetx) == (targety - sourcey)
    if (sourcex < targetx) #moving diagonal down left
      unitCheck == abs(sourcex - targetx) - 1
      x = sourcex + 1
      y = sourcey - 1
      jumpFlag = false

      for unit in 1:unitCheck
        if !((x,y) in keys(board))
          x = x + 1
          y = y - 1
        elseif lowerRank(unit, board[(x,y)][1]) == true
          jumpFlag = true;
          x = x + 1
          y = y - 1
        else
          return false
        end
      end

      if jumpFlag == true
        if (jumpCapture(unit, board[targetx,targety][1]) == false) #jump capturing something that is higher rank
          return false
        end
      end

      return true
    end
  end

  return false
end #diagonalDownLeftValidate

#diagonalDownRight
function rangeDownRightValidate(sourcex, sourcey, targetx, targety, unit)
  if (sourcex - targetx) == (sourcey - targety)
    if (sourcex < targetx) #moving diagonal down left
      unitCheck == abs(sourcex - targetx) - 1
      x = sourcex + 1
      y = sourcey + 1
      jumpFlag = false

      for unit in 1:unitCheck
        if !((x,y) in keys(board))
          x = x + 1
          y = y + 1
        elseif lowerRank(unit, board[(x,y)][1]) == true
          jumpFlag = true
          x = x + 1
          y = y + 1
        else
          return false
        end
      end

      if jumpFlag == true
        if (jumpCapture(unit, board[targetx,targety][1]) == false) #jump capturing something that is higher rank
          return false
        end
      end

  return false
end #diagonalDownRightValidate

#case 5
function viceGeneralValidate(team, sourcex, sourcey, targetx, targety, targetx2, targety2, targetx3, targety3)

  target2 = true
  target3 = true
  if (targetx2 == -1 || targety2 == -1)
    target2 == false;
  if (targetx3 == -1 || targety3 == -1)
    target3 == false;

  #area move
  if (abs(sourcex - targetx) == 1) || (abs(sourcex - targetx) == 0)
    if (abs(sourcey - targety) == 1) || (abs(sourcey - targety) == 0)
      if ! ((targetx,targety) in keys(board)) # Empty
        if (abs(targetx2 - targetx) == 1) || (abs(targetx2 - targetx) == 0)
          if (abs(targety2 - targety) == 1) || (abs(targety2 - targety) == 0)
            if ! ((targetx2,targety2) in keys(board)) # Empty
              if (abs(targetx2 - targetx3) == 1) || (abs(targetx2 - targetx3) == 0)
                if (abs(targety2 - targety3) == 1) || (abs(targety2 - targety3) == 0)
                  return true;
                end
              end
            else
              if (target3 == false)
                return true;
              end
            end
          end
        end
      else
        if (target2 == false) && (target3 == false)
          return true;
      end
    end
  end

  #Range Jump
  if (target2 == false && target3 == false)
    if (sourcex < targetx) #move down
      if (sourcey < targety) #move down Right
        if (rangeDownRightValidate(sourcex, sourcey, targetx, targety, "vicegeneral") == true)
          return true
        end
      else #move down left
        if (rangeDownLeftValidate(sourcex, sourcey, targetx, targety, "vicegeneral") == true)
          return true
        end
      end
    else #move up
      if (sourcey < targety) #move up Right
        if (rangeUpRightValidate(sourcex, sourcey, targetx, targety, "vicegeneral") == true)
          return true
        end
      else #move down left
        if (rangeUpLeftValidate(sourcex, sourcey, targetx, targety, "vicegeneral") == true)
          return true
        end
      end
    end
  end

  return false
end #viceGeneralValidate

#case 6
function greatGeneralValidate(team, sourcex, sourcey, targetx, targety)
  #moves like bishop
  if (abs(sourcex - targetx) == abs(sourcey - targety)) #moves diagonally
    if (sourcex < targetx) #downwards
      if (sourcey < targety) #diagonalDownRight
        if (rangeDownRightValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      else #diagonalDownLeft
        if (rangeDownLeftValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      end
    else #upwards
      if (sourcey < targety) #diagonalUpRightValidate
        if (rangeUpRightValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      else #diagonalUpLeft
        if (rangeUpLeftValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      end
    end
  end

  #moves like rook
  if (sourcex == targetx) && (sourcey != targety) #moving horizontally
    if (sourcey > targety) #horizontal left
      if (rangeLeftValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end

    else #horizontal right
      if (rangeRightValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    end

  elseif (sourcey == targety) && (sourcex != targetx) #moving vertically
    if (sourcex > targetx) #vertical up
      if (rangeUpValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    else #vertical down
      if (rangeDownValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    end
  end

  return false
end #greatGeneralValidate

#case 7
function bishopGeneralValidate(team, sourcex, sourcey, targetx, targety)
  #moves like bishop
  if (abs(sourcex - targetx) == abs(sourcey - targety)) #moves diagonally
    if (sourcex < targetx) #downwards
      if (sourcey < targety) #diagonalDownRight
        if (rangeDownRightValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      else #diagonalDownLeft
        if (rangeDownLeftValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      end
    else #upwards
      if (sourcey < targety) #diagonalUpRightValidate
        if (rangeUpRightValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      else #diagonalUpLeft
        if (rangeUpLeftValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      end
    end
  end

  return false
end #bishopGeneralValidate

#case 8
function rookGeneralValidate(team, sourcex, sourcey, targetx, targety)
  #moves like rook
  if (sourcex == targetx) && (sourcey != targety) #moving horizontally
    if (sourcey > targety) #horizontal left
      if (rangeLeftValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    else #horizontal right
      if (rangeRightValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    end

  elseif (sourcey == targety) && (sourcex != targetx) #moving vertically
    if (sourcex > targetx) #vertical up
      if (rangeUpValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    else #vertical down
      if (rangeDownValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    end
  end

  return false
end #rookGeneralValidate

#case 18
function fireDemonValidate(team, sourcex, sourcey, targetx, targety, targetx2, targety2, targetx3, targety3)
  #range
  if (validateMod.moveDiagonalValidate(sourcex,sourcey,targetx,targety) == true)
    return true
  end

  if (validateMod.moveRightValidate(sourcex,sourcey,targetx,targety) == true)
    return true
  end

  if (validateMod.moveLeftValidate(sourcex,sourcey,targetx,targety) == true)
    return true
  end

  #Area move
  flag2 = false
  flag3 = false

  if (targetx2 != -1 || targety2 != -1)
    flag2 = true
  end

  if (targetx3 != -1 || targety3 != -1)
    flag3 = true
  end

  if (abs(sourcex - targetx) == 1 || abs(sourcex - targetx) == 0) && ((abs(sourcey - targety) == 1) || abs(sourcey - targety == 0))
    if flag2 = true
      if ((targetx,targety) in keys(board)) #captured a piece
        return false
      else
        if (abs(targetx2 - targetx) == 1 || abs(targetx2 - targetx) == 0) && ((abs(targety2 - targety) == 1) || abs(targety2 - targety == 0))
          if flag3 = true
            if ((targetx2,targety2) in keys(board))
                return false
            else
              if (abs(targetx2 - targetx3) == 1 || abs(targetx2 - targetx3) == 0) && ((abs(targety2 - targety3) == 1) || abs(targety2 - targety3 == 0))
                return true
              end
            end
          else
            return true
          end
        end
      end
    else #flag2 = false
      return true
    end
  end
end #fireDemonValidate

#case 19
function heavenlyTetrarchValidate(team, sourcex, sourcey, targetx, targety, targetx2, targety2)

  flag2 = false
  if (targetx2 != -1 || targety2 != -1)
    flag2 = true
  end

  #igui
  if flag2 == true
    if (abs(sourcex - targetx) == 1) || (abs(sourcex - targetx) == 0)
      if (abs(sourcey - targety) == 1) || (abs(sourcey - targety) == 0)
        if (sourcex == targetx2) && (sourcey == targety2)
          return true
        end
      end
    end
  end

  #range
  if flag2 == false
    if (abs(sourcex - targetx) == 1) || (abs(sourcex - targetx) == 0)
      if (abs(sourcey - targety) == 1) || (abs(sourcey - targety) == 0)
        return false
      end

    #side ways
    else if (sourcex == targetx)
      if (abs(sourcey  - targety) == 3)
        if sourcey < targety #move right
          if (validateMod.moveRightValidate(sourcex,sourcey+1,targetx,targety) == true)
            return true
          end
        else #move left
          if (validateMod.moveLeftValidate(sourcex,sourcey-1,targetx,targety) == true)
            return true
          end
        end
      end

    #diagonalUpLeft
    else if abs(sourcex - targetx) == abs(sourcey - targety)
      if sourcex < targetx #move down
        if sourcey < targety #move right
          if (validateMod.diagonalDownRightValidate(sourcex+1,sourcey+1,targetx,targety) == true)
            return true
          end
        else #move left
          if (validateMod.diagonalDownLeftValidate(sourcex+1,sourcey-1,targetx,targety) == true)
            return true
          end
        end
      else #move up
        if sourcey < targety #move right
          if (validateMod.diagonalUpRightValidate(sourcex-1,sourcey+1,targetx,targety) == true)
            return true
          end
        else #move left
          if (validateMod.diagonalUpLeftValidate(sourcex-1,sourcey-1,targetx,targety) == true)
            return true
          end
        end
      end
    end
  end

  return false
end #heavenlyTetrarchValidate

#case 20
function waterBuffaloValidate(team, sourcex, sourcey, targetx, targety)

  #check if moves like bishop
  if (validateMod.moveDiagonalValidate(sourcex,sourcey,targetx,targety) == true)
    return true
  end

  #moves sideways
  if (sourcex == targetx)
    if (sourcey < targety) #move right
      if (validateMod.moveRightValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    else #move left
      if (validateMod.moveLeftValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    end
  end

  #two up or down
  if (sourcey == targety)
    if (abs(sourcex - targetx) == 2)
      return true
    end
  end

  return false
end #waterBuffaloValidate

#case 21
function chariotSoldierValidate(team, sourcex, sourcey, targetx, targety)

  #moves like bishop
  if (validateMod.moveDiagonalValidate(sourcex,sourcey,targetx,targety) == true)
    return true
  end

  #moves vertically
  if (sourcey == targety)
    if (sourcex < targetx) #move down
      if (validateMod.moveDownValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    else #move up
      if (validateMod.moveUpValidate(sourcex,sourcey,targetx,targety) == true)
        return true
      end
    end
  end

  #move two left or right
  if (sourcex == targetx)
    if (abs(sourcey - targety) == 2)
      return true
    end
  end

  return false
end #chariotSoldierValidate

#case 22
function sideSoldierValidate(team, sourcex, sourcey, targetx, targety)
  if (team == 'b')
    if (sourcey == targety)
      if (abs(sourcex - targetx) == 1) || (sourcex - targetx == 2)
        return true
    else #move left or right
      if (sourcey < targety) #move right
        if (validateMod.moveRightValidate(sourcex,sourcey,targetx,targety) == true)
          return true
      else #move left
        if (validateMod.moveLeftValidate(sourcex,sourcey,targetx,targety) == true)
          return true
      end
    end
  elseif (team == 'w')
    if (sourcey == targety)
      if (abs(sourcex - targetx) == 1) || (sourcex - targetx == -2)
        return true
    else #move left or right
      if (sourcey < targety) #move right
        if (validateMod.moveRightValidate(sourcex,sourcey,targetx,targety) == true)
          return true
      else #move left
        if (validateMod.moveLeftValidate(sourcex,sourcey,targetx,targety) == true)
          return true
      end
    end
  end

  return false
end #sideSoldierValidate

#case 23
function verticalSoldierValidate(team, sourcex, sourcey, targetx, targety)

  #sideways two
  if (sourcex == targetx)
    if (abs(sourcey - targety) == 2)
      return true
    end
  end

  if (team == 'b')
    #move forward
    if (sourcey == targety)
      if (sourcex < targetx) #move down
        if ((targetx - sourcex) == 1)
          return true
        end
      else #move up
        if (validateMod.moveUpValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      end
    end

  elseif (team == 'w')
    #move forward
    if (sourcey == targety)
      if (sourcex > targetx)
        if ((targetx - sourcex) == 1)
          return true
        end
      else
        if (validateMod.moveUpValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      end
    end
  end

  return false
end #verticalSoldierValidate

#case 25
function ironGeneralValidate(team, sourcex, sourcey, targetx, targety)
  if (team == 'b')
    if (sourcex - targetx == 1)
      if (abs(sourcey - targety) == 1) || (sourcey == targety)
        return true
      end
    end
  elseif (team == 'w')
    if (sourcex - targetx == -1)
      if (abs(sourcey - targety) == 1) || (sourcey == targety)
        return true
      end
    end
  end

  return false
end #ironGeneralValidate

#case 26
function freeEagleValidate(team, sourcex, sourcey, targetx, targety, targetx2, targety2)

  #Double move
  if (targetx2 != -1 || targety2 != -1)
    if (abs(sourcex - targetx) == 1 && abs(sourcey - targety) == 1 && (!((targetx,targety) in keys(board))))
      if (abs(targetx - targetx2) == 1 && abs(targety - targety2) == 1)
        return true
      end
    end

  #move diagonal
  else if (validateMod.moveDiagonalValidate(sourcex,sourcey,targetx,targety) == true)
    return true

  #move orthogonal
  else if (validateMod.moveOrthogonalValidate(sourcex,sourcey,targetx,targety) == true)
    return true
  end

  return false
end #freeEagleValidate

#case 27
function lionHawkValidate(team, sourcex, sourcey, targetx, targety, targetx2, targety2)

  #lion move
  flag2 = false
  if (targetx2 == -1 || targety2 == -1)
    flag2 = true
  end

  if flag2 == true
    if (abs(sourcex - targetx) == 1 || abs(sourcex - targetx) == 0) && ((abs(sourcey - targety) == 1) || (abs(sourcey2 - targety) == 0))
      if (abs(targetx2 - targetx) == 1 || abs(targetx2 - targetx) == 0) && ((abs(targety2 - targety) == 1) || (abs(targety2 - targety2) == 0))
        return true
      end
    end

  #move diagonal
  else if (validateMod.moveDiagonalValidate(sourcex,sourcey,targetx,targety) == true)
    return true
  end

  return false
end #lionHawkValidate

#case 38
function multiGeneralValidate(team, sourcex, sourcey, targetx, targety)
  if (team =='b')
    #move up
    if (sourcey == targety)
      if (sourcex > targetx) #move up
        if (validateMod.moveUpValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      end
    end

    #diagonal down left or right
    if (abs(sourcex - targetx) == abs(sourcey - targety)) #moving diagonally
      if (targetx > sourcex) #move down
        if (targety < sourcey) #move left
          if (validateMod.diagonalDownLeftValidate(sourcex,sourcey,targetx,targety) == true)
            return true
          end
        else #move right
          if (validateMod.diagonalDownRightValidate(sourcex,sourcey,targetx,targety) == true)
            return true
          end
        end
      end
    end

  elseif (team =='w')
    #move up
    if (sourcey == targety)
      if (sourcex < targetx) #move down
        if (validateMod.moveDownValidate(sourcex,sourcey,targetx,targety) == true)
          return true
        end
      end
    end

    #diagonal down left or right
    if (abs(sourcex - targetx) == abs(sourcey - targety)) #moving diagonally
      if (targetx < sourcex) #move up
        if (targety > sourcey) #move right
          if (validateMod.diagonalUpRightValidate(sourcex,sourcey,targetx,targety) == true)
            return true
          end
        else #move right
          if (validateMod.diagonalUpLeftValidate(sourcex,sourcey,targetx,targety) == true)
            return true
          end
        end
      end
    end

  end

  return false
end #multiGeneralValidate

#40
function dogValidate(team, sourcex, sourcey, targetx, targety)
  if (team == 'b')
    if (sourcex - targetx == 1) && (sourcey == targety)
      return true
    end
    if (sourcex - targetx == -1) && (abs(sourcey - targety) == 1)
      return true
    end
  elseif (team == 'w')
    if (sourcex - targetx == -1) && (sourcey == targety)
      return true
    end
    if (sourcex - targetx == 1) && (abs(sourcey - targety) == 1)
      return true
    end
  end

  return false
end #dogValidate

#implement functions
#case 18,19
#done case: 5,6,7,8,20,21,22,23,25,26,27,38,40
#Pre-existing functions
#case 1,2,3,4,9,10,11,12,13,14,15,16,17,24,28,29,30,31,32,33,34,35,36,37,39,41,42,43,44,45

max_stars_repo_name: kinoroy/Shogi

max_issues_repo_name: kinoroy/Shulia

max_forks_repo_name: kinoroy/Shulia


text:
using Test
using DLX

# prepare test datas
worlds = [(5,5), (5,10), (10, 10), (10, 15), (20, 20), (20, 50)]

sets = [[(3,3), (2,2)],
        [(4,4), (4,3), (4,2), (3,2), (2,2), (2,1)],
        [(8,8), (8,7), (8,6), (7,5), (7,4), (7,3), (6,2), (5,5), (4,2)]]

@testset "Some Random Test" begin
    for w in worlds
        world_area = w[1] * w[2]
        for s in sets
            a = DancingLink(w, sets[1])

            if world_area >= sum(el -> el[1] * el[2], s)
                @test is_solved(a)
            else
                @test !is_solved(a)
            end
        end
    end
end

@testset "Multiple world" begin

    x = DancingLink(worlds[1:2], vcat(sets...))

end


text:
import IntervalArithmetic: diam, isinterior
import Base: iterate, eltype, IteratorSize, copy

export branch_and_prune, Bisection, Newton, RootSearch
export step!

diam(x::Root) = diam(x.interval)

struct RootSearchState{T <: Union{Interval,IntervalBox}}
    working::Vector{T}
    outputs::Vector{Root{T}}
end
RootSearchState(region::T) where {T<:Union{Interval,IntervalBox}} =
    RootSearchState([region], Root{T}[])

copy(state::RootSearchState) =
    RootSearchState(copy(state.working), copy(state.outputs))

"""
    RootSearch{R <: Union{Interval,IntervalBox}, S <: Contractor, T <: Real}

Type implementing the `Base.Iterator` interface to the branch and prune routine.
Returns the `RootSearchState` at each iteration. Note: Each iteration mutates
the `RootSearchState`. Use `copy(state::RootSearchState)` to create an
independent instance if necessary.
"""
struct RootSearch{R <: Union{Interval,IntervalBox}, S <: Contractor, T <: Real}
    region::R
    contractor::S
    tolerance::T
end

eltype(::Type{T}) where {R, T <: RootSearch{R}} = RootSearchState{R}
IteratorSize(::Type{T}) where {T <: RootSearch} = Base.SizeUnknown()

# function start(iter::RootSearch)
#     state = RootSearchState(iter.region)
#     sizehint!(state.outputs, 100)
#     sizehint!(state.working, 1000)
#     return state
# end

function iterate(iter::RootSearch)
    state = RootSearchState(iter.region)
    sizehint!(state.outputs, 100)
    sizehint!(state.working, 1000)
    return state, state
end

"""
    step!(state::RootSearchState, contractor, tolerance)

Progress `state` by treating one of its `working` regions. Note: `state.working`
is always modified. If a root is found, it is added to `state.outputs`.
"""
function step!(state::RootSearchState, contractor, tolerance)
    X = pop!(state.working)
    status, output = contractor(X, tolerance)
    if status == :empty
        return nothing
    elseif status == :unique
        push!(state.outputs, Root(output, :unique))
    elseif diam(output) < tolerance
        push!(state.outputs, Root(output, :unknown))
    else # branch
        X1, X2 = bisect(X)
        push!(state.working, X1, X2)
    end
    return nothing
end

# function next(iter::RootSearch, state::RootSearchState)
#     step!(state, iter.contractor, iter.tolerance)
#     return state, state
# end

function iterate(iter::RootSearch, state::RootSearchState)

    isempty(state.working) && return nothing

    step!(state, iter.contractor, iter.tolerance)
    return state, state
end

# done(iter::RootSearch, state::RootSearchState) = isempty(state.working)

"""
    branch_and_prune(X, contract, tol=1e-3)

Generic branch and prune routine for finding isolated roots using the `contract`
function as the contractor.

Inputs:
- `X`: `Interval` or `IntervalBox`
- `contract`: function that determines the status of a given box `X`. It
    returns the new box and a symbol indicating the status. Current possible
    values are of type `Bisection` or `Newton`

"""
function branch_and_prune(X, contractor, tol=1e-3)
    iter = RootSearch(X, contractor, tol)
    local output
    # complete iteration
    for state in iter
        output = state.outputs
    end
    return output
end

export recursively_branch_and_prune

function recursively_branch_and_prune(h, X, contractor=BisectionContractor, final_tol=1e-14)
    tol = 2
    roots = branch_and_prune(h, X, IntervalRootFinding.BisectionContractor, tol)

    while tol > 1e-14
       tol /= 2
       roots = branch_and_prune(h, roots, IntervalRootFinding.BisectionContractor, tol)
    end

    return roots
end

const IntervalLike{T} = Union{Interval{T}, IntervalBox{T}}
const NewtonLike = Union{Type{Newton}, Type{Krawczyk}}

"""
    roots(f, X, contractor, tol=1e-3)
    roots(f, deriv, X, contractor, tol=1e-3)

Uses a generic branch and prune routine to find in principle all isolated roots of a function
`f:R^n → R^n` in a box `X`, or a vector of boxes.

Inputs:
- `f`: function whose roots will be found
- `X`: `Interval` or `IntervalBox`
- `contractor`: function that, when applied to the function `f`, determines
    the status of a given box `X`. It returns the new box and a symbol indicating
    the status. Current possible values are `Bisection`, `Newton` and `Krawczyk`
- `deriv` ; explicit derivative of `f` for `Newton` and `Krawczyk`
"""
function roots(f, X::IntervalLike{T}, ::Type{Bisection}, tol::Float64=1e-3) where {T}
    branch_and_prune(X, Bisection(f), tol)
end

function roots(f, X::Interval{T}, C::NewtonLike, tol::Float64=1e-3) where {T}

    deriv = x -> ForwardDiff.derivative(f, x)

    roots(f, deriv, X, C, tol)
end

function roots(f, deriv, X::Interval{T}, C::NewtonLike, tol::Float64=1e-3) where {T}
    branch_and_prune(X, C(f, deriv), tol)
end

function roots(f, X::IntervalBox{T}, C::NewtonLike, tol::Float64=1e-3) where {T}

    deriv = x -> ForwardDiff.jacobian(f, x)

    roots(f, deriv, X, C, tol)
end

function roots(f, deriv, X::IntervalBox{T}, C::NewtonLike, tol::Float64=1e-3) where {T}
    branch_and_prune(X, C(f, deriv), tol)
end

roots(f, r::Root, contractor::Type{C}, tol::Float64=1e-3) where {C<:Contractor} =
    roots(f, r.interval, contractor, tol)
roots(f, deriv, r::Root, contractor::Type{C}, tol::Float64=1e-3) where {C<:Contractor} =
    roots(f, deriv, r.interval, contractor, tol)

# Acting on a Vector:

# TODO: Use previous status information about roots:
roots(f, V::Vector{Root{T}}, contractor::Type{C}, tol::Float64=1e-3) where {T, C<:Contractor} =
    vcat(roots.(f, V, contractor, tol)...)
roots(f, deriv, V::Vector{Root{T}}, contractor::Type{C}, tol::Float64=1e-3) where {T, C<:Contractor} =
    vcat(roots.(f, deriv, V, contractor, tol)...)

# Complex:

function roots(f, Xc::Complex{Interval{T}}, contractor::Type{C},
        tol::Float64=1e-3) where {T, C<:Contractor}

    g = realify(f)
    Y = IntervalBox(reim(Xc)...)
    rts = roots(g, Y, contractor, tol)

    return [Root(Complex(root.interval...), root.status) for root in rts]
end

function roots(f, Xc::Complex{Interval{T}}, C::NewtonLike, tol::Float64=1e-3) where {T}

    g = realify(f)

    g_prime = x -> ForwardDiff.jacobian(g, x)

    Y = IntervalBox(reim(Xc)...)
    rts = roots(g, g_prime, Y, C, tol)

    return [Root(Complex(root.interval...), root.status) for root in rts]
end

function roots(f, deriv, Xc::Complex{Interval{T}}, C::NewtonLike, tol::Float64=1e-3) where {T}

    g = realify(f)

    g_prime = realify_derivative(deriv)

    Y = IntervalBox(reim(Xc)...)
    rts = roots(g, g_prime, Y, C, tol)

    return [Root(Complex(root.interval...), root.status) for root in rts]
end

# Default
roots(f::F, deriv::F, X, tol::Float64=1e-15) where {F<:Function} = roots(f, deriv, X, Newton, tol)
roots(f::F, X, tol::Float64=1e-15) where {F<:Function} = roots(f, X, Newton, tol)


text:
module MaxHelpingHandCameraCatchupSpeedTrigger

using ..Ahorn, Maple

@mapdef Trigger "MaxHelpingHand/CameraCatchupSpeedTrigger" CameraCatchupSpeedTrigger(x::Integer, y::Integer, width::Integer=Maple.defaultTriggerWidth, height::Integer=Maple.defaultTriggerHeight,
    catchupSpeed::Number=1.0, revertOnLeave::Bool=true)

const placements = Ahorn.PlacementDict(
    "Camera Catchup Speed (max480's Helping Hand)" => Ahorn.EntityPlacement(
        CameraCatchupSpeedTrigger,
        "rectangle"
    )
)

end

max_stars_repo_name: Kitty-Cats/MaxHelpingHand

max_issues_repo_name: Kitty-Cats/MaxHelpingHand

max_forks_repo_name: Kitty-Cats/MaxHelpingHand


text:
module FactCheckSupportTests

using Fixtures
using FactCheck

@fixture function fixture_that_produces_ten()
  yield_fixture(10)
end

facts("FactCheck support tests", using_fixtures) do
  context("Very basic example no fixtures defined", using_fixtures) do
    @fact 100 --> 100
  end

  global x=0

  add_fixture(:context, function(fn::Function)
                          global x=100
                          try
                            fn()
                          finally
                            global x=0
                          end
                        end)

  @fact x --> 0

  context("Example with fixtures set on a context level", using_fixtures) do
    @fact x --> 100
  end

  @fact x --> 0

  context("Example with fixtures set on a context level (again)", using_fixtures) do
    @fact x --> 100
  end

  @fact x --> 0

  context(using_fixtures) do
    @fact x --> 100
  end

  @fact x --> 0

  add_fixture(:context, :some_name, fixture_that_produces_ten)

  context("Context example with fixture_values=true", using_fixtures, fixture_values=true) do values
    @fact values[:some_name] --> 10
  end

end

add_fixture(:facts, :some_name, fixture_that_produces_ten)

facts("Facts example with fixture_values=true", using_fixtures, fixture_values=true) do values
  @fact values[:some_name] --> 10
end

facts(using_fixtures, fixture_values=true) do values
  @fact values[:some_name] --> 10
end

end


text:
function SpinStabilized(arg0::AttitudeProvider, arg1::AbsoluteDate, arg2::Vector3D, arg3::jdouble)
    return SpinStabilized((AttitudeProvider, AbsoluteDate, Vector3D, jdouble), arg0, arg1, arg2, arg3)
end

function get_attitude(obj::SpinStabilized, arg0::FieldPVCoordinatesProvider, arg1::FieldAbsoluteDate, arg2::Frame)
    return jcall(obj, "getAttitude", FieldAttitude, (FieldPVCoordinatesProvider, FieldAbsoluteDate, Frame), arg0, arg1, arg2)
end

function get_attitude(obj::SpinStabilized, arg0::PVCoordinatesProvider, arg1::AbsoluteDate, arg2::Frame)
    return jcall(obj, "getAttitude", Attitude, (PVCoordinatesProvider, AbsoluteDate, Frame), arg0, arg1, arg2)
end

function get_underlying_attitude_provider(obj::SpinStabilized)
    return jcall(obj, "getUnderlyingAttitudeProvider", AttitudeProvider, ())
end


text:
function ==(x::IDList, y::IDList)
    res = x.sids == y.sids &&
          x.eids == y.eids &&
          x.patrn == y.patrn &&
          x.typ == y.typ &&
          x.supp == y.supp
    return res
end

function unique(v::Array{IDList, 1})
    out = Array{IDList, 1}(0)
    for i = 1:length(v)
        if !in(v[i], out)
            push!(out, v[i])
        end
    end
    return out
end

# function display(x::IDList)
#     if isempty(x)
#         println("$(x.pattern) has support 0")
#     else
#         last = x.sids[end]
#         nchar = 2 + length(string(last))
#
#         println("$(x.pattern)")
#         for i = 1:length(x.sids)
#             println(rpad(x.sids[i], nchar, " "), x.eids[i])
#         end
#     end
# end

# function display(x::Array{IDList,1})
#     for i = 1:length(x)
#         display(x[i])
#         println("\n")
#     end
# end

"""
This function behaves a bit like Python's str.rfind()
method; it gets the indices where the `needle` appears
in the `haystack`. Returns 0:-1 if `needle` is not found.
"""
function rfind(haystack::String, needle::String)
    n = length(haystack)
    nchar = length(needle)
    window = nchar - 1
    start_idx = 0
    stop_idx = -1
    for i = (n - window):-1:1
        if haystack[i:i+window] == needle
            start_idx = i
            stop_idx = i+window
            break
        end
    end
    return UnitRange{Int}(start_idx, stop_idx)
end

function rfind(haystack::String, needle::Char)
    last_idx = findlast(haystack, needle)
    return last_idx
end

function unique_items(s::Sequence)
    d = Dict{String, Int64}()
    for i = 1:length(s.items)
        for k in s.items[i]
            d[k] = get(d, k, 0) + 1
        end
    end
    return collect(keys(d))
end

function sanitize_items(items, excluded_strings = ["{", "}", ", "])
    res = items
    n = length(res)
    for i = 1:n
        for s in excluded_strings
            res[i] = replace(res[i], s, " ")
        end
    end
    return res
end

# itms1 = ["this -> is a {string}", "and {so} is -> {} this"]
# sanitize_items(itms1)

# These two find() functions are just for dev purposes
# to track down cases where we disagree with R
function find(x::Array{IDList, 1}, patrn::String)
    indcs = Array{Int, 1}(0)
    n = length(x)

    for i = 1:n
        if x[i].pattern == patrn
            push!(indcs, i)
        end
    end
    return indcs
end

function find(x::Array{IDList, 1}, patrn::Array{Array{String, 1}, 1})
    indcs = Array{Int, 1}(0)
    n = length(x)

    for i = 1:n
        if x[i].patrn == patrn
            push!(indcs, i)
        end
    end
    return indcs
end

"""
    make_sequences(dat; item_col, sid_col, eid_col, excluded_strings)

Given a data set, `dat`, in long format, this function extracts all
the sequences and returns an array of `Sequence` objects. By "long format"
we mean that each row represents a given item in a given sequence at a given
time. Thus, `dat` must have columns for item, sequence number, and time point

### Arguments
* `dat`: a two-dimensional array-type object (i.e., `Array{T,2}` or `DataFrame`)
* `item_col`: column index for actual item at a given time and in a given sequence.
* `sid_col`: sequence ID column index
* `eid_col`: event ID column index
* `excluded_strings`: vector of strings to be removed from the raw input data
"""
function make_sequences(dat; item_col = 1, sid_col = 2, eid_col = 3, excluded_strings = ["{", "}", ", "])
    seq_ids = unique(dat[:, sid_col])
    num_seqs = length(seq_ids)
    seq_arr = Array{Sequence, 1}(num_seqs)

    dat[:, item_col] = sanitize_items(dat[:, item_col], excluded_strings)

    for (i, sid) in enumerate(seq_ids)
        row_indcs = find(dat[:, sid_col] .== sid)

        dat_subset = dat[row_indcs, :]
        event_ids = unique(dat[row_indcs, eid_col])
        items = Array{Array{String, 1}, 1}(0)

        for eid in event_ids
            indcs = find(eid .== dat_subset[:, eid_col])
            items_arr = convert(Array{String, 1}, dat_subset[indcs, item_col])
            push!(items, sort(items_arr))
        end
        seq_arr[i] = Sequence(sid, event_ids, items)
    end
    return seq_arr
end

# d = readcsv("./data/zaki_data.csv", skipstart = 1)
#
# seq_array = make_sequences(d, 2, 3, 1)

# Given a vector of strings, this function returns
# a single string with all elements of the vector
# having been concatenated.
function join_strings(x::Array{String, 1})
    n = length(x)
    s = ""
    for i = 1:n
        if i < n
            s *= string(x[i], ",")
        elseif i == n
            s *= x[i]
        end
    end
    return s
end

# join_strings(["ab", "cd"])

# Given the pattern from an IDList, this function returns
# a string illustrating the temporal relation of the
# seqeunce. For example: "{A} -> {B,C} -> {D}".
function pattern_string(x::Array{Array{String, 1}, 1})
    n = length(x)
    s = ""
    for i = 1:n
        if i < n
            s *= string("{", join_strings(x[i]), "},")
        elseif i == n
            s *= string("{", join_strings(x[i]), "}")
        end
    end
    return s
end

function pattern_string(args...)
    n = length(args)
    s = ""
    for i = 1:n
        if i < n
            s *= string("{", join_strings(args[i]), "},")
        elseif i == n
            s *= string("{", join_strings(args[i]), "}")
        end
    end
    return s
end

# pattern_string(["ab", "cd"], ["de", "fg"])

pattern_string(s::String) = string("{", s, "}")

# This is our workhorse used in the nloops_gen(), which
# is a function that generates n nested loops.
function addpattern!(v, args...)
    s = pattern_string(args...)
    push!(v, s)
end

# This function gets the counts for each pattern
# we have in our frequent-pattern set.

function count_patterns(F::Array{Array{IDList, 1}, 1})
    m = length(F)
    cnt = Dict{String, Int}()
    for k = 1:m
        n = length(F[k])
        for i = 1:n
            cnt[pattern_string(F[k][i].patrn)] = F[k][i].supp_cnt
        end
    end
    cnt
end

# This function performs a sequence extension for patterns in
# a prefix tree. In essence, we take a single string `s` and
# append it as an array in the sequence pattern `seq`.
sequence_extension(seq::Array{Array{String,1},1}, s::String) = [seq; [[s]]]

s1 = [["A"], ["B", "C"]]
str = "D"
sequence_extension(s1, str)

# Given a sequence pattern in the form of a nested array, `seq`, and
# a single string, `s`, this function takes `s` and appends it to
# the last array in the nested array `seq`. Note that this function
# is a bit messy looking b/c I couldn't get type-inference to work
# without breaking the steps up a bit. So it goes.
function item_extension(seq::Array{Array{String,1},1}, s::String)
    old_last_arr = seq[end]
    new_last_arr::Array{String,1} = [old_last_arr; s]

    child_seq = [seq[1:end-1]; [sort!(new_last_arr)]]
    return child_seq
end

s1 = [["A"], ["B", "C"], ["D"]]
str = "E"
item_extension(s1, str)

# Given two pattern strings such as "{A,B} -> {C}" and
# "{A,B} -> {C} -> {D,E}", where one is a subset of the
# other, this function will extract the postfix from
# the second string, `p2`.
function extract_postfix(p1::String, p2::String)
    last_idx = length(p1)
    out = p2[last_idx+5:end]
    out
end

# extract_postfix("{A,B} -> {C}", "{A,B} -> {C} -> {D,E}")

function postfix(root::Array{Array{String,1},1}, descendant::Array{Array{String,1},1})
    post = Array{Array{String,1},1}(0)
    n = length(root)
    m = length(descendant)
    i = 1

    while i ≤ n
        if root[i] == descendant[i]
            i += 1
        else
            error("Prefix of root doesn't matach descendant")
        end
    end
    for j = i:m
        push!(post, descendant[j])
    end
    post
end

# a = [["a"], ["b"]]
# b = [["a"], ["b"], ["cd"], ["e"]]
# postfix(a, b)

# NOTE: The functions below are used to convert our output to
# match R's returned strings (e.g., "<{A}, {B}> => <{C}>").

function as_set_string(vect::Vector)
    out = "{"
    n = length(vect)
    for (i, x) in enumerate(vect)
        out *= x
        if i ≠ n
            out *= ","
        end
        if i == n
            out *= "}"
        end
    end
    out
end

function as_r_string(r::SeqRule)
    out = "<"
    n = length(r.prefix)
    for (i, timepoint) in enumerate(r.prefix)
        out *= as_set_string(timepoint)
        if i ≠ n
            out *= ","
        end
        if i == n
            out *= ">"
        end
    end
    out *= " => <"

    m = length(r.postfix)
    for (i, timepoint) in enumerate(r.postfix)
        out *= as_set_string(timepoint)
        if i ≠ m
            out *= ","
        end
        if i == m
            out *= ">"
        end
    end
    out
end

function as_r_string(seq::Array{Array{String,1},1})
    out = "<"
    n = length(seq)
    for (i, timepoint) in enumerate(seq)
        out *= as_set_string(timepoint)
        if i ≠ n
            out *= ","
        end
        if i == n
            out *= ">"
        end
    end
    out
end

function rules_to_dataframe(rules::Array{SeqRule,1})
    df = DataFrame()
    n = length(rules)

    df[:rules] = Array{String,1}(n)
    for i = 1:n
        df[i, :rules] = as_r_string(rules[i])
    end
    df
end


text:
# Use Recursion to find the first callback for type-stability

# Base Case: Only one callback
function find_first_continuous_callback(integrator,callback::ContinuousCallback)
  (find_callback_time(integrator,callback)...,1,1)
end

# Starting Case: Compute on the first callback
function find_first_continuous_callback(integrator,callback::ContinuousCallback,args...)
  find_first_continuous_callback(integrator,find_callback_time(integrator,callback)...,1,1,args...)
end

function find_first_continuous_callback(integrator,tmin::Number,upcrossing::Float64,idx::Int,counter::Int,callback2)
  counter += 1 # counter is idx for callback2.
  tmin2,upcrossing2 = find_callback_time(integrator,callback2)

  if (tmin2 < tmin && tmin2 != zero(typeof(tmin))) || tmin == zero(typeof(tmin))
    return tmin2,upcrossing,counter,counter
  else
    return tmin,upcrossing,idx,counter
  end
end

function find_first_continuous_callback(integrator,tmin::Number,upcrossing::Float64,idx::Int,counter::Int,callback2,args...)
  find_first_continuous_callback(integrator,find_first_continuous_callback(integrator,tmin,upcrossing,idx,counter,callback2)...,args...)
end

@inline function determine_event_occurance(integrator,callback)
  event_occurred = false
  if callback.interp_points!=0
    ode_addsteps!(integrator)
  end
  Θs = linspace(typeof(integrator.t)(0),typeof(integrator.t)(1),callback.interp_points)
  interp_index = 0
  # Check if the event occured
  if typeof(callback.idxs) <: Void
    previous_condition = callback.condition(integrator.tprev,integrator.uprev,integrator)
  else
    previous_condition = callback.condition(integrator.tprev,integrator.uprev[callback.idxs],integrator)
  end
  if isapprox(previous_condition,0,rtol=callback.reltol,atol=callback.abstol)
    prev_sign = 0.0
  else
    prev_sign = sign(previous_condition)
  end
  prev_sign_index = 1
  if typeof(callback.idxs) <: Void
    next_sign = sign(callback.condition(integrator.tprev+integrator.dt,integrator.u,integrator))
  else
    next_sign = sign(callback.condition(integrator.tprev+integrator.dt,integrator.u[callback.idxs],integrator))
  end
  if ((prev_sign<0 && !(typeof(callback.affect!)<:Void)) || (prev_sign>0 && !(typeof(callback.affect_neg!)<:Void))) && prev_sign*next_sign<0
    event_occurred = true
    interp_index = callback.interp_points
  elseif callback.interp_points!=0  && !(typeof(integrator.alg) <: Discrete)# Use the interpolants for safety checking
    if typeof(integrator.cache) <: OrdinaryDiffEqMutableCache
      if typeof(callback.idxs) <: Void
        idxs_internal = eachindex(integrator.cache.tmp)
        tmp = integrator.cache.tmp
      elseif typeof(callback.idxs) <: Number
        idxs_internal = callback.idxs
      else
        idxs_internal = callback.idxs
        tmp = @view integrator.cache.tmp[callback.idxs]
      end
    else
      idxs_internal = callback.idxs
    end
    for i in 2:length(Θs)-1
      if typeof(integrator.cache) <: OrdinaryDiffEqMutableCache && !(typeof(callback.idxs) <: Number)
        ode_interpolant!(tmp,Θs[i],integrator,idxs_internal,Val{0})
      else
        tmp = ode_interpolant(Θs[i],integrator,idxs_internal,Val{0})
      end
      new_sign = callback.condition(integrator.tprev+integrator.dt*Θs[i],tmp,integrator)
      if prev_sign == 0
        prev_sign = new_sign
        prev_sign_index = i
      end
      if ((prev_sign<0 && !(typeof(callback.affect!)<:Void)) || (prev_sign>0 && !(typeof(callback.affect_neg!)<:Void))) && prev_sign*new_sign<0
        event_occurred = true
        interp_index = i
        break
      end
    end
  end
  event_occurred,interp_index,Θs,prev_sign,prev_sign_index
end

function find_callback_time(integrator,callback)
  event_occurred,interp_index,Θs,prev_sign,prev_sign_index = determine_event_occurance(integrator,callback)
  if event_occurred
    if typeof(callback.condition) <: Void
      new_t = zero(typeof(integrator.t))
    else
      if callback.interp_points!=0
        top_Θ = Θs[interp_index] # Top at the smallest
      else
        top_Θ = typeof(integrator.t)(1)
      end
      if callback.rootfind && !(typeof(integrator.alg) <: Discrete)
        if typeof(integrator.cache) <: OrdinaryDiffEqMutableCache
          if typeof(callback.idxs) <: Void
            idxs_internal = eachindex(integrator.cache.tmp)
            tmp = integrator.cache.tmp
          elseif typeof(callback.idxs) <: Number
            idxs_internal = callback.idxs
          else
            idxs_internal = callback.idxs
            tmp = @view integrator.cache.tmp[callback.idxs]
          end
        else
          idxs_internal = callback.idxs
        end
        find_zero = (Θ) -> begin
          if typeof(integrator.cache) <: OrdinaryDiffEqMutableCache && !(typeof(callback.idxs) <: Number)
            ode_interpolant!(tmp,Θ,integrator,idxs_internal,Val{0})
          else
            tmp = ode_interpolant(Θ,integrator,idxs_internal,Val{0})
          end
          callback.condition(integrator.tprev+Θ*integrator.dt,tmp,integrator)
        end
        Θ = prevfloat(prevfloat(fzero(find_zero,Θs[prev_sign_index],top_Θ)))
        # 2 prevfloat guerentees that the new time is either 1 or 2 floating point
        # numbers just before the event, but not after. If there's a barrier
        # which is never supposed to be crossed, then this will ensure that
        # The item never leaves the domain. Otherwise Roots.jl can return
        # a float which is slightly after, making it out of the domain, causing
        # havoc.
        new_t = integrator.dt*Θ
      elseif interp_index != callback.interp_points && !(typeof(integrator.alg) <: Discrete)
        new_t = integrator.dt*Θs[interp_index]
      else
        # If no solve and no interpolants, just use endpoint
        new_t = integrator.dt
      end
    end
  else
    new_t = zero(typeof(integrator.t))
  end
  new_t,prev_sign
end

function apply_callback!(integrator,callback::ContinuousCallback,cb_time,prev_sign)
  if cb_time != zero(typeof(integrator.t))
    change_t_via_interpolation!(integrator,integrator.tprev+cb_time)
  end

  @inbounds if callback.save_positions[1]
    savevalues!(integrator)
  end

  integrator.u_modified = true

  if prev_sign < 0
    if typeof(callback.affect!) <: Void
      integrator.u_modified = false
    else
      callback.affect!(integrator)
    end
  elseif prev_sign > 0
    if typeof(callback.affect_neg!) <: Void
      integrator.u_modified = false
    else
      callback.affect_neg!(integrator)
    end
  end

  if integrator.u_modified
    reeval_internals_due_to_modification!(integrator)
    @inbounds if callback.save_positions[2]
      savevalues!(integrator)
    end
    return true
  end
  false
end

#Base Case: Just one
@inline function apply_discrete_callback!(integrator::ODEIntegrator,callback::DiscreteCallback)
  @inbounds if callback.save_positions[1]
    savevalues!(integrator)
  end

  integrator.u_modified = true
  if callback.condition(integrator.tprev+integrator.dt,integrator.u,integrator)
    callback.affect!(integrator)
    @inbounds if callback.save_positions[2]
      savevalues!(integrator)
    end
  end
  integrator.u_modified
end

#Starting: Get bool from first and do next
@inline function apply_discrete_callback!(integrator::ODEIntegrator,callback::DiscreteCallback,args...)
  apply_discrete_callback!(integrator,apply_discrete_callback!(integrator,callback),args...)
end

@inline function apply_discrete_callback!(integrator::ODEIntegrator,discrete_modified::Bool,callback::DiscreteCallback,args...)
  bool = apply_discrete_callback!(integrator,apply_discrete_callback!(integrator,callback),args...)
  discrete_modified || bool
end

@inline function apply_discrete_callback!(integrator::ODEIntegrator,discrete_modified::Bool,callback::DiscreteCallback)
  bool = apply_discrete_callback!(integrator,callback)
  discrete_modified || bool
end


text:
function sxt_correct_level1(level1dir::String)

  cd(level1dir * "/sxt")
  l1orbitdatadir = readdir("./")
  print(l1orbitdatadir)
  print("\n\n")
  for i=1:length(l1orbitdatadir)
    cd(l1orbitdatadir[i] * "/aux/aux2")
      lbtfiles = filter(x -> endswith(x,".lbt"), readdir("./"))
      for j=1:length(lbtfiles)
        print("Orbit ")
        print(l1orbitdatadir[i])
        print(": ")
        sxt_correct_level1lbt(lbtfiles[j])
      end
      cd("../../..")
    end
    cd("../..")
    return
  end

max_stars_repo_name: gulabd/SXTMerger

max_issues_repo_name: gulabd/SXTMerger


text:
# utility methods

isinitialized(obj::Any) = isfilled(obj)

function copy!(to::T, from::T) where T <: ProtoType
    clear(to)
    for name in propertynames(from)
        hasproperty(from, name) && setproperty!(to, name, getproperty(from, name))
    end
    nothing
end

function deepcopy(from::T) where T <: ProtoType
    to = T()
    for name in propertynames(from)
        hasproperty(from, name) && setproperty!(to, name, deepcopy(getproperty(from, name)))
    end
    to
end

# hash method that considers fill status of types
function hash(v::T) where {T<:ProtoType}
    h = 0
    for name in propertynames(v)
        hasproperty(v, name) && (h += hash(getproperty(v, name)))
    end
    hash(h)
end

# equality method that considers fill status of types
function ==(v1::T, v2::T) where {T<:ProtoType}
    for name in propertynames(v1)
        (hasproperty(v1, name) === hasproperty(v2, name)) || (return false)
        if hasproperty(v1, name)
            (getproperty(v1, name) == getproperty(v2, name)) || (return false)
        end
    end
    true
end

# isequal method that considers fill status of types
function isequal(v1::T, v2::T) where {T<:ProtoType}
    for name in propertynames(v1)
        (hasproperty(v1, name) === hasproperty(v2, name)) || (return false)
        if hasproperty(v1, name)
            isequal(getproperty(v1, name), getproperty(v2, name)) || (return false)
        end
    end
    true
end

function enumstr(enumname::T, t::Int32) where {T <: NamedTuple}
    for name in propertynames(enumname)
        (getproperty(enumname, name) == t) && (return string(name))
    end
    error(string("Invalid enum value ", t))
end

import protoc_jll
function protoc(args=``)
    plugin_dir = abspath(joinpath(dirname(pathof(ProtoBuf)), "..", "plugin"))
    plugin = joinpath(plugin_dir, Sys.iswindows() ? "protoc-gen-julia_win.bat" : "protoc-gen-julia")

    protoc_jll.protoc() do protoc_path
        ENV′ = copy(ENV)
        ENV′["PATH"] = string(plugin_dir, Sys.iswindows() ? ";" : ":", ENV′["PATH"])
        ENV′["JULIA"] = joinpath(Sys.BINDIR, Base.julia_exename())
        run(setenv(`$protoc_path --plugin=protoc-gen-julia=$plugin $args`, ENV′))
    end
end


text:
module MCMC

end


text:
"""
`Basics.diagonalize()`  ... diagonalizes matrices of various kinds and by different methods

  + `("matrix: Julia, eigfact", matrix::Array{Float64,2})`
    ... to apply the standard eigfact() method from Julia for a quadratic, full matrix; nothing about the symmetry of
        the matrix is assumed here; an eigen::JAC.Eigen is returned.
"""
function Basics.diagonalize(sa::String, matrix::Array{Float64,2})
    if       sa == "matrix: Julia, eigfact"
        # Use the standard eigfact() method from Julia for a quadratic, full matrix
        wa = eigen( matrix )
        ##x println("diagonalize-ab: values  = ", wa[:values] )
        ##x println("diagonalize-ac: vectors = ", wa[:vectors] )
        vectors = Vector{Float64}[];    wb = wa.vectors;    d = size(wb)[1]
        for  i = 0:d-1    push!(vectors, wb[i*d+1:i*d+d])    end
        wc = Basics.Eigen( wa.values, vectors )
        return( wc )
    elseif   sa == "matrix: Julia method B"     error("Not yet implemented")
    else     error("Unsupported keystring = $sa")
    end
end

"""
  + `("generalized eigenvalues: Julia, eigfact", matrixA::Array{Float64,2}, matrixB::Array{Float64,2})`
    ... to apply the standard eigfact() method from Julia for a generalized eigenvalue problem with two quadratic
        (full) matrices; nothing about the symmetry of the matrix is assumed here; an eigen::JAC.Eigen is returned.
"""
function Basics.diagonalize(sa::String, matrixA::Array{Float64,2}, matrixB::Array{Float64,2})
    if       sa == "generalized eigenvalues: Julia, eigfact"
        # Use the standard eigfact() method from Julia for two quadratic, full matrices
        wa = eigen( matrixA, matrixB )
        ##x println("diagonalize-ab: values  = ", wa[:values] )
        ##x println("diagonalize-ac: vectors = ", wa[:vectors] )
        ##x vectors = Vector{Float64}[];    wb = wa[:vectors];    d = size(wb)[1]
        vectors = Vector{Float64}[];    wb = wa.vectors;    d = size(wb)[1]
        # for  i = 0:d-1    push!(vectors, real(wb[i*d+1:i*d+d]) )    end
        for  i = 0:d-1    push!(vectors, wb[i*d+1:i*d+d] )    end
        ##x wc = JAC.Eigen( wa[:values], vectors )
        # wc = JAC.Eigen( real(wa.values), vectors )
        wc = Basics.Eigen( wa.values, vectors )
        return( wc )
    else     error("Unsupported keystring = $sa")
    end
end


text:
using Base: setindex

include("opticdef.jl")

function (o::AbstractOptic)(f::Function, a)
    m, b = left(o, a)
    b′ = f(b)
    right(o, m, b′)
end

function (o::AbstractOptic)(a)
    m, b = left(o, a)
    b, b′->right(o, m, b′)
end


text:
using ADFPEPS
using ADFPEPS:Nup,Ndn
using Test
using ITensors
using OMEinsum
using LinearAlgebra

@testset "Hubbard" begin
    @test Hubbard(1.0,1.0,1.0) isa HamiltonianModel
    model = Hubbard(rand(),rand(),rand())
    @test hamiltonian(model) == hamiltonian(model)'
    @test all(diag(hamiltonian(Hubbard(1.0,0.0,0.0))) .== 0)
    @test diag(hamiltonian(Hubbard(1.0,4.0,0.0))) == 4*1/4* [0.0,0.0,0.0,1.0,
                                                             0.0,0.0,0.0,1.0,
                                                             0.0,0.0,0.0,1.0,
                                                             1.0,1.0,1.0,2.0]

    @test diag(hamiltonian(Hubbard(1.0,0.0,4.0))) == -4*1/4* [0.0,1.0,1.0,2.0,
                                                              1.0,2.0,2.0,3.0,
                                                              1.0,2.0,2.0,3.0,
                                                              2.0,3.0,3.0,4.0]

    @test diag(hamiltonian(Hubbard(1.0,4.0,2.0)) + 4*1/8*I(16)) == 4*1/8*[1.0, 0.0, 0.0,1.0,
                                                                          0.0,-1.0,-1.0,0.0,
                                                                          0.0,-1.0,-1.0,0.0,
                                                                          1.0, 0.0, 0.0,1.0]
    println(eigen((hamiltonian(Hubbard(1.0,0.0,0.0)))).values)
end

@testset "hop_pair" begin
    @test hop_pair(1.0,1.0) isa HamiltonianModel
    model = hop_pair(rand(),rand())
    @test hamiltonian(model) == hamiltonian(model)'
end

@testset "Hubbard_hand" begin
    H = Hubbard_hand(Hubbard(rand(),rand(),rand()))
    @test H == H'
    @test all(diag(Hubbard_hand(Hubbard(1.0,0.0,0.0))) .== 0)
    @test diag(Hubbard_hand(Hubbard(1.0,4.0,0.0))) == 4*1/4* [0.0,0.0,0.0,1.0,
                                                     0.0,0.0,0.0,1.0,
                                                     0.0,0.0,0.0,1.0,
                                                     1.0,1.0,1.0,2.0]

    @test diag(Hubbard_hand(Hubbard(1.0,0.0,4.0))) == -4*1/4* [0.0,1.0,1.0,2.0,
                                                              1.0,2.0,2.0,3.0,
                                                              1.0,2.0,2.0,3.0,
                                                              2.0,3.0,3.0,4.0]

    @test diag(Hubbard_hand(Hubbard(1.0,4.0,2.0)) + 4*1/8*I(16)) == 4*1/8*[1.0, 0.0, 0.0,1.0,
                                                                          0.0,-1.0,-1.0,0.0,
                                                                          0.0,-1.0,-1.0,0.0,
                                                                          1.0, 0.0, 0.0,1.0]
end

@testset "hop_pair_hand" begin
    H = hop_pair_hand(rand(),rand())
    @test H == H'
end

@testset "observable" begin
    @test hamiltonian(Occupation()) == [0.0 0.0 0.0 0.0; 0.0 1.0 0.0 0.0; 0.0 0.0 1.0 0.0; 0.0 0.0 0.0 2.0]
    @test hamiltonian(DoubleOccupation()) == [0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 1.0]
end

@testset "find U" begin
    # S1 = Hubbard_hand(Hubbard(1.0,0.0,0.0))
    S2 = hamiltonian(Hubbard(1.0,0.0,0.0))
    S3 = hamiltonian(THubbard(1.0,0.0,0.0))
    # for i = 1:16
    #     println(S3[i,:])
    # end
    # U1 = eigen(S1).vectors
    # U2 = eigen(S2).vectors
    # U3 = eigen(S3).vectors
    # U12 = U1*U2'
    # U32 = U3*U2'
    # # U = diagm(ones(16))
    # # for i in [7,14,12]
    # #     U[i,i] = -1.0
    # # end
    U = [1 0 0 0;0 0 1 0;0 -1 0 0;0 0 0 1]
    U32 = reshape(ein"ab,cd -> acbd"(U,I(4)),16,16)
    @test U32'*U32 ≈ I(16)
    # @test U32'≈ U32
    @test S2 ≈ U32'*S3*U32
    # # U32 = map(x->abs(x) < 1e-10 ? 0.0 : x,U32)
    # # @show U
end

@testset "find all -" begin
    for i in [-1.0,1.0], j in [-1.0,1.0], k in [-1.0,1.0], l in [-1.0,1.0]
        H = hamiltonian(THubbard([i,j,k,l],0.0,0.0))
        @show i,j,k,l,sum(H)
    end
end


text:
#=
test_complex_number:
- Julia version: 1.5.0
- Author: shisa
- Date: 2020-08-07
=#

module TestCompNum
    # packages
    using Test

    # external modules
    include("complex_number.jl")

    # method
    function test()
        @testset "CompNum" begin
            @test_nowarn CompNum.main()
        end
    end
end

if abspath(PROGRAM_FILE) == @__FILE__
    using .TestCompNum
    TestCompNum.test()
end

max_stars_repo_name: ShisatoYano/JuliaPractice

max_issues_repo_name: ShisatoYano/JuliaPractice

max_forks_repo_name: ShisatoYano/JuliaPractice


text:
lower_bound(::Type{MV}, Rₙ::AbstractVector{T},
            Rₙₖ::AbstractMatrix{T}) where {T<:AbstractFloat, MV<:MultivariateNormal} = sum(Rₙ)

"Gaussian Mixture Model"
function fit_mm(::Type{MV}, X::AbstractMatrix{T}, k::Int;
                tol::Real=1e-5,             # convergence tolerance
                maxiter::Integer=100,       # number of iterations
                μs::Union{AbstractArray{T,2}, Nothing} = nothing,
                Σs::Union{AbstractArray{T,3}, Nothing} = nothing,
                homoscedastic::Bool=false,
                init::Symbol=:kmeans,
                logprob::Bool=true,
                covreg::Real=1e-6,
                aitken::Bool=false
            ) where {T<:AbstractFloat, MV<:MultivariateNormal}

    d, n = size(X)
    Rₙ = zeros(T, n)
    Σ  = zeros(T, d, d)
    Z = similar(X)

    # initialize parameters
    πₖ, μₖ, Σₖ, Rₙₖ = initialize(MV, X, k, init=init)
    μs !== nothing && copyto!(μₖ, μs)
    Σs !== nothing && copyto!(Σₖ, Σs)
    Tmpₙ, TmpC = auxiliary(MV, X, k)

    ℒ = ℒ′ₐ = ℒₐ = ℒ′′ = ℒ′ = Δℒ = typemin(T)
    for itr in 1:maxiter

        # E Step: Calculate posterior probability
        #   Rₙₖ = E[ωₖ|x] = p(ωₖ=1|x) ∝ πₖ⋅p(x|ωₖ) = πₖ⋅(√(2π)^(-d/2)*|Σₖ⁻¹|)⋅exp(-0.5⋅(x-μₖ)ᵀΣₖ⁻¹(x-μₖ))
        # where ωₖ is the mixture indicator variable, s.t. ωₖ = 1 when the data point was generated by mixture ωₖ
        for j in 1:k
            # calculate responsibilities
            μ = μₖ[:,j]
            Σ = Σₖ[:,:,j]
            R = view(Rₙₖ,:,j)
            if logprob
                F = precision(MV, Σ)
                # logpdf!(R, μ, X, Hermitian(Σ), Z)
                logpdf!(R, X, μ, F, Z)
                R .+= log(πₖ[j])
            else
                pdf!(R, X, μ, Hermitian(Σ), Z)
                R .*= πₖ[j]
            end
        end
        # Calculate (log) responsibilities
        if logprob
            logsumexp!(Rₙ, Rₙₖ, Tmpₙ)
        else
            Rₙₖ[Rₙₖ .< eps(T)] .= eps(T)
            sum!(Rₙ, Rₙₖ)
            Rₙₖ ./= Rₙ
        end

        # Calculate lower bound value on the complete log-likelihood
        ℒ′′ = ℒ′
        ℒ′ = ℒ
        ℒ = lower_bound(MV, (logprob ? Rₙ : cliplog.(Rₙ)), Rₙₖ)

        # M Step: Calculate parameters
        stats!(πₖ, μₖ, X, Rₙₖ)
        covariances!(Σₖ, πₖ, μₖ, X, Rₙₖ, MV, covreg=covreg, aux=TmpC)
        πₖ ./= n

        if homoscedastic
            Σₖ[:,:,1] .*= πₖ[1]
            for j in 2:k
                Σⱼ = view(Σₖ,:,:,j)
                Σⱼ .*= πₖ[j]
                Σₖ[:,:,1] .+= Σⱼ
            end
            for j in 2:k
                Σₖ[:,:,j] .= copy(Σₖ[:,:,1])
            end
        end

        # Check convergence
        Δℒ = ℒ - ℒ′
        # aitken accelerated criterion
        if aitken
            a = Δℒ/(ℒ′-ℒ′′)
            ℒ′ₐ = ℒₐ
            ℒₐ = ℒ′+Δℒ/(1-a)
            Δℒ=ℒ′ₐ-ℒₐ
        end
        @debug "Likelihood" itr ℒ Δℒ
        abs(Δℒ) < tol && break
    end

    if Δℒ > tol
        @warn "No convergence" Δℒ=Δℒ tol=tol
    end

    return MixtureModel([distribution(MV, μₖ, Σₖ, j) for j in 1:k], πₖ)
end

distribution(::Type{FullNormal}, μₖ, Σₖ, j) = MvNormal(μₖ[:,j], Symmetric(Σₖ[:,:,j]))
distribution(::Type{DiagNormal}, μₖ, Σₖ, j) = MvNormal(μₖ[:,j], Diagonal(sqrt.(Σₖ[:,1,j])))
distribution(::Type{IsoNormal}, μₖ, Σₖ, j) = MvNormal(μₖ[:,j], sqrt(Σₖ[1,1,j]))


text:
abstract type CommandBuffer <: LavaAbstraction end

vk_handle_type(::Type{<:CommandBuffer}) = Vk.CommandBuffer

struct SimpleCommandBuffer <: CommandBuffer
    handle::Vk.CommandBuffer
    queue_family_index::Int
end

function Vk.CommandBufferSubmitInfoKHR(cb::CommandBuffer)
    Vk.CommandBufferSubmitInfoKHR(C_NULL, cb, 1)
end

start_recording(cb::SimpleCommandBuffer) = unwrap(Vk.begin_command_buffer(cb, Vk.CommandBufferBeginInfo(flags = Vk.COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)))
end_recording(cb) = unwrap(Vk.end_command_buffer(cb))

struct CommandPools
    device::Vk.Device
    available::Dictionary{Int,Vk.CommandPool}
end

CommandPools(device) = CommandPools(device, Dictionary())

function request_pool!(pools::CommandPools, queue_family_index)
    haskey(pools.available, queue_family_index) && return pools.available[queue_family_index]
    pool = Vk.CommandPool(pools.device, queue_family_index)
    insert!(pools.available, queue_family_index, pool)
    pool
end


text:
import BasisFunctions: apply_multiple
apply_multiple(A::AbstractMatrix, B::AbstractMatrix) = A*B

regularization_threshold(::Type{T}) where {T} = 10^(T(4)/5*log10(eps(T)))
regularization_threshold(::Type{Complex{T}}) where {T} = regularization_threshold(T)

function randomizedsvd(A; threshold = regularization_threshold(eltype(A)), verbose = false, rankestimate = 16, growth_factor = 2, maxiter = Inf)
    verbose && println("Computing randomized SVD of $(typeof(A))")
    T = eltype(A)

    R = min(rankestimate, size(A,2))
    W = rand(T, size(A,2), R)
    C = apply_multiple(A, W)
    sigma = svdvals(C)[end]

    iter = 0
    while (sigma > threshold) && (R < size(A,2)) && (iter < maxiter)
        verbose && println("Smallest singular value : $sigma\t Threshold : $threshold")
        verbose && println("SVD truncated at R = ", R, " out of ", size(A,2))
        R1 = R
        R = min(round(Int,growth_factor*R), size(A,2))
        W_extra = rand(T, size(A,2), R-R1)
        C_extra = apply_multiple(A, W_extra)
        W = [W W_extra]
        C = [C C_extra]
        sigma = svdvals(C)[end]
        iter += 1
    end
    if iter == maxiter
        @warn("Maximum number of iteration reached in randomizedsvd")
    end
    USV = svd(C, full=false)
    U = USV.U
    S = USV.S
    Vt = USV.Vt
    rank = findlast(S .> threshold)
    if rank == nothing
        verbose && println("No singular values larger than $threshold found")
        rank = 1
    end
    verbose && println("Smallest singular value : $(S[rank])\t Threshold : $threshold")
    verbose && println("Done: SVD truncated with rank ", rank, " out of ",size(A,2))
    (W, U[:,1:rank], S[1:rank], Vt[1:rank,:])
end

function randomizedqr(A; threshold = regularization_threshold(eltype(A)), verbose = false, rankestimate = 16, growth_factor = 2, maxiter = 8)
    verbose && println("Computing randomized QR of $(typeof(A))")
    T = eltype(A)

    R = min(rankestimate, size(A,2))
    W = rand(T, size(A,2), R)
    C = apply_multiple(A, W)
    if VERSION ≥ v"1.7-"
        QR = qr(C, ColumnNorm())
    else
        QR = qr(C, Val(true))
    end
    sigma = QR.R[end,end]

    iter = 0
    while (sigma > threshold) && (R < size(A,2)) && (iter < maxiter)
        verbose && println("Smallest diagonal entry of R: $sigma\t Threshold : $threshold")
        verbose && println("QR truncated at R = ", R, " out of ", size(A,2))
        R1 = R
        R = min(round(Int,growth_factor*R), size(A,2))
        W_extra = rand(T, size(A,2), R-R1)
        C_extra = apply_multiple(A, W_extra)
        W = [W W_extra]
        C = [C C_extra]
        QR = qr(C)
        sigma = QR.R[end,end]
        iter += 1
    end
    if iter == maxiter
        @warn("Maximum number of iteration reached in randomizedqr")
    end
    QR = qr(C, full=false)
    rank = findlast(diag(R) .> threshold)
    if rank == nothing
        verbose && println("No diagonal entry larger than $threshold found")
        rank = 1
    end
    verbose && println("Smallest diagonal entry : $(S[rank])\t Threshold : $threshold")
    verbose && println("Done: QR computed of size $R with numerical rank $rank out of $(size(A,2))")
    (W, Q)
end


text:
__precompile__()

module Suppressor

export @suppress, @suppress_out, @suppress_err
export @capture_out, @capture_err
export @color_output

"""
    @suppress expr

Suppress the `stdout` and `stderr` streams for the given expression.
"""
macro suppress(block)
    quote
        if ccall(:jl_generating_output, Cint, ()) == 0
            original_stdout = stdout
            out_rd, out_wr = redirect_stdout()
            out_reader = @async read(out_rd, String)

            original_stderr = stderr
            err_rd, err_wr = redirect_stderr()
            err_reader = @async read(err_rd, String)

            # approach adapted from https://github.com/JuliaLang/IJulia.jl/pull/667/files
            logstate = Base.CoreLogging._global_logstate
            logger = logstate.logger
            if logger.stream == original_stderr
                new_logstate = Base.CoreLogging.LogState(typeof(logger)(err_wr, logger.min_level))
                Core.eval(Base.CoreLogging, Expr(:(=), :(_global_logstate), new_logstate))
            end
        end

        try
            $(esc(block))
        finally
            if ccall(:jl_generating_output, Cint, ()) == 0
                redirect_stdout(original_stdout)
                close(out_wr)

                redirect_stderr(original_stderr)
                close(err_wr)

                if logger.stream == stderr
                    Core.eval(Base.CoreLogging, Expr(:(=), :(_global_logstate), logstate))
                end
            end
        end
    end
end

"""
    @suppress_out expr

Suppress the `stdout` stream for the given expression.
"""
macro suppress_out(block)
    quote
        if ccall(:jl_generating_output, Cint, ()) == 0
            original_stdout = stdout
            out_rd, out_wr = redirect_stdout()
            out_reader = @async read(out_rd, String)
        end

        try
            $(esc(block))
        finally
            if ccall(:jl_generating_output, Cint, ()) == 0
                redirect_stdout(original_stdout)
                close(out_wr)
            end
        end
    end
end

"""
    @suppress_err expr

Suppress the `stderr` stream for the given expression.
"""
macro suppress_err(block)
    quote
        if ccall(:jl_generating_output, Cint, ()) == 0
            original_stderr = stderr
            err_rd, err_wr = redirect_stderr()
            err_reader = @async read(err_rd, String)

            # approach adapted from https://github.com/JuliaLang/IJulia.jl/pull/667/files
            logstate = Base.CoreLogging._global_logstate
            logger = logstate.logger
            if logger.stream == original_stderr
                new_logstate = Base.CoreLogging.LogState(typeof(logger)(err_wr, logger.min_level))
                Core.eval(Base.CoreLogging, Expr(:(=), :(_global_logstate), new_logstate))
            end
        end

        try
            $(esc(block))
        finally
            if ccall(:jl_generating_output, Cint, ()) == 0
                redirect_stderr(original_stderr)
                close(err_wr)

                if logger.stream == stderr
                    Core.eval(Base.CoreLogging, Expr(:(=), :(_global_logstate), logstate))
                end
            end
        end
    end
end

"""
    @capture_out expr

Capture the `stdout` stream for the given expression.
"""
macro capture_out(block)
    quote
        if ccall(:jl_generating_output, Cint, ()) == 0
            original_stdout = stdout
            out_rd, out_wr = redirect_stdout()
            out_reader = @async read(out_rd, String)
        end

        try
            $(esc(block))
        finally
            if ccall(:jl_generating_output, Cint, ()) == 0
                redirect_stdout(original_stdout)
                close(out_wr)
            end
        end

        if ccall(:jl_generating_output, Cint, ()) == 0
            fetch(out_reader)
        else
            ""
        end
    end
end

"""
    @capture_err expr

Capture the `stderr` stream for the given expression.
"""
macro capture_err(block)
    quote
        if ccall(:jl_generating_output, Cint, ()) == 0
            original_stderr = stderr
            err_rd, err_wr = redirect_stderr()
            err_reader = @async read(err_rd, String)

            # approach adapted from https://github.com/JuliaLang/IJulia.jl/pull/667/files
            logstate = Base.CoreLogging._global_logstate
            logger = logstate.logger
            if logger.stream == original_stderr
                new_logstate = Base.CoreLogging.LogState(typeof(logger)(err_wr, logger.min_level))
                Core.eval(Base.CoreLogging, Expr(:(=), :(_global_logstate), new_logstate))
            end
        end

        try
            $(esc(block))
        finally
            if ccall(:jl_generating_output, Cint, ()) == 0
                redirect_stderr(original_stderr)
                close(err_wr)

                if logger.stream == stderr
                    Core.eval(Base.CoreLogging, Expr(:(=), :(_global_logstate), logstate))
                end
            end
        end

        if ccall(:jl_generating_output, Cint, ()) == 0
            fetch(err_reader)
        else
            ""
        end
    end
end

"""
    @color_output enabled::Bool expr

Enable or disable color printing for the given expression. Often useful in
combination with the `@capture_*` macros:

## Example

@color_output false begin
    output = @capture_err begin
        @warn "should get captured, not printed"
    end
end
@test output == "WARNING: should get captured, not printed\n"
"""
macro color_output(enabled::Bool, block)
    quote
        prev_color = Base.have_color
        Core.eval(Base, :(have_color = $$enabled))
        local retval
        try
            retval = $(esc(block))
        finally
            Core.eval(Base, Expr(:(=), :have_color, prev_color))
        end

        retval
    end
end

end    # module


text:
# test_extensions.jl

function test_extensions()
    @testset "$(rpad("Periodic extension",80))" begin
        test_periodic_extensions() end
    @testset "$(rpad("Zero padding",80))" begin
        test_zeropadding_extensions() end
    @testset "$(rpad("Constant padding",80))" begin
        test_constantpadding_extensions() end
    @testset "$(rpad("Symmetric extension",80))" begin
        test_symmetric_extensions() end
end

# A collection of vectors of different types for use in the tests
function test_vectors()
    test_vectors = Array(Any, 0)
    # A regular array
    push!(test_vectors, [1,2,3])
    push!(test_vectors, [1.0+1.0im, 2.0+3.0im, 4.2-2im])
    # A LinSpace object
    push!(test_vectors, [1,2,3])
    push!(test_vectors, OffsetArray([1,2,3,4,5], -1:3))
    test_vectors
end

function test_periodic_extensions()
    vectors = test_vectors()
    for vector in vectors
        test_periodic_extension(vector)
    end
end

function test_periodic_extension(a)
    p = PeriodicSequence(a)

    @test eltype(p) == eltype(a)

    @test !iscompact(p)

    # Equality of the embedded elements
    for i in eachindex(a)
        @test p[i] == a[i]
    end

    firstindex = first(linearindices(a))
    lastindex = last(linearindices(a))
    n = lastindex-firstindex+1
    @test p[firstindex-1] == a[lastindex]
    @test p[firstindex-2] == a[lastindex-1]
    @test p[lastindex+1] == a[firstindex]
    @test p[lastindex+2] == a[firstindex+1]

    large_index = 100
    periodic_index = mod(large_index-firstindex, n) + firstindex
    @test p[large_index] == a[periodic_index]

    # Check time-reversal and (c)transpose
    test_index = firstindex + 1
    @test p'[-test_index] == conj(p[test_index])
    @test p.'[-test_index] == p[test_index]
end

function test_zeropadding_extensions()
    vectors = test_vectors()
    for vector in vectors
        test_zeropadding_extension(vector)
    end
end

function test_zeropadding_extension(a)
    p = ZeroPaddingSequence(a)

    @test eltype(p) == eltype(a)

    @test iscompact(p)

    # Equality of the embedded elements
    for i in eachindex(a)
        @test p[i] == a[i]
    end

    firstindex = first(linearindices(a))
    lastindex = last(linearindices(a))
    n = lastindex-firstindex+1
    @test p[firstindex-1] == 0
    @test p[firstindex-2] == 0
    @test p[lastindex+1] == 0
    @test p[lastindex+2] == 0

    # Check that the zero has the same type as a
    @test eltype(p[firstindex-1]) == eltype(a)

    # Check time-reversal and (c)transpose
    test_index = firstindex + 1
    @test p'[-test_index] == conj(p[test_index])
    @test p.'[-test_index] == p[test_index]
end

function test_constantpadding_extensions()
    vectors = test_vectors()
    for vector in vectors
        test_constantpadding_extension(vector, 1)
    end
end

function test_constantpadding_extension(a, c)
    p = ConstantPaddingSequence(a, c)

    @test eltype(p) == eltype(a)

    @test !iscompact(p)

    # Equality of the embedded elements
    for i in eachindex(a)
        @test p[i] == a[i]
    end

    firstindex = first(linearindices(a))
    lastindex = last(linearindices(a))
    n = lastindex-firstindex+1
    @test p[firstindex-1] == c
    @test p[firstindex-2] == c
    @test p[lastindex+1] == c
    @test p[lastindex+2] == c

    # Check that the constant has the same type as a
    @test eltype(p[firstindex-1]) == eltype(a)

    # Check time-reversal and (c)transpose
    test_index = firstindex + 1
    @test p'[-test_index] == conj(p[test_index])
    @test p.'[-test_index] == p[test_index]
end

function test_symmetric_extensions()
    vectors = test_vectors()
    for vector in vectors
        test_symmetric_extension(vector)
    end
end

function test_symmetric_extension(a)
    p = SymmetricSequence(a)

    @test eltype(p) == eltype(a)

    @test !iscompact(p)

    # Equality of the embedded elements
    for i in eachindex(a)
        @test p[i] == a[i]
    end

    firstindex = first(linearindices(a))
    lastindex = last(linearindices(a))
    n = lastindex-firstindex+1

    p1 = symmetric_extension_wholepoint_even(a)
    @test left_parity(p1) == :even
    @test right_parity(p1) == :even
    @test left_symmetry(p1) == :wp
    @test right_symmetry(p1) == :wp
    @test p1[lastindex+1] == a[lastindex]
    @test p1[lastindex+2] == a[lastindex-1]
    @test p1[firstindex-1] == a[firstindex]
    @test p1[firstindex-2] == a[firstindex+1]
    p2 = symmetric_extension_wholepoint_odd(a)
    @test p2[lastindex+1] == -a[lastindex]
    @test p2[lastindex+2] == -a[lastindex-1]
    @test p2[firstindex-1] == -a[firstindex]
    @test p2[firstindex-2] == -a[firstindex+1]
    p3 = symmetric_extension_halfpoint_even(a)
    @test p3[lastindex+1] == a[lastindex-1]
    @test p3[firstindex-1] == a[firstindex+1]
    p4 = symmetric_extension_halfpoint_odd(a)
    @test p4[lastindex+1] == -a[lastindex-1]
    @test p4[firstindex-1] == -a[firstindex+1]

    # A few mixed cases
    p5 = SymmetricSequence{:wp,:hp,:even,:odd,typeof(a),eltype(a)}(a)
    @test p5[lastindex+1] == -a[lastindex-1]
    @test p5[firstindex-1] == a[firstindex]

    p6 = SymmetricSequence{:hp,:wp,:odd,:even,typeof(a),eltype(a)}(a)
    @test p6[lastindex+1] ==  a[lastindex]
    @test p6[firstindex-1] == -a[firstindex+1]

    # Check time-reversal and (c)transpose
    test_index = firstindex + 1
    @test p'[-test_index] == conj(p[test_index])
    @test p.'[-test_index] == p[test_index]
end


text:
#
# a simple event logger
#

"""
    Logger()

Setup and return a logging variable.
"""
mutable struct Logger <: SEngine
    sim::Union{Clock,Number}
    state::SState
    last::NamedTuple
    ltype::Int64
    lvars::Array{Symbol,1}
    scope::Module
    df::DataFrame

    Logger() = new(0, Undefined(), NamedTuple(), 0, Symbol[], Main, DataFrame())
end

"""
    step!(A::Logger, ::Undefined, σ::Init)

Initialize a logger.
"""
function step!(A::Logger, ::Undefined, σ::Init)
    A.sim = σ.info
    A.state = Empty()
end

"""
    step!(A::Logger, ::Empty, σ::Setup)

Setup a logger with logging variables. They are given by `Setup(vars, scope)`.
"""
function step!(A::Logger, ::Empty, σ::Setup)
    A.lvars = σ.vars
    A.scope = σ.scope
    A.df.time = Float64[]
    for v ∈ A.lvars
        A.df[!, v] = typeof(Core.eval(A.scope, v))[]
    end
    A.state = Idle()
end

"""
    step!(A::Logger, ::Idle, ::Clear)

Clear the last record and the data table of a logger.
"""
function step!(A::Logger, ::Idle, ::Clear)
    A.last = NamedTuple();
    deleterows!(A.df, 1:size(A.df,1))
end

"""
    step!(A::Logger, ::Idle, σ::Log)

Logging event.
"""
function step!(A::Logger, ::Idle, σ::Log)
    time = τ(A.sim)
    val = vcat([time], Array{Any}([Core.eval(A.scope,i) for i in A.lvars]))
    A.last = NamedTuple{Tuple(vcat([:time],A.lvars))}(val)
    if A.ltype == 1
        println(A.last)
    elseif A.ltype == 2
        push!(A.df, [i for i in A.last])
    end
end

"""
    step!(A::Logger, ::Idle, σ::Switch)

Switch the operating mode of a logger by `Switch(to)`.

`to = 0`: no output, `to = 1`: print, `to = 2: store in log table"
"""
function step!(A::Logger, ::Idle, σ::Switch)
    if σ.to ∈ 0:2
        A.ltype = σ.to
    end
end

"""
    switch!(L::Logger, to::Number=0)

Switch the operating mode of a logger.

`to = 0`: no output, `to = 1`: print, `to = 2: store in log table"
"""
switch!(L::Logger, to::Number=0) = step!(L, L.state, Switch(to))

"""
    init!(L::Logger, sim::Clock)

Initialize a Logger.
"""
init!(L::Logger, sim::Clock=Τ) = step!(L, L.state, Init(sim))

"""
    setup!(L::Logger, vars::Array{Symbol})

Setup a logger with logging variables.

# Arguments
- `L::Logger`
- `vars::Array{Symbol}`: An array of symbols, e.g. of global variables
- `scope::Module = Main`: Scope in which to evaluate the variables
"""
setup!(L::Logger, vars::Array{Symbol}; scope::Module = Main) =
        step!(L, L.state, Setup(vars, scope))

"""
    record!(L::Logger)

record the logging variables with the current operating mode.
"""
record!(L::Logger) = step!(L, L.state, Log())

"""
    clear!(L::Logger)

clear the loggers last record and data table.
"""
clear!(L::Logger) = step!(L, L.state, Clear())


text:
# parallel coordinates

#VegaLite
using VegaLite, VegaDatasets

dataset("iris") |>
@vlplot(
    width=600,
    height=300,
    config={
        axisX={domain=false, labelAngle=0, tickColor="#ccc", "title"=nothing},
        view={stroke=nothing},
        style={
            label={baseline="middle", align="right", dx=-5},
            tick={orient="horizontal"}
        }
    },
    transform=[
        { window=[{op="count", as="index" }] },
        {fold=["petalLength", "petalWidth", "sepalLength", "sepalWidth"]},
        {
            joinaggregate=[
                {op="min",field="value",as="min"},
                {op="max",field="value",as="max"}
            ],
            groupby=["key"]
        },
        {
            calculate="(datum.value - datum.min) / (datum.max-datum.min)",
            as="norm_val"
        },
        {
            calculate="(datum.min + datum.max) / 2",
            as="mid"
        },
        {
            calculate="'petalLength: '+datum.petalLength+', '+'petalWidth: '+datum.petalWidth+', sepalLength: '+datum.sepalLength+', '+'sepalWidth: '+datum.sepalWidth",
            as="tt"
        } #How to add a line break?
    ]
) +
@vlplot(
    mark={:rule,color="#ccc"},
    detail={aggregate="count",type="quantitative"},
    x="key:n"
) +
@vlplot(
    mark=:line,
    color={field="species",type="nominal"},
    detail={field="index",type="nominal"},
    opacity={value=0.3},
    x="key:n",
    y={"norm_val:q",axis=nothing},
    tooltip={"tt:n"}
)  +
@vlplot(
    mark={:text,style="label"},
    text={aggregate="max",field="max",type="quantitative"},
    x="key:n",
    y={value=0}
)  +
@vlplot(
    mark={:tick,style="tick",size=8,color="#ccc"},
    x="key:n",
    y={value=0}
)  +
@vlplot(
    mark={:text,style="label"},
    text={aggregate="min",field="mid",type="quantitative"},
    x="key:n",
    y={value=150}
)  +
@vlplot(
    mark={:tick,style="tick",size=8,color="#ccc"},
    x="key:n",
    y={value=150}
)  +
@vlplot(
    mark={:text,style="label"},
    text={aggregate="min",field="min",type="quantitative"},
    x="key:n",
    y={value=300}
)  +
@vlplot(
    mark={:tick,style="tick",size=8,color="#ccc"},
    x="key:n",
    y={value=300}
)

max_stars_repo_name: Ellon-M/visualizations

max_issues_repo_name: Ellon-M/visualizations

max_forks_repo_name: Ellon-M/visualizations