text:
module Relationships

using Inflector
using SearchLight
using SearchLight.Migration

export Relationship, Relationship!, related, isrelated

function create_relationship_migration(r1::Type{T}, r2::Type{R})::String where {T<:AbstractModel, R<:AbstractModel}
  names = map(x -> split(string(x), '.')[end] |> string |> lowercase |> Inflector.to_plural, [r1, r2]) |> sort
  Migration.new_relationship_table("create_relationship_table_$(names[1])_$(names[2])", names...)
end

function relationship_name(r1::Type{T}, r2::Type{R})::String where {T<:AbstractModel, R<:AbstractModel}
  map(x -> split(string(x), '.')[end] |> string |> Inflector.to_plural, [r1, r2]) |> sort |> join
end

function relationship_field_name(x::Type{T})::String where {T<:AbstractModel}
  (split(string(x), '.')[end] |> string |> lowercase |> Inflector.to_plural) * "_id"
end

function Relationship(r1::Type{T}, r2::Type{R}; context::Module = @__MODULE__)::DataType where {T<:AbstractModel, R<:AbstractModel}
  isdefined(context, Symbol(relationship_name(r1, r2))) &&
    return getfield(context, Symbol(relationship_name(r1, r2)))

  struct_str = "mutable struct $(relationship_name(r1, r2)) <: AbstractModel;
                  id::DbId;
                  $(relationship_field_name(r1))::DbId;
                  $(relationship_field_name(r2))::DbId;
                end"

  Core.eval(context, Meta.parse(struct_str))

  kwd_constructor_str = "$(relationship_name(r1, r2))(; id::DbId = DbId(), $(relationship_field_name(r1))::DbId = DbId(), $(relationship_field_name(r2))::DbId = DbId()) = $(relationship_name(r1, r2))(id, $(relationship_field_name(r1)), $(relationship_field_name(r2)))"

  Core.eval(context, Meta.parse(kwd_constructor_str))

  getfield(context, Symbol(relationship_name(r1, r2)))
end

function Relationship!(r1::T, r2::R; context::Module = @__MODULE__)::AbstractModel where {T<:AbstractModel, R<:AbstractModel}
  relationship = Relationship(typeof(r1), typeof(r2); context = context)

  findone_or_create(relationship;
                    NamedTuple{ (Symbol(relationship_field_name(typeof(r1))), Symbol(relationship_field_name(typeof(r2)))) }(
                      (getfield(r1, pk(r1) |> Symbol), getfield(r2, pk(r2) |> Symbol)) )...) |> save!
end

function related(m::T, r::Type{R}; through::Vector = [], context::Module = @__MODULE__)::Vector{R} where {T<:AbstractModel, R<:AbstractModel}
  joins = SQLJoin[]
  models = vcat(typeof(m), through, r) |> pairs

  for i in length(models):-1:2
    relationship = Relationship(models[i], models[i-1]; context = context)

    push!(joins, SQLJoin(relationship,
                        [
                          SQLOn("$(SearchLight.table(models[i])).$(pk(models[i]))",
                              "$(SearchLight.table(relationship)).$(relationship_field_name(models[i]))")
                        ]
                        ))

  push!(joins, SQLJoin(models[i-1],
                        [
                          SQLOn("$(SearchLight.table(models[i-1])).$(pk(models[i-1]))",
                              "$(SearchLight.table(relationship)).$(relationship_field_name(models[i-1]))")
                        ]
                        ))
  end

  find(r, SQLQuery(
    where = SQLWhereEntity[SQLWhereExpression("$(SearchLight.table(typeof(m))).$(pk(m)) = ?", SQLInput[getfield(m, Symbol(pk(m)))])],
  ), joins)
end

function isrelated(m::T, r::R; through::Vector = [], context::Module = @__MODULE__)::Bool where {T<:AbstractModel, R<:AbstractModel}
  r in related(m, typeof(r), through = through)
end

end


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

## IOStream

const sizeof_ios_t = Int(ccall(:jl_sizeof_ios_t, Cint, ()))

"""
    IOStream

A buffered IO stream wrapping an OS file descriptor.
Mostly used to represent files returned by [`open`](@ref).
"""
mutable struct IOStream <: IO
    handle::Ptr{Cvoid}
    ios::Array{UInt8,1}
    name::String
    mark::Int64
    lock::ReentrantLock
    _dolock::Bool

    IOStream(name::AbstractString, buf::Array{UInt8,1}) = new(pointer(buf), buf, name, -1, ReentrantLock(), true)
end

function IOStream(name::AbstractString, finalize::Bool)
    buf = zeros(UInt8,sizeof_ios_t)
    x = IOStream(name, buf)
    if finalize
        finalizer(close, x)
    end
    return x
end
IOStream(name::AbstractString) = IOStream(name, true)

unsafe_convert(T::Type{Ptr{Cvoid}}, s::IOStream) = convert(T, pointer(s.ios))
show(io::IO, s::IOStream) = print(io, "IOStream(", s.name, ")")

macro _lock_ios(s, expr)
    s = esc(s)
    quote
        l = ($s)._dolock
        temp = ($s).lock
        l && lock(temp)
        val = $(esc(expr))
        l && unlock(temp)
        val
    end
end

"""
    fd(stream)

Return the file descriptor backing the stream or file. Note that this function only applies
to synchronous `File`'s and `IOStream`'s not to any of the asynchronous streams.
"""
fd(s::IOStream) = Int(ccall(:jl_ios_fd, Clong, (Ptr{Cvoid},), s.ios))

stat(s::IOStream) = stat(fd(s))

isopen(s::IOStream) = ccall(:ios_isopen, Cint, (Ptr{Cvoid},), s.ios) != 0

function close(s::IOStream)
    bad = @_lock_ios s ccall(:ios_close, Cint, (Ptr{Cvoid},), s.ios) != 0
    systemerror("close", bad)
end

function flush(s::IOStream)
    sigatomic_begin()
    bad = @_lock_ios s ccall(:ios_flush, Cint, (Ptr{Cvoid},), s.ios) != 0
    sigatomic_end()
    systemerror("flush", bad)
end

iswritable(s::IOStream) = ccall(:ios_get_writable, Cint, (Ptr{Cvoid},), s.ios)!=0

isreadable(s::IOStream) = ccall(:ios_get_readable, Cint, (Ptr{Cvoid},), s.ios)!=0

"""
    truncate(file, n)

Resize the file or buffer given by the first argument to exactly `n` bytes, filling
previously unallocated space with '\\0' if the file or buffer is grown.

# Examples
```jldoctest
julia> io = IOBuffer();

julia> write(io, "JuliaLang is a GitHub organization.")
35

julia> truncate(io, 15)
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=15, maxsize=Inf, ptr=16, mark=-1)

julia> String(take!(io))
"JuliaLang is a "

julia> io = IOBuffer();

julia> write(io, "JuliaLang is a GitHub organization.");

julia> truncate(io, 40);

julia> String(take!(io))
"JuliaLang is a GitHub organization.\\0\\0\\0\\0\\0"
```
"""
function truncate(s::IOStream, n::Integer)
    err = @_lock_ios s ccall(:ios_trunc, Cint, (Ptr{Cvoid}, Csize_t), s.ios, n) != 0
    systemerror("truncate", err)
    return s
end

"""
    seek(s, pos)

Seek a stream to the given position.

# Examples
```jldoctest
julia> io = IOBuffer("JuliaLang is a GitHub organization.");

julia> seek(io, 5);

julia> read(io, Char)
'L': ASCII/Unicode U+004C (category Lu: Letter, uppercase)
```
"""
function seek(s::IOStream, n::Integer)
    ret = @_lock_ios s ccall(:ios_seek, Int64, (Ptr{Cvoid}, Int64), s.ios, n)
    systemerror("seek", ret == -1)
    ret < -1 && error("seek failed")
    return s
end

"""
    seekstart(s)

Seek a stream to its beginning.

# Examples
```jldoctest
julia> io = IOBuffer("JuliaLang is a GitHub organization.");

julia> seek(io, 5);

julia> read(io, Char)
'L': ASCII/Unicode U+004C (category Lu: Letter, uppercase)

julia> seekstart(io);

julia> read(io, Char)
'J': ASCII/Unicode U+004A (category Lu: Letter, uppercase)
```
"""
seekstart(s::IO) = seek(s,0)

"""
    seekend(s)

Seek a stream to its end.
"""
function seekend(s::IOStream)
    err = @_lock_ios s ccall(:ios_seek_end, Int64, (Ptr{Cvoid},), s.ios) != 0
    systemerror("seekend", err)
    return s
end

"""
    skip(s, offset)

Seek a stream relative to the current position.

# Examples
```jldoctest
julia> io = IOBuffer("JuliaLang is a GitHub organization.");

julia> seek(io, 5);

julia> skip(io, 10);

julia> read(io, Char)
'G': ASCII/Unicode U+0047 (category Lu: Letter, uppercase)
```
"""
function skip(s::IOStream, delta::Integer)
    ret = @_lock_ios s ccall(:ios_skip, Int64, (Ptr{Cvoid}, Int64), s.ios, delta)
    systemerror("skip", ret == -1)
    ret < -1 && error("skip failed")
    return s
end

"""
    position(s)

Get the current position of a stream.

# Examples
```jldoctest
julia> io = IOBuffer("JuliaLang is a GitHub organization.");

julia> seek(io, 5);

julia> position(io)
5

julia> skip(io, 10);

julia> position(io)
15

julia> seekend(io);

julia> position(io)
35
```
"""
function position(s::IOStream)
    pos = @_lock_ios s ccall(:ios_pos, Int64, (Ptr{Cvoid},), s.ios)
    systemerror("position", pos == -1)
    return pos
end

function filesize(s::IOStream)
    sz = @_lock_ios s ccall(:ios_filesize, Int64, (Ptr{Cvoid},), s.ios)
    if sz == -1
        err = Libc.errno()
        throw(IOError(string("filesize: ", Libc.strerror(err), " for ", s.name), err))
    end
    return sz
end

_eof_nolock(s::IOStream) = ccall(:ios_eof_blocking, Cint, (Ptr{Cvoid},), s.ios) != 0
eof(s::IOStream) = @_lock_ios s _eof_nolock(s)

## constructing and opening streams ##

# "own" means the descriptor will be closed with the IOStream

"""
    fdio([name::AbstractString, ]fd::Integer[, own::Bool=false]) -> IOStream

Create an [`IOStream`](@ref) object from an integer file descriptor. If `own` is `true`, closing
this object will close the underlying descriptor. By default, an `IOStream` is closed when
it is garbage collected. `name` allows you to associate the descriptor with a named file.
"""
function fdio(name::AbstractString, fd::Integer, own::Bool=false)
    s = IOStream(name)
    ccall(:ios_fd, Ptr{Cvoid}, (Ptr{Cvoid}, Clong, Cint, Cint),
          s.ios, fd, 0, own)
    return s
end
fdio(fd::Integer, own::Bool=false) = fdio(string("<fd ",fd,">"), fd, own)

