text:
@enum ParsingState None Delimiter EOF Newline
const P = Ref{ParsingState}

# at start of field: check if eof, remove leading whitespace, check if empty field
# returns `true` if result of initial parsing is a missing field
# also return `b` which is last byte read
macro checkmissingstart()
    return esc(quote
        state[] = None
        eof(io) && (state[] = EOF; @goto missing)
        b = readbyte(io)
        while b != opt.delim && (b == CSV.SPACE || b == CSV.TAB || b == opt.quotechar)
            eof(io) && (state[] = EOF; @goto missing)
            b = readbyte(io)
        end
        if b == opt.delim
            state[] = Delimiter
            @goto missing
        elseif b == NEWLINE
            state[] = Newline
            @goto missing
        elseif b == RETURN
            state[] = Newline
            !eof(io) && peekbyte(io) == NEWLINE && readbyte(io)
            @goto missing
        end
    end)
end

# check if we've successfully finished parsing a field by whether
# we've encountered a delimiter or newline break or reached eof
macro checkdone(label)
    return esc(quote
        b == opt.quotechar && !eof(io) && (b = readbyte(io))
        if b == opt.delim
            state[] = Delimiter
            @goto $label
        elseif b == NEWLINE
            state[] = Newline
            @goto $label
        elseif b == RETURN
            state[] = Newline
            !eof(io) && peekbyte(io) == NEWLINE && readbyte(io)
            @goto $label
        elseif b == opt.quotechar && eof(io)
            state[] = EOF
            @goto $label
        elseif b == CSV.SPACE || b == CSV.TAB
            # trailing whitespace
            while !eof(io) && (b == CSV.SPACE || b == CSV.TAB)
                b = readbyte(io)
            end
            if b == opt.delim
                state[] = Delimiter
                @goto $label
            elseif b == NEWLINE
                state[] = Newline
                @goto $label
            elseif b == RETURN
                state[] = Newline
                !eof(io) && peekbyte(io) == NEWLINE && readbyte(io)
                @goto $label
            elseif eof(io)
                state[] = EOF
                @goto $label
            end
        end
    end)
end

ParsingException(::Type{T}, b, row, col) where {T} = CSV.ParsingException("error parsing a `$T` value on column $col, row $row; encountered '$(Char(b))'")

# as a last ditch effort, after we've trying parsing the correct type,
# we check if the field is equal to a custom missing type
# otherwise we give up and throw an error
macro checkmissingend()
    return esc(quote
        !opt.missingcheck && @goto error
        i = 1
        while true
            b == opt.missingstring[i] || @goto error
            (i == length(opt.missingstring) || eof(io)) && break
            b = readbyte(io)
            i += 1
        end
        if !eof(io)
            b = readbyte(io)
            @checkdone(missing)
        end
        state[] = EOF
        @goto missing
    end)
end
"""
`CSV.parsefield{T}(io::IO, ::Type{T}, opt::CSV.Options=CSV.Options(), row=0, col=0)` => `Union{T, Missing}`
`CSV.parsefield{T}(s::CSV.Source, ::Type{T}, row=0, col=0)` => `Union{T, Missing}``

`io` is an `IO` type that is positioned at the first byte/character of an delimited-file field (i.e. a single cell)
leading whitespace is ignored for Integer and Float types.
Specialized methods exist for Integer, Float, String, Date, and DateTime.
For other types `T`, a generic fallback requires `parse(T, str::String)` to be defined.
the field value may also be wrapped in `opt.quotechar`; two consecutive `opt.quotechar` results in a missing field
`opt.missingstring` is also checked if there is a custom value provided (i.e. "NA", "\\N", etc.)
For numeric fields, if field is non-missing and non-digit characters are encountered at any point before a delimiter or newline, an error is thrown

The second method of `CSV.parsefield` operates on a `CSV.Source` directly allowing for easy usage when writing custom parsing routines.
Do note, however, that the `row` and `col` arguments are for error-reporting purposes only. A `CSV.Source` maintains internal state with
regards to the underlying data buffer and can **only** parse fields sequentially. This means that `CSV.parsefield` needs to be called somewhat like:

```julia
source = CSV.Source(file)

types = Data.types(source)

for col = 1:length(types)
    println(get(CSV.parsefield(source, types[col]), "\"\""))
end
```
"""
function parsefield end

const MISSINGTHROW = (row, col)->throw(Missings.MissingException("encountered a missing value for a column type which does not support them on row = $row, col = $col"))
const MISSINGRETURN = (row, col)->missing

parsefield(source::CSV.Source, ::Type{T}, row=0, col=0, state::P=P()) where {T} = CSV.parsefield(source.io, T, source.options, row, col, state, T !== Missing ? MISSINGTHROW : MISSINGRETURN)
parsefield(source::CSV.Source, ::Type{Union{T, Missing}}, row=0, col=0, state::P=P()) where {T} = CSV.parsefield(source.io, T, source.options, row, col, state, MISSINGRETURN)
parsefield(source::CSV.Source, ::Type{Missing}, row=0, col=0, state::P=P()) = CSV.parsefield(source.io, WeakRefString{UInt8}, source.options, row, col, state, MISSINGRETURN)

