text:
import Dates
import Printf

function read_dcd_meta_info(io::IOStream)::DCDMetaInfo
    unitcell_flag = false # for charmm format

    seekend(io)
    file_size = position(io)
    seekstart(io)

    # read header first block
    skip(io, 4) # skip block size part
    header_sig = Array{Char, 1}(undef, 4)
    for i in 1:4
        header_sig[i] = read(io, Char)
    end
    total_frame_in_header = read(io, Int32)
    first_step = read(io, Int32)
    nstep_save = read(io, Int32)
    total_step = read(io, Int32)
    total_unit = read(io, Int32)
    header_null_4 = Array{Int32, 1}(undef, 4)
    read!(io, header_null_4)
    time_step  = read(io, Float32)
    header_null_9 = Array{Int32, 1}(undef, 9)
    read!(io, header_null_9)
    if header_null_9[1] != 0
        unitcell_flag = true
    end
    version   = read(io, Int32)
    skip(io, 4) # skip block size part

    # read header second block
    skip(io, 4)
    number_of_lines    = read(io, Int32)
    title = []
    for i in 1:number_of_lines
        line = Array{Char, 1}(undef, 80)
        for i in 1:80
            line[i] = read(io, Char)
        end
        push!(title, String(line))
    end
    skip(io, 4) # skip block size part

    # read header third block
    skip(io, 4) # skip block size part
    number_of_atom     = read(io, Int32)
    skip(io, 4) # skip block size part

    header_size = position(io)

    return DCDMetaInfo(file_size, first_step, nstep_save, total_step, total_unit,
                       time_step, unitcell_flag, version, number_of_atom, header_size)
end

"""
    read_dcd(filename::String;
             frame_indices::Union{Vector, OrdinalRange, Colon, Nothing} = nothing,
             step::Union{Int, Nothing} = nothing)
    ::Trajectory

Return Trajectory object which filled `coordinates`, `nframe`, `natom` fields.
If you set `frame_indices`, only specified frame is read.
If you set `step`, every step frame is read.
You can't specify both `frame_indices` and `step` at the same time.
"""
function read_dcd(filename::String;
                  frame_indices::Union{Vector, OrdinalRange, Colon, Nothing} = nothing,
                  step::Union{Int, Nothing} = nothing)::Trajectory
    coordinates_time_series = Matrix{Coordinate{Float32}}(undef, 0, 0)
    target_frame_indices = frame_indices

    open(filename, "r") do io

        dcd_meta::DCDMetaInfo = read_dcd_meta_info(io)
        header_size           = dcd_meta.header_size
        unitcell_flag         = dcd_meta.unitcell_flag
        number_of_atom        = dcd_meta.number_of_atom
        file_size             = dcd_meta.file_size

        # read body block
        seek(io, header_size)
        stepblocksize = (8 + 4 * number_of_atom) * 3
        if unitcell_flag
            stepblocksize += 56 # add unitcell block size (4 + 8 * 6 + 4)
        end
        total_frame = Int32(floor((file_size - header_size) / stepblocksize))
        if frame_indices != nothing && step != nothing
            throw(AssertionError("""
                                 You can't use both frame_indices and step option at the same time.
                                 """))
        elseif frame_indices != nothing
            if typeof(target_frame_indices) == Colon
                target_frame_indices = 1:total_frame
            else
                target_frame_indices = frame_indices
            end
        elseif step != nothing
            target_frame_indices = 1:step:total_frame
        else # both frame_indices and step are nothing
            target_frame_indices = 1:total_frame
        end

        coordinates_time_series =
            Matrix{Coordinate{Float32}}(undef, number_of_atom, length(target_frame_indices))
        output_frame_idx = 1
        for frame_idx in 1:total_frame
            # skip unitcell block
            if unitcell_flag
                skip(io, 56) # skip unitcell block size (4 + 8 * 6 + 4)
            end

            # read x coordinates
            skip(io, 4) # skip block size part
            x_coords = Array{Float32, 1}(undef, number_of_atom)
            read!(io, x_coords)
            skip(io, 4) # skip block size part

            # read y coorinates
            skip(io, 4) # skip block size part
            y_coords = Array{Float32, 1}(undef, number_of_atom)
            read!(io, y_coords)
            skip(io, 4) # skip block size part

            # read z coordinates
            skip(io, 4) # skip block size part
            z_coords = Array{Float32, 1}(undef ,number_of_atom)
            read!(io, z_coords)
            skip(io, 4) # skip block size part

            if frame_idx ∈ target_frame_indices
                atoms = collect(eachrow(hcat(x_coords, y_coords, z_coords)))
                coordinates_time_series[:, output_frame_idx] = Coordinate.(atoms)
                output_frame_idx += 1
            end
        end
    end
    Trajectory(coordinates_time_series)
end

"""
    write_dcd(filename::String, trj::Trajectory;
              save_step::Integer = 1, total_step::Integer = trj.nframe,
              unit_num::Integer  = 1,  time_step::Real = 1.0f0)

Write `coordinates`, `nframe` and `natom` information of `trj` to dcd file, named `filename`.
dcd file contain other information - save interval step, unit(chain) number in the system, total step and time step of original trajectory -, and if you do not specify these parameter, these are filled with default value.
"""
function write_dcd(filename::String, trj::Trajectory;
    save_step::Integer = 1, total_step::Integer = trj.nframe,
    unit_num::Integer = 1, time_step::Real = 1.0f0)

    open(filename, "w") do io

        # write header first block
        write(io, Int32(84))         # block size
        write(io, "CORD")            # signature
        write(io, Int32(trj.nframe)) # number of frames
        write(io, Int32(0))          # first frame index
        write(io, Int32(save_step))  # nstep_save
        write(io, Int32(total_step)) # number of steps
        write(io, Int32(unit_num))   # number of units
        write(io, zeros(Int32, 4))
        write(io, time_step)         # time step
        write(io, zeros(Int32, 9))
        write(io, Int32(24))         # version
        write(io, Int32(84))         # block size

        # write header second block
        write(io, Int32(84))         # block size
        write(io, Int32(1))          # number of lines
        write(io, "Generated by MolHandler.jl ((c) Yutaka Murata 2020) at $(Dates.format(Dates.now(), "yyyy-mm-dd HH:MM:SS"))      ")
        write(io, Int32(84))

        # write header third block
        write(io, Int32(4))
        write(io, Int32(trj.natom))
        write(io, Int32(4))

        # write body block
        coord_part_size = 4 * trj.natom
        each_block_size = 8 + coord_part_size
        for frame_idx in 1:trj.nframe
            # write x coordinates
            write(io, Int32(coord_part_size))
            for atom_idx in 1:trj.natom
                write(io, Float32(trj.coordinates[atom_idx, frame_idx].x))
            end
            write(io, Int32(coord_part_size))

            # write y coordinates
            write(io, Int32(coord_part_size))
            for atom_idx in 1:trj.natom
                write(io, Float32(trj.coordinates[atom_idx, frame_idx].y))
            end
            write(io, Int32(coord_part_size))

            # write z coordinates
            write(io, Int32(coord_part_size))
            for atom_idx in 1:trj.natom
                write(io, Float32(trj.coordinates[atom_idx, frame_idx].z))
            end
            write(io, Int32(coord_part_size))
        end
    end
end

"""
    read_pdb(filename::AbstractString; model = :unspecified)::Trajectory

Return Trajectory object which filled all field.
If you set `:AA` to model field, this function set the mass of particle based on atomname field.
If you set `:CA` to model field, this function set the mass of particcle mase on resname field.
"""
function read_pdb(filename::AbstractString; model = :unspecified)::Trajectory
    lines = open(filename, "r") do io
        readlines(io)
    end

    attributes = Vector{Attribute}()
    coordinates = Vector{Coordinate{Float32}}()
    first_frame = true
    for line in lines
        if occursin(r"^(ATOM|HETATM)", line)
            x_coord  = parse(Float32, line[31:38])
            y_coord  = parse(Float32, line[39:46])
            z_coord  = parse(Float32, line[47:54])
            push!(coordinates, Coordinate(x_coord, y_coord, z_coord))
            if first_frame
                atomid   = parse(Int64, line[7:11])
                atomname = strip(line[13:16])
                resname  = strip(line[18:20])
                resid    = parse(Int64, line[23:26])

                if model == :unspecified
                    push!(attributes, Attribute(resname = resname, resid = resid,
                                                atomname = atomname, atomid = atomid))
                elseif model == :AA
                    push!(attributes, Attribute(resname = resname, resid = resid,
                                                atomname = atomname, atomid = atomid,
                                                mass = atom_mass(atomname)))
                elseif model == :CA
                    push!(attributes, Attribute(resname = resname, resid = resid,
                                               atomname = atomname, atomid = atomid,
                                               mass = residue_mass(resname)))
                end
            end
        elseif occursin(r"^END", line) && first_frame
            first_frame = false
        end
    end

    atom_num  = length(attributes)
    @assert mod(length(coordinates), atom_num) == 0 "All frame should contain same number atoms."
    frame_num = div(length(coordinates), atom_num)
    Trajectory(reshape(coordinates, (atom_num, frame_num)), attributes)
end

"""
    write_pdb(filename::AbstractString, trj::Trajectory;
              tempfactor::Union{RealT, Nothing} = nothing) where RealT <: Real

Write `coordinates`, `resname`, `resid`, `atomname`, `atomid` to `filename` based on `trj`.
If you set Real value to `tempfactor`, all tempfactor will be field with that value.
"""
function write_pdb(filename::AbstractString, trj::Trajectory;
    tempfactor::Union{RealT, Nothing} = nothing,
    conects::Union{Vector{Vector{Int64}}, Nothing} = nothing) where RealT <: Real

    attributes = trj.attributes
    #  check attributes of trj have sufficient information.
    if any(attr->attr.resname==nothing, attributes)
        throw(AssertionError("""
                             There is nothing element in resname field of attribute in trajectory.
                             pdb format need resname for all particle.
                             """))
    elseif any(attr->attr.resid==nothing, attributes)
        throw(AssertionError("""
                             There is nothing element in resid field of attribute in trajectory.
                             pdb format need resid for all particle.
                             """))
    elseif any(attr->attr.atomname==nothing, attributes)
        throw(AssertionError("""
                             There is nothing element in atomname field of attribute in trajectory.
                             pdb format need atomname for all particle.
                             """))
    elseif any(attr->attr.atomid==nothing, attributes)
        throw(AssertionError("""
                             There is nothing element in atomid field of attribute in trajectory.
                             pdb format need atomid for all particle.
                             """))
    end

    open(filename, "w") do io
        # write header
        write(io, "REMARK    Generated by MolHandler.jl ((c) Yutaka Murata 2020) at $(Dates.format(Dates.now(), "yyyy-mm-dd HH:MM:SS"))\n")

        tempfactor_str = "      "
        if tempfactor != nothing
            tempfactor_str = Printf.@sprintf("%6.2f", tempfactor)
        end
        for (step, frame) in enumerate(eachcol(trj.coordinates))
            # write frame info
            write(io, "TITLE     step= $(step)\n")
            for (coordinate, attribute) in zip(frame, attributes)
                atomid_str   = Printf.@sprintf("%5d",   attribute.atomid)
                atomname_str = Printf.@sprintf("%-4s",  attribute.atomname)
                resname_str  = Printf.@sprintf("%3s",   attribute.resname)
                resid_str    = Printf.@sprintf("%4d",   attribute.resid)
                x_coord_str  = Printf.@sprintf("%8.3f", coordinate.x)
                y_coord_str  = Printf.@sprintf("%8.3f", coordinate.y)
                z_coord_str  = Printf.@sprintf("%8.3f", coordinate.z)
                write(io,
                      "ATOM  "*atomid_str*" "*atomname_str*" "*resname_str*"  "*resid_str*"    "*
                      x_coord_str*y_coord_str*z_coord_str*"      "*tempfactor_str*"\n")
            end
            write(io, "TER\n")

            # write CONECT records
            if conects != nothing
                for conect_info in conects
                    conect_str = "CONECT"
                    for idx in conect_info
                        conect_str *= Printf.@sprintf("%5d", idx)
                    end
                    conect_str *= "\n"
                    write(io, conect_str)
                end
            end
            write(io, "END\n")
        end
    end
end

"""
    read_xyz(filename::AbstractString)::Trajectory

Return Trajectory object which filled `coordinates`, `nframe`, `natom` fields.
"""
function read_xyz(filename::AbstractString)::Trajectory

    coordinates_time_series = Matrix{Coordinate{Float32}}(undef, 0, 0)
    attributes              = Vector{Attribute}()

    open(filename, "r") do fp
        # count number of atom
        number_of_atom = parse(Int, readline(fp))
        section_size = number_of_atom + 2

        # read atomname info
        readline(fp) # skip comment line
        for atom_idx in 1:number_of_atom
            atomname = split(readline(fp))[1]
            push!(attributes, Attribute(atomname = atomname))
        end

        # count number of frame
        seekstart(fp)
        line_num = countlines(fp)
        number_of_frame = div(line_num, section_size)

        # read coordinate
        coordinates_time_series =
            Matrix{Coordinate{Float32}}(undef, number_of_atom, number_of_frame)

        seekstart(fp)
        for frame_idx in 1:number_of_frame
            # skip number of atom and comment line
            for i in 1:2
                readline(fp)
            end
            for atom_idx in 1:number_of_atom
                line_elems = split(readline(fp))
                coord = Coordinate(map(c->parse(Float32, c), view(line_elems, 2:4)))
                coordinates_time_series[atom_idx, frame_idx] = coord
            end
        end
    end
    Trajectory(coordinates_time_series, attributes)
end

"""
    write_xyz(filename:AbstractString, trj::Trajectory)

Write `coordinates`, `nframe` and `natom` information of `trj` to xyz file, named `filename`.
"""
function write_xyz(filename::AbstractString, trj::Trajectory)
    atomname_arr = Vector{String}()
    for attr in trj.attributes
        if attr.atomname == nothing
            push!(atomname_arr, "UNK")
        else
            push!(atomname_arr, attr.atomname)
        end
    end

    natom = trj.natom
    open(filename, "w") do io
        for frame_idx in 1:trj.nframe
            write(io, string(natom)*"\n")
            write(io, "Generated by MolHandler.jl ((c) Yutaka Murata 2020)\n")
            for (atomname, coord) in zip(atomname_arr, view(trj.coordinates, :, frame_idx))
                x_coord_str = Printf.@sprintf("%.7f", coord.x)
                y_coord_str = Printf.@sprintf("%.7f", coord.y)
                z_coord_str = Printf.@sprintf("%.7f", coord.z)
                write(io, atomname*" "*x_coord_str*" "*y_coord_str*" "*z_coord_str*"\n")
            end
        end
    end