"""
    open(filename::AbstractString; lock = true, keywords...) -> IOStream

Open a file in a mode specified by five boolean keyword arguments:

| Keyword    | Description             | Default                                 |
|:-----------|:-----------------------|:----------------------------------------|
| `read`     | open for reading       | `!write`                                |
| `write`    | open for writing       | `truncate \\| append`                   |
| `create`   | create if non-existent | `!read & write \\| truncate \\| append` |
| `truncate` | truncate to zero size  | `!read & write`                         |
| `append`   | seek to end            | `false`                                 |

The default when no keywords are passed is to open files for reading only.
Returns a stream for accessing the opened file.

The `lock` keyword argument controls whether operations will be locked for
safe multi-threaded access.

!!! compat "Julia 1.5"
    The `lock` argument is available as of Julia 1.5.
"""
function open(fname::AbstractString; lock = true,
    read     :: Union{Bool,Nothing} = nothing,
    write    :: Union{Bool,Nothing} = nothing,
    create   :: Union{Bool,Nothing} = nothing,
    truncate :: Union{Bool,Nothing} = nothing,
    append   :: Union{Bool,Nothing} = nothing,
)
    flags = open_flags(
        read = read,
        write = write,
        create = create,
        truncate = truncate,
        append = append,
    )
    s = IOStream(string("<file ",fname,">"))
    if !lock
        s._dolock = false
    end
    systemerror("opening file $(repr(fname))",
                ccall(:ios_file, Ptr{Cvoid},
                      (Ptr{UInt8}, Cstring, Cint, Cint, Cint, Cint),
                      s.ios, fname, flags.read, flags.write, flags.create, flags.truncate) == C_NULL)
    if flags.append
        systemerror("seeking to end of file $fname", ccall(:ios_seek_end, Int64, (Ptr{Cvoid},), s.ios) != 0)
    end
    return s
end

"""
    open(filename::AbstractString, [mode::AbstractString]; lock = true) -> IOStream

Alternate syntax for open, where a string-based mode specifier is used instead of the five
booleans. The values of `mode` correspond to those from `fopen(3)` or Perl `open`, and are
equivalent to setting the following boolean groups:

| Mode | Description                   | Keywords                            |
|:-----|:------------------------------|:------------------------------------|
| `r`  | read                          | none                                |
| `w`  | write, create, truncate       | `write = true`                      |
| `a`  | write, create, append         | `append = true`                     |
| `r+` | read, write                   | `read = true, write = true`         |
| `w+` | read, write, create, truncate | `truncate = true, read = true`      |
| `a+` | read, write, create, append   | `append = true, read = true`        |

The `lock` keyword argument controls whether operations will be locked for
safe multi-threaded access.

# Examples
```jldoctest
julia> io = open("myfile.txt", "w");

julia> write(io, "Hello world!");

julia> close(io);

julia> io = open("myfile.txt", "r");

julia> read(io, String)
"Hello world!"

julia> write(io, "This file is read only")
ERROR: ArgumentError: write failed, IOStream is not writeable
[...]

julia> close(io)

julia> io = open("myfile.txt", "a");

julia> write(io, "This stream is not read only")
28

julia> close(io)

julia> rm("myfile.txt")
```

!!! compat "Julia 1.5"
    The `lock` argument is available as of Julia 1.5.
"""
function open(fname::AbstractString, mode::AbstractString; lock = true)
    mode == "r"  ? open(fname, lock = lock, read = true)                  :
    mode == "r+" ? open(fname, lock = lock, read = true, write = true)    :
    mode == "w"  ? open(fname, lock = lock, truncate = true)              :
    mode == "w+" ? open(fname, lock = lock, truncate = true, read = true) :
    mode == "a"  ? open(fname, lock = lock, append = true)                :
    mode == "a+" ? open(fname, lock = lock, append = true, read = true)   :
    throw(ArgumentError("invalid open mode: $mode"))
end

## low-level calls ##

function write(s::IOStream, b::UInt8)
    iswritable(s) || throw(ArgumentError("write failed, IOStream is not writeable"))
    Int(@_lock_ios s ccall(:ios_putc, Cint, (Cint, Ptr{Cvoid}), b, s.ios))
end

function unsafe_write(s::IOStream, p::Ptr{UInt8}, nb::UInt)
    iswritable(s) || throw(ArgumentError("write failed, IOStream is not writeable"))
    return Int(@_lock_ios s ccall(:ios_write, Csize_t, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), s.ios, p, nb))
end

# num bytes available without blocking
bytesavailable(s::IOStream) = @_lock_ios s ccall(:jl_nb_available, Int32, (Ptr{Cvoid},), s.ios)

function readavailable(s::IOStream)
    lock(s.lock)
    nb = ccall(:jl_nb_available, Int32, (Ptr{Cvoid},), s.ios)
    if nb == 0
        ccall(:ios_fillbuf, Cssize_t, (Ptr{Cvoid},), s.ios)
        nb = ccall(:jl_nb_available, Int32, (Ptr{Cvoid},), s.ios)
    end
    a = Vector{UInt8}(undef, nb)
    nr = ccall(:ios_readall, Csize_t, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), s, a, nb)
    if nr != nb
        unlock(s.lock)
        throw(EOFError())
    end
    unlock(s.lock)
    return a
end

function read(s::IOStream, ::Type{UInt8})
    b = @_lock_ios s ccall(:ios_getc, Cint, (Ptr{Cvoid},), s.ios)
    if b == -1
        throw(EOFError())
    end
    return b % UInt8
end

if ENDIAN_BOM == 0x04030201
function read(s::IOStream, T::Union{Type{Int16},Type{UInt16},Type{Int32},Type{UInt32},Type{Int64},Type{UInt64}})
    n = sizeof(T)
    l = s._dolock
    _lock = s.lock
    l && lock(_lock)
    if ccall(:jl_ios_buffer_n, Cint, (Ptr{Cvoid}, Csize_t), s.ios, n) != 0
        l && unlock(_lock)
        throw(EOFError())
    end
    x = ccall(:jl_ios_get_nbyte_int, UInt64, (Ptr{Cvoid}, Csize_t), s.ios, n) % T
    l && unlock(_lock)
    return x
end

read(s::IOStream, ::Type{Float16}) = reinterpret(Float16, read(s, Int16))
read(s::IOStream, ::Type{Float32}) = reinterpret(Float32, read(s, Int32))
read(s::IOStream, ::Type{Float64}) = reinterpret(Float64, read(s, Int64))
end

function unsafe_read(s::IOStream, p::Ptr{UInt8}, nb::UInt)
    nr = @_lock_ios s ccall(:ios_readall, Csize_t, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), s, p, nb)
    if nr != nb
        throw(EOFError())
    end
    nothing
end

## text I/O ##

take!(s::IOStream) =
    @_lock_ios s ccall(:jl_take_buffer, Vector{UInt8}, (Ptr{Cvoid},), s.ios)

function readuntil(s::IOStream, delim::UInt8; keep::Bool=false)
    @_lock_ios s ccall(:jl_readuntil, Array{UInt8,1}, (Ptr{Cvoid}, UInt8, UInt8, UInt8), s.ios, delim, 0, !keep)
end

# like readuntil, above, but returns a String without requiring a copy
function readuntil_string(s::IOStream, delim::UInt8, keep::Bool)
    @_lock_ios s ccall(:jl_readuntil, Ref{String}, (Ptr{Cvoid}, UInt8, UInt8, UInt8), s.ios, delim, 1, !keep)
end

function readline(s::IOStream; keep::Bool=false)
    @_lock_ios s ccall(:jl_readuntil, Ref{String}, (Ptr{Cvoid}, UInt8, UInt8, UInt8), s.ios, '\n', 1, keep ? 0 : 2)
end

function readbytes_all!(s::IOStream,
                        b::Union{Array{UInt8}, FastContiguousSubArray{UInt8,<:Any,<:Array{UInt8}}},
                        nb::Integer)
    olb = lb = length(b)
    nr = 0
    let l = s._dolock, slock = s.lock
        l && lock(slock)
        GC.@preserve b while nr < nb
            if lb < nr+1
                try
                    lb = max(65536, (nr+1) * 2)
                    resize!(b, lb)
                catch
                    l && unlock(slock)
                    rethrow()
                end
            end
            thisr = Int(ccall(:ios_readall, Csize_t, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
                            s.ios, pointer(b, nr+1), min(lb-nr, nb-nr)))
            nr += thisr
            (nr == nb || thisr == 0 || _eof_nolock(s)) && break
        end
        l && unlock(slock)
    end
    if lb > olb && lb > nr
        resize!(b, max(olb, nr)) # shrink to just contain input data if was resized
    end
    return nr
end

function readbytes_some!(s::IOStream,
                         b::Union{Array{UInt8}, FastContiguousSubArray{UInt8,<:Any,<:Array{UInt8}}},
                         nb::Integer)
    olb = length(b)
    if nb > olb
        resize!(b, nb)
    end
    local nr
    @_lock_ios s begin
    nr = GC.@preserve b Int(ccall(:ios_read, Csize_t, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
                                  s.ios, pointer(b), nb))
    end
    lb = length(b)
    if lb > olb && lb > nr
        resize!(b, max(olb, nr)) # shrink to just contain input data if was resized
    end
    return nr
end

"""
    readbytes!(stream::IOStream, b::AbstractVector{UInt8}, nb=length(b); all::Bool=true)

Read at most `nb` bytes from `stream` into `b`, returning the number of bytes read.
The size of `b` will be increased if needed (i.e. if `nb` is greater than `length(b)`
and enough bytes could be read), but it will never be decreased.

If `all` is `true` (the default), this function will block repeatedly trying to read all
requested bytes, until an error or end-of-file occurs. If `all` is `false`, at most one
`read` call is performed, and the amount of data returned is device-dependent. Note that not
all stream types support the `all` option.
"""
function readbytes!(s::IOStream,
                    b::Union{Array{UInt8}, FastContiguousSubArray{UInt8,<:Any,<:Array{UInt8}}},
                    nb=length(b);
                    all::Bool=true)
    return all ? readbytes_all!(s, b, nb) : readbytes_some!(s, b, nb)
end

function read(s::IOStream)
    # First we try to fill the buffer. If that gives us the whole file,
    # copy it out and return. Otherwise look at the file size and use it
    # to prealloate space. Determining the size requires extra syscalls,
    # which we want to avoid for small files.
    @_lock_ios s begin
        nb = ccall(:ios_fillbuf, Cssize_t, (Ptr{Cvoid},), s.ios)
        if nb != -1
            b = StringVector(nb)
            readbytes_all!(s, b, nb)
        else
            sz = try # filesize is just a hint, so ignore if it fails
                filesize(s)
            catch ex
                ex isa IOError || rethrow()
                Int64(-1)
            end
            if sz > 0
                pos = position(s)
                if pos > 0
                    sz -= pos
                end
            end
            b = StringVector(sz < 0 ? 1024 : sz)
            nr = readbytes_all!(s, b, sz < 0 ? typemax(Int) : sz)
            resize!(b, nr)
        end
    end
    return b
end