@inline parsefield(io::IO, ::Type{T}, opt::CSV.Options=CSV.Options(), row=0, col=0, state::P=P()) where {T} = parsefield(io, T, opt, row, col, state, T !== Missing ? MISSINGTHROW : MISSINGRETURN)
@inline parsefield(io::IO, ::Type{Union{T, Missing}}, opt::CSV.Options=CSV.Options(), row=0, col=0, state::P=P()) where {T} = parsefield(io, T, opt, row, col, state, MISSINGRETURN)
@inline parsefield(io::IO, ::Type{Missing}, opt::CSV.Options=CSV.Options(), row=0, col=0, state::P=P()) = parsefield(io, WeakRefString{UInt8}, opt, row, col, state, MISSINGRETURN)

function parsefield(io::IO, ::Type{T}, opt::CSV.Options, row, col, state, ifmissing::Function) where {T <: Integer}
    @checkmissingstart()
    v = zero(T)
    negative = false
    if b == MINUS # check for leading '-' or '+'
        c = peekbyte(io)
        if NEG_ONE < c < TEN
            negative = true
            b = readbyte(io)
        end
    elseif b == PLUS
        c = peekbyte(io)
        if NEG_ONE < c < TEN
            b = readbyte(io)
        end
    end
    while NEG_ONE < b < TEN
        # process digits
        v, ov_mul = Base.mul_with_overflow(v, T(10))
        v, ov_add = Base.add_with_overflow(v, T(b - ZERO))
        (ov_mul | ov_add) && throw(OverflowError("overflow parsing $T, parsed $v"))
        eof(io) && (state[] = EOF; @goto done)
        b = readbyte(io)
    end
    @checkdone(done)
    @checkmissingend()

    @label done
    return ifelse(negative, -v, v)

    @label missing
    return ifmissing(row, col)

    @label error
    throw(ParsingException(T, b, row, col))
end

const BUF = IOBuffer()

getptr(io::IO) = C_NULL
getptr(io::IOBuffer) = pointer(io.data, io.ptr)
incr(io::IO, b) = Base.write(BUF, b)
incr(io::IOBuffer, b) = 1

make(io::IOBuffer, ::Type{WeakRefString{UInt8}}, internstrings::Bool, ptr, len) = WeakRefString(Ptr{UInt8}(ptr), len)
make(io::IOBuffer, ::Type{String}, internstrings::Bool, ptr, len) =
    internstrings ? intern(String, WeakRefString(Ptr{UInt8}(ptr), len)) : unsafe_string(ptr, len)
make(io::IO, ::Type{<:Union{String, WeakRefString{UInt8}}}, internstrings::Bool, ptr, len) =
    internstrings ? intern(String(take!(BUF))) : String(take!(BUF))

function parsefield(io::IO, T::Type{<:AbstractString}, opt::CSV.Options, row, col, state, ifmissing::Function)
    eof(io) && (state[] = EOF; @goto missing)
    ptr = getptr(io)
    len = 0
    missingcheck = opt.missingcheck # if missingstring is "", then we don't need to byte match it
    n = opt.missingstring
    q = opt.quotechar
    e = opt.escapechar
    d = opt.delim
    s = opt.internstrings
    missinglen = length(n)
    @inbounds while !eof(io)
        b = readbyte(io)
        if b == q
            ptr += 1
            while !eof(io)
                b = readbyte(io)
                if b == e
                    if eof(io)
                        break
                    elseif e == q && peekbyte(io) != q
                        break
                    end
                    len += incr(io, b)
                    b = readbyte(io)
                elseif b == q
                    break
                end
                (missingcheck && len+1 <= missinglen && b == n[len+1]) || (missingcheck = false)
                len += incr(io, b)
            end
        elseif b == d
            state[] = Delimiter
            break
        elseif b == NEWLINE
            state[] = Newline
            break
        elseif b == RETURN
            state[] = Newline
            !eof(io) && peekbyte(io) == NEWLINE && readbyte(io)
            break
        else
            (missingcheck && len+1 <= missinglen && b == n[len+1]) || (missingcheck = false)
            len += incr(io, b)
        end
    end
    eof(io) && (state[] = EOF)
    (len == 0 || missingcheck) && @goto missing
    return make(io, T, s, ptr, len)

    @label missing
    take!(BUF)
    return ifmissing(row, col)
end

function parsefield(io::IO, ::Type{Date}, opt::CSV.Options, row, col, state, ifmissing::Function)
    v = parsefield(io, String, opt, row, col, state, ifmissing)
    return v isa Missing ? ifmissing(row, col) : Date(v, opt.dateformat)
end
function parsefield(io::IO, ::Type{DateTime}, opt::CSV.Options, row, col, state, ifmissing::Function)
    v = parsefield(io, String, opt, row, col, state, ifmissing)
    return v isa Missing ? ifmissing(row, col) : DateTime(v, opt.dateformat)
end

function parsefield(io::IO, ::Type{Char}, opt::CSV.Options, row, col, state, ifmissing::Function)
    @checkmissingstart()
    c = b
    eof(io) && (state[] = EOF; @goto done)
    opt.missingcheck && b == opt.missingstring[1] && @goto missing
    b = readbyte(io)
    @checkdone(done)
    @checkmissingend()

    @label done
    return Char(c)

    @label missing
    return ifmissing(row, col)

    @label error
    throw(ParsingException(Char, b, row, col))