end


text:
import Pkg; Pkg.add("JuliaDB")
import Pkg; Pkg.add("RDatasets")
import Pkg; Pkg.add("DataFramesMeta")
import Pkg; Pkg.add("JSON")

include ("src/System.jl")
include ("Files/CombineLeeching.jl")
include ("Files/Leechers.jl")
include ("Files/players.json")

-'-'-'-.'(GENDER.(RACE.(CLASSNAME.(STORY.(-PLAYER-.'NAME'.'-'-')'STORY-'-')CLASSNAME-'-')RACE-'-')GENDER-'-')'.'-'-'-
  -'-'-'-.'(GENDER.(RACE.(CLASSNAME.(STORY.(-PLAYER-.'NAME'.'-'-')STORY-'-')CLASSNAME-'-')RACE-'-')GENDER-'-')'.'-'-'-'
  -'-'-'-.'(MALE.(HUMAN.(WIZARD.(DRESDENFILES.(DRESDEN.(COPPERFIELD.(BLACKSTONE.('-'-.'HARRY'.'-'-')'BLACKSTONE-'-')COPPERFIELD-'-')DRESDEN-'-')DRESDENFILES-'-')WIZARD-'-')HUMAN-'-')MALE-'-')'.'-'-'-
    -'-'-'-.'(MALE.(HUMAN.(WIZARD.(DRESDENFILES.(DRESDEN.(COPPERFIELD.(BLACKSTONE.('-'-.'HARRY'.'-'-')BLACKSTONE-'-')COPPERFIELD-'-')DRESDEN-'-')DRESDENFILES-'-')WIZARD-'-')HUMAN-'-')MALE-'-')'.'-'-'-'
    -'-'-'-.'(FEMALE.(HUMAN.(SORCERER.(DRESDENFILES.(DRESDEN.(COPPERFIELD.(BLACKSTONE.('-'-.'MAGGIE'.'-'-')'BLACKSTONE-'-')COPPERFIELD-'-')DRESDEN-'-')DRESDENFILES-'-')SORCERER-'-')HUMAN-'-')FEMALE-'-')'.'-'-'-
      -'-'-'-.'(FEMALE.(HUMAN.(SORCERER.(DRESDENFILES.(DRESDEN.(COPPERFIELD.(BLACKSTONE.('-'-.'MAGGIE'.'-'-')BLACKSTONE-'-')COPPERFIELD-'-')DRESDEN-'-')DRESDENFILES-'-')SORCERER-'-')HUMAN-'-')FEMALE-'-')'.'-'-'-'
      -'-'-'-.'(FEMALE.(ELF.(SAGE.(DRESDENFILES.(HIGGSFIELD.(STARDUST.(SANDASH.('-'-.'RIN'.'-'-')'SANDASH-'-')STARDUST-'-')HIGGSFIELD-'-')DRESDENFILES-'-')SAGE-'-')ELF-'-')FEMALE-'-')'.'-'-'-
        -'-'-'-.'(FEMALE.(ELF.(SAGE.(DRESDENFILES.(HIGGSFIELD.(STARDUST.(SANDASH.('-'-.'RIN'.'-'-')SANDASH-'-')STARDUST-'-')HIGGSFIELD-'-')DRESDENFILES-'-')SAGE-'-')ELF-'-')FEMALE-'-')'.'-'-'-'
        -'-'-'-.'(MALE.(DRAGON.(KNIGHT.(DRESDENFILES.(HIGGSFIELD.(STARDUST.(SANDASH.('-'-.'ARTHUR'.'-'-')'SANDASH-'-')STARDUST-'-')HIGGSFIELD-'-')DRESDENFILES-'-')KNIGHT-'-')DRAGON-'-')MALE-'-')'.'-'-'-
          -'-'-'-.'(MALE.(DRAGON.(KNIGHT.(DRESDENFILES.(HIGGSFIELD.(STARDUST.(SANDASH.('-'-.'ARTHUR'.'-'-')SANDASH-'-')STARDUST-'-')HIGGSFIELD-'-')DRESDENFILES-'-')KNIGHT-'-')DRAGON-'-')MALE-'-')'.'-'-'-'
          -'-'-'-.'(FEMALE.(HUMAN.(WIZARD.(DRESDENFILES.(CARPENTER.(AMANDA.(KATHERINE.('-'-.'MOLLY'.'-'-')'KATHERINE-'-')AMANDA-'-')CARPENTER-'-')DRESDENFILES-'-')WIZARD-'-')HUMAN-'-')FEMALE-'-')'.'-'-'-
            -'-'-'-.'(FEMALE.(HUMAN.(WIZARD.(DRESDENFILES.(CARPENTER.(AMANDA.(KATHERINE.('-'-.'MOLLY'.'-'-')KATHERINE-'-')AMANDA-'-')CARPENTER-'-')DRESDENFILES-'-')WIZARD-'-')HUMAN-'-')FEMALE-'-')'.'-'-'-'
            -'-'-'-.'(MALE.(HUMAN.(PALADIN.(DRESDENFILES.(STARK.(AARON.(CODEN.('-'-.'ELLIOT'.'-'-')'CODEN-'-')AARON-'-')STARK-'-')DRESDENFILES-'-')PALADIN-'-')HUMAN-'-')MALE-'-')'.'-'-'-
              -'-'-'-.'(MALE.(HUMAN.(PALADIN.(DRESDENFILES.(STARK.(AARON.(CODEN.('-'-.'ELLIOT'.'-'-')CODEN-'-')AARON-'-')STARK-'-')DRESDENFILES-'-')PALADIN-'-')HUMAN-'-')MALE-'-')'.'-'-'-'
              -'-'-'-.'(FEMALE.(DRAGON.(SORCERER.(DRESDENFILES.(HIGGSFIELD.(STARSAND.(BLACKIRON.('-'-.'IRIS'.'-'-')'BLACKIRON-'-')STARSAND-'-')HIGGSFIELD-'-')DRESDENFILES-'-')SORCERER-'-')DRAGON-'-')FEMALE-'-')'.'-'-'-
                -'-'-'-.'(FEMALE.(DRAGON.(SORCERER.(DRESDENFILES.(HIGGSFIELD.(STARSAND.(BLACKIRON.('-'-.'IRIS'.'-'-')BLACKIRON-'-')STARSAND-'-')HIGGSFIELD-'-')DRESDENFILES-'-')SORCERER-'-')DRAGON-'-')FEMALE-'-')'.'-'-'-'
                -'-'-'-.'(MALE.(ELF.(SORCERER.(DRESDENFILES.(HIGGSFIELD.(STARSHADOW.(ICEFLAME.('-'-.'DYLAN'.'-'-')'ICEFLAME-'-')STARSHADOW-'-')HIGGSFIELD-'-')DRESDENFILES-'-')SORCERER-'-')ELF-'-')MALE-'-')'.'-'-'-
                  -'-'-'-.'(MALE.(ELF.(SORCERER.(DRESDENFILES.(HIGGSFIELD.(STARSHADOW.(ICEFLAME.('-'-.'DYLAN'.'-'-')ICEFLAME-'-')STARSHADOW-'-')HIGGSFIELD-'-')DRESDENFILES-'-')SORCERER-'-')ELF-'-')MALE-'-')'.'-'-'-'
                  -'.'('Binary-'Language-'Binary).'-'-
                  '-'.'('Language-'Binary-'Language).'-'
                  '-'.'('Language-'Hexidecimal-'Language).'-'
                  '-'.'('Hexidecimal-'Language-'Hexidecimal).'-'
                  '-'.'('Language-'Technology-'Language).'-'
                  '-'.'('Technology-'Language-'Technology).'-'
                  '-'.'('Language-'Programming-'Language).'-'
                  '-'.'('Self-'Language-'Programming).'-'
                  '-'.'('Programming-'Language-'Self).'-'
                  '-'.'('Language-'Self-'Programming).'-'
                  '-'.'('Enemy-'Language-'Programming).'-'
                  '-'.'('Programming-'Language-'Enemy).'-'
                  '-'.'('Language-'Enemy-'Programming).'-'
                  '-'.'('Self-'Record-'Self).'-'
                  '-'.'('Record-'Self-'Record).'-'
                  '-'.'('STORY-'PLAYER-'STORY).'-'
                  '-'.'('PLAYER-'STORY-'PLAYER).'-'
                  '-'.'('Story-'Player-'Story).'-'
                  '-'.'('Player-'Story-'Player).'-'
                  '-'.'('MAGIC-'PLAYER-'MAGIC).'-'
                  '-'.'('PLAYER-'MAGIC-'PLAYER).'-'
                  '-'.'('Magic-'Player-'Magic).'-'
                  '-'.'('Player-'Magic-'Player).'-'
                  '-'.'('Language-'Self-'Movement).'-'
                  '-'.'('Movement-'Self-'Language).'-'
                  '-'.'('Language-'Teleportation-'Language).'-'
                  '-'.'('Teleportation-'Language-'Teleportation).'-'
                  '-'.'('Language-'Magic-'Language).'-'
                  '-'.'('Magic-'Language-'Magic).'-'
                  '-'.'('Options-'System-'Options).'-'
                  '-'.'('System-'Options-'System).'-'
                  '-'.'('List-'Options-'List).'-'
                  '-'.'('Options-'List-'Options).'-'
                  '-'.'('Stats-'Character-'Stats).'-'
                  '-'.'('Character-'Stats-'Character).'-'
                  '-'.'('List-'Stats-'List).'-'
                  '-'.'('Stat-'List-'Stat).'-'
                  '-'.'('StatName-'Stat-'StatName).'-'
                  '-'.'('Strength-'Stat-'Strength).'-'
                  '-'.'('Vitality-'Stat-'Vitality).'-'
                  '-'.'('Intelligence-'Stat-'Intelligence).'-'
                  '-'.'('Wisdom-'Stat-'Wisdom).'-'
                  '-'.'('Agility-'Stat-'Agility).'-'
                  '-'.'('Dexterity-'Stat-'Dexterity).'-'
                  '-'.'('Charisma-'Stat-'Charisma).'-'
                  '-'.'('Luck-'Stat-'Luck).'-'
                  '-'.'('Health-'Stat-'Health).'-'
                  '-'.'('Mana-'Stat-'Mana).'-'
                  '-'.'('Stamina-'Stat-'Stamina).'-'
                  '-'.'('Stat-'StatName-'Stat).'-'
                  '-'.'('Number-'Stat-'Number).'-'
                  '-'.'('Number-'Strength-'Number).'-'
                  '-'.'('Number-'Vitality-'Number).'-'
                  '-'.'('Number-'Intelligence-'Number).'-'
                  '-'.'('Number-'Wisdom-'Number).'-'
                  '-'.'('Number-'Agility-'Number).'-'
                  '-'.'('Number-'Dexterity-'Number).'-'
                  '-'.'('Number-'Charisma-'Number).'-'
                  '-'.'('Number-'Luck-'Number).'-'
                  '-'.'('Number-'Health-'Number).'-'
                  '-'.'('Number-'Mana-'Number).'-'
                  '-'.'('Number-'Ki-'Number).'-'
                  '-'.'('Number-'Stamina-'Number).'-'
                  '-'.'('Stat-'Number-'Stat).'-'
                  '-'.'('Name-'Character-'Name).'-'
                  '-'.'('Character-'Name-'Character).'-'
                  '-'.'('Gender-'Character-'Gender).'-'
                  '-'.'('Character-'Gender-'Character).'-'
                  '-'.'('Race-'Character-'Race).'-'
                  '-'.'('Character-'Race-'Character).'-'
                  '-'.'('Class-'Player.Class-'Class).'-'
                  '-'.'('Class-'Character-'Class).'-'
                  '-'.'('Player.class-'Class-'Player.Class).'-'
                  '-'.'('ClassName-'Player.Class-'ClassName).'-'
                  '-'.'('Class-'ClassName-'Class).'-'
                  '-'.'('Character-'Class-'Character).'-'
                  '-'.'('ClassSkill-'ClassName-'ClassSkill).'-'
                  '-'.'('ClassName-'ClassSkill-'ClassName).'-'
                  '-'.'('ClassSkill-'SkillName-'ClassSkill).'-'
                  '-'.'('SkillName-'ClassSkill-'SkillName).'-'
                  '-'.'('Level-'Class-'Level).'-'
                  '-'.'('Number-'Level-'Number).'-'
                  '-'.'('Character-'Level-'Character).'-'
                  '-'.'('Level-'Character-'Level).'-'
                  '-'.'('Class-'Level-'Class).'-'
                  '-'.'('Inventory-'Character-'Inventory).'-'
                  '-'.'('Character-'Inventory-'Character).'-'
                  '-'.'('Storage-'Character-'Storage).'-'
                  '-'.'('Character-'Storage-'Character).'-'
                  '-'.'('Items-'Character-'Items).'-'
                  '-'.'('Character-'Items-'Character).'-'
                  '-'.'('Weapons-'Items-'Weapons).'-'
                  '-'.'('Spears-'Weapons-'Spears).'-'
                  '-'.'('Swords-'Weapons-'Swords).'-'
                  '-'.'('Daggers-'Weapons-'Daggers).'-'
                  '-'.'('Staves-'Weapons-'Staves).'-'
                  '-'.'('Rods-'Weapons-'Rods).'-'
                  '-'.'('Wands-'Weapons-'Wands).'-'
                  '-'.'('Books-'Weapons-'Books).'-'
                  '-'.'('Items-'Weapons-'Items).'-'
                  '-'.'('Armour-'Items-'Armour).'-'
                  '-'.'('Chest-'Armour-'Chest).'-'
                  '-'.'('Shoulders-'Armour-'Shoulders).'-'
                  '-'.'('Cloak-'Armour-'Cloak).'-'
                  '-'.'('Bracers-'Armour-'Bracers).'-'
                  '-'.'('Gloves-'Armour-'Gloves).'-'
                  '-'.'('Legs-'Armour-'Legs).'-'
                  '-'.'('Shoes-'Armour-'Shoes).'-'
                  '-'.'('Headgear-'Armour-'Headgear).'-'
                  '-'.'('Items-'Armour-'Items).'-'
                  '-'.'('Accessories-'Items-'Accessories).'-'
                  '-'.'('Necklace-'Accessories-'Necklace).'-'
                  '-'.'('Accessories-'Necklace-'Accessories).'-'
                  '-'.'('Glasses-'Accessories-'Glasses).'-'
                  '-'.'('Accessories-'Glasses-'Accessories).'-'
                  '-'.'('Earring-'Accessories-'Earring).'-'
                  '-'.'('Accessories-'Earring-'Accessories).'-'
                  '-'.'('Ring-'Accessories-'Ring).'-'
                  '-'.'('Accessories-'Ring-'Accessories).'-'
                  '-'.'('Bracelet-'Accessories-'Bracelet).'-'
                  '-'.'('Accessories-'Bracelet-'Accessories).'-'
                  '-'.'('Items-'Accessories-'Items).'-'
                  '-'.'('Usable-'Items-'Usable).'-'
                  '-'.'('Potions-'Usable-'Potions).'-'
                  '-'.'('Items-'Usable-'Items).'-'
                  '-'.'('Crafting-'Character-'Crafting).'-'
                  '-'.'('ItemName-'Craft-'ItemName).'-'
                  '-'.'('Craft-'ItemName-'Craft).'-'
                  '-'.'('Item-'Repair-'Item).'-'
                  '-'.'('Repair-'Item-'Repair).'-'
                  '-'.'('Character-'Crafting-'Character).'-'
                  '-'.'('Enchanting-'Character-'Enchanting).'-'
                  '-'.'('Weapon-'Enchant-'Weapon).'-'
                  '-'.'('Enchant-'Weapon-'Enchant).'-'
                  '-'.'('Armour-'Enchant-'Armour).'-'
                  '-'.'('Enchant-'Armour-'Enchant).'-'
                  '-'.'('Clothes-'Enchant-'Clothes).'-'
                  '-'.'('Enchant-'Clothes-'Enchant).'-'
                  '-'.'('Fabric-'Enchant-'Fabric).'-'
                  '-'.'('Enchant-'Fabric-'Enchant).'-'
                  '-'.'('Necklace-'Enchant-'Necklace).'-'
                  '-'.'('Enchant-'Necklace-'Enchant).'-'
                  '-'.'('Bracelet-'Enchant-'Bracelet).'-'
                  '-'.'('Enchant-'Bracelet-'Enchant).'-'
                  '-'.'('Glasses-'Enchant-'Glasses).'-'
                  '-'.'('Enchant-'Glasses-'Enchant).'-'
                  '-'.'('Gloves-'Enchant-'Gloves).'-'
                  '-'.'('Enchant-'Gloves-'Enchant).'-'
                  '-'.'('Shoes-'Enchant-'Shoes).'-'
                  '-'.'('Enchant-'Shoes-'Enchant).'-'
                  '-'.'('Cloak-'Enchant-'Cloak).'-'
                  '-'.'('Enchant-'Cloak-'Enchant).'-'
                  '-'.'('Character-'Enchanting-'Character).'-'
                  '-'.'('Message-'Personal-'Message).'-'
                  '-'.'('Personal-'Message-'Personal).'-'
                  '-'.'('Party-'Character-'Party).'-'
                  '-'.'('Chat-'Party-'Chat).'-'
                  '-'.'('Party-'Chat-'Party).'-'
                  '-'.'('Name-'Party-'Name).'-'
                  '-'.'('Party-'Name-'Party).'-'
                  '-'.'('Character-'Party-'Character).'-'
                  '-'.'('FriendList-'Character-'FriendList).'-'
                  '-'.'('Character-'FriendList-'Character).'-'
                  '-'.'('Guild-'Character-'Guild).'-'
                  '-'.'('Chat-'Guild-'Chat).'-'
                  '-'.'('Guild-'Chat-'Guild).'-'
                  '-'.'('Character-'Guild-'Character).'-'
                  '-'.'('Magic-'Flight-'Magic).'-'
                  '-'.'('Flight-'Magic-'Flight).'-'
                  '-'.'('Magic-'Fire-'Magic).'-'
                  '-'.'('Fire-'Magic-'Fire).'-'
                  '-'.'('Magic-'Wind-'Magic).'-'
                  '-'.'('Wind-'Magic-'Wind).'-'
                  '-'.'('Magic-'Lightning-'Magic).'-'
                  '-'.'('Lightning-'Magic-'Lightning).'-'
                  '-'.'('Magic-'Hadouken-'Magic).'-'
                  '-'.'('Hadouken-'Magic-'Hadouken).'-'
                  '-'.'('Magic-'Telekinesis-'Magic).'-'
                  '-'.'('Telekinesis-'Magic-'Telekinesis).'-'
                  '-'.'('Self-'Magic-'Self).'-'
                  '-'.'('Magic-'Self-'Magic).'-'
                  '-'.'('Change-'Magic-'Change).'-'
                  '-'.'('Magic-'Change-'Magic).'-'
                  '-'.'('Gender-'Change-'Gender).'-'
                  '-'.'('Change-'Gender-'Change).'-'
                  '-'.'('Body-'Change-'Body).'-'
                  '-'.'('Change-'Body-'Change).'-'
                  '-'.'('Body-'Shape-'Body).'-'
                  '-'.'('Shape-'Body-'Shape).'-'
                  '-'.'('Eyes-'Color-'Eyes).'-'
                  '-'.'('Color-'Eyes-'Color).'-'
                  '-'.'('Hair-'Color-'Hair).'-'
                  '-'.'('Color-'Hair-'Color).'-'
                  '-'.'('Skin-'Color-'Skin).'-'
                  '-'.'('Color-'Skin-'Color).'-'
                  '-'.'('Height-'Character-'Height).'-'
                  '-'.'('Character-'Height-'Character).'-'
                  '-'.'('Touch-'Magic-'Touch).'-'
                  '-'.'('Magic-'Touch-'Magic).'-'
                  '-'.'('Push-'Magic-'Push).'-'
                  '-'.'('Magic-'Push-'Magic).'-'
                  '-'.'('Pull-'Magic-'Pull).'-'
                  '-'.'('Magic-'Pull-'Magic).'-'
                  '-'.'('Object-'Grab-'Object).'-'
                  '-'.'('Grab-'Object-'Grab).'-'
                  '-'.'('Grab-'Magic-'Grab).'-'
                  '-'.'('Magic-'Grab-'Magic).'-'
                  '-'.'('Freeze-'Magic-'Freeze).'-'
                  '-'.'('Magic-'Freeze-'Magic).'-'
                  '-'.'('Heart-'Magic-'Heart).'-'
                  '-'.'('Magic-'Heart-'Magic).'-'
                  '-'.'('Soul-'Magic-'Soul).'-'
                  '-'.'('Magic-'Soul-'Magic).'-'
                  '-'.'('Sword-'Magic-'Sword).'-'
                  '-'.'('Magic-'Sword-'Magic).'-'
                  '-'.'('Staff-'Magic-'Staff).'-'
                  '-'.'('Magic-'Staff-'Magic).'-'
                  '-'.'('Wand-'Magic-'Wand).'-'
                  '-'.'('Magic-'Wand-'Magic).'-'
                  '-'.'('Shapeshift-'Magic-'Shapeshift).'-'
                  '-'.'('Magic-'Shapeshift-'Magic).'-'
                  '-'.'('Magic-'Gender-'Change).'-'
                  '-'.'('Gender-'Change-'Magic).'-'
                  '-'.'('Magic-'Shape-'Change).'-'
                  '-'.'('Change-'Shape-'Magic).'-'
                  '-'.'('Heal-'Magic-'Heal).'-'
                  '-'.'('Magic-'Heal-'Magic).'-'
                  '-'.'('Magic-'Resurrection-'Magic).'-'
                  '-'.'('Resurrection-'Magic-'Resurrection).'-'
                  '-'.'('Speed-'Magic-'Speed).'-'
                  '-'.'('Magic-'Speed-'Magic).'-'
                  '-'.'('Magic-'Body-'Building).'-'
                  '-'.'('Magic-'Building-'Body).'-'
                  '-'.'('Magic-'Body-'Magic).'-'
                  '-'.'('Body-'Magic-'Body).'-'
                  '-'.'('Magic-'Self-'Magic).'-'
                  '-'.'('Self-'Magic-'Self).'-'
                  '-'.'('Magic-'Player-'Magic).'-'
                  '-'.'('Player-'Magic-'Player).'-'
                  '-'.'('Aura-'Self-'Aura).'-'
                  '-'.'('Self-'Aura-'Self).'-'
                  '-'.'('Aura-'Self-'Self).'-'
                  '-'.'('Self-'Self-'Aura).'-'
                  '-'.'('Crackle-'Aura-'Intensity).'-'
                  '-'.'('Intensity-'Aura-'Crackle).'-'
                  '-'.'('Aura-'Intensity-'Crackle).'-'
                  '-'.'('Crackle-'Intensity-'Aura).'-'
                  '-'.'('Fire-'Aura-'Fire).'-'
                  '-'.'('Aura-'Fire-'Aura).'-'
                  '-'.'('Color-'Aura-'Color).'-'
                  '-'.'('Aura-'Color-'Aura).'-'
                  '-'.'('Ki-'Aura-'Control).'-'
                  '-'.'('Control-'Aura-'Ki).'-'
                  '-'.'('Ki-'Control-'Aura).'-'
                  '-'.'('Aura-'Control-'Ki).'-'
                  '-'.'('Control-'Ki-'Aura).'-'
                  '-'.'('Aura-'Ki-'Control).'-'
                  '-'.'('Aura-'Control-'Aura).'-'
                  '-'.'('Control-'Aura-'Control).'-'
                  '-'.'('Ki-'Aura-'Ki).'-'
                  '-'.'('Aura-'Ki-'Aura).'-'
                  '-'.'('Aura-'Air-'Walk).'-'
                  '-'.'('Aura-'Walk-'Air).'-'
                  '-'.'('Air-'Walk-'Aura).'-'
                  '-'.'('Walk-'Aura-'Air).'-'
                  '-'.'('Air-'Walk-'Air).'-'
                  '-'.'('Walk-'Air-'Walk).'-'
                  '-'.'('Getsuga Tensho-'SwordSkill-'Getsuga Tensho).'-'
                  '-'.'('SwordSkill-'Getsuga Tensho-'SwordSkill).'-'
                  '-'.'('Kamehameha-'KiSkill-'Kamehameha).'-'
                  '-'.'('KiSkill-'Kamehameha-'KiSkill).'-'
                  '-'.'('Kamehameha-'Magic-'Kamehameha).'-'
                  '-'.'('Magic-'Kamehameha-'Magic).'-'
                  '-'.'('KiSkill-'Flight-'KiSkill).'-'
                  '-'.'('Flight-'KiSkill-'Flight).'-'
                  '-'.'('AuraSkill-'Flight-'AuraSkill).'-'
                  '-'.'('Flight-'AuraSkill-'Flight).'-'
                  '-'.'('Aura-'AuraSkill-'Flare).'-'
                  '-'.'('Flare-'AuraSkill-'Aura).'-'
                  '-'.'('AuraSkill-'Flare-'Aura).'-'
                  '-'.'('AuraSkill-'Aura-'Flare).'-'
                  '-'.'('Flare-'Aura-'AuraSkill).'-'
                  '-'.'('Aura-'Flare-'AuraSkill).'-'
                  '-'.'('AuraSkill-'PlayerTarget-'CloseWounds).'-'
                  '-'.'('CloseWounds-'PlayerTarget-'AuraSkill).'-'
                  '-'.'('PlayerTarget-'AuraSkill-'CloseWounds).'-'
                  '-'.'('CloseWounds-'AuraSkill-'PlayerTarget).'-'
                  '-'.'('PlayerTarget-'CloseWounds-'AuraSkill).'-'
                  '-'.'('AuraSkill-'CloseWounds-'PlayerTarget).'-'
                  '-'.'('MagicSkill-'EnemyTarget-'MagicMissle).'-'
                  '-'.'('MagicMissle-'EnemyTarget-'MagicSkill).'-'
                  '-'.'('EnemyTarget-'MagicSkill-'MagicMissle).'-'
                  '-'.'('EnemyTarget-'MagicMissle-'MagicSkill).'-'
                  '-'.'('MagicSkill-'MagicMissle-'EnemyTarget).'-'
                  '-'.'('MagicMissle-'MagicSkill-'EnemyTarget).'-'
                  '-'.'('MagicSkill-'PreviousTarget-'MagicSkill).'-'
                  '-'.'('PreviousTarget-'MagicSkill-'PreviousTarget).'-'
                  '-'.'('KiBlast-'AuraSkill-'KiBlast).'-'
                  '-'.'('AuraSkill-'KiBlast-'AuraSkill).'-'
                  '-'.'('MagneticEarth-'SageSkill-'MagneticEarth).'-'
                  '-'.'('SageSkill-'MagneticEarth-'SageSkill).'-'
                  '-'.'('FreezeTarget-'SageSkill-'FreezeTarget).'-'
                  '-'.'('SageSkill-'FreezeEarth-'SageSkill).'-'
                  '-'.'('PlayerTarget-'CloseWounds-'AuraSkill).'-'
                  '-'.'('AuraSkill-'CloseWounds-'PlayerTarget).'-'
                  '-'.'('MistressSunglasses-'SageGlasses-'MistressSunglasses).'-'
                  '-'.'('SageGlasses-'MistressSunglasses-'SageGlasses).'-'
                  '-'.'('StoneCurse-'SageSkill-'StoneCurse).'-'
                  '-'.'('SageSkill-'StoneCurse-'SageSkill).'-'
                  '-'.'('FrostDiver-'SageSkill-'FrostDiver).'-'
                  '-'.'('SageSkill-'FrostDiver-'SageSkill).'-'
                  '-'.'('HealTargetedPlayer-'SageSkill-'HealTargetedPlayer).'-'
                  '-'.'('SageSkill-'HealTargetedPlayer-'SageSkill).'-'
                  '-'.'('Heal-'SageSkil-'Heal).'-'
                  '-'.'('SageSkill-'Heal-'SageSkill).'-'
                  '-'.'('HealTargetedEnemy-'SageSkill-'HealTargetedEnemy).'-'
                  '-'.'('SageSkill-'HealTargetedEnemy-'SageSkill).'-'
                  '-'.'('AoEHealAll-'SageSkill-'AoEHealAll).'-'
                  '-'.'('SageSkill-'AoEHealAll-'SageSkill).'-'
                  '-'.'('AoEHealFriendlies-'SageSkill-'AoEHealFriendlies).'-'
                  '-'.'('SageSkill-'AoEHealFriendlies-'SageSkill).'-'
                  '-'.'('Splash-'AoESkill-'Damage).'-'
                  '-'.'('Splash-'Damage-'AoESkill).'-'
                  '-'.'('AoESkill-'Damage-'Splash).'-'
                  '-'.'('AoESkill-'Splash-'Damage).'-'
                  '-'.'('Damage-'AoESkill-'Splash).'-'
                  '-'.'('Damage-'Splash-'AoESkill).'-'
                  '-'.'('Splash-'AoESkill-'Heal).'-'
                  '-'.'('Splash-'Heal-'AoESkill).'-'
                  '-'.'('AoESkill-'Heal-'Splash).'-'
                  '-'.'('AoESkill-'Splash-'Heal).'-'
                  '-'.'('Heal-'AoESkill-'Splash).'-'
                  '-'.'('Heal-'Splash-'AoESkill).'-'
                  '-'.'('ReverseTime-'SageSkill-'ReverseTime).'-'
                  '-'.'('SageSkill-'ReverseTime-'SkillSkill).'-'
                  '-'.'('FreezeTime-'SageSkill-'FreezeTime).'-'
                  '-'.'('SageSkill-'FreezeTime-'SageSkill).'-'
                  '-'.'('ReverseTargetEntropy-'SageSkill-'ReverseTargetEntropy).'-'
                  '-'.'('SageSkill-'ReverseTargetEntropy-'SageSkill).'-'
                  '-'.'('Gravity-'SageSkill-'Manipulation).'-'
                  '-'.'('Manipulation-'SageSkill-'Gravity).'-'
                  '-'.'('Magic-'ManipulateGravity-'Magic).'-'
                  '-'.'('ManipulateGravity-'Magic-'ManipulateGravity).'-'
                  '-'.'('Resurrect-'SageSkill-'Resurrect).'-'
                  '-'.'('SageSkill-'Resurrect-'SageSkill).'-'
                  '-'.'('Shunpo-'SageSkill-'Shunpo).'-'
                  '-'.'('SageSkill-'Shunpo-'SageSkill).'-'
                  '-'.'('Sonido-'SageSkill-'Sonido).'-'
                  '-'.'('SageSkill-'Sonido-'SageSkill).'-'
                  '-'.'('AuraShield-'SageSkill-'AuraShiled).'-'
                  '-'.'('SageSkill-'AuraShield-'SageSkill).'-'
                  '-'.'('Share-'SageSkill-'AuraShield).'-'
                  '-'.'('Share-'AuraShield-'Sageskill).'-'
                  '-'.'('SageSkill-'Share-'AuraShield).'-'
                  '-'.'('AuraShield-'Share-'SageSkill).'-'
                  '-'.'('AuraShield-'SageSkill-'Share).'-'
                  '-'.'('SageSkill-'AuraShield-'Share).'-'
                  '-'.'('ShareLanguage-'SageSkill-'ShareLanguage).'-'
                  '-'.'('SageSkill-'ShareLanguage-'SageSkill).'-'
                  '-'.'('ShareKnowledge-'SageSkill-'ShareKnowledge).'-'
                  '-'.'('SageSkill-'ShareKnowledge-'SageSkill).'-'
                  '-'.'('ShareLore-'SageSkill-'ShareLore).'-'
                  '-'.'('SageSkill-'ShareLore-'SageSkill).'-'
                  '-'.'('ShareData-'SageSkill-'ShareData).'-'
                  '-'.'('SageSkill-'ShareData-'SageSkill).'-'
                  '-'.'('FamilyStorage-'SageSkill-'FamilyStorage).'-'
                  '-'.'('SageSkill-'FamilyStorage-'SageSkill).'-'
                  '-'.'('FamilyInventory-'FamilyStorage-'FamilyInventory).'-'
                  '-'.'('FamilyStorage-'FamilyInventory-'FamilyStorage).'-'
                  '-'.'('Headgear-'FamilyInventory-'Headgear).'-'
                  '-'.'('FamilyInventory-'Headgear-'FamilyInventory).'-'
                  '-'.'('Weapons-'FamilyInventory-'Weapons).'-'
                  '-'.'('FamilyInventory-'Weapons-'FamilyInventory).'-'
                  '-'.'('Armour-'FamilyInventory-'Armour).'-'
                  '-'.'('FamilyInventory-'Armour-'FamilyInventory).'-'
                  '-'.'('Accessories-'FamilyInventory-'Accessories).'-'
                  '-'.'('FamilyInventory-'Accessories-'FamilyInventory).'-'
                  '-'.'('UsableItems-'FamilyInventory-'UsableItems).'-'
                  '-'.'('FamilyInventory-'UsableItems-'FamilyInventory).'-'
                  '-'.'('CraftableItems-'FamilyInventory-'CraftableItems).'-'
                  '-'.'('FamilyInventory-'CraftableItems-'FamilyInventory).'-'
                  '-'.'('Misc-'FamilyInventory-'Misc).'-'
                  '-'.'('FamilyInventory-'Misc-'FamilyInventory).'-'
                  '-'.'('Record-'FamilyInventory-'Transactions).'-'
                  '-'.'('Transactions-'FamilyInventory-'Record).'-'
                  '-'.'('Record-'FamilyStorage-'Transactions).'-'
                  '-'.'('Transactions-'FamilyStorage-'Record).'-'
                  '-'.'('Record-'Inventory-'Transactions).'-'
                  '-'.'('Record-'Transactions-'Inventory).'-'
                  '-'.'('Transactions-'Inventory-'Record).'-'
                  '-'.'('Transactions-'Record-'Inventory).'-'
                  '-'.'('Inventory-'Record-'Transactions).'-'
                  '-'.'('Inventory-'Transactions-'Record).'-'
                  '-'.'('Inventory-'TransactionRecords-'Inventory).'-'
                  '-'.'('TransactionRecords-'Inventory-'TransactionRecords).'-'
                  '-'.'('FamilyInventory-'TransactionRecords-'FamilyInventory).'-'
                  '-'.'('TransactionRecords-'FamilyInventory-'TransactionRecords).'-'
                  '-'.'('Trade-'FromInventory-'Trade).'-'
                  '-'.'('FromInventory-'Trade-'FromInventory).'-'
                  '-'.'('ShareQuest-'SageSkill-'ShareQuest).'-'
                  '-'.'('SageSkill-'ShareQuest-'SageSkill).'-'
                  '-'.'('ShareQuestLog-'SageSkill-'ShareQuestLog).'-'
                  '-'.'('SageSkill-'ShareQuestLog-'SageSkill).'-'
                  '-'.'('ShareAvailableQuests-'SageSkill-'ShareAvailableQuests).'-'
                  '-'.'('SageSkill-'ShareAvailableQuests-'SageSkill).'-'
                  '-'.'('ShareQuestDetails-'SageSkill-'ShareQuestDetails).'-'
                  '-'.'('SageSkill-'ShareQuestDetails-'SageSkill).'-'
                  '-'.'('SageAura-'SageSkill-'ShieldArea).'-'
                  '-'.'('ShieldArea-'SageSkill-'SageAura).'-'
                  '-'.'('MagicRod-'SageSkill-'MagicRod).'-'
                  '-'.'('SageSkill-'MagicRod-'SageSkill).'-'
                  '-'.'('EnergyCoat-'SageSkill-'EnergyCoat).'-'
                  '-'.'('SageSkill-'EnergyCoat-'SageSkill).'-'
                  '-'.'('SoulSyphon-'SageSkill-'SoulSyphon).'-'
                  '-'.'('SageSkill-'SoulSyphon-'SageSkill).'-'
                  '-'.'('Indulge-'SageSkill-'Indulge).'-'
                  '-'.'('SageSkill-'Indulge-'SageSkill).'-'
                  '-'.'('SoulExhale-'SageSkill-'SoulExhale).'-'
                  '-'.'('SageSkill-'SoulExhale-'SageSkill).'-'
                  '-'.'('ClearCast-'SageSkill-'ClearCast).'-'
                  '-'.'('SageSkill-'ClearCast-'SageSkill).'-'
                  '-'.'('SpellBreaker-'SageSkill-'SpellBreaker).'-'
                  '-'.'('SageSkill-'SpellBreaker-'SageSkill).'-'
                  '-'.'('Indulge-'SageSkill-'Indulge).'-'
                  '-'.'('SageSkill-'Indulge-'SageSkill).'-'
                  '-'.'('SoulExhale-'SageSkill-'SoulExhale).'-'
                  '-'.'('SageSkill-'SoulExhale-'SageSkill).'-'
                  '-'.'('ClearCast-'SageSkill-'ClearCast).'-'
                  '-'.'('SageSkill-'ClearCast-'SageSkill).'-'
                  '-'.'('SpellBreaker-'SageSkill-'SpellBreaker).'-'
                  '-'.'('SageSkill-'SpellBreaker-'SageSkill).'-'
                  '-'.'('Craft-'SageSkill-'ElementalConverter).'-'
                  '-'.'('ElementalConverter-'SageSkill-'Craft).'-'
                  '-'.'('TargetWeapon-'ElementalConverter-'TargetWeapon).'-'
                  '-'.'('ElementalConverter-'TargetWeapon-'ElementalConverter).'-'
                  '-'.'('ElementChange-'SageSkill-'ElementChange).'-'
                  '-'.'('SageSkill-'ElementChange-'SageSkill).'-'
                  '-'.'('Hindsight-'SageSkill-'Hindsight).'-'
                  '-'.'('SageSkill-'Hindsight-'SageSkill).'-'
                  '-'.'('HeavensDrive-'SageSkill-'HeavensDrive).'-'
                  '-'.'('SageSkill-'HeavensDrive-'HeavensDrive).'-'
                  '-'.'('EarthSpike-'SageSkill-'EarthSpike).'-'
                  '-'.'('SageSkill-'EarthSpike-'SageSkill).'-'
                  '-'.'('Dragonology-'SageSkill-'Dragonology).'-'
                  '-'.'('SageSkill-'Dragonology-'SageSkill).'-'
                  '-'.'('Dispell-'SageSkill-'Dispell).'-'
                  '-'.'('SageSkill-'Dispell-'SageSkill).'-'
                  '-'.'('FreeCast-'SageSkill-'FreeCast).'-'
                  '-'.'('SageSkill-'FreeCast-'SageSkill).'-'
                  '-'.'('Deluge-'SageSkill-'Deluge).'-'
                  '-'.'('SageSkill-'Deluge-'SageSkill).'-'
                  '-'.'('EndowBlaze-'SageSkill-'EndowBlaze).'-'
                  '-'.'('SageSkill-'EndowBlaze-'SageSkill).'-'
                  '-'.'('EndowQuake-'SageSkill-'EndowQuake).'-'
                  '-'.'('SageSkill-'EndowQuake-'SageSkill).'-'
                  '-'.'('EndowTornado-'SageSkill-'EndowTornado).'-'
                  '-'.'('SageSkill-'EndowTornado-'SageSkill).'-'
                  '-'.'('EndowTsunami-'SageSkill-'EndowTsunami).'-'
                  '-'.'('SageSkill-'EndowTsunami-'SageSkill).'-'
                  '-'.'('Study-'SageSkill-'Study).'-'
                  '-'.'('SageSkill-'Study-'SageSkill).'-'
                  '-'.'('Volcano-'SageSkill-'Volcano).'-'
                  '-'.'('SageSkill-'Volcano-'SageSkill).'-'
                  '-'.'('Sense-'SageSkill-'Sense).'-'
                  '-'.'('SageSkill-'Sense-'SageSkill).'-'
                  '-'.'('SoulLink-'SageSkill-'SoulLink).'-'
                  '-'.'('SageSkill-'SoulLink-'SageSkill).'-'
                  '-'.'('FiberLock-'SageSkill-'FiberLock).'-'
                  '-'.'('SageSkill-'FiberLock-'SageSkill).'-'
                  '-'.'('Foresight-'SageSkill-'Foresight).'-'
                  '-'.'('SageSkill-'Foresight-'SageSkill).'-'
                  '-'.'('DoubleBolt-'SageSkill-'DoubleBolt).'-'
                  '-'.'('SageSkill-'DoubleBolt-'SagSkill).'-'
                  '-'.'('MindBreaker-'SageSkill-' MindBreaker).'-'
                  '-'.'('SageSkill-'MindBreaker-'SageSkill).'-'
                  '-'.'('BlindingMist-'SageSkill-'BlindingMist).'-'
                  '-'.'('SageSkill-'BlindingMist-'SageSkill).'-'
                  '-'.'('SafetyWall-'SageSkill-'SafetyWall).'-'
                  '-'.'('SageSkill-'SafetyWall-'SageSkill).'-'
                  '-'.'('SoulLinker-'SageSkill-'SoulLinker).'-'
                  '-'.'('SageSkill-'SoulLinker-'SageSkill).'-'
                  '-'.'('LinkSoul-'SoulLinker-'LinkSoul).'-'
                  '-'.'('SoulLinker-'LinkSoul-'SoulLinker).'-'
                  '-'.'('Eska-'SoulLinker-'Eska).'-'
                  '-'.'('SoulLinker-'Eska-'SoulLinker).'-'
                  '-'.'('Eske-'SoulLinker-'Eske).'-'
                  '-'.'('SoulLinker-'Eske-'SoulLinker).'-'
                  '-'.'('Esma-'SoulLinker-'Esma).'-'
                  '-'.'('SoulLinker-'Esma-'SoulLinker).'-'
                  '-'.'('Estin-'SoulLinker-'Estin).'-'
                  '-'.'('SoulLinker-'Estin-'SoulLinker).'-'
                  '-'.'('Estun-'SoulLinker-'Estun).'-'
                  '-'.'('SoulLinker-'Estun-'SoulLinker).'-'
                  '-'.'('Eswoo-'SoulLinker-'Eswoo).'-'
                  '-'.'('SoulLinker-'Eswoo-'SoulLinker).'-'
                  '-'.'('Kaahi-'SoulLinker-'Kaahi).'-'
                  '-'.'('SoulLinker-'Kaahi-'SoulLinker).'-'
                  '-'.'('Kaina-'SoulLinker-'Kaina).'-'
                  '-'.'('SoulLinker-'Kaina-'SoulLinker).'-'
                  '-'.'('Kaite-'SoulLinker-'Kaite).'-'
                  '-'.'('SoulLinker-'Kaite-'SoulLinker).'-'
                  '-'.'('Kaizel-'SoulLinker-'Kaizel).'-'
                  '-'.'('SoulLinker-'Kaizel-'SoulLinker).'-'
                  '-'.'('Kaupe-'SoulLinker-'Kaupe).'-'
                  '-'.'('SoulLinker-'Kaupe-'SoulLinker).'-'
                  '-'.'('TransSpirit-'SoulLinker-'TransSpirit).'-'
                  '-'.'('SoulLinker-'TransSpirit-'SoulLinker).'-'
                  ('-('Wizard Eyes)'WizardSkill'('Wizard Eyes')'
                  '('WizardSkill'-Wizard Eyes-'WizardSkill')'-).-
                  ('-'('Wizard Eyes)'SageSkill'('Wizard Eyes')'
                  '('SageSkill'-Wizard Eyes-'SageSkill')'-)
                  ('-'('Monkey Eyes)'SageSkill'('Monkey Eyes')'
                  '('SageSkill'-Monkey Eyes-'SageSkill')'-).-'
                  '-'.'('Magic-'Aura-'Control).'-'
                  '-'.'('Control-'Aura-'Magic).'-'
                  '-'.'('Magic-'Control-'Aura).'-'
                  '-'.'('Aura-'Magic-'Control).'-'
                  '-'.'('Flight-'Aura-'Manipluation).'-'
                  '-'.'('Manipluation-'Aura-'Flight).'-'
                  '-'.'('Aura-'Manipulation-'Flight).'-'
                  '-'.'('Aura-'Flight-'Manipulation).'-'
                  '-'.'('Flight-'Magic-'Manipluation).'-'
                  '-'.'('Manipluation-'Magic-'Flight).'-'
                  '-'.'('Magic-'Manipulation-'Flight).'-'
                  '-'.'('Magic-'Flight-'Manipulation).'-'
                  '-'.'('MP-'Magic-'MP).'-'
                  '-'.'('Magic-'MP-'Magic).'-'
                  '-'.'('HP-'Magic-'HP).'-'
                  '-'.'('Magic-'HP-'Magic).'-'
                  '-'.'('Shield-'Magic-'Shield).'-'
                  '-'.'('Magic-'Shield-'Magic).'-'
                  '-'.'('Armour-'Magic-'Armour).'-'
                  '-'.'('Magic-'Armour-'Magic).'-'
                  '-'.'('Inventory-'Magic-'Inventory).'-'
                  '-'.'('Magic-'Inventory-'Magic).'-'
                  '-'.'('EnvironmentLocation-'ItemDrop-'EnvironmentLocation).'-'
                  '-'.'('ItemDrop-'EnvironmentLocation-'ItemDrop).'-'
                  '-'.'('ItemNumber-'EnvironmentLocation-'ItemNumber).'-'
                  '-'.'('ItemNumber-'Magic-'ItemName).'-'
                  '-'.'('ItemName-'Magic-'ItemNumber).'-'
                  '-'.'('EnvironmentLocation-'ItemNumber-'AddToInventory).'-'
                  '-'.'('AddToInventory-'ItemNumber-'EnvironmentLocation).'-'
                  '-'.'('ItemName-'ItemNumber-'ItemName).'-'
                  '-'.'('ItemNumber-'ItemName-'ItemNumber).'-'
                  '-'.'('Craft-'Magic-'Items).'-'
                  '-'.'('Items-'Magic-'Craft).'-'
                  '-'.'('Magic-'Craft-'Items).'-'
                  '-'.'('Magic-'Items-'Craft).'-'
                  '-'.'('Magic-'Self-'Improve).'-'
                  '-'.'('Improve-'Self-'Magic).'-'
                  '-'.'('Enchant-'Magic-'Items).'-'
                  '-'.'('Items-'Magic-'Enchant).'-'
                  '-'.'('Magic-'Items-'Enchant).'-'
                  '-'.'('Enchant-'Items-'Magic).'-'
                  '-'.'('Language-'Movement-'Self).'-'
                  '-'.'('Self-'Movement-'Self).'-'
                  '-'.'('Movement-'Self-'Movement).'-'
                  '-'.'('Self-'Movement-'Language).'-'
                  '-'.'('Flight-'Self-'Flight).'-'
                  '-'.'('Self-'Flight-'Self).'-'
                  '-'.'('Self-'Flight-'Flight).'-'
                  '-'.'('Flight-'Flight-'Self).'-'
                  '-'.'('Flight-'Accelerate-'Speed).'-'
                  '-'.'('Speed-'Accelerate-'Flight).'-'
                  '-'.'('Flight-'Accellerate-'Accellerate).'-'
                  '-'.'('Accellerate-'Accellerate-'Flight).'-'
                  '-'.'('Language-'Memory-'Language).'-'
                  '-'.'('Memory-'Language-'Memory).'-'
                  '-'.'('Language-'Human-'Language).'-'
                  '-'.'('Human-'Language-'Human).'-'
                  '-'.'('Language-'Baby-'Language).'-'
                  '-'.'('Baby-'Language-'Baby).'-'
                  '-'.'('Male-'Language-'Male).'-'
                  '-'.'('Language-'Male-'Language).'-'
                  '-'.'('Female-'Language-'Female).'-'
                  '-'.'('Language-'Female-'Language).'-'
                  '-'.'('Male-'Language-'Male).'-'
                  '-'.'('Language-'Male-'Language).'-'
                  '-'.'('Language-'Demon-'Language).'-'
                  '-'.'('Demon-'Language-'Demon).'-'
                  '-'.'('Language-'Elf-'Language).'-'
                  '-'.'('Elf-'Language-'Elf).'-'
                  '-'.'('Language-'Dwarf-'Language).'-'
                  '-'.'('Dwarf-'Language-'Dwarf).'-'
                  '-'.'('Language-'Monsters-'Language).'-'
                  '-'.'('Monsters-'Language-'Monsters).'-'
                  '-'.'('Language-'Animals-'Language).'-'
                  '-'.'('Animals-'Language-'Animals).'-'
                  '-'.'('Language-'Time-'Language).'-'
                  '-'.'('Time-'Language-'Time).'-'
                  '-'.'('Language-'Space-'Language).'-'
                  '-'.'('Space-'Language-'Space).'-'
                  '-'.'('Language-'Multivere-'Language).'-'
                  '-'.'('Multiverse-'Language-'Multiverse).'-'
                  '-'.'('Language-'Flight-'Language).'-'
                  '-'.'('Flight-'Language-'Flight).'-'
                  '-'.'('Language-'Gravity-'Language).'-'
                  '-'.'('Gravity-'Language-'Gravity).'-'
                  '-'.'('Language-'Everything-'Language).'-'
                  '-'.'('Everything-'Language-'Everything).'-'
                  '-'.'('Language-'Nothing-'Language).'-'
                  '-'.'('Nothing-'Language-'Nothing).'-'
                  '-'.'('Self-'Language-'Self).'-'
                  '-'.'('Language-'Love-'Language).'-'
                  '-'.'('Love-'Language-'Language).'-'
                  '-'.'('Language-'War-'Language).'-'
                  '-'.'('War-'Language-'Language).'-'
                  '-'.'('Language-'Battle-'Language).'-'
                  '-'.'('Battle-'Language-'Language).'-'
                  '-'.'('Hunger-'Battle-'Hunger).'-'
                  '-'.'('Battle-'Hunger-'Language).'-'
                  '-'.'('Sight-'Human-'Sight).'-'
                  '-'.'('Human-'Sight-'Human).'-'
                  '-'.'('Sound-'Human-'Sound).'-'
                  '-'.'('Human-'Sound-'Human).'-'
                  '-'.'('Voice-'Human-'Voice).'-'
                  '-'.'('Human-'Voice-'Human).'-'
                  '-'.'('Speech-'Human-'Speech).'-'
                  '-'.'('Human-'Speech-'Human).'-'
                  '-'.'('Gender-'Human-'Gender).'-'
                  '-'.'('Human-'Gender-'Human).'-'
                  '-'.'('Interface-'Developer-'Interface).'-'
                  '-'.'('Developer-'Interface-'Developer).'-'
                  '-'.'('Interface-'Player-'Interface).'-'
                  '-'.'('Player-'Interface-'Player).'-'
                  '-'.'('Interface-'System-'Interface).'-'
                  '-'.'('System-'Interface-'System).'-'
                  '-'.'('Interface-'User-'Interface).'-'
                  '-'.'('User-'Interface-'User).'-'
                  '-'.'('Interface-'Self-'Interface).'-'
                  '-'.'('Self-'Interface-'Self).'-'
                  '-'.'('Magic-'Wizard-'Magic).'-'
                  '-'.'('Wizard-'Magic-'Wizard).'-'
                  '-'.'('Sight-'Wizard-'Sight).'-'
                  '-'.'('Wizard-'Sight-'Wizard).'-'
                  '-'.'('Language-'Wizard-'Language).'-'
                  '-'.'('Wizard-'Language-'Wizard).'-'
                  '-'.'('Sound-'Wizard-'Sound).'-'
                  '-'.'('Wizard-'Sound-'Wizard).'-'
                  '-'.'('Voice-'Wizard-'Smell).'-'
                  '-'.'('Wizard-'Smell-'Wizard).'-'
                  '-'.'('Wizard-'Color-'Wizard).'-'
                  '-'.'('Wizard-'Gender-'Wizard).'-'
                  '-'.'('Gender-'Wizard-'Gender).'-'
                  '-'.'('Taste-'Wizard-'Taste).'-'
                  '-'.'('Wizard-'Taste-'Wizard).'-'
                  '-'.'('Magic-'Sage-'Magic).'-'
                  '-'.'('Sage-'Magic-'Sage).'-'
                  '-'.'('Color-'Sage-'Color).'-'
                  '-'.'('Sage-'Color-'Sage).'-'
                  '-'.'('Smell-'Sage-'Smell).'-'
                  '-'.'('Sage-'Smell-'Sage).'-'
                  '-'.'('Taste-'Sage-'Taste).'-'
                  '-'.'('Sage-'Taste-'Sage).'-'
                  '-'.'('Gender-'Sage-'Gender).'-'
                  '-'.'('Sage-'Gender-'Sage).'-'
                  '-'.'('FireBolt-'Skills-'FireBolt).'-'
                  '-'.'('LightningBolt-'Skills-'LightingBolt).'-'
                  '-'.'('Male-'Elf-'Male).'-'
                  '-'.'('Elf-'Male-'Elf).'-'
                  '-'.'('Female-'Elf-'Female).'-'
                  '-'.'('Elf-'Female-'Elf).'-'
                  '-'.'('Taste-'Elf-'Taste).'-'
                  '-'.'('Elf-'Taste-'Elf).'-'
                  '-'.'('Change-'Self-'Change).'-'
                  '-'.'('Self-'Change-'Self).'-'
                  '-'.'('Target-'Change-'Target).'-'
                  '-'.'('Change-'Target-'Change).'-'
                  '-'.'('Touch-'Self-'Touch).'-'
                  '-'.'('Self-'Touch-'Self).'-'
                  '-'.'('Taste-'DemonKing-'Taste).'-'
                  '-'.'('DemonKing-'Taste-'DemonKing).'-'
                  '-'.'('Mirror-'Magic-'Mirror).'-'
                  '-'.'('Magic-'Mirror-'Magic).'-'