"""
    read(s::IOStream, nb::Integer; all=true)

Read at most `nb` bytes from `s`, returning a `Vector{UInt8}` of the bytes read.

If `all` is `true` (the default), this function will block repeatedly trying to read all
requested bytes, until an error or end-of-file occurs. If `all` is `false`, at most one
`read` call is performed, and the amount of data returned is device-dependent. Note that not
all stream types support the `all` option.
"""
function read(s::IOStream, nb::Integer; all::Bool=true)
    # When all=false we have to allocate a buffer of the requested size upfront
    # since a single call will be made
    b = Vector{UInt8}(undef, all && nb == typemax(Int) ? 1024 : nb)
    nr = readbytes!(s, b, nb, all=all)
    resize!(b, nr)
    return b
end

## peek ##

function peek(s::IOStream, ::Type{UInt8})
    b = @_lock_ios s ccall(:ios_peekc, Cint, (Ptr{Cvoid},), s.ios)
    if b == -1
        throw(EOFError())
    end
    return b % UInt8
end

ext: jl

max_stars_repo_name: wentasah/julia

max_issues_repo_name: wentasah/julia

max_forks_repo_name: wentasah/julia


text:
using OMEinsum, LightGraphs, BenchmarkTools
using OMEinsum: getixs, getiy

function uniformsize(code::EinCode, size::Int)
    Dict([c=>size for c in [OMEinsum.flatten(getixs(code))..., getiy(code)...]])
end
uniformsize(ne::OMEinsum.NestedEinsum, size::Int) = uniformsize(OMEinsum.flatten(ne), size)

function random_regular_eincode(n, k)
	g = LightGraphs.random_regular_graph(n, k)
	ixs = [minmax(e.src,e.dst) for e in LightGraphs.edges(g)]
	code = EinCode((ixs..., [(i,) for i in LightGraphs.vertices(g)]...), ())
end

number_of_nodes = 200
code = random_regular_eincode(number_of_nodes, 3)
optcode = @benchmark optimize_greedy($code, $(uniformsize(code, 2)); nrepeat=10, method=OMEinsum.MinSpaceOut())


text:
using PlotThemes
using Test, PlotUtils

@test in(:sand, keys(PlotThemes._themes))
@test in(:sand_grad, PlotUtils.cgradients(:misc))


text:
#################################################################################
# Comments
#
# - Ideally the net_injection variables would be bounded.  This can be done using an adhoc data model extention
#
#################################################################################
# Model Definitions

""
function instantiate_nip_model(data::Dict{String, Any}, model_constructor; kwargs...)
    return PM.instantiate_model(data, model_constructor, build_nip; kwargs...)
end

""
function build_nip(pm::PM.AbstractPowerModel)
    for (n, network) in PM.nws(pm)
        @assert !PM.ismulticonductor(pm, nw = n)
        PM.variable_bus_voltage(pm, nw = n)
        variable_net_injection(pm, nw = n)
        PM.variable_branch_power(pm, nw = n, bounded = false)
        PM.variable_dcline_power(pm, nw = n)

        PM.constraint_model_voltage(pm, nw = n)

        for i in PM.ids(pm, :ref_buses, nw = n)
            PM.constraint_theta_ref(pm, i, nw = n)
        end

        for i in PM.ids(pm, :bus, nw = n)
            constraint_power_balance_ni(pm, i, nw = n)
        end

        for i in PM.ids(pm, :branch, nw = n)
            PM.constraint_ohms_yt_from(pm, i, nw = n)
            PM.constraint_ohms_yt_to(pm, i, nw = n)

            PM.constraint_voltage_angle_difference(pm, i, nw = n)

            #PM.constraint_thermal_limit_from(pm, i, nw=n)
            #PM.constraint_thermal_limit_to(pm, i, nw=n)
        end

        for i in PM.ids(pm, :dcline)
            PM.constraint_dcline_power_losses(pm, i, nw = n)
        end
    end

    return

end

""
function instantiate_nip_expr_model(data::Dict{String, Any}, model_constructor; kwargs...)
    return PM.instantiate_model(data, model_constructor, instantiate_nip_expr; kwargs...)
end

""
function instantiate_nip_expr(pm::PM.AbstractPowerModel)
    for (n, network) in PM.nws(pm)
        @assert !PM.ismulticonductor(pm, nw = n)
        PM.variable_bus_voltage(pm, nw = n)
        PM.variable_branch_power(pm, nw = n; bounded = false)
        PM.variable_dcline_power(pm, nw = n)

        PM.constraint_model_voltage(pm, nw = n)

        for i in PM.ids(pm, :ref_buses, nw = n)
            PM.constraint_theta_ref(pm, i, nw = n)
        end

        for i in PM.ids(pm, :bus, nw = n)
            constraint_power_balance_ni_expr(pm, i, nw = n)
        end

        for i in PM.ids(pm, :branch, nw = n)
            PM.constraint_ohms_yt_from(pm, i, nw = n)
            PM.constraint_ohms_yt_to(pm, i, nw = n)

            PM.constraint_voltage_angle_difference(pm, i, nw = n)

            #PM.constraint_thermal_limit_from(pm, i, nw=n)
            #PM.constraint_thermal_limit_to(pm, i, nw=n)
        end

        for i in PM.ids(pm, :dcline)
            PM.constraint_dcline_power_losses(pm, i, nw = n)
        end
    end

    return

end

#################################################################################
# Model Extention Functions

"generates variables for both `active` and `reactive` net injection"
function variable_net_injection(pm::PM.AbstractPowerModel; kwargs...)
    variable_active_net_injection(pm; kwargs...)
    variable_reactive_net_injection(pm; kwargs...)

    return

end

""
function variable_active_net_injection(pm::PM.AbstractPowerModel; nw::Int = pm.cnw)
    PM.var(pm, nw)[:pni] = JuMP.@variable(
        pm.model,
        [i in PM.ids(pm, nw, :bus)],
        base_name = "$(nw)_pni",
        start = 0.0
    )

    return

end

""
function variable_reactive_net_injection(pm::PM.AbstractPowerModel; nw::Int = pm.cnw)
    PM.var(pm, nw)[:qni] = JuMP.@variable(
        pm.model,
        [i in PM.ids(pm, nw, :bus)],
        base_name = "$(nw)_qni",
        start = 0.0
    )

    return
end

""
function constraint_power_balance_ni(pm::PM.AbstractPowerModel, i::Int; nw::Int = pm.cnw)
    if !haskey(PM.con(pm, nw), :power_balance_p)
        PM.con(pm, nw)[:power_balance_p] = Dict{Int, JuMP.ConstraintRef}()
    end
    if !haskey(PM.con(pm, nw), :power_balance_q)
        PM.con(pm, nw)[:power_balance_q] = Dict{Int, JuMP.ConstraintRef}()
    end

    bus = PM.ref(pm, nw, :bus, i)
    bus_arcs = PM.ref(pm, nw, :bus_arcs, i)
    bus_arcs_dc = PM.ref(pm, nw, :bus_arcs_dc, i)

    constraint_power_balance_ni(pm, nw, i, bus_arcs, bus_arcs_dc)

    return

end

""
function constraint_power_balance_ni(
    pm::PM.AbstractPowerModel,
    n::Int,
    i::Int,
    bus_arcs,
    bus_arcs_dc,
)
    p = PM.var(pm, n, :p)
    q = PM.var(pm, n, :q)
    pni = PM.var(pm, n, :pni, i)
    qni = PM.var(pm, n, :qni, i)
    p_dc = PM.var(pm, n, :p_dc)
    q_dc = PM.var(pm, n, :q_dc)

    PM.con(pm, n, :power_balance_p)[i] = JuMP.@constraint(
        pm.model,
        sum(p[a] for a in bus_arcs) + sum(p_dc[a_dc] for a_dc in bus_arcs_dc) == pni
    )
    PM.con(pm, n, :power_balance_q)[i] = JuMP.@constraint(
        pm.model,
        sum(q[a] for a in bus_arcs) + sum(q_dc[a_dc] for a_dc in bus_arcs_dc) == qni
    )

    return

end

""
function constraint_power_balance_ni_expr(
    pm::PM.AbstractPowerModel,
    i::Int;
    nw::Int = pm.cnw,
)
    if !haskey(PM.con(pm, nw), :power_balance_p)
        PM.con(pm, nw)[:power_balance_p] = Dict{Int, JuMP.ConstraintRef}()
    end
    if !haskey(PM.con(pm, nw), :power_balance_q)
        PM.con(pm, nw)[:power_balance_q] = Dict{Int, JuMP.ConstraintRef}()
    end

    bus = PM.ref(pm, nw, :bus, i)
    bus_arcs = PM.ref(pm, nw, :bus_arcs, i)
    bus_arcs_dc = PM.ref(pm, nw, :bus_arcs_dc, i)

    pni_expr = PM.ref(pm, nw, :bus, i, "pni")
    qni_expr = PM.ref(pm, nw, :bus, i, "qni")

    constraint_power_balance_ni_expr(pm, nw, i, bus_arcs, bus_arcs_dc, pni_expr, qni_expr)

    return

end

""
function constraint_power_balance_ni_expr(
    pm::PM.AbstractPowerModel,
    n::Int,
    i::Int,
    bus_arcs,
    bus_arcs_dc,
    pni_expr,
    qni_expr,
)
    p = PM.var(pm, n, :p)
    q = PM.var(pm, n, :q)
    p_dc = PM.var(pm, n, :p_dc)
    q_dc = PM.var(pm, n, :q_dc)

    PM.con(pm, n, :power_balance_p)[i] = JuMP.@constraint(
        pm.model,
        sum(p[a] for a in bus_arcs) + sum(p_dc[a_dc] for a_dc in bus_arcs_dc) == pni_expr
    )
    PM.con(pm, n, :power_balance_q)[i] = JuMP.@constraint(
        pm.model,
        sum(q[a] for a in bus_arcs) + sum(q_dc[a_dc] for a_dc in bus_arcs_dc) == qni_expr
    )

    return

end

"active power only models ignore reactive power variables"
function variable_reactive_net_injection(pm::PM.AbstractActivePowerModel; kwargs...)
    return
end

"active power only models ignore reactive power flows"
function constraint_power_balance_ni(
    pm::PM.AbstractActivePowerModel,
    n::Int,
    i::Int,
    bus_arcs,
    bus_arcs_dc,
)
    p = PM.var(pm, n, :p)
    pni = PM.var(pm, n, :pni, i)
    p_dc = PM.var(pm, n, :p_dc)

    PM.con(pm, n, :power_balance_p)[i] = JuMP.@constraint(
        pm.model,
        sum(p[a] for a in bus_arcs) + sum(p_dc[a_dc] for a_dc in bus_arcs_dc) == pni
    )

    return

end

""
function constraint_power_balance_ni_expr(
    pm::PM.AbstractActivePowerModel,
    n::Int,
    i::Int,
    bus_arcs,
    bus_arcs_dc,
    pni_expr,
    qni_expr,
)
    p = PM.var(pm, n, :p)
    p_dc = PM.var(pm, n, :p_dc)

    PM.con(pm, n, :power_balance_p)[i] = JuMP.@constraint(
        pm.model,
        sum(p[a] for a in bus_arcs) + sum(p_dc[a_dc] for a_dc in bus_arcs_dc) == pni_expr
    )

    return

end