end

function parsefield(io::IO, ::Type{Bool}, opt::CSV.Options, row, col, state, ifmissing::Function)
    @checkmissingstart()
    truestring = opt.truestring
    falsestring = opt.falsestring
    i = 1
    if b == truestring[i]
        v = true
        while true
            if eof(io)
                if i == length(truestring)
                    state[] = EOF
                    @goto done
                end
                @goto error
            end
            b = readbyte(io)
            i += 1
            i > length(truestring) && break
            b == truestring[i] || @goto error
        end
        @checkdone(done)
    elseif b == falsestring[i]
        v = false
        while true
            if eof(io)
                if i == length(falsestring)
                    state[] = EOF
                    @goto done
                end
                @goto error
            end
            b = readbyte(io)
            i += 1
            i > length(falsestring) && break
            b == falsestring[i] || @goto error
        end
        @checkdone(done)
    end
    @checkmissingend()

    @label done
    return v

    @label missing
    return ifmissing(row, col)

    @label error
    throw(ParsingException(Bool, b, row, col))
end

function parsefield(io::IO, ::Type{<:Union{CategoricalValue, CategoricalString}}, opt::CSV.Options, row, col, state, ifmissing::Function)
    v = parsefield(io, WeakRefString{UInt8}, opt, row, col, state, ifmissing)
    return v isa Missing ? ifmissing(row, col) : v
end

# Generic fallback
function parsefield(io::IO, T, opt::CSV.Options, row, col, state, ifmissing::Function)
    v = parsefield(io, String, opt, row, col, state, ifmissing)
    ismissing(v) && return ifmissing(row, col)
    T === Missing && throw(ParsingException("encountered non-missing value for a missing-only column on row = $row, col = $col: '$v'"))
    return parse(T, v)
end


text:
"""
    function getS(m::Model; zeros=spzeros)::Tuple{Vector{String},Vector{String},AbstractMatrix{Float64}}

Extract the vector of species (aka metabolite) identifiers, vector of reaction
identifiers, and the (dense) stoichiometry matrix from an existing `Model`.
Returns a tuple with these values.

The matrix is sparse by default (initially constructed by
`SparseArrays.spzeros`). You can fill in a custom empty matrix constructed to
argument `zeros`; e.g. running with `zeros=zeros` will produce a dense matrix.
"""
function getS(
    m::Model;
    zeros = spzeros,
)::Tuple{Vector{String},Vector{String},AbstractMatrix{Float64}}
    rows = [k for k in keys(m.species)]
    cols = [k for k in keys(m.reactions)]
    rowsd = Dict(k => i for (i, k) in enumerate(rows))
    S = zeros(Float64, length(rows), length(cols))
    for col = 1:length(cols)
        stoi = m.reactions[cols[col]].stoichiometry
        S[getindex.(Ref(rowsd), keys(stoi)), col] .= values(stoi)
    end
    return rows, cols, S
end

"""
    function getLBs(m::Model)::Vector{Tuple{Float64,String}}

Extract a vector of lower bounds of reaction rates from the model. All bounds
are accompanied with the unit of the corresponding value (this behavior is
based on SBML specification).
"""
function getLBs(m::Model)::Vector{Tuple{Float64,String}}
    return broadcast(x -> x.lb, values(m.reactions))
end

"""
    function getUBs(m::Model)::Vector{Tuple{Float64,String}}

Likewise to `getLBs`, extract the upper bounds.
"""
function getUBs(m::Model)::Vector{Tuple{Float64,String}}
    return broadcast(x -> x.ub, values(m.reactions))
end

"""
    function getOCs(m::Model)::Vector{Float64}

Extract the vector of objective coefficients of each reaction.
"""
function getOCs(m::Model)::Vector{Float64}
    return broadcast(x -> x.oc, values(m.reactions))
end

ext: jl


text:
# Normed{T,f} maps UInts from 0 to 2^f-1 to the range [0.0, 1.0]
# For example, Normed{UInt8,8} == N0f8 maps 0x00 to 0.0 and 0xff to 1.0

immutable Normed{T<:Unsigned,f} <: FixedPoint{T,f}
    i::T

    (::Type{Normed{T, f}}){T, f}(i::Integer,_) = new{T, f}(i%T)   # for setting by raw representation
    (::Type{Normed{T, f}}){T, f}(x) = convert(Normed{T,f}, x)
end

typechar{X<:Normed}(::Type{X}) = 'N'
signbits{X<:Normed}(::Type{X}) = 0

for T in (UInt8, UInt16, UInt32, UInt64)
    for f in 0:sizeof(T)*8
        sym = Symbol(String(take!(showtype(_iotypealias, Normed{T,f}))))
        @eval begin
            const $sym = Normed{$T,$f}
            export $sym
        end
    end
end

reinterpret{T<:Unsigned, f}(::Type{Normed{T,f}}, x::T) = Normed{T,f}(x, 0)

zero{T,f}(::Type{Normed{T,f}}) = Normed{T,f}(zero(T),0)
function one{T<:Normed}(::Type{T})
    T(typemax(rawtype(T)) >> (8*sizeof(T)-nbitsfrac(T)), 0)