ext: jl

max_stars_repo_name: Physolia/-THE-Magic-Button

max_issues_repo_name: Physolia/-The-System-

max_forks_repo_name: Physolia/-The-System-


text:
using Flux, Flux.Data.MNIST, Statistics
using Flux: onehotbatch, onecold, crossentropy, throttle
using Base.Iterators: repeated, partition

# Classify MNIST digits with a convolutional network

imgs = MNIST.images()

labels = onehotbatch(MNIST.labels(), 0:9)

# Partition into batches of size 1,000
train = [(cat(float.(imgs[i])..., dims = 4), labels[:,i])
         for i in partition(1:60_000, 1000)]

train = gpu.(train)

# Prepare test set (first 1,000 images)
tX = cat(float.(MNIST.images(:test)[1:1000])..., dims = 4) |> gpu
tY = onehotbatch(MNIST.labels(:test)[1:1000], 0:9) |> gpu

m = Chain(
  Conv((2,2), 1=>16, relu),
  x -> maxpool(x, (2,2)),
  Conv((2,2), 16=>8, relu),
  x -> maxpool(x, (2,2)),
  x -> reshape(x, :, size(x, 4)),
  Dense(288, 10), softmax) |> gpu

m(train[1][1])

loss(x, y) = crossentropy(m(x), y)