""
function powermodels_network!(
    psi_container::PSIContainer,
    system_formulation::Type{S},
    sys::PSY.System,
) where {S <: PM.AbstractPowerModel}

    time_steps = model_time_steps(psi_container)
    pm_data, PM_map = pass_to_pm(sys, time_steps[end])
    buses = PSY.get_components(PSY.Bus, sys)

    _remove_undef!(psi_container.expressions[:nodal_balance_active])
    _remove_undef!(psi_container.expressions[:nodal_balance_reactive])

    for t in time_steps, bus in buses
        pm_data["nw"]["$(t)"]["bus"]["$(bus.number)"]["pni"] =
            psi_container.expressions[:nodal_balance_active][bus.number, t]
        pm_data["nw"]["$(t)"]["bus"]["$(bus.number)"]["qni"] =
            psi_container.expressions[:nodal_balance_reactive][bus.number, t]
    end

    psi_container.pm = instantiate_nip_expr_model(
        pm_data,
        system_formulation,
        jump_model = psi_container.JuMPmodel,
    )
    psi_container.pm.ext[:PMmap] = PM_map

    return

end

""
function powermodels_network!(
    psi_container::PSIContainer,
    system_formulation::Type{S},
    sys::PSY.System,
) where {S <: PM.AbstractActivePowerModel}

    time_steps = model_time_steps(psi_container)
    pm_data, PM_map = pass_to_pm(sys, time_steps[end])
    buses = PSY.get_components(PSY.Bus, sys)

    _remove_undef!(psi_container.expressions[:nodal_balance_active])

    for t in time_steps, bus in buses
        pm_data["nw"]["$(t)"]["bus"]["$(PSY.get_number(bus))"]["pni"] =
            psi_container.expressions[:nodal_balance_active][PSY.get_number(bus), t]
        #pm_data["nw"]["$(t)"]["bus"]["$(bus.number)"]["qni"] = 0.0
    end

    psi_container.pm = instantiate_nip_expr_model(
        pm_data,
        system_formulation,
        jump_model = psi_container.JuMPmodel,
    )
    psi_container.pm.ext[:PMmap] = PM_map

    return

end

#### PM accessor functions ########

function PMvarmap(system_formulation::Type{S}) where {S <: PM.AbstractDCPModel}
    pm_var_map = Dict{Type, Dict{Symbol, Union{Symbol, NamedTuple}}}()

    pm_var_map[PSY.Bus] = Dict(:va => :theta)
    pm_var_map[PSY.ACBranch] = Dict(:p => (from_to = :Fp, to_from = nothing))
    pm_var_map[PSY.DCBranch] = Dict(:p_dc => (from_to = :Fp, to_from = nothing))

    return pm_var_map
end

function PMvarmap(system_formulation::Type{S}) where {S <: PM.AbstractActivePowerModel}
    pm_var_map = Dict{Type, Dict{Symbol, Union{Symbol, NamedTuple}}}()

    pm_var_map[PSY.Bus] = Dict(:va => :theta)
    pm_var_map[PSY.ACBranch] = Dict(:p => (from_to = :FpFT, to_from = :FpTF))
    pm_var_map[PSY.DCBranch] = Dict(:p_dc => (from_to = :FpFT, to_from = :FpTF))

    return pm_var_map
end

function PMvarmap(system_formulation::Type{S}) where {S <: PM.AbstractPowerModel}
    pm_var_map = Dict{Type, Dict{Symbol, Union{String, NamedTuple}}}()

    pm_var_map[PSY.Bus] = Dict(:va => THETA, :vm => VM)
    pm_var_map[PSY.ACBranch] = Dict(
        :p =>
            (from_to = FLOW_ACTIVE_POWER_FROM_TO, to_from = FLOW_ACTIVE_POWER_TO_FROM),
        :q => (
            from_to = FLOW_REACTIVE_POWER_FROM_TO,
            to_from = FLOW_REACTIVE_POWER_TO_FROM,
        ),
    )
    pm_var_map[PSY.DCBranch] = Dict(
        :p_dc =>
            (from_to = FLOW_ACTIVE_POWER_FROM_TO, to_from = FLOW_ACTIVE_POWER_TO_FROM),
        :q_dc => (
            from_to = FLOW_REACTIVE_POWER_FROM_TO,
            to_from = FLOW_REACTIVE_POWER_TO_FROM,
        ),
    )

    return pm_var_map
end

function add_pm_var_refs!(
    psi_container::PSIContainer,
    system_formulation::Type{S},
    sys::PSY.System,
) where {S <: PM.AbstractPowerModel}

    time_steps = model_time_steps(psi_container)
    bus_dict = psi_container.pm.ext[:PMmap].bus
    ACbranch_dict = psi_container.pm.ext[:PMmap].arcs
    ACbranch_types = typeof.(values(ACbranch_dict))
    DCbranch_dict = psi_container.pm.ext[:PMmap].arcs_dc
    DCbranch_types = typeof.(values(DCbranch_dict))

    pm_var_names = keys(psi_container.pm.var[:nw][1])

    pm_var_map = PMvarmap(system_formulation)

    for (pm_v, ps_v) in pm_var_map[PSY.Bus]
        if pm_v in pm_var_names
            container = PSI.container_spec(
                psi_container.JuMPmodel,
                (PSY.get_name(b) for b in values(bus_dict)),
                time_steps,
            )
            assign_variable!(psi_container, ps_v, container)
            for t in time_steps, (pm_bus, bus) in bus_dict
                name = PSY.get_name(bus)
                container[name, t] = PM.var(psi_container.pm, t, pm_v)[pm_bus] #pm_vars[pm_v][pm_bus]
            end
        end
    end

    add_pm_var_refs!(
        psi_container,
        PSY.ACBranch,
        ACbranch_types,
        ACbranch_dict,
        pm_var_map,
        pm_var_names,
        time_steps,
    )
    add_pm_var_refs!(
        psi_container,
        PSY.DCBranch,
        DCbranch_types,
        DCbranch_dict,
        pm_var_map,
        pm_var_names,
        time_steps,
    )

end

function add_pm_var_refs!(
    psi_container::PSIContainer,
    d_class::Type,
    device_types::Vector,
    pm_map::Dict,
    pm_var_map::Dict,
    pm_var_names::Base.KeySet,
    time_steps::UnitRange{Int},
)

    for d_type in Set(device_types)
        devices = [d for d in pm_map if typeof(d[2]) == d_type]
        for (pm_v, ps_v) in pm_var_map[d_class]
            if pm_v in pm_var_names
                for dir in fieldnames(typeof(ps_v))
                    isnothing(getfield(ps_v, dir)) && continue
                    # TODO: make a better mapping with the var names in the definitions file
                    var_name =
                        Symbol("$(getfield(ps_v, dir))$(PSI_NAME_DELIMITER)$(d_type)")
                    container = PSI.container_spec(
                        psi_container.JuMPmodel,
                        (PSY.get_name(d[2]) for d in devices),
                        time_steps,
                    )
                    assign_variable!(psi_container, var_name, container)
                    for t in time_steps, (pm_d, d) in devices
                        container[PSY.get_name(d), t] =
                            PM.var(psi_container.pm, t, pm_v, getfield(pm_d, dir))
                    end
                end
            end
        end
    end
end


text:
using DecimalNumbers, Base.Test

@testset "from int" begin
    d = DecimalNumbers.Decimal(1)
    @test d.value == 1
    @test d.exp == 0
    # denormalize
    d = DecimalNumbers.Decimal(10)
    @test d.value == 1
    @test d.exp == 1

    d = DecimalNumbers.Decimal(23487300)
    @test d.value == 234873
    @test d.exp == 2

    # specific integer type
    d = DecimalNumbers.Decimal(Int8(40))
    @test typeof(d.value) == Int8
    @test d.value === Int8(4)
    @test d.exp === Int8(1)
end

@testset "to int" begin
    d = DecimalNumbers.Decimal(1)
    @test Int(d) === 1

    d = DecimalNumbers.Decimal(23487300)
    @test Int(d) === 23487300

    @test_throws InexactError Int(DecimalNumbers.Decimal(3.14))
end

@testset "from float" begin
    d = DecimalNumbers.Decimal(3.0)
    @test d.value == 3
    @test d.exp == 0

    d = DecimalNumbers.Decimal(3.14)
    @test d.value == 314
    @test d.exp == -2
    @test typeof(d.value) == Int64

    d = DecimalNumbers.Decimal(Float16(-3.14))
    @test d.value === Int16(-314)
    @test d.exp === Int16(-2)
end

@testset "comparisons" begin
    @test DecimalNumbers.Decimal(1) == DecimalNumbers.Decimal(1)
    @test DecimalNumbers.Decimal(1) != DecimalNumbers.Decimal(10)
    @test DecimalNumbers.Decimal(1, -1) != DecimalNumbers.Decimal(10)
    @test DecimalNumbers.Decimal(1, -1) == DecimalNumbers.Decimal(1, -1)
    @test DecimalNumbers.Decimal(1, -2) < DecimalNumbers.Decimal(1, -1)
    @test DecimalNumbers.Decimal(1) < DecimalNumbers.Decimal(2)
    # denormalized
    a = DecimalNumbers.Decimal(10, 1)
    b = DecimalNumbers.Decimal(100, 0)
    @test a == b
    @test !(a < b)
    @test !(b < a)
end

@testset "parse" begin
    @test parse(DecimalNumbers.Decimal{Int64}, "-101") == DecimalNumbers.Decimal(-101)
    @test parse(DecimalNumbers.Decimal{Int64}, "101") == DecimalNumbers.Decimal(101)
    @test parse(DecimalNumbers.Decimal{Int64}, "101.") == DecimalNumbers.Decimal(101)
    @test parse(DecimalNumbers.Decimal{Int64}, "101.0") == DecimalNumbers.Decimal(101)
    @test parse(DecimalNumbers.Decimal{Int64}, "1.01") == DecimalNumbers.Decimal(101, -2)
    @test parse(DecimalNumbers.Decimal{Int64}, ".101") == DecimalNumbers.Decimal(101, -3)
    @test parse(DecimalNumbers.Decimal{Int64}, "0.101") == DecimalNumbers.Decimal(101, -3)
    @test parse(DecimalNumbers.Decimal{Int64}, "0.0101") == DecimalNumbers.Decimal(101, -4)
end

@testset "show" begin
    @test string( DecimalNumbers.Decimal(101, 3)) == "dec\"101000.0\""
    @test string( DecimalNumbers.Decimal(101, 2)) == "dec\"10100.0\""
    @test string( DecimalNumbers.Decimal(101, 1)) == "dec\"1010.0\""
    @test string( DecimalNumbers.Decimal(-101)) == "dec\"-101.0\""
    @test string( DecimalNumbers.Decimal(101)) == "dec\"101.0\""
    @test string( DecimalNumbers.Decimal(101, 0)) == "dec\"101.0\""
    @test string( DecimalNumbers.Decimal(101, -2)) == "dec\"1.01\""
    @test string( DecimalNumbers.Decimal(101, -3)) == "dec\"0.101\""
    @test string( DecimalNumbers.Decimal(101, -4)) == "dec\"0.0101\""
end