end
zero(x::Normed) = zero(typeof(x))
 one(x::Normed) =  one(typeof(x))
rawone(v) = reinterpret(one(v))

# Conversions
convert{T<:Unsigned,f}(::Type{Normed{T,f}}, x::Normed{T,f}) = x
@inline convert{T1<:Unsigned,T2<:Unsigned,f}(::Type{Normed{T1,f}}, x::Normed{T2,f}) = Normed{T1,f}(convert(T1, x.i), 0)
@inline function convert{T<:Unsigned,T2<:Unsigned,f}(::Type{Normed{T,f}}, x::Normed{T2})
    U = Normed{T,f}
    y = round((rawone(U)/rawone(x))*reinterpret(x))
    (0 <= y) & (y <= typemax(T)) || throw_converterror(U, x)
    reinterpret(U, _unsafe_trunc(T, y))
end
@inline convert{U<:Normed}(::Type{U}, x::Real) = _convert(U, rawtype(U), x)

@inline convert(::Type{N0f16}, x::N0f8) = reinterpret(N0f16, convert(UInt16, 0x0101*reinterpret(x)))
@inline function _convert{U<:Normed,T}(::Type{U}, ::Type{T}, x)
    y = @fastmath round(widen1(rawone(U))*x)
    (0 <= y) & (y <= typemax(T)) || throw_converterror(U, x)
    U(_unsafe_trunc(T, y), 0)
end
@inline function _convert{U<:Normed}(::Type{U}, ::Type{UInt128}, x)
    y = round(rawone(U)*x)   # for UInt128, we can't widen
    (0 <= y) & (y <= typemax(UInt128)) & (x <= Float64(typemax(U))) || throw_converterror(U, x)
    U(_unsafe_trunc(UInt128, y), 0)
end

rem{T<:Normed}(x::T, ::Type{T}) = x
@inline rem{T<:Normed}(x::Normed, ::Type{T}) = reinterpret(T, _unsafe_trunc(rawtype(T), round((rawone(T)/rawone(x))*reinterpret(x))))
@inline rem{T<:Normed}(x::Integer, ::Type{T}) = reinterpret(T, _unsafe_trunc(rawtype(T), round(rawone(T)*x)))
@inline rem{T<:Normed}(x::Real, ::Type{T}) = reinterpret(T, _unsafe_trunc(rawtype(T), round(rawone(T)*x)))

# convert(::Type{AbstractFloat}, x::Normed) = convert(floattype(x), x)
float(x::Normed) = convert(floattype(x), x)

convert(::Type{BigFloat}, x::Normed) = reinterpret(x)*(1/BigFloat(rawone(x)))
@inline function convert{T<:AbstractFloat}(::Type{T}, x::Normed)
    y = @fastmath reinterpret(x)*(one(rawtype(x))/convert(T, rawone(x)))
    convert(T, y)  # needed for types like Float16 which promote arithmetic to Float32
end
convert(::Type{Bool}, x::Normed) = x == zero(x) ? false : true
@inline convert{T<:Integer}(::Type{T}, x::Normed) = convert(T, x*(1/one(T)))
@inline convert{Ti<:Integer}(::Type{Rational{Ti}}, x::Normed) = convert(Ti, reinterpret(x))//convert(Ti, rawone(x))
convert(::Type{Rational}, x::Normed) = reinterpret(x)//rawone(x)

# Traits
abs(x::Normed) = x

(-){T<:Normed}(x::T) = T(-reinterpret(x), 0)
(~){T<:Normed}(x::T) = T(~reinterpret(x), 0)

+{T,f}(x::Normed{T,f}, y::Normed{T,f}) = Normed{T,f}(convert(T, x.i+y.i),0)
-{T,f}(x::Normed{T,f}, y::Normed{T,f}) = Normed{T,f}(convert(T, x.i-y.i),0)
*{T<:Normed}(x::T, y::T) = convert(T,convert(floattype(T), x)*convert(floattype(T), y))
/{T<:Normed}(x::T, y::T) = convert(T,convert(floattype(T), x)/convert(floattype(T), y))

# Comparisons
 <{T<:Normed}(x::T, y::T) = reinterpret(x) < reinterpret(y)
<={T<:Normed}(x::T, y::T) = reinterpret(x) <= reinterpret(y)

# Functions
trunc{T<:Normed}(x::T) = T(div(reinterpret(x), rawone(T))*rawone(T),0)
floor{T<:Normed}(x::T) = trunc(x)
function round{T,f}(x::Normed{T,f})
    mask = convert(T, 1<<(f-1))
    y = trunc(x)
    return convert(T, reinterpret(x)-reinterpret(y)) & mask>0 ?
            Normed{T,f}(y+one(Normed{T,f})) : y
end
function ceil{T,f}(x::Normed{T,f})
    k = 8*sizeof(T)-f
    mask = (typemax(T)<<k)>>k
    y = trunc(x)
    return convert(T, reinterpret(x)-reinterpret(y)) & (mask)>0 ?
            Normed{T,f}(y+one(Normed{T,f})) : y
end