accuracy(x, y) = mean(onecold(m(x)) .== onecold(y))

evalcb = throttle(() -> @show(accuracy(tX, tY)), 10)
opt = ADAM(params(m))

Flux.train!(loss, train, opt, cb = evalcb)

max_stars_repo_name: aquatiko/model-zoo

max_issues_repo_name: aquatiko/model-zoo

max_forks_repo_name: aquatiko/model-zoo


text:
"""
    Estimators

Functions for computing thermal expectation values as ensemble averages.
"""
module Estimators

using NQCDynamics:
    AbstractSimulation,
    Simulation,
    RingPolymerSimulation,
    Calculators,
    DynamicsUtils,
    RingPolymers,
    ndofs,
    natoms,
    nbeads,
    masses,
    get_temperature

using StatsBase: mean
using ComponentArrays: ComponentVector
using RingPolymerArrays: get_centroid

"""
    @estimate f(simulation, vector)

Evaluate `f(simulation, vector[i])` for all `i` and return the average.

Can be used for any function defined in `Estimators.jl`.
"""
macro estimate(expr)
    func = expr.args[1]
    sim = expr.args[2]
    configurations = expr.args[3]
    first_config, rest, result, config = gensym(), gensym(), gensym(), gensym()

    return esc(quote
        local ($first_config, $rest) = Iterators.peel($configurations)
        local $result = Estimators.$func($sim, $first_config)
        for $config in $rest
            $result += Estimators.$func($sim, $config)
        end
        $result / length($configurations)
    end)