@testset "math" begin
    local T, xD, x, i
    try
        for T in (Int8, Int16, Int32, Int64, Int128)
            xD = DecimalNumbers.Decimal(T(0))
            x = T(0)
            for i in rand(T, 10)
                @test abs(DecimalNumbers.Decimal(i)) == abs(i)
                @test DecimalNumbers.Decimal(i) + xD == i + x
                @test DecimalNumbers.Decimal(i) - xD == i - x
                @test DecimalNumbers.Decimal(widen(i)) * DecimalNumbers.Decimal(widen(i)) == widen(i) * widen(i)
                xD += DecimalNumbers.Decimal(i)
                x += i
            end
        end
    catch e
        @show T, xD, x, i
        rethrow(e)
    end

    @test DecimalNumbers.Decimal(1) + DecimalNumbers.Decimal(1) == DecimalNumbers.Decimal(2)
    @test DecimalNumbers.Decimal(10) + DecimalNumbers.Decimal(1) == DecimalNumbers.Decimal(11)
    @test DecimalNumbers.Decimal(10, 2) + DecimalNumbers.Decimal(1, -1) == DecimalNumbers.Decimal(10001, -1)
    @test DecimalNumbers.Decimal(1, -1) + DecimalNumbers.Decimal(2, -1) == DecimalNumbers.Decimal(3, -1)
    @test DecimalNumbers.Decimal(1) - DecimalNumbers.Decimal(1) == DecimalNumbers.Decimal(0)
    @test DecimalNumbers.Decimal(1) * DecimalNumbers.Decimal(1) == DecimalNumbers.Decimal(1)
    @test DecimalNumbers.Decimal(10) * DecimalNumbers.Decimal(1, -1) == DecimalNumbers.Decimal(1)
    @test DecimalNumbers.Decimal(1) / DecimalNumbers.Decimal(1) == DecimalNumbers.Decimal(1)
    @test DecimalNumbers.Decimal(10) / DecimalNumbers.Decimal(1) == DecimalNumbers.Decimal(10)
    @test DecimalNumbers.Decimal(-10) / DecimalNumbers.Decimal(1) == DecimalNumbers.Decimal(-10)
    @test DecimalNumbers.Decimal(1) / DecimalNumbers.Decimal(1.5) == DecimalNumbers.Decimal(66666666666666667, -17)
    @test DecimalNumbers.Decimal(1) / DecimalNumbers.Decimal(0.5) == DecimalNumbers.Decimal(2)

    # division
    # Int8
    @test DecimalNumbers.Decimal(Int8(22)) / DecimalNumbers.Decimal(Int8(7)) == DecimalNumbers.Decimal(31, -1)
    # Int16
    @test DecimalNumbers.Decimal(Int16(22)) / DecimalNumbers.Decimal(Int16(7)) == DecimalNumbers.Decimal(3143, -3)
    # Int32
    @test DecimalNumbers.Decimal(Int32(22)) / DecimalNumbers.Decimal(Int32(7)) == DecimalNumbers.Decimal(314285714, -8)
    # Int64
    @test DecimalNumbers.Decimal(Int64(22)) / DecimalNumbers.Decimal(Int64(7)) == DecimalNumbers.Decimal(314285714285714286, -17)
    # Int128
    @test DecimalNumbers.Decimal(Int128(22)) / DecimalNumbers.Decimal(Int128(7)) == DecimalNumbers.Decimal(31428571428571428571428571428571428571, -37)
end

max_stars_repo_name: quinnj/DecimalNumbers

max_issues_repo_name: quinnj/DecimalNumbers

max_forks_repo_name: quinnj/DecimalNumbers


text: @time f(DamerauLevenshtein(), x, y, min_score = 0.8)


text:
VERSION >= v"0.4.0-dev+6521" && __precompile__(true)
module FixedSizeArrays

importall Base
import Base.Func

include("core.jl")
include("functors.jl")
include("constructors.jl")

if VERSION <= v"0.5.0"
    supertype(x) = super(x)
end

# put them here due to #JuliaLang/julia#12814
# needs to be befor indexing and ops, but after constructors
immutable Mat{Row, Column, T} <: FixedMatrix{Row, Column, T}
    _::NTuple{Column, NTuple{Row, T}}
end
function similar{FSA <: Mat, T}(::Type{FSA}, ::Type{T}, SZ::NTuple{2, Int})
    Mat{SZ[1], SZ[2], T}
end

# most common FSA types
immutable Vec{N, T} <: FixedVector{N, T}
    _::NTuple{N, T}
end
immutable Point{N, T} <: FixedVector{N, T}
    _::NTuple{N, T}
end

include("mapreduce.jl")
include("destructure.jl")
include("indexing.jl")
include("ops.jl")
include("expm.jl")
include("array_of_fixedsize.jl")
include("conversion.jl")

function show{R,C,T}(io::IO, m::Mat{R,C,T})
	println(io, typeof(m), "(")
	for i=1:R
		println(io, "    ", join(row(m, i), " "))
	end
	println(io, ")")
end

showcompact(io::IO, v::FixedVector{0}) = print(io, typeof(v).name.name, "()")
function showcompact{N}(io::IO, v::FixedVector{N})
    print(io, typeof(v).name.name, "(", v[1])
    for i = 2:N
        print(io, ",", v[i])
    end
    print(io, ")")
end

export FixedArray
export FixedVector
export FixedMatrix
export MutableFixedArray
export MutableFixedVector
export MutableFixedMatrix
export Mat, Vec, Point
export @fsa

export unit
export normalize
export row
export column
export MatMulFunctor
export setindex
export eltype_or, size_or, ndims_or
export @fslice
export destructure

end


text:
# This file is a part of Julia. License is MIT: http://julialang.org/license