trunc{T<:Integer}(::Type{T}, x::Normed) = convert(T, div(reinterpret(x), rawone(x)))
round{T<:Integer}(::Type{T}, x::Normed) = round(T, reinterpret(x)/rawone(x))
floor{T<:Integer}(::Type{T}, x::Normed) = trunc(T, x)
 ceil{T<:Integer}(::Type{T}, x::Normed) =  ceil(T, reinterpret(x)/rawone(x))

isfinite(x::Normed) = true
isnan(x::Normed) = false
isinf(x::Normed) = false

bswap{f}(x::Normed{UInt8,f}) = x
bswap(x::Normed)  = typeof(x)(bswap(reinterpret(x)),0)

function minmax{T<:Normed}(x::T, y::T)
    a, b = minmax(reinterpret(x), reinterpret(y))
    T(a,0), T(b,0)
end

# Iteration
# The main subtlety here is that iterating over 0x00uf8:0xffuf8 will wrap around
# unless we iterate using a wider type
@inline start{T<:Normed}(r::StepRange{T}) = widen1(reinterpret(r.start))
@inline next{T<:Normed}(r::StepRange{T}, i::Integer) = (T(i,0), i+reinterpret(r.step))
@inline function done{T<:Normed}(r::StepRange{T}, i::Integer)
    i1, i2 = reinterpret(r.start), reinterpret(r.stop)
    isempty(r) | (i < min(i1, i2)) | (i > max(i1, i2))
end

function decompose(x::Normed)
    g = gcd(reinterpret(x), rawone(x))
    div(reinterpret(x),g), 0, div(rawone(x),g)
end

# Promotions
promote_rule{T<:Normed,Tf<:AbstractFloat}(::Type{T}, ::Type{Tf}) = promote_type(floattype(T), Tf)
promote_rule{T<:Normed, R<:Rational}(::Type{T}, ::Type{R}) = R
function promote_rule{T<:Normed, Ti<:Union{Signed,Unsigned}}(::Type{T}, ::Type{Ti})
    floattype(T)
end
@generated function promote_rule{T1,T2,f1,f2}(::Type{Normed{T1,f1}}, ::Type{Normed{T2,f2}})
    f = max(f1, f2)  # ensure we have enough precision
    T = promote_type(T1, T2)
    # make sure we have enough integer bits
    i1, i2 = 8*sizeof(T1)-f1, 8*sizeof(T2)-f2  # number of integer bits for each
    i = 8*sizeof(T)-f
    while i < max(i1, i2)
        T = widen1(T)
        i = 8*sizeof(T)-f
    end
    :(Normed{$T,$f})
end

_unsafe_trunc{T}(::Type{T}, x::Integer) = x % T
_unsafe_trunc{T}(::Type{T}, x)          = unsafe_trunc(T, x)


text:
for t in (Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128)
    @eval begin
        unsafe_trunc(::Type{$t}, x::BFloat16) = unsafe_trunc($t, Float32(x))
    end
end
trunc(::Type{T}, x::BFloat16) where {T<:Integer} = trunc(T, Float32(x))
floor(::Type{T}, x::BFloat16) where {T<:Integer} = floor(T, Float32(x))
ceil(::Type{T}, x::BFloat16) where {T<:Integer}  = ceil(T, Float32(x))
round(::Type{T}, x::BFloat16) where {T<:Integer} = round(T, Float32(x))

round(x::BFloat16, r::RoundingMode{:ToZero})  = BFloat16(round(Float32(x), r))
round(x::BFloat16, r::RoundingMode{:Down})    = BFloat16(round(Float32(x), r))
round(x::BFloat16, r::RoundingMode{:Up})      = BFloat16(round(Float32(x), r))
round(x::BFloat16, r::RoundingMode{:Nearest}) = BFloat16(round(Float32(x), r))

-(x::BFloat16) = reinterpret(BFloat16, reinterpret(uinttype(BFloat16), x) ⊻ sign_mask(BFloat16))

# TODO: Write native BF16 arithmetic functions
for op in (:+, :-, :*, :/, :\, :^)
    @eval ($op)(a::BFloat16, b::BFloat16) = BFloat16(($op)(Float32(a), Float32(b)))
end

function muladd(a::BFloat16, b::BFloat16, c::BFloat16)
    BFloat16(muladd(Float32(a), Float32(b), Float32(c)))
end

for func in (:div,:fld,:cld,:rem,:mod)
    @eval begin
        $func(a::BFloat16,b::BFloat16) = BFloat16($func(Float32(a),Float32(b)))
    end
end

function ==(x::BFloat16, y::BFloat16)
    ix = reinterpret(uinttype(BFloat16), x)
    iy = reinterpret(uinttype(BFloat16), y)
    if (ix|iy) & ~sign_mask(BFloat16) > NaNB16 # isnan(x) || isnan(y)
        return false
    end
    if (ix|iy) & ~sign_mask(BFloat16) == 0x0000
        return true
    end
    return ix == iy
end

for op in (:<, :<=, :isless)
    @eval ($op)(a::BFloat16, b::BFloat16) = ($op)(Float32(a), Float32(b))
end