end

"""
    total_energy(sim, u)
"""
function total_energy(sim::AbstractSimulation, u)
    kinetic_energy(sim, u) + potential_energy(sim, u)
end

"""
    potential_energy(sim, u)
"""
function potential_energy(sim::AbstractSimulation, u)
    potential_energy(sim, DynamicsUtils.get_positions(u))
end

function potential_energy(sim::Simulation, r::AbstractMatrix)
    Calculators.evaluate_potential!(sim.calculator, r)
    sim.calculator.potential
end

function potential_energy(sim::RingPolymerSimulation, r::AbstractArray{T,3}) where {T}
    Calculators.evaluate_potential!(sim.calculator, r)
    mean(sim.calculator.potential)
end

"""
    kinetic_energy(sim, u)
"""
function kinetic_energy(sim::Simulation, u)
    kinetic_energy(sim, DynamicsUtils.get_velocities(u))
end

function kinetic_energy(sim::Simulation, v::AbstractMatrix)
    DynamicsUtils.classical_kinetic_energy(sim, v)
end

function kinetic_energy(sim::RingPolymerSimulation, u)
    kinetic_energy(sim, DynamicsUtils.get_positions(u))
end

function kinetic_energy(sim::RingPolymerSimulation, r::AbstractArray{T,3}) where {T}
    centroid = get_centroid(r)

    Calculators.evaluate_derivative!(sim.calculator, r)

    kinetic = ndofs(sim) * natoms(sim) * get_temperature(sim)

    for I in CartesianIndices(r)
        kinetic += (r[I] - centroid[I[1], I[2]]) * sim.calculator.derivative[I]
    end

    return kinetic / 2nbeads(sim)