# prime method cache with some things we know we'll need right after startup
precompile(!=, (Bool, Bool))
precompile(!=, (SubString{String}, String))
precompile(*, (String, String, String))
precompile(-, (Int,))
precompile(==, (String, String))
precompile(==, (String, Char))
precompile(==, (String, Int))
precompile(==, (Array{Char, 1}, Array{Char, 1}))
precompile(==, (Array{Char,1}, Array{Char,1}))
precompile(==, (Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}, Base.LineEdit.Prompt))
precompile(==, (Base.LineEdit.Prompt, Base.LineEdit.Prompt))
precompile(==, (Base.Multimedia.TextDisplay, Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}))
precompile(==, (Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}, Base.Multimedia.TextDisplay))
precompile(==, (Int32, Int32))
precompile(==, (Int32, Int64))
precompile(==, (Int64, Int32))
precompile(==, (Int64, Int64))
precompile(==, (Bool,Bool))
precompile(==, (Char, String))
precompile(==, (IOStream,Void))
precompile(==, (Type{String}, Type{Any}))
precompile(==, (Type{Base.LineEdit.Prompt}, Type{Base.LineEdit.Prompt}))
precompile(==, (Type{Function}, Int))
precompile(==, (Type{Function}, Type{String}))
precompile(Base._atreplinit, (Base.REPL.LineEditREPL,))
precompile(Base.BitArray, (Int,))
precompile(Base.Dict, ())
precompile(Base.Dict{Any,Any}, (Int,))
precompile(Base.IOStream, (String, Array{UInt8,1}))
precompile(Base.KeyError, (Int,))
precompile(Base.LineEdit.Prompt, (String, String, String, Function, Function, Base.REPL.LineEditREPL, Base.REPL.REPLCompletionProvider, Function, Function, Base.LineEdit.EmptyHistoryProvider, Bool))
precompile(Base.LineEdit.Prompt, (String, String, String, Function, Function, Base.REPL.LineEditREPL, Base.REPL.ShellCompletionProvider, Function, Function, Base.LineEdit.EmptyHistoryProvider, Bool))
precompile(Base.LineEdit.Prompt, (String, String, Function, Function, Base.REPL.LineEditREPL, Base.REPL.REPLCompletionProvider, Function, Function, Base.LineEdit.EmptyHistoryProvider, Bool, String))
precompile(Base.LineEdit.Prompt, (String, String, Function, Function, Base.REPL.LineEditREPL, Base.REPL.ShellCompletionProvider, Function, Function, Base.LineEdit.EmptyHistoryProvider, Bool, String))
precompile(Base.LineEdit.PromptState, (Base.Terminals.TTYTerminal, Base.LineEdit.Prompt, IOBuffer, Base.LineEdit.InputAreaState, Int))
precompile(Base.LineEdit.activate, (Base.LineEdit.Prompt, Base.LineEdit.MIState, Base.Terminals.TTYTerminal))
precompile(Base.LineEdit.activate, (Base.LineEdit.Prompt, Base.LineEdit.PromptState, Base.Terminals.TTYTerminal))
precompile(Base.LineEdit.activate, (Base.LineEdit.Prompt, Base.LineEdit.PromptState, Base.Terminals.TerminalBuffer))
precompile(Base.LineEdit.add_history, (Base.LineEdit.PromptState,))
precompile(Base.LineEdit.buffer, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.buffer, (Base.LineEdit.PromptState,))
precompile(Base.LineEdit.char_move_left, (IOBuffer,))
precompile(Base.LineEdit.clear_input_area, (Base.Terminals.TTYTerminal, Base.LineEdit.InputAreaState))
precompile(Base.LineEdit.commit_line, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.deactivate, (Base.LineEdit.Prompt,Base.LineEdit.PromptState, Base.Terminals.TerminalBuffer))
precompile(Base.LineEdit.edit_backspace, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.edit_backspace, (Base.LineEdit.PromptState,))
precompile(Base.LineEdit.edit_backspace, (IOBuffer,))
precompile(Base.LineEdit.edit_clear, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.edit_delete, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.edit_delete, (IOBuffer,))
precompile(Base.LineEdit.edit_insert, (Base.LineEdit.MIState, Char))
precompile(Base.LineEdit.edit_insert, (Base.LineEdit.PromptState, Char))
precompile(Base.LineEdit.edit_insert, (IOBuffer, String))
precompile(Base.LineEdit.edit_move_down, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.edit_move_left, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.edit_move_left, (Base.LineEdit.PromptState,))
precompile(Base.LineEdit.edit_move_left, (IOBuffer,))
precompile(Base.LineEdit.edit_move_right, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.edit_move_right, (Base.LineEdit.PromptState,))
precompile(Base.LineEdit.edit_move_right, (IOBuffer,))
precompile(Base.LineEdit.edit_move_up, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.edit_move_up, (IOBuffer,))
precompile(Base.LineEdit.postprocess!, (Void, Int))
precompile(Base.LineEdit.history_prev, (Base.LineEdit.MIState, Base.REPL.REPLHistoryProvider))
precompile(Base.LineEdit.history_prev, (Base.LineEdit.MIState, Base.REPL.REPLHistoryProvider, Int))
precompile(Base.LineEdit.init_state, (Base.Terminals.TTYTerminal, Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}))
precompile(Base.LineEdit.init_state, (Base.Terminals.TTYTerminal, Base.LineEdit.Prompt))
precompile(Base.LineEdit.input_string, (Base.LineEdit.PromptState,))
precompile(Base.LineEdit.keymap, (Base.LineEdit.PromptState, Base.LineEdit.Prompt))
precompile(Base.LineEdit.keymap_data, (Base.LineEdit.PromptState, Base.LineEdit.Prompt))
precompile(Base.LineEdit.keymap_fcn, (Function, String))
precompile(Base.LineEdit.match_input, (Dict{Char,Any},Base.LineEdit.MIState))
precompile(Base.LineEdit.match_input, (Dict{Char, Any}, Base.LineEdit.MIState, Base.Terminals.TTYTerminal))
precompile(Base.LineEdit.match_input, (Function, Base.LineEdit.MIState, Base.Terminals.TTYTerminal, Array{Char,1}))
precompile(Base.LineEdit.mode, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.move_line_end, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.on_enter, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.on_enter, (Base.LineEdit.PromptState,))
precompile(Base.LineEdit.prompt!, (Base.Terminals.TTYTerminal, Base.LineEdit.ModalInterface, Base.LineEdit.MIState))
precompile(Base.LineEdit.refresh_line, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.refresh_multi_line, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.refresh_multi_line, (Base.LineEdit.PromptState,))
precompile(Base.LineEdit.refresh_multi_line, (Base.Terminals.TTYTerminal, Base.LineEdit.PromptState))
precompile(Base.LineEdit.refresh_multi_line, (Base.Terminals.TerminalBuffer, Base.LineEdit.SearchState))
precompile(Base.LineEdit.refresh_multi_line, (Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.LineEdit.PromptState))
precompile(Base.LineEdit.replace_line, (Base.LineEdit.PromptState, String))
precompile(Base.LineEdit.replace_line, (Base.LineEdit.PromptState, Base.IOBuffer))
precompile(Base.LineEdit.reset_key_repeats, (Function, Base.LineEdit.MIState,))
precompile(Base.LineEdit.reset_state, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.reset_state, (Base.LineEdit.PromptState,))
precompile(Base.LineEdit.reset_state, (Base.LineEdit.SearchState,))
precompile(Base.LineEdit.run_interface, (Base.Terminals.TTYTerminal, Base.LineEdit.ModalInterface))
precompile(Base.LineEdit.setup_search_keymap, (Base.REPL.REPLHistoryProvider,))
precompile(Base.LineEdit.splice_buffer!, (IOBuffer, UnitRange{Int}, String))
precompile(Base.LineEdit.state, (Base.LineEdit.MIState, Base.LineEdit.Prompt))
precompile(Base.LineEdit.terminal, (Base.LineEdit.MIState,))
precompile(Base.LineEdit.terminal, (Base.LineEdit.PromptState,))
precompile(Base.LineEdit.transition, (Base.LineEdit.MIState, Base.LineEdit.Prompt))
precompile(Base.LineEdit.transition, (Base.LineEdit.MIState, Symbol))
precompile(Base.LineEdit.update_key_repeats, (Base.LineEdit.MIState, Array{Char, 1}))
precompile(Base.LineEdit.update_key_repeats, (Base.LineEdit.MIState, Array{Char,1}))
precompile(Base.LineEdit.write_prompt, (Base.Terminals.TTYTerminal, Base.LineEdit.Prompt))
precompile(Base.LineEdit.write_prompt, (Base.Terminals.TerminalBuffer, Base.LineEdit.PromptState))
precompile(Base.Multimedia.TextDisplay, (Base.TTY,))
precompile(Base.Multimedia.display, (Int,))
precompile(Base.ProcessGroup, (Int, Array{Any,1}, Array{Any,1}))
precompile(Base.REPL.:(==), (Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}, Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}))
precompile(Base.REPL.LineEditREPL, (Base.Terminals.TTYTerminal, Bool, String, String, String, String, String, Bool, Bool, Bool, Bool))
precompile(Base.REPL.LineEditREPL, (Base.Terminals.TTYTerminal,))
precompile(Base.REPL.REPLBackendRef, (Channel{Any}, Channel{Any}))
precompile(Base.REPL.REPLDisplay, (Base.REPL.BasicREPL,))
precompile(Base.REPL.REPLDisplay, (Base.REPL.LineEditREPL,))
precompile(Base.REPL.add_history, (Base.REPL.REPLHistoryProvider, Base.LineEdit.PromptState))
precompile(Base.REPL.backend, (Base.REPL.LineEditREPL,))
precompile(Base.REPL.display, (Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}, Base.Multimedia.MIME{Symbol("text/plain")}, Int))
precompile(Base.REPL.display, (Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}, Int))
precompile(Base.REPL.ends_with_semicolon, (String,))
precompile(Base.REPL.find_hist_file, ())
precompile(Base.REPL.hist_from_file, (Base.REPL.REPLHistoryProvider, IOStream, String))
precompile(Base.REPL.history_next, (Base.LineEdit.MIState,  Base.REPL.REPLHistoryProvider, Int))
precompile(Base.REPL.history_next_prefix, (Base.LineEdit.MIState, Base.REPL.REPLHistoryProvider,))
precompile(Base.REPL.history_prev_prefix, (Base.LineEdit.MIState, Base.REPL.REPLHistoryProvider,))
precompile(Base.REPL.mode_idx, (Base.REPL.REPLHistoryProvider, Base.LineEdit.Prompt))
precompile(Base.REPL.reset, (Base.REPL.LineEditREPL,))
precompile(Base.REPL.reset_state, (Base.REPL.REPLHistoryProvider,))
precompile(Base.REPL.respond, (Function, Base.REPL.LineEditREPL, Base.LineEdit.Prompt))
precompile(Base.REPL.return_callback, (Base.LineEdit.PromptState,))
precompile(Base.REPL.run_repl, (Base.REPL.LineEditREPL,))
precompile(Base.REPL.send_to_backend, (Expr, Base.REPL.REPLBackendRef))
precompile(Base.REPL.send_to_backend, (Expr, Channel{Any}, Channel{Any}))
precompile(Base.REPL.send_to_backend, (Symbol, Base.REPL.REPLBackendRef))
precompile(Base.REPL.start_repl_backend, (Channel{Any}, Channel{Any}))
precompile(Base.REPLCompletions.complete_methods, (String,))
precompile(Base.REPLCompletions.complete_symbol, (String, Function))
precompile(Base.REPLCompletions.completions, (String, Int))
precompile(Base.Random.srand, ())
precompile(Base.Random.srand, (String, Int))
precompile(Base.Random.srand, (UInt,))
precompile(Base.RemoteChannel, (Int, Int, Int))
precompile(Base.RemoteValue, ())
precompile(Base.Set, ())
precompile(Base.SystemError, (String,))
precompile(Base.TCPSocket, (Ptr{Void},))
precompile(Base.TTY, (Ptr{Void},))
precompile(Base.Terminals.TTYTerminal, (String, Base.TTY, Base.TTY, Base.TTY))
precompile(Base.Terminals.beep, (Base.Terminals.TTYTerminal,))
precompile(Base.Terminals.raw!, (Base.Terminals.TTYTerminal, Bool))
precompile(Base.Terminals.write, (Base.Terminals.TTYTerminal, Array{UInt8, 1}))
precompile(Libc.TmStruct, (Float64,))
precompile(Base.VersionNumber, (Int, Int, Int, Tuple{}, Tuple{String}))
precompile(Base._atexit, ())
precompile(Base._deleteat!, (Array{UInt8, 1}, Int, Int))
precompile(Base._growat!, (Array{UInt8, 1}, Int, Int))
precompile(Base._setindex!, (Base.Dict{Symbol, Any}, Base.LineEdit.Prompt, Symbol, Int))
precompile(Base._setindex!, (Dict{Any, Any}, Base.LineEdit.PromptState, Base.LineEdit.Prompt, Int))
precompile(Base._setindex!, (Dict{Any, Any}, Bool, WeakRef, Int))
precompile(Base._setindex!, (Dict{UInt8, Any}, Base.LineEdit.Prompt, UInt8, Int))
precompile(Base._start, ())
precompile(Base.abs, (Char,))
precompile(Base.abspath, (String, String))
precompile(Base.abspath, (String,))
precompile(Base.alignment, (Base.IOContext, Float64,))
precompile(Base.any, (Function, Array{Any,1}))
precompile(Base.arg_gen, (String,))
precompile(Base.associate_julia_struct, (Ptr{Void}, Base.TTY))
precompile(Base.async_run_thunk, (Function,))
precompile(Base.atexit, (Function,))
precompile(Base.banner, (Base.Terminals.TTYTerminal,))
precompile(Base.startswith, (String, String))
precompile(Base.String, (String,))
precompile(Base.chop, (String,))
precompile(Base.close, (Base.TTY,))
precompile(Base.close, (IOStream,))
precompile(Base.cmp, (Int32, Int32))
precompile(Base.convert, (Type{Any}, Base.LineEdit.ModalInterface))
precompile(Base.convert, (Type{Any}, Base.LineEdit.Prompt))
precompile(Base.convert, (Type{Any}, Base.ObjectIdDict))
precompile(Base.convert, (Type{Any}, Base.REPL.LatexCompletions))
precompile(Base.convert, (Type{Any}, Base.REPL.REPLHistoryProvider))
precompile(Base.convert, (Type{Any}, Function))
precompile(Base.convert, (Type{Any}, IOStream))
precompile(Base.convert, (Type{Any}, Int))
precompile(Base.convert, (Type{Any}, Void))
precompile(Base.convert, (Type{Base.IPAddr}, Base.IPv4))
precompile(Base.convert, (Type{Base.LineEdit.InputAreaState}, Base.LineEdit.InputAreaState))
precompile(Base.convert, (Type{Char}, Char))
precompile(Base.convert, (Type{Function}, Function))
precompile(Base.convert, (Type{IOBuffer}, IOBuffer))
precompile(Base.convert, (Type{Module}, Module))
precompile(Base.convert, (Type{AbstractString}, String))
precompile(Base.copy!, (Array{Dict{Any, Any}, 1}, Int, Array{Dict{Any, Any}, 1}, Int, Int))
precompile(Base.copy, (Bool,))
precompile(Base.deleteat!, (Array{UInt8, 1}, Base.UnitRange{Int}))
precompile(Base.done, (Array{Base.LineEdit.TextInterface, 1}, Int))
precompile(Base.done, (Dict{Any,Any}, Int))
precompile(Base.done, (Dict{Symbol,Any}, Int))
precompile(Base.done, (IntSet, Int))
precompile(Base.done, (UnitRange{Int},Int))
precompile(Base.endof, (Array{Any,1},))
precompile(Base.enq_work, (Task,))
precompile(Base.eval_user_input, (Expr, Bool))
precompile(Base.fdio, (Int32,))
precompile(Base.fill!, (BitArray{1}, Bool))
precompile(Base.first, (UnitRange{Int},))
precompile(Base.flush, (IOStream,))
precompile(Base.flush_gc_msgs, ())
precompile(Base.flush_gc_msgs, (Base.Worker,))
precompile(Base.get, (Base.EnvHash, String, String))
precompile(Base.get, (Dict{Any, Any}, Tuple{Int, Int}, Bool))
precompile(Base.get, (Dict{Any,Any}, Symbol, String))
precompile(Base.get_chunks_id, (Int,))
precompile(Base.getindex, (Array{Base.LineEdit.TextInterface, 1}, Int))
precompile(Base.getindex, (BitArray{1}, Int,))
precompile(Base.getindex, (Dict{Any, Any}, Base.LineEdit.Prompt))
precompile(Base.getindex, (Dict{Any,Any}, Int32))
precompile(Base.getindex, (Dict{Symbol,Any},Symbol))
precompile(Base.getindex, (Type{AbstractString},))
precompile(Base.getindex, (Type{String}, String, String))
precompile(Base.getindex, (Type{Dict{Any, Any}}, Dict{Any, Any}, Dict{Any, Any}, Dict{Any, Any}, Dict{Any, Any}, Dict{Any, Any}))
precompile(Base.getpid, ())
precompile(Base.hash, (Int,))
precompile(Base.hash, (RemoteChannel, UInt))
precompile(Base.hash, (RemoteChannel,))
precompile(Base.haskey, (Base.EnvHash, String))
precompile(Base.haskey, (Dict{Symbol,Any}, Symbol))
precompile(Base.haskey, (ObjectIdDict, Symbol))
precompile(Base.hex, (Char, Int))
precompile(Base.ht_keyindex, (Dict{Any, Any}, Base.LineEdit.Prompt))
precompile(Base.ht_keyindex, (Dict{Any,Any}, Int32))
precompile(Base.ht_keyindex, (Dict{UInt8, Any}, UInt8))
precompile(Base.ht_keyindex2, (Dict{Any, Any}, Base.LineEdit.Prompt))
precompile(Base.ht_keyindex2, (Dict{UInt8, Any}, UInt8))
precompile(Base.in, (Char, String))
precompile(Base.in, (Int, Base.UnitRange{Int}))
precompile(Base.in, (UInt8, Base.KeyIterator{Dict{UInt8, Any}}))
precompile(Base.include_from_node1, (String,))
precompile(Base.init_stdio, (Ptr{Void},))
precompile(Base.input_color, ())
precompile(Base.insert!, (Array{Any,1}, Int, Base.GlobalRef))
precompile(Base.Int, (Int,))
precompile(Base.Int, (UInt,))
precompile(Base.isabspath, (String,))
precompile(Base.isempty, (String,))
precompile(Base.isempty, (Array{Any,1},))
precompile(Base.isempty, (Base.LineEdit.MIState,))
precompile(Base.isempty, (Base.LineEdit.PromptState,))
precompile(Base.isempty, (SubString{String},))
precompile(Base.isequal, (Tuple{Int,Int},Tuple{Int,Int}))
precompile(Base.isequal, (Base.LineEdit.Prompt, Base.LineEdit.Prompt))
precompile(Base.isequal, (Bool, Bool))
precompile(Base.isequal, (Char, String))
precompile(Base.isequal, (Int,Int))
precompile(Base.isequal, (RemoteChannel, RemoteChannel))
precompile(Base.isequal, (RemoteChannel, WeakRef))
precompile(Base.isequal, (Symbol, Symbol))
precompile(Base.isequal, (VersionNumber, VersionNumber))
precompile(Base.isequal, (Void, Void))
precompile(Base.isfile, (String,))
precompile(Base.ismatch, (Regex, String))
precompile(Base.isslotempty, (Dict{Any,Any}, Int))
precompile(Base.istaskdone, (Task,))
precompile(Base.joinpath, (String, String))
precompile(Base.joinpath, (String, String, String))
precompile(Base.keys, (Dict{UInt8, Any},))
precompile(Base.last, (UnitRange{Int},))
precompile(Base.length, (String,))
precompile(Base.length, (Array{UInt8,1},))
precompile(Base.length, (UnitRange{Int},))
precompile(Base.match, (Regex, String))
precompile(Base.match, (Regex, String, Int))
precompile(Base.min, (Int32, Int32))
precompile(Base.next, (Array{Base.LineEdit.TextInterface, 1}, Int))
precompile(Base.next, (Dict{Any,Any}, Int))
precompile(Base.next, (Dict{Symbol,Any},Int))
precompile(Base.next, (IntSet, Int))
precompile(Base.next, (UnitRange{Int},Int))
precompile(Base.nextind, (String, Int))
precompile(Base.normpath, (String, String))
precompile(Base.normpath, (String,))
precompile(Base.notify, (Condition, Any))
precompile(Base.open, (String, String))
precompile(Base.parse_input_line, (String,))
precompile(Base.parse, (Type{Int}, String, Int))
precompile(Base.peek, (Base.IOBuffer,))
precompile(Base.pop!, (Array{Any,1},))
precompile(Base.position, (IOBuffer,))
precompile(Base.prepend!, (Array{Dict{Any, Any}, 1}, Array{Dict{Any, Any}, 1}))
precompile(Base.print, (String,))
precompile(Base.print, (Base.TTY, String))
precompile(Base.print, (Base.TTY,Char))
precompile(Base.print, (Base.Terminals.TTYTerminal, String))
precompile(Base.print, (Base.Terminals.TTYTerminal, String, Char))
precompile(Base.print, (Base.Terminals.TTYTerminal, String, Char,))
precompile(Base.print, (Float64,))
precompile(Base.print, (IOBuffer, String))
precompile(Base.print, (IOBuffer, VersionNumber))
precompile(Base.print, (IOStream, Int32))
precompile(Base.print, (IOStream,String))
precompile(Base.join, (IOBuffer, Tuple{String}, Char))
precompile(Base.join, (IOBuffer, Tuple{Int}, Char))
precompile(Base.join, (IOBuffer, Array{String,1}, Char))
precompile(Base.join, (IOBuffer, Array{AbstractString,1}, String))
precompile(Base.join, (IOBuffer, Array{SubString{String}, 1}, String))
precompile(Base.println, (Base.TTY,))
precompile(Base.println, (Base.Terminals.TTYTerminal,))
precompile(Base.promote_type, (Type{Base.LineEdit.Prompt}, Type{Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}}))
precompile(Base.promote_type, (Type{Base.LineEdit.Prompt}, Type{Base.LineEdit.Prompt}))
precompile(Base.promote_type, (Type{Base.LineEdit.Prompt}, Type{Base.LineEdit.TextInterface}))
precompile(Base.promote_type, (Type{Int}, Bool))
precompile(Base.push!, (Array{AbstractString, 1}, String))
precompile(Base.push!, (Array{AbstractString,1}, String))
precompile(Base.push!, (Array{Base.Multimedia.Display, 1}, Base.Multimedia.TextDisplay))
precompile(Base.push!, (Array{Char, 1}, Char))
precompile(Base.push!, (Array{Union{String, String}, 1}, String))
precompile(Base.pushdisplay, (Base.Multimedia.TextDisplay,))
precompile(Base.pwd, ())
precompile(Base.read, (Base.Terminals.TTYTerminal, Type{Char}))
precompile(Base.read, (IOBuffer, Type{Char}))
precompile(Base.read, (IOBuffer, Type{UInt8}))
precompile(Base.read, (IOStream, Array{UInt32,1}))
precompile(Base.readline, (String,))
precompile(Base.readline, (IOBuffer,))
precompile(Base.readline, (IOStream,))
precompile(Base.readuntil, (IOBuffer, Char))
precompile(Base.readuntil, (IOBuffer, UInt8))
precompile(Base.rehash!, (Dict{Any,Any}, Int))
precompile(Base.rehash!, (Dict{UInt8, Any}, Int))
precompile(Base.reinit_stdio, ())
precompile(Base.repeat, (String, Int))
precompile(Base.repl_cmd, (Cmd, Base.Terminals.TTYTerminal))
precompile(Base.require, (Symbol,))
precompile(Base.remoteref_id, (RemoteChannel,))
precompile(Base.rsearch, (String, Char))
precompile(Base.rstrip, (String,))
precompile(Base.run, (Cmd,))
precompile(Base.search, (String, Regex, Int))
precompile(Base.search, (IOBuffer, UInt8))
precompile(Base.seek, (IOBuffer, Int))
precompile(Base.seekend, (IOStream,))
precompile(Base.setindex!, (Array{AbstractString, 1}, String, Int))
precompile(Base.setindex!, (Array{Any, 1}, Array{UInt8, 1}, Int))
precompile(Base.setindex!, (Array{Any, 1}, Base.NewvarNode, Int))
precompile(Base.setindex!, (Array{Any, 1}, GlobalRef, Int))
precompile(Base.setindex!, (Array{Any,1}, WeakRef, Int))
precompile(Base.setindex!, (Array{Base.LineEdit.TextInterface, 1}, Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}, UnitRange{Int}))
precompile(Base.setindex!, (Array{Base.LineEdit.TextInterface, 1}, Base.LineEdit.Prompt, UnitRange{Int}))
precompile(Base.setindex!, (Array{Char, 1}, Char, Int))
precompile(Base.setindex!, (Array{Symbol, 1}, Symbol, Int))
precompile(Base.setindex!, (Array{UInt8,1}, UInt8, Int))
precompile(Base.setindex!, (Base.Dict{Symbol, Any}, Base.LineEdit.Prompt, Symbol))
precompile(Base.setindex!, (BitArray{1}, Bool, Int,))
precompile(Base.setindex!, (Dict{Any, Any}, Base.LineEdit.PromptState, Base.LineEdit.Prompt))
precompile(Base.setindex!, (Dict{Any,Any}, Base.LineEdit.SearchState, Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}))
precompile(Base.setindex!, (Dict{Any,Any}, Bool, Cmd))
precompile(Base.setindex!, (Dict{UInt8, Any}, Base.LineEdit.Prompt, UInt8))
precompile(Base.setindex!, (Base.EnvHash, String, String))
precompile(Base.setindex!, (Vector{Any}, UInt8, Int))
precompile(Base.setindex!, (Vector{Any}, Vector{Any}, Int))
precompile(Base.show, (Base.Terminals.TTYTerminal, Int))
precompile(Base.show, (Float64,))
precompile(Base.show, (IOStream, Int32))
precompile(Base.showcompact, (Base.Terminals.TTYTerminal, Int))
precompile(Base.similar, (Array{Base.LineEdit.Prompt, 1}, Type{Base.LineEdit.TextInterface}, Tuple{Int}))
precompile(Base.size, (Base.Terminals.TTYTerminal,))
precompile(Base.sizehint!, (Base.Dict{Symbol, Any}, Int))
precompile(Base.sizeof, (String,))
precompile(Base.source_path, (Void,))
precompile(Base.splice!, (Array{UInt8, 1}, Base.UnitRange{Int}, Array{UInt8, 1}))
precompile(Base.split, (String, String))
precompile(Base.split, (String, Regex))
precompile(Base.split, (String,))
precompile(Base.srand, (Array{UInt32,1},))
precompile(Base.start, (Array{Base.LineEdit.TextInterface, 1},))
precompile(Base.start, (Dict{Any,Any},))
precompile(Base.start, (Dict{Symbol,Any},))
precompile(Base.start, (UnitRange{Int},))
precompile(Base.start_reading, (Base.TTY,))
precompile(Base.stop_reading, (Base.TTY,))
precompile(Libc.strftime, (String, Libc.TmStruct))
precompile(Base.string, (Int,))
precompile(Base.strip, (String,))
precompile(Base.strwidth, (String,))
precompile(Base.Symbol, (SubString{String},))
precompile(Base.sync_begin, ())
precompile(Base.sync_end, ())
precompile(Base.systemerror, (Symbol, Bool))
precompile(Base.take!, (Base.RemoteValue,))
precompile(Base.take!, (RemoteChannel,))
precompile(Base.take_ref, (Tuple{Int,Int},))
precompile(Base.take!, (IOBuffer,))
precompile(Base.task_local_storage, ())
precompile(Base.terminate_all_workers, ())
precompile(Base.try_include, (String,))
precompile(Base.UInt, (UInt,))
precompile(Base.unsafe_copy!, (Array{Dict{Any, Any}, 1}, Int, Array{Dict{Any, Any}, 1}, Int, Int))
precompile(Base.unsafe_copy!, (Ptr{Dict{Any, Any}}, Ptr{Dict{Any, Any}}, Int))
precompile(Base.unshift!, (Array{Any,1}, Task))
precompile(Base.uv_error, (String, Bool))
precompile(Base.uvfinalize, (Base.TTY,))
precompile(Base.vcat, (Base.LineEdit.Prompt,))
precompile(Base.wait, ())
precompile(Base.wait, (RemoteChannel,))
precompile(Base.write, (Base.Terminals.TTYTerminal, String))
precompile(Base.write, (Base.Terminals.TerminalBuffer, String))
precompile(Base.write, (IOBuffer, Vector{UInt8}))
precompile(Base.show, (Base.Terminals.TTYTerminal, Base.Multimedia.MIME{Symbol("text/plain")}, Int))