for op in (:(==), :<, :<=)
    @eval begin
        ($op)(x::BFloat16, y::Union{Int128,UInt128,Int64,UInt64}) = ($op)(Float64(x), Float64(y))
        ($op)(x::Union{Int128,UInt128,Int64,UInt64}, y::BFloat16) = ($op)(Float64(x), Float64(y))

        ($op)(x::Union{BFloat16,Float32}, y::Union{Int32,UInt32}) = ($op)(Float64(x), Float64(y))
        ($op)(x::Union{Int32,UInt32}, y::Union{BFloat16,Float32}) = ($op)(Float64(x), Float64(y))

        ($op)(x::BFloat16, y::Union{Int16,UInt16}) = ($op)(Float32(x), Float32(y))
        ($op)(x::Union{Int16,UInt16}, y::BFloat16) = ($op)(Float32(x), Float32(y))
    end
end

abs(x::BFloat16) = reinterpret(BFloat16, reinterpret(uinttype(BFloat16), x) & ~sign_mask(BFloat16))

isnan(x::BFloat16) = reinterpret(uinttype(BFloat16), x) & ~sign_mask(BFloat16) > NaNB16
isfinite(x::BFloat16) = reinterpret(uinttype(BFloat16), x) & NaNB16 != NaNB16

precision(::Type{BFloat16}) = significand_bits(BFloat16) + 1

function nextfloat(f::BFloat16, d::Integer)
    F = typeof(f)
    fumax = reinterpret(UInt16, F(Inf))
    U = typeof(fumax)

    isnan(f) && return f
    fi = reinterpret(Int16, f)
    fneg = fi < 0
    fu = unsigned(fi & typemax(fi))

    dneg = d < 0
    da = Base.uabs(d)
    if da > typemax(U)
        fneg = dneg
        fu = fumax
    else
        du = da % U
        if fneg ⊻ dneg
            if du > fu
                fu = min(fumax, du - fu)
                fneg = !fneg
            else
                fu = fu - du
            end
        else
            if fumax - fu < du
                fu = fumax
            else
                fu = fu + du
            end
        end
    end
    if fneg
        fu |= sign_mask(F)
    end
    reinterpret(F, fu)
end
nextfloat(x::BFloat16) = nextfloat(x, 1)
prevfloat(x::BFloat16, d::Integer) = nextfloat(x, -d)
prevfloat(x::BFloat16) = nextfloat(x, -1)

function issubnormal(x::BFloat16)
    y = reinterpret(Unsigned, x)
    (y & exponent_mask(BFloat16) == 0) & (y & significand_mask(BFloat16) != 0)
end

typemin(::Type{BFloat16})  = bitcast(BFloat16, 0xff80)
typemax(::Type{BFloat16})  = InfB16
floatmin(::Type{BFloat16}) = bitcast(BFloat16, 0x0080)
floatmax(::Type{BFloat16}) = bitcast(BFloat16, 0x7f7f)
eps(::Type{BFloat16})      = bitcast(BFloat16, 0x3c00)

truncmask(x::BFloat16, mask) = reinterpret(BFloat16, mask & reinterpret(uinttype(BFloat16), x))
truncbits(x::BFloat16, nb) = truncmask(x, typemax(uinttype(BFloat16)) << nb)

bswap(x::BFloat16) = bswap_int(x)

iszero(x::BFloat16) = reinterpret(uinttype(BFloat16), x) & ~sign_mask(BFloat16) == 0x0000


text:
include("utils.jl")

Random.seed!(42)

@testset "K-Means" begin
    M = Sphere(2)
    p1 = 1/sqrt(3) .* [1.0, 1.0, 1.0]
    p2 = 1/sqrt(3) .* [-1.0, -1.0, 1.0]
    c1 = [exp(M,p1, project(M, p1, 0.7 .* (rand(3) .- 0.5 ))) for i=1:20]
    c2 = [exp(M,p2, project(M, p2, 0.7 .* (rand(3) .- 0.5 ))) for i=1:20]

    pts = [p1, p2, c1..., c2...]
    o = kmeans(M, pts; num_centers=2)
    @test distance(M,p1,o.centers[1]) ≈ 0
    @test distance(M,p2,o.centers[2]) ≈ 0
    @test sum(o.assignment .== 1) == 21
    @test sum(o.assignment .== 2) == 21
end

max_stars_repo_name: JuliaManifolds/ManifoldML

max_issues_repo_name: JuliaManifolds/ManifoldML

max_forks_repo_name: JuliaManifolds/ManifoldML


text:
using Documenter, ImageFiltering

makedocs(modules  = [ImageFiltering, Kernel, KernelFactors],
         format   = Documenter.Formats.HTML,
         sitename = "ImageFiltering",
         pages    = ["index.md", "Function reference" => "function_reference.md"])

deploydocs(repo   = "github.com/JuliaImages/ImageFiltering.jl.git",
           target = "build",
           deps   = nothing,
           make   = nothing)


text:
module ExtraHelpers
export @traits_test, @traits_get_state, @traits_show_implementation
import WhereTraits
using WhereTraits: CONFIG
using WhereTraits.Utils
using WhereTraits.Syntax.Rendering
using WhereTraits.InternalState
import WhereTraits.Syntax.Rendering: render, RenderOuterFunc, RenderInnerFunc
using Markdown