end

"""
    radius_of_gyration(sim, r)
"""
function radius_of_gyration(::RingPolymerSimulation, r::AbstractArray{T,3}) where {T}
    centroid = get_centroid(r)
    deviation = (r .- centroid) .^ 2
    mean_deviation = dropdims(mean(deviation; dims=3); dims=3)
    return sqrt.(mean_deviation)
end

"""
    diabatic_population
"""
function diabatic_population end

"""
    adiabatic_population
"""
function adiabatic_population end

initial_diabatic_population(sim, u) = diabatic_population(sim, u)
initial_adiabatic_population(sim, u) = adiabatic_population(sim, u)

end # module


text:
using Coexist, PyCall#env using Conda
using Test
using Dates
using DataFrames
Coexist.pyCoexist_setup()

py"""
import os
relative_path = os.getcwd()
path = os.path.join(relative_path, 'test.py')
exec(open(path).read())
"""

## Setup for testing
initial_state = (nAge=9, nHS=8, nIso=4, nI=4, nTest=4, nR=2)

# `trFunc_travelInfectionRate_ageAdjusted`
t = 10 # Time within simulation

# `trFunc_testCapacity`
rTime = Date("2020-05-25", "yyyy-mm-dd") # Real Time
py"""
_trFunc_testCapacity = __trFunc_testCapacity
"""

# `inpFunc_testSpecifications`
_other, _name, __truePosHealthState = py"inpFunc_testSpecifications()"
other = Coexist.inpFunc_testSpecifications(;initial_state...)
name = convert(Array, select(other, :Name))
name = reshape(name, size(name)[1])
_truePosHealthState = [[] for i in 1:size(__truePosHealthState)[1]]
for i in 1:24
	_len = size(__truePosHealthState[i])[1]
	_temp = [0 for i in 1:_len]
	for j in 1:size(__truePosHealthState[i])[1]
		_temp[j] = __truePosHealthState[i][j]
	end
	_truePosHealthState[i] = _temp
end
truePosHealthState = convert(Array, select(other, :TruePosHealthState))
truePosHealthState = reshape(truePosHealthState, size(truePosHealthState)[1])

other = select(other, Not(:Name))
other = select(other, Not(:TruePosHealthState))
other = convert(Array, other)

# End of setup

@testset "DiseaseProg & HospitalAdmission" begin
    @test  py"np.transpose(trFunc_diseaseProgression())"==
	Coexist.trFunc_diseaseProgression(;initial_state...)
	@test py"np.transpose(trFunc_HospitalAdmission())"≈ # Approximate equality?
	Coexist.trFunc_HospitalAdmission(;initial_state...)
	@test py"np.transpose(trFunc_HospitalDischarge())"≈
	Coexist.trFunc_HospitalDischarge(;initial_state...)
	@test py"np.transpose(trFunc_travelInfectionRate_ageAdjusted(10))"≈
	Coexist.trFunc_travelInfectionRate_ageAdjusted(t)
	@test py"_trFunc_testCapacity"==
	Coexist.trFunc_testCapacity(Date("2020-05-25", "yyyy-mm-dd"))

	# inpFunc_testSpecifications
	@test _other == other
	@test _name == name
	@test _truePosHealthState == truePosHealthState

	@test py"ageSocialMixingBaseline" ≈ Coexist.ageSocialMixingBaseline
	@test py"ageSocialMixingDistancing" ≈ Coexist.ageSocialMixingDistancing
	@test transpose(Coexist.einsum("ijk,j->ik", Coexist.stateTensor[3:end,4,2:(4+1),:], Coexist.transmissionInfectionStage, eltype(Coexist.transmissionInfectionStage))*(Coexist.ageSocialMixingBaseline.-Coexist.ageSocialMixingDistancing))≈
	py"np.matmul(ageSocialMixingBaseline-ageSocialMixingDistancing,np.einsum('ijk,j->ik',stateTensor[:,1:(4+1),3,2:], transmissionInfectionStage))"
	@test py"trFunc_newInfections_Complete(stateTensor=stateTensor,policySocialDistancing=False, policyImmunityPassports=True)"≈
	permutedims(Coexist.trFunc_newInfections_Complete(Coexist.stateTensor,false,true;initial_state...),[3,2,1])
end

max_stars_repo_name: vollmersj/coexist-julia

max_forks_repo_name: vollmersj/coexist-julia


text:
using DataStructures
using Base.Meta
using StaticArrays
using AutoHashEquals

@auto_hash_equals struct EClass
    id::Int64
end

@auto_hash_equals struct ENode
    head::Any
    args::MVector{T, Int64} where T
    sourcetype::Type
    metadata::Any
end

ariety(n::ENode) = length(n.args)

struct EClass
    id::Int64
end

function ENode(e, c_ids::AbstractVector{Int64})
    @assert length(getargs(e)) == length(c_ids)
    static_args = MVector{length(c_ids), Int64}(c_ids...)
    ENode(gethead(e), static_args, typeof(e), getmetadata(e))
end

ENode(e) = ENode(e, Int64[])

ENode(a::ENode) =
    error("constructor of ENode called on enode. This should never happen")


text:
include("common.jl")