# The following are intended to help speed Pkg.update()
precompile(Base.Pkg.Entry.update, (String,))
precompile(Base.Pkg.Query.prune_dependencies, (Dict{String, Base.Pkg.Types.VersionSet}, Dict{String, Dict{VersionNumber, Base.Pkg.Types.Available}}))
precompile(Base.Pkg.Read.installed_version, (String, Dict{VersionNumber, Base.Pkg.Types.Available}))
precompile(Base.Pkg.Resolve.resolve, (Dict{String, Base.Pkg.Types.VersionSet}, Dict{String, Dict{VersionNumber, Base.Pkg.Types.Available}}))
precompile(Base.Pkg.update, ())
precompile(Base.Sort.sort!, (Array{Any, 1}, Base.Sort.MergeSortAlg, Base.Order.ForwardOrdering))
precompile(Base.Sort.sort!, (Array{Any, 1}, Int, Int, Base.Sort.InsertionSortAlg, Base.Order.ForwardOrdering))
precompile(Base.Sort.sort!, (Array{Any,1},))
precompile(Base.Sort.sort!, (Array{VersionNumber, 1}, Int, Int, Base.Sort.InsertionSortAlg, Base.Order.ForwardOrdering))
precompile(Base.info, (String,))
precompile(Base.isempty, (Array{Void, 1},))
precompile(Base.setindex!, (Dict{String, VersionNumber}, VersionNumber, String))
precompile(Base.spawn, (Cmd, Tuple{Base.TTY, Base.TTY, Base.TTY}, Bool, Bool))
precompile(Base.spawn, (Cmd,))