"""
like @traits, and works within Test.@testset, but cannot be doc-stringed

needed because of https://github.com/JuliaLang/julia/issues/34263
"""
macro traits_test(expr_original)
  expr = macroexpand(__module__, expr_original)
  expr_traits = WhereTraits.Syntax._traits(@MacroEnv, expr, expr_original)
  # :(eval($(QuoteNode(...))) is a workaround for @testset, see https://github.com/JuliaLang/julia/issues/34263
  expr_traits = :(eval($(QuoteNode(expr_traits))))
  expr_traits = esc(expr_traits)
  if CONFIG.suppress_on_traits_definitions
    expr_traits = :(@suppress $expr_traits)
  end
  expr_traits
end

"""
    @traits_get_state functionname

Helper function which returns all the stored states which define the traitfunctions for the given function name,
one for each traits-enabled method signature.
"""
macro traits_get_state(funcname)
  get_traitsstores(__module__, funcname)
end

function get_traitsstores(mod, funcname)
  mod_original, funcname_original = normalize_mod_and_name(mod, funcname)
  isdefined(mod_original, funcname_original) || return []

  func = Core.eval(mod_original, funcname_original)
  traits_enabled_signatures = []
  for m in methods(func)
    parameters = Base.unwrap_unionall(m.sig).parameters
    if (m.sig <: Tuple
        && length(parameters) == 3
        && parameters[2] === WhereTraits.InternalState.TraitsStoreSingleton
        && parameters[3] <: Type{<:Tuple})
      # third parameter is the Type{SignatureTuple}
      signature = parameters[3].parameters[1]
      push!(traits_enabled_signatures, signature)
    end
  end
  for sig in traits_enabled_signatures
      if isnothing(get_traitsstore(mod, funcname, sig))
        error("mod = $mod, funcname = $funcname, sig = $sig")
      end
    end
  [get_traitsstore(mod, funcname, sig) for sig in traits_enabled_signatures]
end

"""
    @traits_show_implementation mytraitsenabled_function

Render a whole TraitsStore. To get an easy fealing of what is going on and inspect errors.

For debugging purposes only.
"""
macro traits_show_implementation(funcname)
  traits_show_implementation(@MacroEnv, funcname)
end

function traits_show_implementation(env, funcname)
  stores = get_traitsstores(env.mod, funcname)
  traits_show_implementation_stores(env, stores)
end

"""
render a whole TraitsStore

for debugging purposes only
"""
function traits_show_implementation_stores(env::MacroEnv, stores)
  exprs = []
  for store in stores
    outerfunc, innerfuncs = store.definitions.outer, store.definitions.inners
    push!(exprs, Markdown.parse("Outer function for signature $(outerfunc.fixed.signature)"))
    push!(exprs, Markdown.parse("""
    ```
    $(render(env, store, RenderOuterFunc(outerfunc))))
    ```
    """))
    push!(exprs, Markdown.parse("\n- - -\n"))
    push!(exprs, Markdown.parse("Inner functions for signature $(outerfunc.fixed.signature)"))
    for (fixed, nonfixed) in innerfuncs
      innerfunc = WhereTraits.InternalState.DefInnerFunc(fixed = fixed, nonfixed = nonfixed)
      push!(exprs, Markdown.parse("""
      ```
      $(render(env, store, RenderInnerFunc(outerfunc, innerfunc)))
      ```
      """))
      push!(exprs, Markdown.parse("\n- - -\n"))
    end
    # nice separtor between several outer functions
    push!(exprs, Markdown.HorizontalRule())
  end
  Markdown.MD(exprs...)
end

end # module


text:
export PoolingFunction, Pooling
@compat abstract type PoolingFunction end
@compat abstract type StdPoolingFunction <: PoolingFunction end # built-in poolings

module Pooling
using ..Mocha.StdPoolingFunction

type Max <: StdPoolingFunction end
type Mean <: StdPoolingFunction end

end # module Pooling


text:
"""
    relax(t, M0, T1, T2)

Simulate relaxation.

# Arguments
- `t::Real`: Duration of relaxation
- `M0::Real`: Equilibrium magnetization
- `T1::Real`: Spin-lattice recovery time constant
- `T2::Real`: Spin-spin recovery time constant

## Note
Inputs `t`, `T1`, and `T2` should all have the same units, typically ms.

# Return
- `A::Matrix`: 3×3 matrix that describes relaxation
- `B::Vector`: 3-vector that describes recovery

# Examples
```jldoctest
julia> (A, B) = relax(100, 1, 1000, 100); A * [1, 0, 0] + B
3-element Array{Float64,1}:
 0.36787944117144233
 0.0
 0.09516258196404048
```
"""
function relax(t::Real, M0::Real, T1::Real, T2::Real)

    E1 = exp(-t/T1)
    E2 = exp(-t/T2)
    A = [E2 0 0; 0 E2 0; 0 0 E1]
    B = [0, 0, M0 * (1 - E1)]
    return (A, B)

end

"""
    rotatex(α)

Simulate left-handed rotation about the x-axis.

# Arguments
- `α::Real`: Rotation angle (rad)

# Return
- `R::Matrix`: 3×3 matrix that describes rotation about the x-axis by angle `α`

# Examples
```jldoctest
julia> R = rotatex(π/2); R * [0, 0, 1]
3-element Array{Float64,1}:
 0.0
 1.0
 6.123233995736766e-17
```
"""
function rotatex(α::Real)

    return [1 0 0; 0 cos(α) sin(α); 0 -sin(α) cos(α)]