function IVT_algorithm{T <: Real}(time::Array{T, 1}, coords::Array{T, 2}, velthresh)
    n = length(time) - 1
    tdiff, cdiff = diff(time), diff(coords)

    spacediff = zeros(n)
    for i in 1:n
        spacediff[i] = √(cdiff[i, :] * cdiff[i, :]')[1] # euclidean distance
    end

    veldiff = spacediff ./ tdiff
    isfix = veldiff .< velthresh # boolean array (BitArray{1})
    hcat(time, coords, assign(isfix))
end

function IVT{T <: Real}(time::Array{T, 1}, x::Array{T, 1}, y::Array{T, 1}; velthresh = 0)
    IVT_algorithm(time, hcat(x, y), velthresh)
end

function IVT{T <: Real}(time::Array{T, 1}, coords::Array{T, 2}; velthresh = 0)
    IVT_algorithm(time, coords, velthresh)
end

function IVT{T <: Real}(dat::Array{T, 2}; velthresh = 0)
    @assert size(dat, 2) == 3
    IVT_algorithm(dat[:, 1], dat[:, 2:3], velthresh)
end


text:
using ITensors
using LinearAlgebra
using TBLIS

let
  d = 25

  nthreads = 4

  i = Index(d, "i")
  j = Index(d, "j")
  k = Index(d, "k")
  l = Index(d, "l")
  a = Index(d, "a")
  b = Index(d, "b")

  A = randomITensor(i, a, j, b)
  B = randomITensor(b, l, k, a)
  C = randomITensor(i, j, k, l)

  println("Contracting (d x d x d x d) tensors A * B -> C, d = ", d)
  @show inds(A)
  @show inds(B)
  @show inds(C)

  #
  # Use BLAS
  #

  disable_tblis!()
  BLAS.set_num_threads(nthreads)

  println()
  println("Using BLAS with $nthreads threads")

  C_blas = copy(C)
  time_blas = @belapsed $C_blas .= $A .* $B samples = 100

  println()
  println("Time (BLAS) = ", time_blas, " seconds")

  #
  # Use TBLIS
  #

  enable_tblis!()
  TBLIS.set_num_threads(4)

  println()
  println("Using TBLIS with $(TBLIS.get_num_threads()) threads")

  C_tblis = copy(C)
  time_tblis = @belapsed $C_tblis .= $A .* $B samples = 100

  println()
  println("Time (TBLIS) = ", time_tblis, " seconds")

  println()
  @show C_blas ≈ C_tblis

  println()
  println("Time (TBLIS) / Time (BLAS) = ", time_tblis / time_blas)
end


text:
import SimpleValueGraphs: typetuple

@testset "Edgeval setters" begin

    @testset "set_edgeval!(::$G{\$V, \$E_VALS}, s, d, :, vals)" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        @testset "Params: V = $V, E_VALS = $E_VALS" for
            V in TEST_VERTEX_TYPES_SMALL,
            E_VALS in TEST_EDGEVAL_TYPES_SMALL

            gs = is_directed(G) ? cycle_digraph(V(5)) : cycle_graph(V(4))
            g = G(gs, edgeval_types=typetuple(E_VALS), edgeval_init=(s, d) -> rand_sample(E_VALS))
            @assert g isa G{V, Tuple{}, E_VALS}

            @testset "Correct values set" begin
                edges_to_test = is_directed(g) ? edges(gs) :
                            edges(gs) ∪ reverse.(edges(gs))

                @test all(edges_to_test) do e
                    s, d = src(e), dst(e)

                    vals = rand_sample(E_VALS)
                    set_edgeval!(g, s, d, :, vals)
                    get_edgeval(g, s, d, :) == vals || return false

                end
            end

            if !is_directed(g)
                @testset "Correct values set for reverse edge" begin
                    @test all(edges(gs) ∪ reverse.(edges(gs))) do e
                        s, d = src(e), dst(e)
                        vals = rand_sample(E_VALS)
                        set_edgeval!(g, s, d, :, vals)

                        get_edgeval(g, d, s, :) == vals
                    end
                end
            end
        end
    end

    @testset "set_edgeval!(::$G{\$V, \$E_VALS}, s, d, val, \$key)" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        @testset "Params: V = $V, E_VALS = $E_VALS, key = $key" for
            V in TEST_VERTEX_TYPES_SMALL,
            E_VALS in TEST_EDGEVAL_TYPES_SMALL,
            key in allkeys_for_E_VALS(E_VALS)

            gs = is_directed(G) ? cycle_digraph(V(5)) : cycle_graph(V(4))
            g = G(gs, edgeval_types=typetuple(E_VALS), edgeval_init=(s, d) -> rand_sample(E_VALS))
            @assert g isa G{V, Tuple{}, E_VALS}

            @testset "Correct values set" begin
                edges_to_test = is_directed(g) ? edges(gs) :
                            edges(gs) ∪ reverse.(edges(gs))

                @test all(edges_to_test) do e
                    s, d = src(e), dst(e)
                    val = rand_sample(E_VALS)[key]
                    set_edgeval!(g, s, d, key, val)

                    get_edgeval(g, s, d, :)[key] == val

                end
            end

            if !is_directed(g)
                @testset "Correct values set for reverse edge" begin
                    @test all(edges(gs) ∪ reverse.(edges(gs))) do e
                        s, d = src(e), dst(e)
                        val = rand_sample(E_VALS)[key]
                        set_edgeval!(g, s, d, key, val)

                        get_edgeval(g, d, s, :)[key] == val
                    end
                end
            end
        end
    end

    @testset "set_edgeval!(::$G{\$V, \$E_VALS}, s, d, val)" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        @testset "Params: V = $V, E_VALS = $E_VALS" for
            V in TEST_VERTEX_TYPES_SMALL,
            E_VALS in TEST_EDGEVAL_TYPES_SINGE_VALUE_SMALL

            gs = is_directed(G) ? cycle_digraph(V(5)) : cycle_graph(V(4))
            g = G(gs, edgeval_types=typetuple(E_VALS), edgeval_init=(s, d) -> rand_sample(E_VALS))
            @assert g isa G{V, Tuple{}, E_VALS}

            @testset "Correct values set" begin
                edges_to_test = is_directed(g) ? edges(gs) :
                            edges(gs) ∪ reverse.(edges(gs))

                @test all(edges_to_test) do e
                    s, d = src(e), dst(e)
                    val = rand_sample(E_VALS.types[1])
                    set_edgeval!(g, s, d, val)

                    get_edgeval(g, s, d, :)[1] == val

                end
            end

            if !is_directed(g)
                @testset "Correct values set for reverse edge" begin
                    @test all(edges(gs) ∪ reverse.(edges(gs))) do e
                        s, d = src(e), dst(e)
                        val = rand_sample(E_VALS.types[1])
                        set_edgeval!(g, s, d, val)

                        get_edgeval(g, d, s, :)[1] == val
                    end
                end
            end
        end
    end

    @testset "set_edgeval(g, s, d, :, values) where values must be converted to E_VALS)" begin

        g1 = ValGraph(2, edgeval_types=(Int8, Float32))
        add_edge!(g1, 1, 2, (1.0, 2))
        set_edgeval!(g1, 1, 2, :, (11.0, 22))
        @test get_edgeval(g1, 1, 2, :) == (11, 22.0)

        g2 = ValDiGraph(2, edgeval_types=(a=Int8, b=Float32))
        add_edge!(g2, 1, 2, (a=1.0, b=2))
        set_edgeval!(g2, 1, 2, :, (a=11.0, b=22))
        @test get_edgeval(g2, 1, 2, :) == (a=11, b=22.0)

        g3 = ValOutDiGraph(2, edgeval_types=(a=Union{Int, Nothing, Missing},))
        add_edge!(g3, 1, 2, (a=1,))
        set_edgeval!(g3, 1, 2, :, (a=nothing,))
        @test get_edgeval(g3, 1, 2) == nothing
        set_edgeval!(g3, 1, 2, :, (a=missing,))
        @test ismissing(get_edgeval(g3, 1, 2))
    end
end

@testset "Edgeval getters" begin

    @testset "get_edgeval(::$G{\$V, \$E_VALS}, s, d, :)" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        @testset "Params: V = $V, E_VALS = $E_VALS" for
            V in TEST_VERTEX_TYPES_SMALL,
            E_VALS in TEST_EDGEVAL_TYPES_SMALL

            gs = is_directed(G) ? cycle_digraph(V(5)) : cycle_graph(V(4))
            g = G(gs, edgeval_types=typetuple(E_VALS), edgeval_init=(s, d) -> rand_sample(E_VALS))
            @assert g isa G{V, Tuple{}, E_VALS}

            @testset "Getting correct values" begin
                edges_to_test = is_directed(g) ? edges(gs) :
                            edges(gs) ∪ reverse.(edges(gs))

                @test all(edges_to_test) do e
                    s, d = src(e), dst(e)
                    vals = rand_sample(E_VALS)
                    set_edgeval!(g, s, d, :, vals)

                    get_edgeval(g, s, d, :) == vals
                end
            end
        end
    end

    @testset "get_edgeval_or(::$G{\$V, \$E_VALS}, s, d, :, \$default)" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        @testset "Params: V = $V, E_VALS = $E_VALS, default = $(repr(default))" for
            V in TEST_VERTEX_TYPES_SMALL,
            E_VALS in TEST_EDGEVAL_TYPES_SMALL,
            default in (nothing, 0)

            gs = is_directed(G) ? cycle_digraph(V(5)) : cycle_graph(V(4))
            g = G(gs, edgeval_types=typetuple(E_VALS), edgeval_init=(s, d) -> rand_sample(E_VALS))
            @assert g isa G{V, Tuple{}, E_VALS}

            @testset "Getting correct values" begin

                @test all(Iterators.product(vertices(g), vertices(g))) do (s, d)
                    vals = rand_sample(E_VALS)
                    if has_edge(g, s, d)
                        set_edgeval!(g, s, d, :, vals)
                    end

                    get_edgeval_or(g, s, d, :, default) == (has_edge(g, s, d) ? vals : default)
                end
            end
        end
    end

    # covering a special case
    @testset "get_edgeval_or for ValGraph with colon key - deg(s) > deg(d)" begin

        g = ValGraph(star_graph(3), edgeval_types=(Int, ), edgeval_init=(s, d) -> (rand(Int),))

        @test get_edgeval_or(g, 1, 2, :, nothing) == get_edgeval_or(g, 2, 1, :, nothing)
    end

    @testset "get_edgeval with colon for non existing edge should throw error" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        g = G(3, edgeval_types=(Int, Float64))

        @test_throws ErrorException get_edgeval(g, 1, 2, :)
    end

    @testset "get_edgeval(::$G{\$V, \$E_VALS}, s, d, \$key)" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        @testset "Params: V = $V, E_VALS = $E_VALS, key = $key" for
            V in TEST_VERTEX_TYPES_SMALL,
            E_VALS in TEST_EDGEVAL_TYPES_SMALL,
            key in allkeys_for_E_VALS(E_VALS)

            gs = is_directed(G) ? cycle_digraph(V(5)) : cycle_graph(V(4))
            g = G(gs, edgeval_types=typetuple(E_VALS), edgeval_init=(s, d) -> rand_sample(E_VALS))
            @assert g isa G{V, Tuple{}, E_VALS}

            @testset "Getting correct value" begin
                edges_to_test = is_directed(g) ? edges(gs) :
                            edges(gs) ∪ reverse.(edges(gs))

                @test all(edges_to_test) do e
                    s, d = src(e), dst(e)
                    vals = rand_sample(E_VALS)
                    set_edgeval!(g, s, d, :, vals)

                    get_edgeval(g, s, d, key) == vals[key]
                end
            end
        end
    end

    @testset "get_edgeval(::$G{\$V, \$E_VALS}, s, d)" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        @testset "Params: V = $V, E_VALS = $E_VALS" for
            V in TEST_VERTEX_TYPES_SMALL,
            E_VALS in TEST_EDGEVAL_TYPES_SINGE_VALUE_SMALL

            gs = is_directed(G) ? cycle_digraph(V(5)) : cycle_graph(V(4))
            g = G(gs, edgeval_types=typetuple(E_VALS), edgeval_init=(s, d) -> rand_sample(E_VALS))
            @assert g isa G{V, Tuple{}, E_VALS}

            @testset "Getting correct value" begin
                edges_to_test = is_directed(g) ? edges(gs) :
                            edges(gs) ∪ reverse.(edges(gs))

                @test all(edges_to_test) do e
                    s, d = src(e), dst(e)
                    vals = rand_sample(E_VALS)
                    set_edgeval!(g, s, d, :, vals)

                    get_edgeval(g, s, d) == vals[1]
                end
            end
        end
    end

    @testset "get_edgeval with correct key for non existing edge should throw error" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        g = G(4, edgeval_types=(Int, ))

        @test_throws ErrorException get_edgeval(g, 1, 2, 1)
    end

    @testset "get_edgeval_or(::$G{\$V, \$E_VALS}, s, d, \$key, default)" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        @testset "Params: V = $V, E_VALS = $E_VALS, key = $key, default = $(repr(default))" for
            V in TEST_VERTEX_TYPES_SMALL,
            E_VALS in TEST_EDGEVAL_TYPES_SMALL,
            key in allkeys_for_E_VALS(E_VALS),
            default in (nothing, 0)

            gs = is_directed(G) ? cycle_digraph(V(5)) : cycle_graph(V(4))
            g = G(gs, edgeval_types=typetuple(E_VALS), edgeval_init=(s, d) -> rand_sample(E_VALS))
            @assert g isa G{V, Tuple{}, E_VALS}

            @testset "Getting correct value" begin

                @test all(Iterators.product(vertices(g), vertices(g))) do (s, d)
                    vals = rand_sample(E_VALS)
                    if has_edge(g, s, d)
                        set_edgeval!(g, s, d, :, vals)
                    end

                    get_edgeval_or(g, s, d, key, default) == (has_edge(g, s, d) ?
                        vals[key] : default)
                end
            end
        end
    end

    @testset "get_edgeval_or(::$G{\$V, \$E_VALS}, s, d, default)" for
        G in (ValGraph, ValOutDiGraph, ValDiGraph)

        @testset "Params: V = $V, E_VALS = $E_VALS, default = $(repr(default))" for
            V in TEST_VERTEX_TYPES_SMALL,
            E_VALS in TEST_EDGEVAL_TYPES_SINGE_VALUE_SMALL,
            default in (nothing, 0)

            gs = is_directed(G) ? cycle_digraph(V(5)) : cycle_graph(V(4))
            g = G(gs, edgeval_types=typetuple(E_VALS), edgeval_init=(s, d) -> rand_sample(E_VALS))
            @assert g isa G{V, Tuple{}, E_VALS}

            @testset "Getting correct value" begin

                @test all(Iterators.product(vertices(g), vertices(g))) do (s, d)
                    vals = rand_sample(E_VALS)
                    if has_edge(g, s, d)
                        set_edgeval!(g, s, d, :, vals)
                    end

                    get_edgeval_or(g, s, d, default) == (has_edge(g, s, d) ?
                        vals[1] : default)
                end
            end
        end
    end

end


text:
#=
The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3).
In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.

Find the smallest cube for which exactly five permutations of its digits are cube.
=#
include("projecteulerutils.jl")

function largest_permutation(i)
  nd(reverse(sort(reverse(digits(i)))))
end

function calc()
  i, max_permutations = 1, 5
  hash = Dict{Int64, Array{Int64}}()  #largest_permutation => [smallest_cube, count]
  while true
    current_cube = i ^ 3
    largest = largest_permutation(current_cube)
    v = get(hash, largest, [current_cube, 0])
    count = v[2] + 1
    hash[largest] = [v[1], count]
    if count == max_permutations
      return v[1]
    end
    i = i + 1
  end
end
@time println(calc())

max_stars_repo_name: daniel-beard/JuliaProjectEuler

max_issues_repo_name: daniel-beard/JuliaProjectEuler

max_forks_repo_name: daniel-beard/JuliaProjectEuler