# For repl startup
precompile(Base.yieldto, (Task, Int))
precompile(Base.open, (String, Bool, Bool, Bool, Bool, Bool))
precompile(Base.setindex!, (Base.Dict{Any, Any}, Char, Char))
precompile(Base.setindex!, (Base.Dict{Any, Any}, Char, String))
precompile(Base.in, (String, Array{Any, 1}))
precompile(Base.getindex, (Base.Dict{Any, Any}, String))
precompile(Base.LineEdit.setup_prefix_keymap, (Base.REPL.REPLHistoryProvider, Base.LineEdit.Prompt))
precompile(Base.convert, (Type{Any}, Base.Dict{Char, Any}))
precompile(Base.REPL.mode_keymap, (Base.LineEdit.Prompt,))
precompile(Base.promote_type, (Type{Base.LineEdit.Prompt}, Type{Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}}, Type))
precompile(Base.promote_type, (Type{Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}}, Type{Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}))
precompile(Base.similar, (Array{Base.LineEdit.Prompt, 1}, Type{Base.LineEdit.TextInterface}, Tuple{Int64}))
precompile(Base.setindex!, (Array{Base.LineEdit.TextInterface, 1}, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}, Base.UnitRange{Int64}))
precompile(Base.LineEdit.init_state, (Base.Terminals.TTYTerminal, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}))
precompile(Base.setindex!, (Base.Dict{Any, Any}, Base.LineEdit.PrefixSearchState, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}))
precompile(Base.take_ref, (Tuple{Int64, Int64},))
precompile(Base.get, (Base.Dict{Any, Any}, Tuple{Int64, Int64}, Bool))
precompile(Base.LineEdit.refresh_multi_line, (Array{Any, 1}, Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.IOBuffer, Base.LineEdit.InputAreaState, Base.LineEdit.PromptState))
precompile(Base.schedule, (Array{Any, 1}, Task, Void))
precompile(Base.LineEdit.match_input, (Function, Base.LineEdit.MIState, Base.Terminals.TTYTerminal, Array{Char, 1}, Base.Dict{Char, Any}))
precompile(==, (Base.RemoteChannel, WeakRef))
precompile(==, (Base.RemoteChannel, Base.RemoteChannel))
precompile(Base.send_del_client, (Base.RemoteChannel,))
precompile(!=, (Base.SubString{String}, String))
precompile(Base.join, (Base.IOBuffer, Array{Base.SubString{String}, 1}, String))
precompile(Base.joinpath, (String, String, String, String))
precompile(Base.string, (String, String, Char))
precompile(Base.string, (String, String, Int))
precompile(Base.vect, (Base.LineEdit.Prompt, String))

# Speed up type inference in the post-Base world redefinition of convert
isdefined(Core, :Inference) && Base.code_typed(Base.code_typed)

# Speeding up addprocs for LocalManager
precompile(Base.start_worker, ())
precompile(Base.start_worker, (Base.TTY,))
precompile(Base.process_messages, (Base.TCPSocket, Base.TCPSocket))
precompile(Base.process_messages, (Base.TCPSocket, Base.TCPSocket, Void))
precompile(Base.process_tcp_streams, (Base.TCPSocket, Base.TCPSocket, Void))
precompile(Base.message_handler_loop, (Base.TCPSocket, Base.TCPSocket, Void))
precompile(Base.connect_to_peer, (Base.LocalManager, Int64, Base.WorkerConfig))
precompile(Base.connect, (Base.LocalManager, Int64, Base.WorkerConfig))
precompile(Base.connect_w2w, (Int64, Base.WorkerConfig))
precompile(Base.connect_to_worker, (String, Int64))
precompile(Base.addprocs, (Base.LocalManager, ))
precompile(Base.addprocs, (Int, ))
precompile(Base.setup_launched_worker, (Base.LocalManager, Dict, Base.WorkerConfig, Array{Int,1}))
precompile(Base.create_worker, (Base.LocalManager, Dict, Base.WorkerConfig))
precompile(Base.launch, (Base.LocalManager, Dict, Array{Base.WorkerConfig, 1}, Base.Condition))
precompile(Base.set_valid_processes, (Array{Int, 1}, ))

# Speed up repl help
sprint(Markdown.term, @doc mean)
sprint(Docs.repl_search, "mean")
sprint(Docs.repl_corrections, "meen")

# Speed up repl completions
Base.REPLCompletions.completions("IOBuffer().",11)
Base.REPLCompletions.completions("max([1],",8)

max_stars_repo_name: oxinabox/julia

max_issues_repo_name: oxinabox/julia

max_forks_repo_name: oxinabox/julia


text:
"""
Thread-safe logging
"""
module Log

@inline puts(s) = ccall(:puts, Cint, (Ptr{Int8},), string(s))

function error(msg::String)
    puts("ERROR: $msg")
end

function warn(msg::String)
    puts("WARN: $msg")
end

function info(msg::String)
    puts("INFO: $msg")
end

function debug(msg::String)
    puts("DEBUG: $msg")
end

end


text:
"""
Utility functions for learning and using background genomic hidden markov models
"""
#function to split random sample dataframe into training and test sets (divide total sequence length by half)
function split_obs_sets(sample_dfs::Dict{String,DataFrame})
    training_sets = Dict{String,Vector{LongSequence{DNAAlphabet{2}}}}()
    test_sets = Dict{String,Vector{LongSequence{DNAAlphabet{2}}}}()

    for (partition_id, partition) in sample_dfs
        partition = partition[shuffle(1:size(partition, 1)),:] #shuffle the samples to avoid any effect from sampling without replacement
        partition.sampleLength = (partition.SampleEnd - partition.SampleStart) .+ 1
        midway = sum(partition.sampleLength)÷2
        split_index = 0
        counter = 0
        while split_index == 0
            counter += 1
            length_sum = sum(partition.sampleLength[1:counter])
            if length_sum > midway
                split_index = counter
            end
        end

        training_sets[partition_id]  = partition.SampleSequence[1:split_index-1]
        test_sets[partition_id] = partition.SampleSequence[split_index:end]
    end
    return training_sets, test_sets
end


text:
using FinalProjectRepo
using Test, ReferenceTests, BSON

printstyled("Testing Part 1 of FinalProjectRepo.jl\n"; bold = true, color = :white)
include("part1.jl")

# Run tests for part 2 in save testing environment and the tests are split into different files because of MPI initialisation.
function runtests()
      exename = joinpath(Sys.BINDIR, Base.julia_exename())
      testdir = pwd()
      istestpart2(f) = endswith(f, ".jl") && startswith(basename(f), "part2_")
      testfiles = sort(filter(istestpart2, vcat([joinpath.(root, files) for (root, dirs, files) in walkdir(testdir)]...)))

      nfail = 0
      printstyled("Testing Part 2 of FinalProjectRepo.jl\n"; bold = true, color = :white)

      for f in testfiles
            try
			run(`$exename -O3 --startup-file=no --check-bounds=no $(joinpath(testdir, f))`)
            catch ex
                  nfail += 1
            end
      end
      return nfail
end

exit(runtests())


text:
function test_shape_function()
    radius = 1.0f0
    origin = Point3f0(0, 0, 0)
    mesh = icosphere(4, radius)
    n_samples = 10000
    min_all = 0
    max_a3 = pi
    max_d1 = 1.0f0
    max_d2 = 2.0f0
    # max_d3 =
    # max_d4 =
    res_a3 = a3fn(mesh, n_samples)
    res_d1 = d1fn(mesh, n_samples)
    res_d2 = d2fn(mesh, n_samples)
    res_d3 = d3fn(mesh, n_samples)
    res_d4 = d4fn(mesh, n_samples)
    @test isapprox(mean(res_d1), 1.0f0, atol = 0.001)
    @test isapprox(std(res_d1), 0.0f0, atol = 0.001)
end


text:
using DiscO
using Test

@testset "Fitnesses" begin
    # OneMax
    fakeinstance = Dict(["size" => 0])
    @test onemax(fakeinstance, BitArray([1])) == 1
    @test onemax(fakeinstance, BitArray([0])) == 0
    @test onemax(fakeinstance, BitArray([0,1,0,1,1])) == 3

    # ZeroMax
    @test zeromax(fakeinstance, BitArray([1])) == 0
    @test zeromax(fakeinstance, BitArray([0])) == 1
    @test zeromax(fakeinstance, BitArray([0,1,0,1,1])) == 2

end

max_stars_repo_name: ahrajabi/DiscO

max_issues_repo_name: ahrajabi/DiscO

max_forks_repo_name: ahrajabi/DiscO