end

"""
    rotatey(α)

Simulate left-handed rotation about the y-axis.

# Arguments
- `α::Real`: Rotation angle (rad)

# Return
- `R::Matrix`: 3×3 matrix that describes rotation about the y-axis by angle `α`

# Examples
```jldoctest
julia> R = rotatey(π/2); R * [0, 0, 1]
3-element Array{Float64,1}:
 -1.0
  0.0
  6.123233995736766e-17
```
"""
function rotatey(α::Real)

    return [cos(α) 0 -sin(α); 0 1 0; sin(α) 0 cos(α)]

end

"""
    rotatez(ϕ)

Simulate left-handed rotation about the z-axis.

# Arguments
- `ϕ::Real`: Rotation angle (rad)

# Return
- `R::Matrix`: 3×3 matrix that describes rotation about the z-axis by angle `ϕ`

# Examples
```jldoctest
julia> R = rotatez(π/2); R * [0, 1, 0]
3-element Array{Float64,1}:
 1.0
 6.123233995736766e-17
 0.0
```
"""
function rotatez(ϕ::Real)

    return [cos(ϕ) sin(ϕ) 0; -sin(ϕ) cos(ϕ) 0; 0 0 1]

end

"""
    rotatetheta(θ, α)

Simulate left-handed rotation about an axis in the x-y plane that makes angle
`θ` with the negative y-axis.

# Arguments
- `θ::Real`: Orientation of the axis about which to rotate (rad)
- `α::Real`: Rotation angle (rad)

# Return
- `R::Matrix`: 3×3 matrix that describes rotation by angle `α` about an axis in
    the x-y plane that makes angle `θ` with the negative y-axis

## Note
`rotatetheta(θ, α) == rotatez(θ) * rotatey(-α) * rotatez(-θ)`

# Examples
```jldoctest
julia> R = rotatetheta(π/4, π/2); R * [0, 0, 1]
3-element Array{Float64,1}:
  0.7071067811865476
 -0.7071067811865475
  6.123233995736766e-17
```
"""
function rotatetheta(θ::Real, α::Real)

    return [ sin(θ)^2+cos(α)*cos(θ)^2           sin(θ)*cos(θ)-cos(α)*sin(θ)*cos(θ)  sin(α)*cos(θ);
             sin(θ)*cos(θ)-cos(α)*sin(θ)*cos(θ) cos(θ)^2+cos(α)*sin(θ)^2           -sin(α)*sin(θ);
            -sin(α)*cos(θ)                      sin(α)*sin(θ)                       cos(α)]

end

"""
    freeprecess(t, M0, T1, T2, Δf)

Simulate free-precession, i.e., relaxation and off-resonance precession.

# Arguments
- `t::Real`: Duration of free-precession (ms)
- `M0::Real`: Equilibrium magnetization
- `T1::Real`: Spin-lattice recovery time constant (ms)
- `T2::Real`: Spin-spin recovery time constant (ms)
- `Δf::Real`: Off-resonance frequency (Hz)

# Return
- `A::Matrix`: 3×3 matrix that describes relaxation and precession
- `B::Vector`: 3-vector that describes recovery

# Examples
```jldoctest
julia> (A, B) = freeprecess(100, 1, 1000, 100, 3.75); A * [1, 0, 0] + B
3-element Array{Float64,1}:
 -0.2601300475114444
 -0.2601300475114445
  0.09516258196404048
```
"""
function freeprecess(t::Real, M0::Real, T1::Real, T2::Real, Δf::Real)

    (A, B) = relax(t, M0, T1, T2)
    C = rotatez(2π * Δf * t/1000)
    return (C * A, B)

end


text:
function mark_all(r::Robot)
    count_horizont = moves!(r, West)
    count_verticale = moves!(r, Sud)

    flag =  mod(count_horizpnt + count_verticale, 2)
    put_all_markers(r, flag)

    moves!(r, Sud)
    back(r, Ost, count_horizont)
    back(r, Nord, count_verticale)
  end

  function put_all_markers(r::Robot, flag::Int)
    while true
        while !isborder(r, Ost)
            if  flag== 0
                putmarker!(r)
                flag = 1
            else
                flag = 0
            end
            move!(r, Ost)
        end

        if !check_last_cell(r)
            move!(r, Ost)
            putmarker!(r)
        end

        moves!(r, West)

        if !isborder(r, Nord)
            move!(r, Nord)
        else
            break
        end
    end
  end

  # cheking last cell on existence of marker , returning true or false
  function check__last_cell(r::Robot)
    move!(r, West)
    return ismarker(r)
  end

  function moves!(r::Robot, side::HorizonSide)
    count = 0
    while !isborder(r, side)
        move!(r, side)
        count += 1
    end
    return count
  end

  # back to where i belong to
  function back(r::Robot, side::HorizonSide, steps::Int)
    for i = 1:steps
        move!(r, side)
    end
  end

max_stars_repo_name: NikitaDestroyer/Basics

max_issues_repo_name: NikitaDestroyer/Basics

max_forks_repo_name: NikitaDestroyer/Basics