text:
#=
    float(Int1
=#
import Base:signed, unsigned

@inline floating(::Type{ UInt16}) = Float16
@inline floating(::Type{ UInt32}) = Float32
@inline floating(::Type{ UInt64}) = Float64
@inline floating(::Type{  Int16}) = Float16
@inline floating(::Type{  Int32}) = Float32
@inline floating(::Type{  Int64}) = Float64
@inline floating(::Type{Float16}) = Float16
@inline floating(::Type{Float32}) = Float32
@inline floating(::Type{Float64}) = Float64

@inline signed(::Type{ UInt16}) = Int16
@inline signed(::Type{ UInt32}) = Int32
@inline signed(::Type{ UInt64}) = Int64
@inline signed(::Type{UInt128}) = Int128
@inline signed(::Type{  Int16}) = Int16
@inline signed(::Type{  Int32}) = Int32
@inline signed(::Type{  Int64}) = Int64
@inline signed(::Type{ Int128}) = Int128
@inline signed(::Type{Float16}) = Int16
@inline signed(::Type{Float32}) = Int32
@inline signed(::Type{Float64}) = Int64

@inline unsigned(::Type{ UInt16}) = UInt16
@inline unsigned(::Type{ UInt32}) = UInt32
@inline unsigned(::Type{ UInt64}) = UInt64
@inline unsigned(::Type{UInt128}) = UInt128
@inline unsigned(::Type{  Int16}) = UInt16
@inline unsigned(::Type{  Int32}) = UInt32
@inline unsigned(::Type{  Int64}) = UInt64
@inline unsigned(::Type{ Int128}) = UInt128
@inline unsigned(::Type{Float16}) = UInt16
@inline unsigned(::Type{Float32}) = UInt32
@inline unsigned(::Type{Float64}) = UInt64

@inline floating(x::T) where T<:Union{Signed, Unsigned, Base.IEEEFloat} =
   reinterpret(floating(T), x)
@inline signed(x::T) where T<:Union{Signed, Unsigned, Base.IEEEFloat} =
   reinterpret(signed(T), x)
@inline unsigned(x::T) where T<:Union{Signed, Unsigned, Base.IEEEFloat} =
   reinterpret(unsigned(T), x)


text:
#################### File I/O ####################
"""
    Base.read(name::AbstractString, ::Type{T}) where {T<:AbstractChains}

Read a chain from an external file.

Returns an `AbstractChains` subtype read from an external file.

* `name` : file to read or write. Recommended convention is for the file name to be specified with a `.jls` extension.

* `T` : chain type to read.

* `c` : chain to write.
"""
function Base.read(name::AbstractString, ::Type{T}) where {T<:AbstractChains}
  c = open(deserialize, name, "r")
  isa(c, T) || throw(TypeError(:open, "read(\"$name\", $T)", T, c))
  c
end
"""
    Base.write(name::AbstractString, c::AbstractChains)

Write a chain to an external file.

Returns a written external file containing a subtype.

* `name` : file to read or write. Recommended convention is for the file name to be specified with a `.jls` extension.

* `T` : chain type to read.

* `c` : chain to write.
"""
function Base.write(name::AbstractString, c::AbstractChains)
  open(file -> serialize(file, c), name, "w")
end

"""
    readcoda(output::AbstractString, index::AbstractString)

Read MCMC sampler output generated in the CODA format by OpenBUGS. The function only retains those sampler iterations at which all model parameters were monitored.

Returns a `Chains` object containing the read sampler output.

* `output` : text file containing the iteration numbers and sampled values for the model parameters.

* `index` : text file containing the names of the parameters, followed by the first and last rows in which their output can be found in the `output` file.

"""
function readcoda(output::AbstractString, index::AbstractString)
  out = readdlm(output, Any)
  ind = readdlm(index, Any)

  firstind = ind[:, 2]
  firstiter = out[firstind, 1]
  lastind = ind[:, 3]
  lastiter = out[lastind, 1]

  thin = Int((lastiter[1] - firstiter[1]) / (lastind[1] - firstind[1]))
  window = maximum(firstiter):thin:minimum(lastiter)
  startind = firstind .+ (first(window) .- firstiter) ./ step(window)
  stopind = lastind .- (lastiter .- last(window)) ./ step(window)

  names = AbstractString[ind[:, 1]...]

  value = Array{Float64}(undef, length(window), length(names))
  for i in 1:size(value, 2)
    inds = Int(startind[i]):Int(stopind[i])
    value[:, i] = out[inds, 2]
  end

  Chains(value, start=first(window), thin=step(window), names=names)
end


text:
import Base.Iterators: flatten
using ModelingToolkit
using Catlab.Graphics.Graphviz
import Catlab.Graphics.Graphviz: Graph, Edge

graph_attrs = Attributes(:rankdir=>"LR")
node_attrs  = Attributes(:shape=>"plain", :style=>"filled", :color=>"white")
edge_attrs  = Attributes(:splines=>"splines")

"""    edgify(root::Operation, transition::Int, reverse::Bool)

convert a Model tranition into a Graphviz edge statement.
if reverse i true assume that this is the outgoing edge.
"""
function edgify(root::Operation, transition::Int, reverse::Bool)
    attr = Attributes()
    i = transition
    if root.op == (+)
        return map(root.args) do x
            weight = ""
            if x.op == (*)
                a = x.args[2].op.name
                weight = "$(x.args[1].value)"
            else
                a = x.op.name
            end
            b = string(a)
            attr =  Attributes(:label=>"$weight", :labelfontsize=>"6")
            return Edge(reverse ? ["T$i", "$b"] : ["$b", "T$i"],attr)
        end
    end
    if root.op == (*)
        b = string(root.args[2].op.name)
        weight = "$(root.args[1].value)"
        attr =  Attributes(:label=>"$weight", :labelfontsize=>"6")
    else
        b = string(root.op.name)
    end
    return [Edge(reverse ? ["T$i", "$b"] : ["$b", "T$i"], attr)]
end

"""    Graph(model::Model)

convert a Model into a GraphViz Graph. Transition are green boxes and states are blue circles. Arrows go from the input states to the output states for each transition.
"""
function Graph(model::Model)
    statenodes = [Node(string("$s"), Attributes(:shape=>"circle", :color=>"dodgerblue2")) for s in model.S]
    transnodes = [Node("T$i", Attributes(:shape=>"square", :color=>"forestgreen")) for i in 1:length(model.Δ)]

    stmts = vcat(statenodes, transnodes)
    edges = map(enumerate(model.Δ)) do (i,t)
        vcat(edgify(t[1], i, false), edgify(t[2], i, true))
    end |> flatten |> collect
    stmts = vcat(stmts, edges)
    g = Graphviz.Graph("G", true, stmts, graph_attrs, node_attrs,edge_attrs)
    return g
end


text:
using JLSO
import MLJModelInterface: save, restore
import MLJBase: Machine, machine

## SERIALIZATION

# helper:
_filename(file::IO) = string(rand(UInt))
_filename(file::String) = splitext(file)[1]

# saving:
"""
    MLJ.save(filename, mach::Machine; kwargs...)
    MLJ.save(io, mach::Machine; kwargs...)

    MLJBase.save(filename, mach::Machine; kwargs...)
    MLJBase.save(io, mach::Machine; kwargs...)

Serialize the machine `mach` to a file with path `filename`, or to an
input/output stream `io` (at least `IOBuffer` instances are
supported).

The format is JLSO (a wrapper for julia native or BSON serialization).
For some model types, a custom serialization will be additionally performed.

### Keyword arguments

These keyword arguments are passed to the JLSO serializer:

keyword        | values                        | default
---------------|-------------------------------|-------------------------
`format`       | `:julia_serialize`, `:BSON`   | `:julia_serialize`
`compression`  | `:gzip`, `:none`              | `:none`

See [https://github.com/invenia/JLSO.jl](https://github.com/invenia/JLSO.jl)
for details.

Any additional keyword arguments are passed to model-specific
serializers.

Machines are de-serialized using the `machine` constructor as shown in
the example below. Data (or nodes) may be optionally passed to the
constructor for retraining on new data using the saved model.

### Example

    using MLJ
    tree = @load DecisionTreeClassifier
    X, y = @load_iris
    mach = fit!(machine(tree, X, y))

    MLJ.save("tree.jlso", mach, compression=:none)
    mach_predict_only = machine("tree.jlso")
    predict(mach_predict_only, X)

    mach2 = machine("tree.jlso", selectrows(X, 1:100), y[1:100])
    predict(mach2, X) # same as above

    fit!(mach2) # saved learned parameters are over-written
    predict(mach2, X) # not same as above

    # using a buffer:
    io = IOBuffer()
    MLJ.save(io, mach)
    seekstart(io)
    predict_only_mach = machine(io)
    predict(predict_only_mach, X)

!!! warning "Only load files from trusted sources"
    Maliciously constructed JLSO files, like pickles, and most other
    general purpose serialization formats, can allow for arbitrary code
    execution during loading. This means it is possible for someone
    to use a JLSO file that looks like a serialized MLJ machine as a
    [Trojan
    horse](https://en.wikipedia.org/wiki/Trojan_horse_(computing)).

"""
function save(file::Union{String,IO},
              mach::Machine;
              verbosity=1,
              format=:julia_serialize,
              compression=:none,
              kwargs...)
    isdefined(mach, :fitresult)  ||
        error("Cannot save an untrained machine. ")

    # fallback `save` method returns `mach.fitresult` and saves nothing:
    serializable_fitresult =
        save(_filename(file), mach.model, mach.fitresult; kwargs...)

    JLSO.save(file,
              :model => mach.model,
              :fitresult => serializable_fitresult,
              :report => mach.report;
              format=format,
              compression=compression)
end

# deserializing:
function machine(file::Union{String,IO}, args...; cache=true, kwargs...)
    dict = JLSO.load(file)
    model = dict[:model]
    serializable_fitresult = dict[:fitresult]
    report = dict[:report]
    fitresult = restore(_filename(file), model, serializable_fitresult)
    if isempty(args)
        mach = Machine(model, cache=cache)
    else
        mach = machine(model, args..., cache=cache)
    end
    mach.state = 1
    mach.fitresult = fitresult
    mach.report = report
    return mach
end


text:
function dbscan(arr::Array{Float64,2} , ϵ::Number, minPoints::Int)

	nPoints = size(arr,1)
	dists = fill(0.0, nPoints, nPoints)
	connectedPaths = fill(0, nPoints, nPoints)

	seeds = Int[]
	counts = Int[]
	clusters = zeros(Int, nPoints)
	visited = zeros(Bool, nPoints)

	# Make superpixel distance matrix and connectivity matrix
	for i in  1:nPoints
		for j in 1:nPoints
			dists[i,j] = euclidean(arr[i,:],arr[j,:])
		end
	end

	reachable = findall(x->x <= ϵ, dists)
	connectedPaths[reachable] .= 1

	function regionQuery(idx)
		neighbors = findall(x -> x == 1, connectedPaths[:,idx])
		return neighbors
	end

	k = 0

	for pt in 1:nPoints
		if clusters[pt] == 0 && !visited[pt]
			visited[pt] == true
			neighbors = regionQuery(pt)
			if length(neighbors) >= minPoints
				k += 1
				clusters[pt] = k
				cnt = 1
				while !isempty(neighbors)
					q = popfirst!(neighbors)
					if !visited[q]
						visited[q] = true
						qNeighbors = regionQuery(q)
						for x in qNeighbors
							if clusters[x] == 0
								push!(neighbors, x)
							end
						end
					end
					if clusters[q] == 0
						clusters[q] = k
						cnt += 1
					end
				end
				push!(seeds, pt)
				push!(counts, cnt)

			end
		end
	end

	return clusters
end

max_stars_repo_name: neuro-myoung/CellSegmenter

max_issues_repo_name: neuro-myoung/CellSegmenter

max_forks_repo_name: neuro-myoung/CellSegmenter


text:
# R̂ of Gelman: page 284
function Rhat_gelman(chain, Npop, Ngeneration, Npar)
    # split each chain in two
    n = Int(floor(Ngeneration/2)) # length of chains that are split
    m = Npop*2
    chainsplit = zeros(eltype(chain), (m, Npar, n))
    chainsplit[1:Npop, :, :] .= chain[:,:,1:n]
    chainsplit[Npop+1:end, :, :] .= chain[:,:,n+1:2*n]
    # avg overall and within chain
    avg_par = mean(chainsplit, dims = [1,3])
    avg_chains = mean(chainsplit, dims = 3)
    # variance btw chains and within chain
    B = n/(m-1) * sum((avg_chains .- avg_par).^2, dims = 1)
    sj = 1/(n-1)*sum((chainsplit .- avg_chains).^2, dims =  3)
    W = 1/m * sum(sj, dims = 1)
    varhat = (n-1)/n * W .+ 1/n*B
    # Rhat is the ratio of (between + within) / within variance -> 1 if correct
    Rhat = sqrt.(varhat./W)[:]
    return Rhat
end

function flatten_chain(chain, Npop, Ngeneration, Npar)
    flatchain = zeros(eltype(chain), Npar, Npop*Ngeneration)
    for i = 1:Npar
        count = 0
        for  ig = 1:Ngeneration, ic = 1:Npop
            count += 1
            flatchain[i, count] = chain[ic, i, ig]
        end
    end
    return flatchain
end

function convergence_check(chain, log_obj, figure_path; verbose = true, parnames = [])
    Npop, Npar, Ngeneration = size(chain)
    return convergence_check(chain, log_obj, Npop, Ngeneration, Npar, figure_path; verbose = verbose, parnames = parnames)
end

function convergence_check(chain, log_obj, Npop, Ngeneration, Npar, figure_path; verbose = true, parnames = [])
    nrow, ncol = size(log_obj)
    @assert nrow == Npop "number of rows of log_obj is not equal to number of chains"
    @assert ncol == Ngeneration "number of columns of log_obj is not equal to number of generations simulated"
    n1, n2, n3 = size(chain)
    @assert n1 == Npop "#elements in first dimension of chain is not equal to number of chains simulated"
    @assert n2 == Npar "#elements in second dimension is not equal to number of parameters"
    @assert n3 == Ngeneration "#elements in third dimension of chain is not equal to number of generations simulated"

    if parnames == []
        for ip = 1:Npar
            append!(parnames, [string("par ", ip)])
        end
    end
    if verbose
        try
            mkpath(string(figure_path))
        catch e
            println(e)
        end
    end
    # acceptance ratio
    accept_ratio = sum(diff(log_obj, dims = 2).!=0., dims = 2)./ (Ngeneration-1)
    # plot the trace of the obj function value of the chains, clean out extreme values
    if verbose
        p_trace = plot(log_obj')
        savefig(p_trace, string(figure_path, "trace_logobj.png"))

        traceplots = []
        for par in 1:Npar
            append!(traceplots, [plot(reshape(chain[:, par , :], Npop, Ngeneration)', title=parnames[par])])
        end
        for par in 1:Npar
            par_trace = plot(traceplots[par])
            savefig(par_trace, string(figure_path, "trace_par_", par, ".png"))
        end
        for par in 1:Npar
            hi = histogram(chain[:, par , :][:], nbins = 33, normed=true)
            savefig(hi, string(figure_path, "hist_par_", par, ".png"))
        end
    end

    # Rhat Gelman
    Rhat = Rhat_gelman(chain, Npop, Ngeneration, Npar)
    if verbose
        println("Summary Checks")
        println(" ")
        println("Acceptance Ratio of each chain:")
        println(accept_ratio)
        println(" ")
        println("Rhat Gelman: $Rhat")
        println(" ")
        display(p_trace)
    end
    return accept_ratio, Rhat
end

function mean_cov_chain(chain, Npop, Ngeneration, Npar)
    n1, n2, n3 = size(chain)
    @assert n1 == Npop "#elements in first dimension of chain is not equal to number of chains simulated"
    @assert n2 == Npar "#elements in second dimension is not equal to number of parameters"
    @assert n3 == Ngeneration "#elements in third dimension of chain is not equal to number of generations simulated"

    flatchain = flatten_chain(chain, Npop, Ngeneration, Npar)
    b = mean(flatchain, dims=2)[:]
    cov = 1 ./(Ngeneration*Npop) * (flatchain .- b) * (flatchain .- b)'
    return b, cov
end

function mean_cov_chain(chain)
    Npop, Npar, Ngeneration = size(chain)
    return mean_cov_chain(chain, Npop, Ngeneration, Npar)
end

function save_res(b, Σb, Rhat, accept_ratio, path)
    writecsv(string(path, "_b.csv"), b)
    writecsv(string(path, "_Sigmab.csv"), Σb)
    writecsv(string(path, "_Rhat.csv"), Rhat)
    writecsv(string(path, "_accept_ratio.csv"), accept_ratio)
end

function extract_best(mc)
    bestval = maximum(mc.log_obj)
    (rows, cols) = findn(bestval.==mc.log_obj)
    bestpar = mc.chain[rows[1], :, cols[1]]
    return bestval, bestpar
end


text:
module ExtraDirectDep

end


text:
@testset "Embeddings" begin
  Qx, x = QQ["x"]
  K, a = number_field(x^3 - 2, "a")
  @test (1, 1) == @inferred signature(K)
  emb = @inferred complex_embeddings(K)
  @test (@inferred number_field(emb[1])) === K
  @test length(emb) == 3
  @test length(real_embeddings(K)) == 1
  @test real_embeddings(K) == real_embeddings(K)
  @test complex_embeddings(K) === complex_embeddings(K) # caching

  @test @inferred isreal(emb[1])
  @test @inferred !isreal(emb[2])
  @test @inferred is_imaginary(emb[2])
  @test conj(emb[1]) === emb[1]
  @test conj(emb[2]) === emb[3]
  @test conj(emb[3]) === emb[2]

  for e in emb
    @test sprint(show, MIME"text/plain"(), e) isa String
    @test sprint(show, e) isa String
  end

  for e in emb
    for p in [32, 64, 128, 256]
      @test Hecke.radiuslttwopower(e(a, p), -p)
      @test Hecke.radiuslttwopower(evaluate(a, e, p), -p)
    end
  end

  @test overlaps(conj(emb[2](a)), (conj(emb[2]))(a))

  k, b = number_field(x - 1)
  f = hom(k, K, one(K))
  for e in emb
    length(unique([restrict(e, f) for e in emb])) == 1
  end

  ee = complex_embeddings(k)[1]
  @test length(@inferred extend(ee, f)) == 3

  ee = restrict(emb[1], f)
  c = ee(b)
  @test overlaps(c, one(parent(c)))

  z = rand(K, -10:10)^100
  for p in [32, 128, 256, 1024]
    for e in emb
      fn = evaluation_function(e, p)
      @test Hecke.radiuslttwopower(fn(z), -p)
      c = e(z, p)
      @test Hecke.radiuslttwopower(c, -p)
    end
  end

end