text:
#
# TCP Client implementation. It works in pair with Server
# module. It also works in asynchronous way (like a server)
# and implements simple RPC-like logic. All you need to do is
# create a client, add listeners to EVENT_AFTER_REQUEST event if needed
# and call request() method as many times as needed. The answer
# will be obtained through onAnswer() callback.
#
# It uses green threads (or coroutines) inside. See this link
# http://julia.readthedocs.org/en/latest/manual/control-flow/#man-tasks
# for more details regarding green threads. Comparing with
# server, it has only one place, where "magic" occures. It's
# request() method. It uses tasks for sending non blocking
# requests and obtaining answers (see @async macro in code).
# Every request creates one tasks
# TODO: describe server-to-client requests logic Nd EVENT_BEFORE_RESPONSE event
# TODO: describe fast mode
#
# @author DeadbraiN
#
# See example below for details:
#
#     #
#     # This callback will be called as many times
#     # as many answers will be obtained from server.
#     #
#     function onAnswer(ans::Connection.Answer)
#       # do something with ans.data
#     end
#     #
#     # Creates the client and connects to server
#     #
#     connection = Client.create(ip"127.0.0.1", 2001)
#     #
#     # Starts to listen EVENT_AFTER_REQUEST event
#     #
#     Event.on(connection.observer, EVENT_AFTER_REQUEST, onAnswer)
#     #
#     # Makes a request to the server. An answer will
#     # be obtained in onAnswer() callback.
#     #
#     Client.request(connection, FUNCTION_ID, arg1, arg2)
#     #
#     # ...
#     #
#     Client.stop(conneciton)
#
# Events:
#     answer{Connection.Answer} Answer object with data
#           obtained from server. May be empty.
#
# @author DeadbraiN
#
module Client
  import Config.@if_debug
  import Event
  import Helper
  using Connection

  export create
  export request
  export stop
  export isOk

  export ClientConnection
  #
  # Describes one connected client. Contains socket and observer.
  #
  type ClientConnection
    sock    ::Base.TCPSocket
    observer::Event.Observer
  end
  #
  # Creates client and it's possibility to send requests to server.
  # In case of connection errors connection object will be created
  # in any case. You have to check this calling isopen() function.
  # Using zero port you may create "empty" connection. In fact,
  # client will not be created/started.
  # @param host Host we are connecting to
  # @param port Port number we are connecting to
  # @param fast Turns on serialization mode (slow speed mode).
  # @return Client connection object
  #
  function create(host::Base.IPAddr, port::Int, fast::Bool = false)
    local sock::Base.TCPSocket = Base.TCPSocket()
    local obs::Event.Observer = Event.create()

    if port > 0
      try
        sock = Base.connect(host, port)
        #
        # All "magic" occures here. This is how we start answers
        # handling. It listens clients responses all the time
        # using green thread (Task).
        #
        @async while (fast ? fastAnswer(sock, obs, _onAnswerException) : answer(sock, obs, _onAnswerException)) end
      catch e
        Helper.warn("Client.create(): $e")
        @if_debug showerror(STDOUT, e, catch_backtrace())
        if Helper.isopen(sock) close(sock) end
      end
      yield()
    end

    Client.ClientConnection(sock, obs)
  end
  #
  # Makes request to server. This method is not blocking. It returns
  # just after the call. Answer will be obtained in create() method
  # async loop.
  # @param con Connection object returned by create() method
  # @param fn Callback function id, which will be called if answer
  #           will be obtained from server.
  # @param args Custom fn arguments
  # @return true - request was sent, false wasn't
  #
  function request(con::Client.ClientConnection, fn::Int, args...)
    Connection.request(con.sock, fn, args...)
  end
  #
  # Fast version of request function. It uses native read()/write()
  # function for data transfer. This function is non blocking one.
  # TODO: describe dataIndex and data
  # @param sock Client socket returned by accept() function
  # @param dataIndex Index in api array
  # @param args Data to transfer in request
  #
  function request(con::Client.ClientConnection, dataIndex::UInt8, args...)
    fastRequest(con.sock, dataIndex, args...)
  end
  #
  # Returns Socket state. true means - created and connected.
  # @param con Client connection state
  # @return {Bool}
  #
  function isOk(con::Client.ClientConnection)
    Helper.isopen(con.sock)
  end
  #
  # Closes client's socket. After this call, we have to call create()
  # method again, if we want to send another request...
  # @param con Client's connection object, returned by create()
  #
  function stop(con::Client.ClientConnection)
    try
      close(con.sock)
      Helper.info("Client has stopped")
    catch e
      Helper.warn("Client.stop(): $e")
      @if_debug showerror(STDOUT, e, catch_backtrace())
    finally
      yield()
    end
  end
  #
  # Shows warning message if socket throws an exception
  # TODO: arguments + return
  #
  function _onAnswerException(sock::Base.TCPSocket, e::Exception)
    #
    # This error means that client has disconnected
    #
    if !isa(e, EOFError)
      Helper.warn(string("Server._onAnswerException(): ", e))
    end
    if Helper.isopen(sock) close(sock) end

    false
  end
end

max_stars_repo_name: tmptrash/jevo

max_issues_repo_name: tmptrash/jevo

max_forks_repo_name: tmptrash/jevo


text:
module MSys2
using IniFile
import Base: *, spawn, ProcessChain, StdIOSet, Callback
export *, msys
# package code goes here
const bash_dir = joinpath(Pkg.dir("MSys2"), "deps", "msys64", "usr", "bin")
const prefix = "mingw-w64-x86_64-"
type msys <: Base.AbstractCmd
  cmd :: Cmd
end
function *(::Type{msys}, cmd :: Cmd)
  msys(cmd)
end

function Base.spawn(cmd::msys, stdios::Base.StdIOSet, exitcb::Callback, closecb::Callback; chain::Nullable{ProcessChain}=Nullable{ProcessChain}())
  first_part = `$bash_dir\\bash --login -c`
  c = Cmd(ByteString[first_part.exec; join(cmd.cmd.exec, " ")])
  Base.spawn(c, stdios, exitcb, closecb)
end

function update()
  run(msys`pacman -Sy`)
end
function upgrade()
  run(msys`pacman -Syuu --noconfirm`)
end
function search_call(package :: AbstractString)

  readall(msys`pacman -Ss $(package)`)
end
function search(package :: AbstractString)
  raw = search_call(package)
  lines = split(raw, "\n")
  descs = filter(n -> startswith(n, " "), lines)
  names = filter(n -> !startswith(n, " ") && n != "", lines)
  map!(strip, descs)
  names
end
function exists(package :: AbstractString)
  success(msys`pacman -Si $(package)`)
end
function info(package :: AbstractString)
  raw = readall(msys`pacman -Si $(package)`)
  read(Inifile(), IOBuffer(raw))
end
function install(package :: AbstractString)
  run(msys`pacman -S --noconfirm $package`)
end

include("mingw64_bindeps.jl")

end # module

ext: jl


text:
if abspath(PROGRAM_FILE) == @__FILE__
    a::Vector{String} = append!([PROGRAM_FILE], ARGS)
    cmd::String = a[1]
    if cmd == "dart"
        #= pass =#
    else
        @assert(findfirst("sys_argv", cmd) != Nothing)
    end
    if length(a) > 1
        println(a[2])
    else
        println("OK")
    end
end


text:
function consume(component::Type{<:Component}, text::SubString{String})
    matcher = orgmatcher(component)
    if isnothing(matcher)
        @warn "No matcher is defined for $(component), should it have a matcher or dedicated consumer?" maxlog=1
        nothing
    else
        if matcher isa Regex
            rxmatch = match(matcher, text)
            if !isnothing(rxmatch)
                (ncodeunits(rxmatch.match), component(rxmatch.captures))
            end
        elseif matcher isa Function
            @warn "$(component) is using a Function matcher, this should be changed to a dedicated consumer" maxlog=1
            matchresult = matcher(text)
            if isnothing(matchresult) || matchresult isa Tuple{Int64, Component}
                matchresult
            else
                @warn "Matcher for $(component) returned an unworkable result type: $(typeof(matchresult))"
                nothing
            end
        end
    end
end

# Some utility functions

"""
    startofline(::Union{String, SubString})::Bool
Return whether the (Sub)String starts with a line,
i.e. is not part-way through a line."""
startofline(::String) = true
function startofline(s::SubString)
    s.offset == 0 && return true
    prevind(s.string, s.offset+1) == s.offset || return false
    i = s.offset
    while i > 0 && s.string[i] in (' ', '\t')
        i -= 1
    end
    s.string[i] == '\n'
end

function ensurelowercase(s::SubString{String})
    if any(c -> c in 'A':'Z', s)
        lowercase(s)
    else
        s
    end
end

# Consume a category of elements

function consume(::Type{Element}, text::SubString{String})
    el = parseorg(text, org_element_matchers, org_element_fallbacks;
                  partial=true, maxobj=1)
    if !isnothing(el)
        (el[1], el[2][1])
    end
end

function consume(::Type{Object}, text::SubString{String})
    obj = parseorg(text, org_object_matchers, org_object_fallbacks;
                   partial=true, maxobj=1)
    if !isnothing(obj)
        (obj[1], obj[2][1])
    end
end

# Some more complicated elements can not simply be matched, and so need
# specific consumers.

# ---------------------
# Elements
# ---------------------

# Greater Elements

function consume(::Type{AffiliatedKeyword}, text::SubString{String})
    function finalise(key, optval, val)
        key = ensurelowercase(key)
        if haskey(org_keyword_translations, key)
            key = org_keyword_translations[key]
        end
        if key in org_parsed_keywords
            !isnothing(optval) && (optval = parseobjects(Keyword, optval))
            !isnothing(val) && (val = parseobjects(Keyword, val))
        end
        key, optval, val
    end
    keymatch = match(r"^[ \t]*#\+([^\s\[\]]+)([:\[])", text)
    if !isnothing(keymatch)
        key::SubString{String}, kendchar::SubString{String} = keymatch.captures
        if kendchar[1] == '[' && ensurelowercase(key) in org_dual_keywords #+key[optval]: val
            optvalend = forwardsbalenced(text, ncodeunits(keymatch.match),
                                         bracketpairs=Dict('[' => ']'))
            if !isnothing(optvalend)
                optval = @inbounds @view text[1+ncodeunits(keymatch.match):prevind(text, optvalend)]
                valmatch = match(r"^:(?:[ \t]+([^\n]*))?\n", @inbounds @view text[1+optvalend:end])
                if !occursin('\n', optval) && !isnothing(valmatch)
                    val = if !isnothing(valmatch.captures[1])
                        valmatch.captures[1]
                    end
                    key, optval, val = finalise(key, optval, val)
                    (optvalend + ncodeunits(valmatch.match),
                     AffiliatedKeyword(key, optval, val))
                end
            end
        else #+key: val
            keyval = match(r"^[ \t]*#\+(\S+?):(?:[ \t]+?([^\n]*))?\n", text)
            if !isnothing(keyval)
                key, val = keyval.captures
                key, _, val = finalise(key, nothing, val)
                (ncodeunits(keyval.match),
                 AffiliatedKeyword(key, nothing, val))
            end
        end
    end
end

function consume(::Type{AffiliatedKeywordsWrapper}, text::SubString{String})
    affiliatedkeywords = AffiliatedKeyword[]
    point = 1
    textend = lastindex(text)
    nextkw = consume(AffiliatedKeyword, @inbounds @view text[point:textend])
    while !isnothing(nextkw) &&
        (nextkw[2].key in org_affilated_keywords ||
         startswith(nextkw[2].key, "attr_"))
        nextkw::Tuple{Int64, AffiliatedKeyword}
        if occursin(r"^[ \t\r]*\n", @inbounds @view text[point+nextkw[1]:textend])
            return nothing
        end
        push!(affiliatedkeywords, nextkw[2])
        point += nextkw[1]
        nextkw = consume(AffiliatedKeyword, @inbounds @view text[point:textend])
    end
    if length(affiliatedkeywords) > 0
        element = parseorg((@inbounds @view text[point:textend]),
                           org_element_matchers, org_element_fallbacks[1:end-1],
                           partial = true, maxobj = 1)
        if !isnothing(element) && any(isa.(Ref(element[2][1]), org_affiliable_elements))
            (point - 1 + element[1],
                AffiliatedKeywordsWrapper(element[2][1], affiliatedkeywords))
        end
    end
end

const org_footnote_element_matchers =
    filter(p -> !isempty(p.second),
           Dict{Char, Vector{<:Type}}(key => filter(v -> v != FootnoteDefinition, value)
                                      for (key, value) in org_element_matchers))

function consume(::Type{FootnoteDefinition}, text::SubString{String})
    labelfn = match(r"^\[fn:([A-Za-z0-9\-_]+)\][ \t]*\n?", text)
    if !isnothing(labelfn)
        fnend, contents = parseorg((@inbounds @view text[1+ncodeunits(labelfn.match):end]),
                                   org_footnote_element_matchers, org_element_fallbacks[1:end-1];
                                   partial=true)
        (ncodeunits(labelfn.match) + fnend,
         FootnoteDefinition(labelfn.captures[1]::SubString{String}, contents))
    end
end

function consume(::Type{InlineTask}, text::SubString{String})
    inlinetaskmatch = match(r"^\*{15,} [^\n]*\n(?:(?!\*+ )[^\n]+\n*)+(\*{15,} +END(?:[ \t\r]*\n|$))?", text)
    if !isnothing(inlinetaskmatch)
        endtask::SubString{String} = inlinetaskmatch.captures[1]
        heading = consume(Heading,
                          @inbounds @view text[1:(ncodeunits(inlinetaskmatch.match) -
                              if !isnothing(endtask); ncodeunits(endtask) else 0 end)])
        if !isnothing(heading)
            heading::Tuple{Int64, Heading}
            (ncodeunits(inlinetaskmatch.match),
             InlineTask(heading[2]))
        end
    end
end

const org_item_element_matchers =
    filter(p -> !isempty(p.second),
           Dict{Char, Vector{<:Type}}(key => filter(v -> v !== List, value)
                                      for (key, value) in org_element_matchers))

function consume(::Type{Item}, text::SubString{String})
    function itemconsume(text, indent)
        indentedlines = let lastindentedpos = something(findfirst('\n', text), ncodeunits(text))
            rest = @inbounds @view text[lastindentedpos+1:end]
            while startswith(rest, indent * "  ")
                lastindentedpos += something(findfirst('\n', rest), ncodeunits(rest))
                rest = @inbounds @view text[lastindentedpos+1:end]
            end
            @inbounds @view text[1:prevind(text, lastindentedpos+1)]
        end
        something(consume(Paragraph, indentedlines), # paragraphs must be entirely indented
                  parseorg(text, org_item_element_matchers, [List],
                           partial=true, maxobj=1) |>
                               o -> if !isempty(o[2])
                                   (o[1], o[2][1])
                               else (o[1], nothing) end)
    end
    itemstart = match(r"^([ \t]*)(\+|\-| \*|(?:[A-Za-z]|[0-9]+)[\.\)]) ", text)
    if !isnothing(itemstart)
        indent::SubString{String}, bullet::SubString{String} = itemstart.captures
        if bullet == "*"
            indent *= " "
        end
        itemextras = match(r"^(?:[ \t]+\[\@([A-Za-z]|[0-9]+)\])?(?:[ \t]+\[([ \-X])\])?(?:[ \t]+([^\n]+?)[ \t]::)?[ \t]+",
                           @inbounds @view text[ncodeunits(itemstart.match):end])
        counterset, checkbox, tag = itemextras.captures
        # collect contents
        rest = @inbounds @view text[ncodeunits(itemstart.match) + ncodeunits(itemextras.match):end]
        contentlen, contentobjs = 0, Component[]
        len, obj = itemconsume(rest, indent)
        contentlen += len
        push!(contentobjs, obj)
        rest = @inbounds @view text[contentlen + ncodeunits(itemstart.match) + ncodeunits(itemextras.match):end]
        while startswith(rest, indent * "  ") && !isnothing(obj)
            len, obj = itemconsume(rest, indent)
            contentlen += len
            push!(contentobjs, obj)
            rest = @inbounds @view text[contentlen + ncodeunits(itemstart.match) + ncodeunits(itemextras.match):end]
        end
        trailingspace = match(r"^(?:[ \t\r]*\n)+", rest)
        if !isnothing(trailingspace)
            contentlen += ncodeunits(trailingspace.match)
        end
        (contentlen + ncodeunits(itemstart.match) + ncodeunits(itemextras.match) - 1,
         Item(bullet, counterset, if !isnothing(checkbox) checkbox[1] end,
              if !isnothing(tag) parseobjects(Item, tag) end, contentobjs))
    end
end

function itemtype(item::Item)
        if !isnothing(item.tag)
            DescriptiveList
        elseif item.bullet in ("+", "-", "*")
            UnorderedList
        else
            OrderedList
        end
end

function consume(::Type{List}, text::SubString{String})
    itemstart = match(r"^([ \t]*)(\+|\-| \*|(?:[A-Za-z]|[0-9]+)[\.\)]) ", text)
    if !isnothing(itemstart)
        nextitem = consume(Item, text)
        if !isnothing(nextitem)
            nextitem::Tuple{Int64, Item}
            listindent::SubString{String} = itemstart.captures[1]
            point = 1
            items = Item[]
            listtype = itemtype(nextitem[2])
            while !isnothing(nextitem) && point < ncodeunits(text)
                len, item = nextitem
                (itemtype(item) != listtype) && break
                point += len
                push!(items, item)
                rest = @inbounds @view text[point:end]
                nextitem = if startswith(rest, listindent)
                    consume(Item, rest)
                end
            end
        point-1, listtype(items)
        end
    end
end

# Leser Elements

function consume(::Type{Clock}, text::SubString{String})
    clockmatch = match(r"^[ \t]*clock:[ \t]+(\[[^\n]*?)[ \t\r]*(?:\n(?:[ \t\r]*\n)*|$)"i, text)
    if !isnothing(clockmatch)
        rest::SubString{String} = clockmatch.captures[1]
        timestamp = consume(Timestamp, rest)
        if !isnothing(timestamp)
            tslen::Int64, ts::Timestamp = timestamp
            if ts isa TimestampInactive && tslen == ncodeunits(rest)
                (ncodeunits(clockmatch.match),
                    Clock(ts, nothing))
            elseif ts isa TimestampInactiveRange
                durationmatch = match(r"^[ \t]+=>[ \t]+(\d+):(\d\d)$",
                                      @inbounds @view rest[1+tslen:end])
                if !isnothing(durationmatch)
                    hours::SubString{String}, mins::SubString{String} = durationmatch.captures
                    (ncodeunits(clockmatch.match),
                     Clock(ts, (parse(Int, hours), parse(Int, mins))))
                end
            end
        end
    end
end

function consume(::Type{Planning}, text::SubString{String})
    plan = Dict{String, Union{Nothing, Timestamp}}(
        "DEADLINE" => nothing,
        "SCHEDULED" => nothing,
        "CLOSED" => nothing)
    point = 1
    clen = lastindex(text)
    while point <= clen+1
        kwdmatch = match(r"^[ \t]*(DEADLINE|SCHEDULED|CLOSED):[ \t]*", view(text, point:clen))
        if !isnothing(kwdmatch)
            point += ncodeunits(kwdmatch.match)
            tsmatch = consume(Timestamp, view(text, point:clen))
            if !isnothing(tsmatch)
                tslen, ts = tsmatch
                plan[kwdmatch.captures[1]] = ts
                point += tslen
            else
                return nothing
            end
        elseif any(.!(isnothing.(values(plan))))
            rest = match(r"^[ \t]*(?:\n|$)", view(text, point:clen))
            return if !isnothing(rest)
                (point + ncodeunits(rest.match),
                 Planning(plan["DEADLINE"], plan["SCHEDULED"], plan["CLOSED"]))
            end
        else
            return nothing
        end
    end
end

function consume(::Type{ParagraphForced}, text::SubString{String})
    line = text[1:something(findfirst('\n', text), end+1)-1]
    location = if text isa SubString
        let char=1+length(text.string[1:text.offset])
            linenum=1+count(==('\n'), text.string[1:text.offset])
            column=length(text.string[1+something(findprev('\n', text.string, text.offset), 0):1+text.offset])
        "\n(line $linenum, column $column, char $char)"
            end
        else
        ""
        end
    @warn "The following line is being coerced to a paragraph:

$line$location

This is unusual, and likely caused by a malformed Org document."
    rest = @inbounds @view text[1+length(line):end]
    trailingspace = match(r"^[ \t\r\n]+", rest)
    blanklength = if !isnothing(trailingspace)
        ncodeunits(trailingspace.match)
    else
        0
    end
    ncodeunits(line)+blanklength, Paragraph(parseobjects(Paragraph, line))
end

# ---------------------
# Objects
# ---------------------

function consume(::Type{Entity}, text::SubString{String})
    # TODO work out how to properly handle \entitity{}
    # maybe this should be handled at the render stage?
    entitymatch = match(r"^\\([A-Za-z]+)(?:{}|[^A-Za-z]|$)", text)
    if !isnothing(entitymatch)
        name::SubString{String} = entitymatch.captures[1]
        if name in keys(Entities)
            1+ncodeunits(name), Entity(name)
        end
    end
end

function consume(::Type{Citation}, text::SubString{String})
    if startswith(text, "[cite") && ncodeunits(text) >= 8
        citeend = forwardsbalenced(text, 1, bracketpairs=Dict('[' => ']'))
        if !isnothing(citeend)
            citeinner = @inbounds @view text[6:citeend-1]
            @assert occursin(':', citeinner)
            styles, body = split(citeinner, ':', limit=2)
            stylematch = match(r"^(?:\/([A-Za-z0-9\-_]+)(?:\/([A-Za-z0-9\-_\/]+))?)?$", styles)
            if !isnothing(stylematch) && !isnothing(match(r"@[\w\-\.:?!`'\/*@+|(){}<>&_^$#^~]", body))
                style, substyle = stylematch.captures
                citerefs = map(split(body, ';')) do keycite
                    keymatch = match(r"^(.+?)?@([\w\-\.:?!`'\/*@+|(){}<>&_^$#^~]+)(.+)?$", keycite)
                    if isnothing(keymatch)
                        keycite
                    else
                        prefixstr, key, suffixstr = keymatch.captures
                        prefix = if isnothing(prefixstr)
                            Object[]
                        else
                            parseobjects(CitationReference, prefixstr)
                        end
                        suffix = if isnothing(suffixstr)
                            Object[]
                        else
                            parseobjects(CitationReference, suffixstr)
                        end
                        CitationReference(prefix, key, suffix)
                    end
                end
                globalprefix = if !isa(citerefs[1], CitationReference)
                    parseobjects(CitationReference, popfirst!(citerefs))
                else
                    Object[]
                end
                globalsuffix = if !isa(citerefs[end], CitationReference)
                    parseobjects(CitationReference, pop!(citerefs))
                else
                    Object[]
                end
                (citeend,
                 Citation((style, substyle), globalprefix, citerefs, globalsuffix))
            end
        end
    end
end

function consume(::Type{FootnoteReference}, text::SubString{String})
    if startswith(text, "[fn:") && ncodeunits(text) >= 6 && text[5] != ']'
        labelfn = match(r"^\[fn:([A-Za-z0-9\-_]+)(\]|:)", text)
        if !isnothing(labelfn) && !startofline(text) && labelfn.captures[2] == "]"
            (ncodeunits(labelfn.match), FootnoteReference(labelfn.captures[1], nothing))
        else
            label = if text[5] == ':'
                Some(nothing)
            elseif labelfn.captures[2] == ":"
                labelfn.captures[1]
            end
            defend = forwardsbalenced(text, 1, bracketpairs=Dict('[' => ']'))
            if !isnothing(label) && !isnothing(defend)
                labellen = if isnothing(something(label)) 0 else ncodeunits(label) end
                definition = parseobjects(FootnoteReference,
                                          @inbounds view(text, 6+labellen:defend-1))
                (defend, FootnoteReference(something(label), definition))
            end
        end
    end
end

function consume(::Type{InlineSourceBlock}, text::SubString{String})
    srcmatch = match(r"^src_(\S+?)(?:\[([^\n]+)\])?{", text)
    if !isnothing(srcmatch)
        codeend = forwardsbalenced(text, ncodeunits(srcmatch.match),
                                   bracketpairs=Dict('{' => '}'),
                                   escapechars=['\\'], quotes=['"'])
        if !isnothing(codeend)
            lang::SubString{String}, options = srcmatch.captures
            code = @inbounds @view text[1+ncodeunits(srcmatch.match):codeend-1]
            codeend, InlineSourceBlock(lang, options, code)
        end
    end
end

function consume(::Type{RegularLink}, text::SubString{String})
    path = match(r"^\[\[((?:[^\]\[\\]+|\\(?:\\\\)*[\[\]]|\\+[^\]\[])+)\]", text)
    if !isnothing(path) && ncodeunits(path.match) < ncodeunits(text)
        linkpath = parse(LinkPath, path.captures[1]::SubString{String})
        matchoffset = 1+ncodeunits(path.match)
        if text[matchoffset] == ']'
            (1 + matchoffset,
             RegularLink(linkpath, nothing))
        else
            descriptionend = forwardsbalenced(text, matchoffset, bracketpairs=Dict('[' => ']'))
            if !isnothing(descriptionend)
                (1 + descriptionend,
                RegularLink(linkpath,
                            parseobjects(RegularLink,
                                         @inbounds @view text[1+matchoffset:prevind(text, descriptionend)])))
            end
        end
    end
end

function consume(::Type{Timestamp}, text::SubString{String})
    rodtypes = Dict("+" => :cumulative,
                    "++" => :catchup,
                    ".+" => :restart,
                    "-" => :warningall,
                    "--" => :warningfirst)
    function parsenum(s::SubString{String})
        n = tryparse(Int, s)
        if !isnothing(n); n else parse(Float64, n) end
    end
    function DateTimeRD(type, date, time, mark, value, unit, warnmark, warnvalue, warnunit)
        type(Date(date),
             if isnothing(time) nothing else Time(time) end,
             if isnothing(mark) nothing else
                 TimestampRepeaterOrDelay(rodtypes[mark], parsenum(value), unit[1]) end,
             if isnothing(warnmark) nothing else
                 TimestampRepeaterOrDelay(rodtypes[warnmark], parsenum(warnvalue), warnunit[1]) end)
    end
    fullts = r"^(?:(<)|\[)(\d{4}-\d\d-\d\d)(?: +[A-Za-z]+)?(?: +(\d?\d:\d\d)(?:-(\d?\d:\d\d))?)?(?: +((?:\+|\+\+|\.\+))(\d[\d.]*)([hdwmy]))?(?: +(-|--)(\d[\d.]*)([hdwmy]))? *(?(1)>|\])"
    tsmatch = match(fullts, text)
    if !isnothing(tsmatch)
        active, date::SubString{String}, timea, timeb, mark, value, unit, warnmark, warnvalue, warnunit = tsmatch.captures
        range, type = if isnothing(active)
            (TimestampInactiveRange, TimestampInactive)
        else
            (TimestampActiveRange, TimestampActive)
        end
        tsmatch2 = if isnothing(timeb) && startswith(text[1+length(tsmatch.match):end], "--")
            match(fullts, text[3+length(tsmatch.match):end])
        end
        if isnothing(tsmatch2) ||
            !isnothing(tsmatch2.captures[4]) || # time b must not be set
            active !== tsmatch2.captures[1] # active/inactive must match
            if isnothing(timeb)
                (ncodeunits(tsmatch.match),
                 DateTimeRD(type, date, timea, mark, value, unit, warnmark, warnvalue, warnunit))
            else
                (ncodeunits(tsmatch.match),
                 range(DateTimeRD(type, date, timea, mark, value, unit, warnmark, warnvalue, warnunit),
                       DateTimeRD(type, date, timeb, mark, value, unit, warnmark, warnvalue, warnunit)))
            end
        else
            _, date2::SubString{String}, time2a, _, mark2, value2, unit2, warnmark2, warnvalue2, warnunit2 = tsmatch2.captures
            (tsmatch.match.ncodeunits + 1 + tsmatch2.match.ncodeunits,
             range(DateTimeRD(type, date, timea, mark, value, unit, warnmark, warnvalue, warnunit),
                   DateTimeRD(type, date2, time2a, mark2, value2, unit2, warnmark2, warnvalue2, warnunit2)))
        end
    elseif startswith(text, "<%%(")
        tsdiaryend = forwardsbalenced(text, 4; bracketpairs=Dict('(' => ')'),
                                      escapechars=['\\'], quotes=['"'])
        if !isnothing(tsdiaryend) && ncodeunits(text) > tsdiaryend &&
            text[tsdiaryend+1] == '>'
            (tsdiaryend, TimestampDiary(text[4:tsdiaryend]))
        end
    end
end

function consume(T::Type{<:Timestamp}, text::SubString{String})
    ts = consume(Timestamp, text)
    if !isnothing(ts)
        @parseassert(T, ts isa T, "\"$text\" is a $(typeof(ts))")
        ts
    end
end

function consume(::Type{TextMarkup}, text::SubString{String})
    if text[1] in ('*', '/', '_', '=', '~', '+') &&
        if text isa SubString
            text.offset == 0 ||
            text.string[prevind(text.string, 1+text.offset)] in
            (' ', '\t', '\n', '-', '(', '{', ''', '"') # pre condition
        else
            true
        end
        markupmatch = match(r"^([*\/_=~+])(\S[^\n]*?(?:\n[^\n]+?(?:\n[^\n]+?)?)?(?<=\S))\1([ \t\n\-.,;:!?'\")\[}]|$)", text)
        if !isnothing(markupmatch)
            char::SubString{String}, content::SubString{String}, _ = markupmatch.captures
            formatting = org_markup_formatting[char[1]]
            parsedcontent = if formatting in (:verbatim, :code)
                content
            else
                parseobjects(TextMarkup, content)
            end
            (2 + ncodeunits(content),
             TextMarkup(formatting, parsedcontent))
        end
    end
end

function consume(::Type{TextPlain}, content::SubString{String})
    alph(c) = c in 'a':'z' || c in 'A':'Z'
    alphnum(c) = alph(c) || c in '0':'9'
    spc(c) = c in (' ', '\t', '\n')
    regularisewhitespace(s) = replace(s, r"[ \t\n]{2,}|\n" => " ")
    function textobjupto(index)
        substr = @inbounds @view content[1:index]
        if index > 0
        (ncodeunits(substr),
         TextPlain(if occursin('\n', substr) || occursin("  ", substr)
                       replace(substr, r"[ \t\n]{2,}|\n" => " ")
                   else
                       substr
                   end))
        end
    end
    clen = lastindex(content)
    if clen == 1
        return (1, TextPlain(content))
    end
    # last index/char, current index/char, next index/char
    # using lc = ' ' should ensure type stability without affecting the result
    li, i, ni = 0, 1, nextind(content, 1)
    lc, c, nc = ' ', content[i], content[ni]
    cc = 1 # char count
    while true
        if alphnum(c) || c in (' ', '\t')
        elseif c == '\n' && lc == '\n' # empty line
            return if i > 1 textobjupto(li) end
        elseif c in ('+', '-', '*') && lc == '\n' && spc(nc) # list items, heading
            return if i > 1 textobjupto(li) end
        elseif c == '|' && lc == '\n'
            return if i > 1 textobjupto(li) end
        elseif c == '^' && (nc in ('{', '+', '-') || alphnum(nc)) # superscripts
            return if i > 2 textobjupto(prevind(content, li)) end
        elseif c == '_' && !spc(lc) && !spc(nc)
            if 5 < cc && content[prevind(content, li, 3)] == 'c' # inline babel call
                return if cc > 5 textobjupto(prevind(content, li, 4)) end
            elseif 4 < cc && content[prevind(content, li, 2)] == 's' # inline src block
                return if cc > 4 textobjupto(prevind(content, li, 3)) end
            else # subscript
                return if cc > 2 textobjupto(prevind(content, li)) end
            end
        elseif c == ':' && lc ∉ (' ', '\t') # plain link
            return if i > 1 textobjupto(something(findprev(c -> !(alphnum(c) || c in ('_', '-', '/', '+', '\'', '"')),
                                                           content, li), li)) end
        elseif c == '[' && (nc == '[' || nc == 'f' || nc == 'c' || nc in '0':'9') # regular link, citations, footnotes & inactive timestamps & statistics cookies
            return if i > 1 textobjupto(li) end
        elseif c == '{' && nc == '{' && i+1 < clen && content[nextind(content, ni)] == '{' # macro
            return if i > 1 textobjupto(li) end
        elseif c == '@' && nc == '@' # export snippet
            return if i > 1 textobjupto(li) end
        elseif c in ('*', '/', '+', '_', '~', '=') && (spc(lc) || lc in ('-', '(', '{', '\'', '"')) && !spc(nc) # markup
            return if cc > 2 textobjupto(li) end
        elseif c == '\\' && !spc(nc) # entities & latex & line break
            return if i > 1 textobjupto(li) end
        elseif c == '<' # angle links, targets, active timestamps
            return if i > 1 textobjupto(li) end
        end
        li, i, ni = i, ni, nextind(content, ni)
        if i < clen
            lc, c, nc = content[li], content[i], content[ni]
            cc += 1
        else
            return textobjupto(clen)
        end
    end
end

forcematchwarn = false
function setforcematchwarn(b::Bool)
    global forcematchwarn = b
end

function consume(::Type{TextPlainForced}, s::SubString{String})
    c = SubString(s, 1, 1)
    if forcematchwarn
        printstyled(stderr, "Warning:", bold=true, color=:yellow)
        print(stderr, " Force matching ")
        printstyled(stderr, '\'', if c == '\n' "\\n" else c end, '\'', color=:cyan)
        print(stderr, " from ")
        b = IOBuffer()
        show(b, s[1:min(50,end)])
        printstyled(stderr, String(take!(b)), if length(s) > 50 "…" else "" end, color=:green)
        print(stderr, "\n         This usually indicates a case where the plain text matcher can be improved.\n")
    end
    if c == "\n"
        (1, TextPlain(" "))
    else
        (ncodeunits(c), TextPlain(c))
    end
end


text:
using Test
using PolynomialBasis
using ImplicitDomainQuadrature
using HDGElasticity

HDGE = HDGElasticity

function allequal(v1,v2)
    return all(v1 .== v2)
end

function allapprox(v1,v2)
    return all(v1 .≈ v2)
end

function allapprox(v1,v2,tol)
    @assert length(v1) == length(v2)
    return all([isapprox(v1[i],v2[i],atol=tol) for i = 1:length(v1)])
end

m = [1.0 2.0
     3.0 4.0]
v = [5.0,6.0,7.0]
result = [5.0  10.0 6.0  12.0  7.0  14.0
          15.0 20.0 18.0 24.0  21.0 28.0]
@test allequal(HDGE.make_row_matrix(v,m),result)

result = [5.0 0.0 6.0 0.0 7.0 0.0
          0.0 5.0 0.0 6.0 0.0 7.0]
@test allequal(HDGE.interpolation_matrix(v,2),result)
result = [5.0 0.0 0.0 6.0 0.0 0.0 7.0 0.0 0.0
          0.0 5.0 0.0 0.0 6.0 0.0 0.0 7.0 0.0
          0.0 0.0 5.0 0.0 0.0 6.0 0.0 0.0 7.0]
@test allequal(HDGE.interpolation_matrix(v,3),result)

Ek = HDGE.vec_to_symm_mat_converter(2)
@test length(Ek) == 2
E1 = [1.0 0.0 0.0
      0.0 0.0 1.0]'
E2 = [0.0 0.0 1.0
      0.0 1.0 0.0]'
@test allequal(Ek[1],E1)
@test allequal(Ek[2],E2)

Ek = HDGElasticity.vec_to_symm_mat_converter(3)
@test length(Ek) == 3
E1 = zeros(3,6)
E1[1,1] = 1.0
E1[2,4] = 1.0
E1[3,5] = 1.0
E1 = E1'
@test allequal(Ek[1],E1)
E2 = zeros(3,6)
E2[1,4] = 1.0
E2[2,2] = 1.0
E2[3,6] = 1.0
E2 = E2'
@test allequal(Ek[2],E2)
E3 = zeros(3,6)
E3[1,5] = 1.0
E3[2,6] = 1.0
E3[3,3] = 1.0
E3 = E3'
@test allequal(Ek[3],E3)

@test_throws ArgumentError HDGE.vec_to_symm_mat_converter(4)
@test_throws ArgumentError HDGE.vec_to_symm_mat_converter(1)

@test HDGE.symmetric_tensor_dimension(2) == 3
@test HDGE.symmetric_tensor_dimension(3) == 6

@test_throws ArgumentError HDGE.symmetric_tensor_dimension(1)
@test_throws ArgumentError HDGE.symmetric_tensor_dimension(4)

basis = TensorProductBasis(1,1)
quad = tensor_product_quadrature(1,2)
matrix = HDGE.mass_matrix(basis,quad,1.0,1)
testmatrix = [2/3 1/3
              1/3 2/3]
@test allapprox(matrix,testmatrix)

vals = [1. 1.]
rhs = HDGE.linear_form(vals,basis,quad)
@test allapprox(rhs,ones(2))

basis = TensorProductBasis(2,1)
facequad = tensor_product_quadrature(1,2)

imap = InterpolatingPolynomial(2,1,1)
coeffs = [1.  1.
          -1. 1.]
update!(imap,coeffs)
N(x) = [(x[1]+1.)*(x[2]+1.)/4.]
matrix = zeros(1,1)
HDGElasticity.update_mass_matrix!(matrix,N,facequad,imap,[1.,1.],1)
@test allapprox(matrix,[2/3])

func(x) = [1.0]
matrix = zeros(1,1)
quad = tensor_product_quadrature(1,5)
quad_imap = InterpolatingPolynomial(2,1,2)
coeffs = [-1.,0.,0.,1.,1.,0.]
update!(quad_imap,coeffs)
normals = HDGElasticity.curve_normals(quad_imap,quad.points)
cellmap = HDGElasticity.CellMap([-1.,-1.],[1.,1.])
facescale = HDGElasticity.scale_area(cellmap,normals)
HDGElasticity.update_mass_matrix!(matrix,func,quad,quad_imap,
    facescale,1)
testmatrix = [sqrt(5) + 0.5*asinh(2.0)]
@test allapprox(testmatrix,matrix,1e-2)

N(x) = [(x[1]+1.)*(x[2]+1.)/4.]
matrix = zeros(1,1)
linemap = HDGElasticity.LineMap([+1.,-1.],[1.,1.])
HDGElasticity.update_mass_matrix!(matrix,N,facequad,linemap,1.,1)
@test allapprox(matrix,[2/3])

fill!(matrix,0.0)
HDGElasticity.update_mass_matrix!(matrix,N,facequad,linemap,2.,1)
@test allapprox(matrix,[4/3])

matrix = zeros(1,1)
N(x) = [(1.0 - x[1])*(1.0 - x[2])/4.0]
map1 = HDGElasticity.LineMap([-1.,-1.],[1.,-1.])
map2 = HDGElasticity.LineMap([-1.,-1.],[-1.,1.])
facequads = [facequad,facequad]
facemaps = [map1,map2]
HDGElasticity.update_mass_matrix_on_faces!(matrix,N,facequads,facemaps,[1.,1.],1)
@test allapprox(matrix,[4/3])

fill!(matrix,0.0)
HDGElasticity.update_mass_matrix_on_faces!(matrix,N,facequads,facemaps,[1.,2.],1)
@test allapprox(matrix,[2.])

fill!(matrix,0.0)
map1 = HDGElasticity.LineMap([1.,-1.],[1.,1.])
map2 = HDGElasticity.LineMap([-1.,1.],[1.,1.])
facequads = [facequad,facequad]
facemaps = [map1,map2]
HDGElasticity.update_mass_matrix_on_faces!(matrix,N,facequads,facemaps,[1.,1.],1)
@test allapprox(matrix,[0.0])

N(x) = [(1.0-x[1])*(1.0-x[2])/4.0]
quad = tensor_product_quadrature(1,3)
imap = InterpolatingPolynomial(2,1,1)
icoeffs = [0.0  -1.0
          -1.0   0.0]
update!(imap,icoeffs)
matrix = zeros(1,1)
HDGElasticity.update_mass_matrix!(matrix,N,quad,imap,[1.,1.,1.],1)
@test matrix[1] ≈ 4.7/16*sqrt(2.)

facequad = tensor_product_quadrature(1,2)
map1 = HDGElasticity.LineMap([-1.,-1.],[1.,-1.])
map2 = HDGElasticity.LineMap([1.,-1.],[1.,1.])
map3 = HDGElasticity.LineMap([-1.,1.],[1.,1.])
map4 = HDGElasticity.LineMap([-1.,-1.],[-1.,1.])
fq = repeat([facequad],4)
fm = [map1,map2,map3,map4]
scale = ones(4)
matrix = HDGElasticity.mass_matrix_on_boundary(basis,fq,fm,scale,1)
testmatrix = [4/3 1/3 1/3 0.
              1/3 4/3 0. 1/3
              1/3 0. 4/3 1/3
              0.  1/3 1/3 4/3]
@test allapprox(matrix,testmatrix)

quad1d = ImplicitDomainQuadrature.ReferenceQuadratureRule(2)
N(x) = [(1-x[1])*(1-x[2])/4.0]
fq = QuadratureRule(ImplicitDomainQuadrature.transform(quad1d,-1.,0.)...)
facequads = [fq,fq]
map1 = HDGElasticity.LineMap([-1.,-1.],[1.,-1.])
map2 = HDGElasticity.LineMap([-1.,-1.],[-1.,1.])
facemaps = [map1,map2]

matrix = zeros(1,1)
HDGElasticity.update_mass_matrix!(matrix,N,fq,map1,1.0,1)
@test allapprox(matrix,[7/12])

basis = TensorProductBasis(2,1)
fq = QuadratureRule(ImplicitDomainQuadrature.transform(quad1d,-1.,0.)...)
facequads = [fq,fq]
iquad = tensor_product_quadrature(1,3)
map1 = HDGElasticity.LineMap([-1.,-1.],[1.,-1.])
map2 = HDGElasticity.LineMap([-1.,-1.],[-1.,1.])
facemaps = [map1,map2]
imap = InterpolatingPolynomial(2,1,1)
icoeffs = [0.0  -1.0
          -1.0   0.0]
update!(imap,icoeffs)
normals = reshape(1/sqrt(2)*ones(6),2,3)
cellmap = HDGElasticity.CellMap([-1.,-1.],[1.,1.])
iscale = HDGElasticity.scale_area(cellmap,normals)

matrix = zeros(4,4)
matrix = HDGElasticity.mass_matrix_on_boundary(basis,facequads,facemaps,[1.,1.],
    iquad,imap,iscale,1,4)
@test matrix[1] ≈ 14/12 + 4.7/16*sqrt(2)

v = [0.0]
quad = tensor_product_quadrature(2,2)
rhsvals = ones(length(quad))'
N(x) = [0.25*(1-x[1])*(1-x[2])]
cellmap = HDGElasticity.CellMap([0.0,-1.0],[1.0,1.0])
HDGElasticity.linear_form!(v,rhsvals,N,cellmap,quad)
@test allapprox(v,[0.25])


text:
A=[1,2,3]
println(sin.(A))
println(@. sin(A))

max_stars_repo_name: terasakisatoshi/juliaExer

max_issues_repo_name: terasakisatoshi/juliaExer

max_forks_repo_name: terasakisatoshi/juliaExer


text:
function Kprec( pw::PWGrid, psi::Array{ComplexF64,2}, ik::Int )

    Ngwx  = size(psi)[1]
    Ncols = size(psi)[2]

    Ngwk = pw.gkvec.Ngw[ik]
    idx_gkk = pw.gkvec.idx_gk[ik]
    G = pw.gvec.G[:,idx_gkk]

    Kpsi  = zeros( ComplexF64, Ngwk, Ncols )

    for ic = 1:Ncols
        for ig = 1:Ngwk
            Gk = G[:,ig] + pw.gkvec.kpts[:,ik]
            Kpsi[ig,ic] = psi[ig,ic] / ( 1.0 + Gk[1]^2 + Gk[2]^2 + Gk[3]^2 )
        end
    end
    return Kpsi
end


text:
# This file is auto-generated by AWSMetadata.jl

module AWSServices

using AWS
using OrderedCollections: LittleDict

const accessanalyzer = AWS.RestJSONService("access-analyzer", "2019-11-01")
const acm = AWS.JSONService("acm", "2015-12-08", "1.1", "CertificateManager")
const acm_pca = AWS.JSONService("acm-pca", "2017-08-22", "1.1", "ACMPrivateCA")
const alexa_for_business = AWS.JSONService("a4b", "2017-11-09", "1.1", "AlexaForBusiness")
const amp = AWS.RestJSONService("aps", "2020-08-01")
const amplify = AWS.RestJSONService("amplify", "2017-07-25")
const amplifybackend = AWS.RestJSONService("amplifybackend", "2020-08-11")
const api_gateway = AWS.RestJSONService("apigateway", "2015-07-09")
const apigatewaymanagementapi = AWS.RestJSONService("execute-api", "2018-11-29")
const apigatewayv2 = AWS.RestJSONService("apigateway", "2018-11-29")
const app_mesh = AWS.RestJSONService("appmesh", "2019-01-25")
const appconfig = AWS.RestJSONService("appconfig", "2019-10-09")
const appflow = AWS.RestJSONService("appflow", "2020-08-23")
const appintegrations = AWS.RestJSONService("app-integrations", "2020-07-29")
const application_auto_scaling = AWS.JSONService("application-autoscaling", "2016-02-06", "1.1", "AnyScaleFrontendService")
const application_discovery_service = AWS.JSONService("discovery", "2015-11-01", "1.1", "AWSPoseidonService_V2015_11_01")
const application_insights = AWS.JSONService("applicationinsights", "2018-11-25", "1.1", "EC2WindowsBarleyService")
const appstream = AWS.JSONService("appstream2", "2016-12-01", "1.1", "PhotonAdminProxyService")
const appsync = AWS.RestJSONService("appsync", "2017-07-25")
const athena = AWS.JSONService("athena", "2017-05-18", "1.1", "AmazonAthena")
const auditmanager = AWS.RestJSONService("auditmanager", "2017-07-25")
const auto_scaling = AWS.QueryService("autoscaling", "2011-01-01")
const auto_scaling_plans = AWS.JSONService("autoscaling-plans", "2018-01-06", "1.1", "AnyScaleScalingPlannerFrontendService")
const backup = AWS.RestJSONService("backup", "2018-11-15")
const batch = AWS.RestJSONService("batch", "2016-08-10")
const braket = AWS.RestJSONService("braket", "2019-09-01")
const budgets = AWS.JSONService("budgets", "2016-10-20", "1.1", "AWSBudgetServiceGateway")
const chime = AWS.RestJSONService("chime", "2018-05-01")
const cloud9 = AWS.JSONService("cloud9", "2017-09-23", "1.1", "AWSCloud9WorkspaceManagementService")
const clouddirectory = AWS.RestJSONService("clouddirectory", "2017-01-11")
const cloudformation = AWS.QueryService("cloudformation", "2010-05-15")
const cloudfront = AWS.RestXMLService("cloudfront", "2020-05-31")
const cloudhsm = AWS.JSONService("cloudhsm", "2014-05-30", "1.1", "CloudHsmFrontendService")
const cloudhsm_v2 = AWS.JSONService("cloudhsmv2", "2017-04-28", "1.1", "BaldrApiService")
const cloudsearch = AWS.QueryService("cloudsearch", "2013-01-01")
const cloudsearch_domain = AWS.RestJSONService("cloudsearchdomain", "2013-01-01")
const cloudtrail = AWS.JSONService("cloudtrail", "2013-11-01", "1.1", "com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101")
const cloudwatch = AWS.QueryService("monitoring", "2010-08-01")
const cloudwatch_events = AWS.JSONService("events", "2015-10-07", "1.1", "AWSEvents")
const cloudwatch_logs = AWS.JSONService("logs", "2014-03-28", "1.1", "Logs_20140328")
const codeartifact = AWS.RestJSONService("codeartifact", "2018-09-22")
const codebuild = AWS.JSONService("codebuild", "2016-10-06", "1.1", "CodeBuild_20161006")
const codecommit = AWS.JSONService("codecommit", "2015-04-13", "1.1", "CodeCommit_20150413")
const codedeploy = AWS.JSONService("codedeploy", "2014-10-06", "1.1", "CodeDeploy_20141006")
const codeguru_reviewer = AWS.RestJSONService("codeguru-reviewer", "2019-09-19")
const codeguruprofiler = AWS.RestJSONService("codeguru-profiler", "2019-07-18")
const codepipeline = AWS.JSONService("codepipeline", "2015-07-09", "1.1", "CodePipeline_20150709")
const codestar = AWS.JSONService("codestar", "2017-04-19", "1.1", "CodeStar_20170419")
const codestar_connections = AWS.JSONService("codestar-connections", "2019-12-01", "1.0", "com.amazonaws.codestar.connections.CodeStar_connections_20191201")
const codestar_notifications = AWS.RestJSONService("codestar-notifications", "2019-10-15")
const cognito_identity = AWS.JSONService("cognito-identity", "2014-06-30", "1.1", "AWSCognitoIdentityService")
const cognito_identity_provider = AWS.JSONService("cognito-idp", "2016-04-18", "1.1", "AWSCognitoIdentityProviderService")
const cognito_sync = AWS.RestJSONService("cognito-sync", "2014-06-30")
const comprehend = AWS.JSONService("comprehend", "2017-11-27", "1.1", "Comprehend_20171127")
const comprehendmedical = AWS.JSONService("comprehendmedical", "2018-10-30", "1.1", "ComprehendMedical_20181030")
const compute_optimizer = AWS.JSONService("compute-optimizer", "2019-11-01", "1.0", "ComputeOptimizerService")
const config_service = AWS.JSONService("config", "2014-11-12", "1.1", "StarlingDoveService")
const connect = AWS.RestJSONService("connect", "2017-08-08")
const connect_contact_lens = AWS.RestJSONService("contact-lens", "2020-08-21")
const connectparticipant = AWS.RestJSONService("participant.connect", "2018-09-07")
const cost_and_usage_report_service = AWS.JSONService("cur", "2017-01-06", "1.1", "AWSOrigamiServiceGatewayService")
const cost_explorer = AWS.JSONService("ce", "2017-10-25", "1.1", "AWSInsightsIndexService")
const customer_profiles = AWS.RestJSONService("profile", "2020-08-15")
const data_pipeline = AWS.JSONService("datapipeline", "2012-10-29", "1.1", "DataPipeline")
const database_migration_service = AWS.JSONService("dms", "2016-01-01", "1.1", "AmazonDMSv20160101")
const databrew = AWS.RestJSONService("databrew", "2017-07-25")
const dataexchange = AWS.RestJSONService("dataexchange", "2017-07-25")
const datasync = AWS.JSONService("datasync", "2018-11-09", "1.1", "FmrsService")
const dax = AWS.JSONService("dax", "2017-04-19", "1.1", "AmazonDAXV3")
const detective = AWS.RestJSONService("api.detective", "2018-10-26")
const device_farm = AWS.JSONService("devicefarm", "2015-06-23", "1.1", "DeviceFarm_20150623")
const devops_guru = AWS.RestJSONService("devops-guru", "2020-12-01")
const direct_connect = AWS.JSONService("directconnect", "2012-10-25", "1.1", "OvertureService")
const directory_service = AWS.JSONService("ds", "2015-04-16", "1.1", "DirectoryService_20150416")
const dlm = AWS.RestJSONService("dlm", "2018-01-12")
const docdb = AWS.QueryService("rds", "2014-10-31")
const dynamodb = AWS.JSONService("dynamodb", "2012-08-10", "1.0", "DynamoDB_20120810")
const dynamodb_streams = AWS.JSONService("streams.dynamodb", "2012-08-10", "1.0", "DynamoDBStreams_20120810")
const ebs = AWS.RestJSONService("ebs", "2019-11-02")
const ec2 = AWS.QueryService("ec2", "2016-11-15")
const ec2_instance_connect = AWS.JSONService("ec2-instance-connect", "2018-04-02", "1.1", "AWSEC2InstanceConnectService")
const ecr = AWS.JSONService("api.ecr", "2015-09-21", "1.1", "AmazonEC2ContainerRegistry_V20150921")
const ecr_public = AWS.JSONService("api.ecr-public", "2020-10-30", "1.1", "SpencerFrontendService")
const ecs = AWS.JSONService("ecs", "2014-11-13", "1.1", "AmazonEC2ContainerServiceV20141113")
const efs = AWS.RestJSONService("elasticfilesystem", "2015-02-01")
const eks = AWS.RestJSONService("eks", "2017-11-01")
const elastic_beanstalk = AWS.QueryService("elasticbeanstalk", "2010-12-01")
const elastic_inference = AWS.RestJSONService("api.elastic-inference", "2017-07-25")
const elastic_load_balancing = AWS.QueryService("elasticloadbalancing", "2012-06-01")
const elastic_load_balancing_v2 = AWS.QueryService("elasticloadbalancing", "2015-12-01")
const elastic_transcoder = AWS.RestJSONService("elastictranscoder", "2012-09-25")
const elasticache = AWS.QueryService("elasticache", "2015-02-02")
const elasticsearch_service = AWS.RestJSONService("es", "2015-01-01")
const emr = AWS.JSONService("elasticmapreduce", "2009-03-31", "1.1", "ElasticMapReduce")
const emr_containers = AWS.RestJSONService("emr-containers", "2020-10-01")
const eventbridge = AWS.JSONService("events", "2015-10-07", "1.1", "AWSEvents")
const firehose = AWS.JSONService("firehose", "2015-08-04", "1.1", "Firehose_20150804")
const fms = AWS.JSONService("fms", "2018-01-01", "1.1", "AWSFMS_20180101")
const forecast = AWS.JSONService("forecast", "2018-06-26", "1.1", "AmazonForecast")
const forecastquery = AWS.JSONService("forecastquery", "2018-06-26", "1.1", "AmazonForecastRuntime")
const frauddetector = AWS.JSONService("frauddetector", "2019-11-15", "1.1", "AWSHawksNestServiceFacade")
const fsx = AWS.JSONService("fsx", "2018-03-01", "1.1", "AWSSimbaAPIService_v20180301")
const gamelift = AWS.JSONService("gamelift", "2015-10-01", "1.1", "GameLift")
const glacier = AWS.RestJSONService("glacier", "2012-06-01", LittleDict("x-amz-glacier-version" => "2012-06-01"))
const global_accelerator = AWS.JSONService("globalaccelerator", "2018-08-08", "1.1", "GlobalAccelerator_V20180706")
const glue = AWS.JSONService("glue", "2017-03-31", "1.1", "AWSGlue")
const greengrass = AWS.RestJSONService("greengrass", "2017-06-07")
const greengrassv2 = AWS.RestJSONService("greengrass", "2020-11-30")
const groundstation = AWS.RestJSONService("groundstation", "2019-05-23")
const guardduty = AWS.RestJSONService("guardduty", "2017-11-28")
const health = AWS.JSONService("health", "2016-08-04", "1.1", "AWSHealth_20160804")
const healthlake = AWS.JSONService("healthlake", "2017-07-01", "1.0", "HealthLake")
const honeycode = AWS.RestJSONService("honeycode", "2020-03-01")
const iam = AWS.QueryService("iam", "2010-05-08")
const identitystore = AWS.JSONService("identitystore", "2020-06-15", "1.1", "AWSIdentityStore")
const imagebuilder = AWS.RestJSONService("imagebuilder", "2019-12-02")
const importexport = AWS.QueryService("importexport", "2010-06-01")
const inspector = AWS.JSONService("inspector", "2016-02-16", "1.1", "InspectorService")
const iot = AWS.RestJSONService("iot", "2015-05-28")
const iot_1click_devices_service = AWS.RestJSONService("devices.iot1click", "2018-05-14")
const iot_1click_projects = AWS.RestJSONService("projects.iot1click", "2018-05-14")
const iot_data_plane = AWS.RestJSONService("data.iot", "2015-05-28")
const iot_events = AWS.RestJSONService("iotevents", "2018-07-27")
const iot_events_data = AWS.RestJSONService("data.iotevents", "2018-10-23")
const iot_jobs_data_plane = AWS.RestJSONService("data.jobs.iot", "2017-09-29")
const iot_wireless = AWS.RestJSONService("api.iotwireless", "2020-11-22")
const iotanalytics = AWS.RestJSONService("iotanalytics", "2017-11-27")
const iotdeviceadvisor = AWS.RestJSONService("api.iotdeviceadvisor", "2020-09-18")
const iotfleethub = AWS.RestJSONService("api.fleethub.iot", "2020-11-03")
const iotsecuretunneling = AWS.JSONService("api.tunneling.iot", "2018-10-05", "1.1", "IoTSecuredTunneling")
const iotsitewise = AWS.RestJSONService("iotsitewise", "2019-12-02")
const iotthingsgraph = AWS.JSONService("iotthingsgraph", "2018-09-06", "1.1", "IotThingsGraphFrontEndService")
const ivs = AWS.RestJSONService("ivs", "2020-07-14")
const kafka = AWS.RestJSONService("kafka", "2018-11-14")
const kendra = AWS.JSONService("kendra", "2019-02-03", "1.1", "AWSKendraFrontendService")
const kinesis = AWS.JSONService("kinesis", "2013-12-02", "1.1", "Kinesis_20131202")
const kinesis_analytics = AWS.JSONService("kinesisanalytics", "2015-08-14", "1.1", "KinesisAnalytics_20150814")
const kinesis_analytics_v2 = AWS.JSONService("kinesisanalytics", "2018-05-23", "1.1", "KinesisAnalytics_20180523")
const kinesis_video = AWS.RestJSONService("kinesisvideo", "2017-09-30")
const kinesis_video_archived_media = AWS.RestJSONService("kinesisvideo", "2017-09-30")
const kinesis_video_media = AWS.RestJSONService("kinesisvideo", "2017-09-30")
const kinesis_video_signaling = AWS.RestJSONService("kinesisvideo", "2019-12-04")
const kms = AWS.JSONService("kms", "2014-11-01", "1.1", "TrentService")
const lakeformation = AWS.JSONService("lakeformation", "2017-03-31", "1.1", "AWSLakeFormation")
const lambda = AWS.RestJSONService("lambda", "2015-03-31")
const lex_model_building_service = AWS.RestJSONService("models.lex", "2017-04-19")
const lex_models_v2 = AWS.RestJSONService("models-v2-lex", "2020-08-07")
const lex_runtime_service = AWS.RestJSONService("runtime.lex", "2016-11-28")
const lex_runtime_v2 = AWS.RestJSONService("runtime-v2-lex", "2020-08-07")
const license_manager = AWS.JSONService("license-manager", "2018-08-01", "1.1", "AWSLicenseManager")
const lightsail = AWS.JSONService("lightsail", "2016-11-28", "1.1", "Lightsail_20161128")
const location = AWS.RestJSONService("geo", "2020-11-19")
const lookoutvision = AWS.RestJSONService("lookoutvision", "2020-11-20")
const machine_learning = AWS.JSONService("machinelearning", "2014-12-12", "1.1", "AmazonML_20141212")
const macie = AWS.JSONService("macie", "2017-12-19", "1.1", "MacieService")
const macie2 = AWS.RestJSONService("macie2", "2020-01-01")
const managedblockchain = AWS.RestJSONService("managedblockchain", "2018-09-24")
const marketplace_catalog = AWS.RestJSONService("catalog.marketplace", "2018-09-17")
const marketplace_commerce_analytics = AWS.JSONService("marketplacecommerceanalytics", "2015-07-01", "1.1", "MarketplaceCommerceAnalytics20150701")
const marketplace_entitlement_service = AWS.JSONService("entitlement.marketplace", "2017-01-11", "1.1", "AWSMPEntitlementService")
const marketplace_metering = AWS.JSONService("metering.marketplace", "2016-01-14", "1.1", "AWSMPMeteringService")
const mediaconnect = AWS.RestJSONService("mediaconnect", "2018-11-14")
const mediaconvert = AWS.RestJSONService("mediaconvert", "2017-08-29")
const medialive = AWS.RestJSONService("medialive", "2017-10-14")
const mediapackage = AWS.RestJSONService("mediapackage", "2017-10-12")
const mediapackage_vod = AWS.RestJSONService("mediapackage-vod", "2018-11-07")
const mediastore = AWS.JSONService("mediastore", "2017-09-01", "1.1", "MediaStore_20170901")
const mediastore_data = AWS.RestJSONService("data.mediastore", "2017-09-01")
const mediatailor = AWS.RestJSONService("api.mediatailor", "2018-04-23")
const migration_hub = AWS.JSONService("mgh", "2017-05-31", "1.1", "AWSMigrationHub")
const migrationhub_config = AWS.JSONService("migrationhub-config", "2019-06-30", "1.1", "AWSMigrationHubMultiAccountService")
const mobile = AWS.RestJSONService("mobile", "2017-07-01")
const mobile_analytics = AWS.RestJSONService("mobileanalytics", "2014-06-05")
const mq = AWS.RestJSONService("mq", "2017-11-27")
const mturk = AWS.JSONService("mturk-requester", "2017-01-17", "1.1", "MTurkRequesterServiceV20170117")
const mwaa = AWS.RestJSONService("airflow", "2020-07-01")
const neptune = AWS.QueryService("rds", "2014-10-31")
const network_firewall = AWS.JSONService("network-firewall", "2020-11-12", "1.0", "NetworkFirewall_20201112")
const networkmanager = AWS.RestJSONService("networkmanager", "2019-07-05")
const opsworks = AWS.JSONService("opsworks", "2013-02-18", "1.1", "OpsWorks_20130218")
const opsworkscm = AWS.JSONService("opsworks-cm", "2016-11-01", "1.1", "OpsWorksCM_V2016_11_01")
const organizations = AWS.JSONService("organizations", "2016-11-28", "1.1", "AWSOrganizationsV20161128")
const outposts = AWS.RestJSONService("outposts", "2019-12-03")
const personalize = AWS.JSONService("personalize", "2018-05-22", "1.1", "AmazonPersonalize")
const personalize_events = AWS.RestJSONService("personalize-events", "2018-03-22")
const personalize_runtime = AWS.RestJSONService("personalize-runtime", "2018-05-22")
const pi = AWS.JSONService("pi", "2018-02-27", "1.1", "PerformanceInsightsv20180227")
const pinpoint = AWS.RestJSONService("pinpoint", "2016-12-01")
const pinpoint_email = AWS.RestJSONService("email", "2018-07-26")
const pinpoint_sms_voice = AWS.RestJSONService("sms-voice.pinpoint", "2018-09-05")
const polly = AWS.RestJSONService("polly", "2016-06-10")
const pricing = AWS.JSONService("api.pricing", "2017-10-15", "1.1", "AWSPriceListService")
const qldb = AWS.RestJSONService("qldb", "2019-01-02")
const qldb_session = AWS.JSONService("session.qldb", "2019-07-11", "1.0", "QLDBSession")
const quicksight = AWS.RestJSONService("quicksight", "2018-04-01")
const ram = AWS.RestJSONService("ram", "2018-01-04")
const rds = AWS.QueryService("rds", "2014-10-31")
const rds_data = AWS.RestJSONService("rds-data", "2018-08-01")
const redshift = AWS.QueryService("redshift", "2012-12-01")
const redshift_data = AWS.JSONService("redshift-data", "2019-12-20", "1.1", "RedshiftData")
const rekognition = AWS.JSONService("rekognition", "2016-06-27", "1.1", "RekognitionService")
const resource_groups = AWS.RestJSONService("resource-groups", "2017-11-27")
const resource_groups_tagging_api = AWS.JSONService("tagging", "2017-01-26", "1.1", "ResourceGroupsTaggingAPI_20170126")
const robomaker = AWS.RestJSONService("robomaker", "2018-06-29")
const route53resolver = AWS.JSONService("route53resolver", "2018-04-01", "1.1", "Route53Resolver")
const route_53 = AWS.RestXMLService("route53", "2013-04-01")
const route_53_domains = AWS.JSONService("route53domains", "2014-05-15", "1.1", "Route53Domains_v20140515")
const s3 = AWS.RestXMLService("s3", "2006-03-01")
const s3_control = AWS.RestXMLService("s3-control", "2018-08-20")
const s3outposts = AWS.RestJSONService("s3-outposts", "2017-07-25")
const sagemaker = AWS.JSONService("api.sagemaker", "2017-07-24", "1.1", "SageMaker")
const sagemaker_a2i_runtime = AWS.RestJSONService("a2i-runtime.sagemaker", "2019-11-07")
const sagemaker_edge = AWS.RestJSONService("edge.sagemaker", "2020-09-23")
const sagemaker_featurestore_runtime = AWS.RestJSONService("featurestore-runtime.sagemaker", "2020-07-01")
const sagemaker_runtime = AWS.RestJSONService("runtime.sagemaker", "2017-05-13")
const savingsplans = AWS.RestJSONService("savingsplans", "2019-06-28")
const schemas = AWS.RestJSONService("schemas", "2019-12-02")
const secrets_manager = AWS.JSONService("secretsmanager", "2017-10-17", "1.1", "secretsmanager")
const securityhub = AWS.RestJSONService("securityhub", "2018-10-26")
const serverlessapplicationrepository = AWS.RestJSONService("serverlessrepo", "2017-09-08")
const service_catalog = AWS.JSONService("servicecatalog", "2015-12-10", "1.1", "AWS242ServiceCatalogService")
const service_catalog_appregistry = AWS.RestJSONService("servicecatalog-appregistry", "2020-06-24")
const service_quotas = AWS.JSONService("servicequotas", "2019-06-24", "1.1", "ServiceQuotasV20190624")
const servicediscovery = AWS.JSONService("servicediscovery", "2017-03-14", "1.1", "Route53AutoNaming_v20170314")
const ses = AWS.QueryService("email", "2010-12-01")
const sesv2 = AWS.RestJSONService("email", "2019-09-27")
const sfn = AWS.JSONService("states", "2016-11-23", "1.0", "AWSStepFunctions")
const shield = AWS.JSONService("shield", "2016-06-02", "1.1", "AWSShield_20160616")
const signer = AWS.RestJSONService("signer", "2017-08-25")
const simpledb = AWS.QueryService("sdb", "2009-04-15")
const sms = AWS.JSONService("sms", "2016-10-24", "1.1", "AWSServerMigrationService_V2016_10_24")
const snowball = AWS.JSONService("snowball", "2016-06-30", "1.1", "AWSIESnowballJobManagementService")
const sns = AWS.QueryService("sns", "2010-03-31")
const sqs = AWS.QueryService("sqs", "2012-11-05")
const ssm = AWS.JSONService("ssm", "2014-11-06", "1.1", "AmazonSSM")
const sso = AWS.RestJSONService("portal.sso", "2019-06-10")
const sso_admin = AWS.JSONService("sso", "2020-07-20", "1.1", "SWBExternalService")
const sso_oidc = AWS.RestJSONService("oidc", "2019-06-10")
const storage_gateway = AWS.JSONService("storagegateway", "2013-06-30", "1.1", "StorageGateway_20130630")
const sts = AWS.QueryService("sts", "2011-06-15")
const support = AWS.JSONService("support", "2013-04-15", "1.1", "AWSSupport_20130415")
const swf = AWS.JSONService("swf", "2012-01-25", "1.0", "SimpleWorkflowService")
const synthetics = AWS.RestJSONService("synthetics", "2017-10-11")
const textract = AWS.JSONService("textract", "2018-06-27", "1.1", "Textract")
const timestream_query = AWS.JSONService("query.timestream", "2018-11-01", "1.0", "Timestream_20181101")
const timestream_write = AWS.JSONService("ingest.timestream", "2018-11-01", "1.0", "Timestream_20181101")
const transcribe = AWS.JSONService("transcribe", "2017-10-26", "1.1", "Transcribe")
const transfer = AWS.JSONService("transfer", "2018-11-05", "1.1", "TransferService")
const translate = AWS.JSONService("translate", "2017-07-01", "1.1", "AWSShineFrontendService_20170701")
const waf = AWS.JSONService("waf", "2015-08-24", "1.1", "AWSWAF_20150824")
const waf_regional = AWS.JSONService("waf-regional", "2016-11-28", "1.1", "AWSWAF_Regional_20161128")
const wafv2 = AWS.JSONService("wafv2", "2019-07-29", "1.1", "AWSWAF_20190729")
const wellarchitected = AWS.RestJSONService("wellarchitected", "2020-03-31")
const workdocs = AWS.RestJSONService("workdocs", "2016-05-01")
const worklink = AWS.RestJSONService("worklink", "2018-09-25")
const workmail = AWS.JSONService("workmail", "2017-10-01", "1.1", "WorkMailService")
const workmailmessageflow = AWS.RestJSONService("workmailmessageflow", "2019-05-01")
const workspaces = AWS.JSONService("workspaces", "2015-04-08", "1.1", "WorkspacesService")
const xray = AWS.RestJSONService("xray", "2016-04-12")

end


text:
using Random: seed!

seed!(123)

function testfunc(n, dt, tsleep)
    p = ProgressMeter.Progress(n, dt)
    for i = 1:n
        sleep(tsleep)
        ProgressMeter.next!(p)
    end
end
println("Testing original interface...")
testfunc(107, 0.01, 0.01)

function testfunc2(n, dt, tsleep, desc, barlen)
    p = ProgressMeter.Progress(n, dt, desc, barlen)
    for i = 1:n
        sleep(tsleep)
        ProgressMeter.next!(p)
    end
end
println("Testing desc and progress bar")
testfunc2(107, 0.01, 0.01, "Computing...", 50)
println("Testing no desc and no progress bar")
testfunc2(107, 0.01, 0.01, "", 0)

function testfunc3(n, tsleep, desc)
    p = ProgressMeter.Progress(n, desc)
    for i = 1:n
        sleep(tsleep)
        ProgressMeter.next!(p)
    end
end
println("Testing tty width...")
testfunc3(107, 0.02, "Computing (use tty width)...")
println("Testing no description...")
testfunc3(107, 0.02, "")

function testfunc4()  # test "days" format
    p = ProgressMeter.Progress(10000000, "Test...")
    for i = 1:105
        sleep(0.02)
        ProgressMeter.next!(p)
    end
end

println("Testing that not even 1% required...")
testfunc4()

function testfunc5(n, dt, tsleep, desc, barlen)
    p = ProgressMeter.Progress(n, dt, desc, barlen)
    for i = 1:round(Int, floor(n/2))
        sleep(tsleep)
        ProgressMeter.next!(p)
    end
    for i = round(Int, ceil(n/2)):n
        sleep(tsleep)
        ProgressMeter.next!(p, :red)
    end
end

println("\nTesting changing the bar color")
testfunc5(107, 0.01, 0.01, "Computing...", 50)

function testfunc6(n, dt, tsleep)
    ProgressMeter.@showprogress dt for i in 1:n
        if i == div(n, 2)
            break
        end
        if rand() < 0.7
            sleep(tsleep)
            continue
        end
    end
end

function testfunc6a(n, dt, tsleep)
    ProgressMeter.@showprogress dt for i in 1:n, j in 1:n
        if i == div(n, 2)
            break
        end
        if rand() < 0.7
            sleep(tsleep)
            continue
        end
    end
end

println("Testing @showprogress macro on for loop")
testfunc6(3000, 0.01, 0.002)
testfunc6a(30, 0.01, 0.002)

function testfunc7(n, dt, tsleep)
    s = ProgressMeter.@showprogress dt "Calculating..." [(sleep(tsleep); z) for z in 1:n]
    @test s == [1:n;]
end

function testfunc7a(n, dt, tsleep)
    s = ProgressMeter.@showprogress dt "Calculating..." [(sleep(tsleep); z) for z in 1:n, y in 1:n]
    @test s == [z for z in 1:n, y in 1:n]
end

println("Testing @showprogress macro on comprehension")
testfunc7(25, 0.1, 0.1)
testfunc7a(5, 0.1, 0.1)

function testfunc8(n, dt, tsleep)
    ProgressMeter.@showprogress dt for i in 1:n
        if rand() < 0.7
            sleep(tsleep)
            continue
        end
        for j in 1:10
            if j % 2 == 0
                continue
            end
        end
        while rand(Bool)
            continue
        end
        while true
            break
        end
    end
end

println("Testing @showprogress macro on a for loop with inner loops containing continue and break statements")
testfunc8(3000, 0.01, 0.002)

function testfunc9(n, dt, tsleep)
    s = ProgressMeter.@showprogress dt "Calculating..." Float64[(sleep(tsleep); z) for z in 1:n]
    @test s == [1:n;]
end

function testfunc9a(n, dt, tsleep)
    s = ProgressMeter.@showprogress dt "Calculating..." Float64[(sleep(tsleep); z) for z in 1:n, y in 1:n]
    @test s == [z for z in 1:n, y in 1:n]
end

println("Testing @showprogress macro on typed comprehension")
testfunc9(100, 0.1, 0.01)
testfunc9a(10, 0.1, 0.01)

function testfunc10(n, k, dt, tsleep)
    p = ProgressMeter.Progress(n, dt)
    for i = 1:k
        sleep(tsleep)
        ProgressMeter.next!(p)
    end
    ProgressMeter.finish!(p)
end
println("Testing under-shooting progress with finish!...")
testfunc10(107, 105, 0.01, 0.01)
println("Testing over-shooting progress with finish!...")
testfunc10(107, 111, 0.01, 0.01)

function testfunc11(n, dt, tsleep)
    p = ProgressMeter.Progress(n, dt)
    for i = 1:n÷2
        sleep(tsleep)
        ProgressMeter.next!(p)
    end
    sleep(tsleep)
    ProgressMeter.update!(p, 0)
    for i = 1:n
        sleep(tsleep)
        ProgressMeter.next!(p)
    end
end
println("Testing update! to 0...")
testfunc11(6, 0.01, 0.3)

function testfunc13()
    ProgressMeter.@showprogress 1 for i=1:10
        return
    end
end

println("Testing @showprogress macro on loop ending with return statement")
testfunc13()

function testfunc13()
    n = 30
    # no keyword arguments
    p = ProgressMeter.Progress(n)
    for i in 1:n
        sleep(0.1)
        ProgressMeter.next!(p)
    end
    # full keyword argumetns
    p = ProgressMeter.Progress(n, dt=0.01, desc="", color=:red, output=stderr, barlen=40)
    for i in 1:n
        sleep(0.1)
        ProgressMeter.next!(p)
    end
end

println("Testing keyword arguments")
testfunc13()

function testfunc14(barglyphs)
    n = 30
    # with the string constructor
    p = ProgressMeter.Progress(n, barglyphs=ProgressMeter.BarGlyphs(barglyphs))
    for i in 1:n
        sleep(0.1)
        ProgressMeter.next!(p)
    end
    # with the 5 char constructor
    chars = (barglyphs...,)
    p = ProgressMeter.Progress(n, barglyphs=ProgressMeter.BarGlyphs(chars...))
    for i in 1:n
        sleep(0.1)
        ProgressMeter.next!(p)
    end
    p = ProgressMeter.Progress(n, dt=0.01, desc="",
                               color=:red, output=stderr, barlen=40,
                               barglyphs=ProgressMeter.BarGlyphs(barglyphs))
    for i in 1:n
        sleep(0.1)
        ProgressMeter.next!(p)
    end
end

println("Testing custom bar glyphs")
testfunc14("[=> ]")
@test_throws ErrorException testfunc14("gklelt")

# Threshold-based progress reports
println("Testing threshold-based progress")
prog = ProgressMeter.ProgressThresh(1e-5, "Minimizing:")
for val in 10 .^ range(2, stop=-6, length=20)
    ProgressMeter.update!(prog, val)
    sleep(0.1)
end

# ProgressUnknown progress reports
println("Testing progress unknown")
prog = ProgressMeter.ProgressUnknown("Reading entry:")
for _ in 1:10
    ProgressMeter.next!(prog)
    sleep(0.1)
end
ProgressMeter.finish!(prog)

prog = ProgressMeter.ProgressUnknown("Reading entry:")
for k in 1:2:20
    ProgressMeter.update!(prog, k)
    sleep(0.1)
end

colors = [:red, :blue, :green]
prog = ProgressMeter.ProgressUnknown("Reading entry:")
for k in 1:2:20
    ProgressMeter.update!(prog, k, rand(colors))
    sleep(0.1)
end
ProgressMeter.finish!(prog)

println("Testing fractional bars")
for front in (['▏','▎','▍','▌','▋','▊', '▉'], ['▁' ,'▂' ,'▃' ,'▄' ,'▅' ,'▆', '▇'], ['░', '▒', '▓',])
    p = ProgressMeter.Progress(100, dt=0.01, barglyphs=ProgressMeter.BarGlyphs('|','█',front,' ','|'), barlen=10)
    for i in 1:100
        ProgressMeter.next!(p)
        sleep(0.02)
    end
end

function testfunc15(n, dt, tsleep)
    result = ProgressMeter.@showprogress dt @distributed (+) for i in 1:n
        if rand() < 0.7
            sleep(tsleep)
        end
        i ^ 2
    end
    @test result == sum(abs2.(1:n))
end

println("Testing @showprogress macro on distributed for loop with reducer")
testfunc15(3000, 0.01, 0.002)

function testfunc16(n, dt, tsleep)
    ProgressMeter.@showprogress dt "Description: " @distributed for i in 1:n
        if rand() < 0.7
            sleep(tsleep)
        end
        i ^ 2
    end
end

println("Testing @showprogress macro on distributed for loop without reducer")
testfunc15(3000, 0.01, 0.002)


text:
using TaskGraphs

using Dates
## set up the environment
using GraphUtils

indicator_grid = IndicatorGrid(zeros(Bool,7,5))                           # initialize a 10x10 environment with no obstacles
indicator_grid[4,4] = true                                                                # obstacle at position 4,4
indicator_grid[1:6,2] .= true
indicator_grid[1:6,4] .= true                                                          # obstacle covering positions 6:7,6:7
env = construct_factory_env_from_indicator_grid(indicator_grid) # initialize the factory environment
@show env.vtx_map                                                                     # visualize the mapping from grid position to vertex indices

## set up the environment
# vtx_grid = initialize_dense_vtx_grid(7,5) # 4 x 4 grid world
#  1   2   3   4	5
#  5   6   7   8
#  9  10  11  12
# 13  14  15  16
# env = construct_factory_env_from_vtx_grid(vtx_grid)
# add_obstacle!(env)
## Define the initial conditions of the robots
robot_ics = [
    ROBOT_AT(1,23), # robot 1 starts at vertex 2
    ROBOT_AT(2,20), # robot 2 starts at vertex 9
]

## Define the manufacturing project
spec = ProjectSpec()
# set initial conditions of "raw materials"
set_initial_condition!(spec,OBJECT_AT(1,23)) # object 1 starts at vertex 4
set_initial_condition!(spec,OBJECT_AT(2,20))  # object 2 starts at vertex

# set_initial_condition!(spec,OBJECT_AT(5,7))
# set_initial_condition!(spec,OBJECT_AT(6,2))
# set_initial_condition!(spec,OBJECT_AT(7,12))

# define the operations that need to take place
# define the operations that need to take place

op1 = Operation(Δt=0)
op2 = Operation(Δt=0)

# inputs
set_precondition!(op1,OBJECT_AT(1,17))
set_precondition!(op2,OBJECT_AT(2,11))

# outputs
set_postcondition!(op1,OBJECT_AT(3,14))
set_postcondition!(op2,OBJECT_AT(4,8))
add_operation!(spec,op1)
add_operation!(spec,op2)

# add a terminal operation with no outputs
op3 = Operation(Δt=0)
op4 = Operation(Δt=0)

# outputs
set_precondition!(op3,OBJECT_AT(3,2))
set_precondition!(op4,OBJECT_AT(4,5))
add_operation!(spec,op3)
add_operation!(spec,op4)

## define solver
# solver = NBSSolver()
solver = NBSSolver(
    assignment_model = TaskGraphsMILPSolver(AssignmentMILP()),
    path_planner = CBSSolver(ISPS())
    )
# finalize problem construction (the solver is passed as an argument here
# because it determines what cost model is used for the problem)
prob = pctapf_problem(solver,spec,env,robot_ics)
# solve the problem
# solution, cost = solve!(solver,prob)
# println(env.vtx_map)
# println(solution)
# println(cost)
# # check if the problem was solved to optimality
# reset_solver!(solver)
start_time = Dates.format(now(), "HH:MM:SS")
println()
cbs = solver.path_planner
isps = cbs.low_level_planner
astar = isps.low_level_planner
# set_verbosity!(cbs, 0)
# set_verbosity!(isps, 0)
# set_verbosity!(astar, 0)

reset_solver!(solver)
set_runtime_limit!(solver, 10000)
set_runtime_limit!(cbs, 10000)
set_iteration_limit!(cbs, 10000000)
set_verbosity!(solver, 0)
# set_verbosity!(cbs, 0)
# set_verbosity!(isps, 0)
# set_verbosity!(astar, 0)

solve!(solver, prob)
println()

println(start_time)
println(Dates.format(now(), "HH:MM:SS"))
@show feasible_status(solver)
@show optimal_status(solver)


text:
using Revise
using Soss

mt = @model x begin
    α = 1.0
    β = 3.0
    σ = 0.5
    yhat = α .+ β .* x
    y ~ For(eachindex(x)) do j
        Mix([Normal(yhat[j], σ), Normal(yhat[j],10σ)], [0.8,0.2])
    end
end;

x = randn(100);
truth = rand(mt(x=x));

# using JLD
# save("strata-truth.jld",
#     "α", truth.α,
#     "β", truth.β,
#     "σ", truth.σ,
#     "x", truth.x,
#     "y", truth.y)

# truth = let
#     d  = load("strata-truth.jld")
#     (α = d["α"], β = d["β"], σ = d["σ"], x = d["x"], y = d["y"])
# end

x = truth.x

using Plots
xx = range(extrema(truth.x)...,length=100)
scatter(truth.x,truth.y, legend=false, c=1)
plot!(xx, truth.α .+ truth.β .* xx, dpi=300,legend=false, lw=3, c=2)
savefig("rawdata.png")

m = @model x begin
    α ~ Cauchy()
    β ~ Normal()
    σ ~ HalfNormal(10)
    yhat = α .+ β .* x
    y ~ For(eachindex(x)) do j
            Normal(yhat[j], σ)
        end
end;

post = dynamicHMC(m(x=truth.x), (y=truth.y,))

ppost = particles(post)

eachplot(xx, ppost.α .+ ppost.β .* xx, lw=3, dpi=300)
scatter!(truth.x,truth.y, legend=false, c=1)
plot!(xx, truth.α .+ truth.β .* xx, legend=false, lw=3, c=2)
savefig("fit1.png")

pred = predictive(m, :α, :β, :σ)

postpred = [rand(pred(θ)((x=x,))) for θ ∈ post] |> particles

pvals = mean.(truth.y .> postpred.y)

# PPC vs x
scatter(truth.x, pvals, legend=false, dpi=300)
xlabel!("x")
ylabel!("Bayesian p-value")
savefig("ppc-x.png")

# PPC vs y
scatter(truth.y, pvals, legend=false, dpi=300)
xlabel!("y")
ylabel!("Bayesian p-value")
savefig("ppc-y.png")

using AverageShiftedHistograms

o = ash(pvals, rng=0:0.01:1, kernel=Kernels.cosine,m=8)
plot(o, legend=false,dpi=300)
xlabel!("Bayesian p-values")
savefig("ppc.png")

##########################################

m2 = @model x begin
    α ~ Cauchy()
    β ~ Normal()
    σ ~ HalfNormal(10)
    νinv ~ HalfNormal()
    ν = 1/νinv
    yhat = α .+ β .* x
    y ~ For(eachindex(x)) do j
            StudentT(1/νinv,yhat[j],σ)
        end
end;

post2 = dynamicHMC(m2(x=truth.x), (y=truth.y,))
ppost2 = particles(post2)

eachplot(xx, ppost2.α .+ ppost2.β .* xx, lw=3, dpi=300)
scatter!(truth.x,truth.y, legend=false, c=1)
plot!(xx, truth.α .+ truth.β .* xx, legend=false, lw=3, c=2)
savefig("fit2.png")

pred2 = predictive(m2, setdiff(stochastic(m2), [:y])...)

post2pred= [rand(pred2(θ)((x=x,))) for θ ∈ post2]  |> particles

pvals2 = mean.(truth.y .> post2pred.y)

# PPC vs x
scatter(truth.x, pvals2, legend=false, dpi=300)
xlabel!("x")
ylabel!("Bayesian p-value")
savefig("ppc2-x.png")

# PPC vs y
scatter(truth.y, pvals2, legend=false, dpi=300)
xlabel!("y")
ylabel!("Bayesian p-value")
savefig("ppc2-y.png")

o = ash(pvals2, rng=0:0.01:1, kernel=Kernels.cosine,m=8)
plot(o, legend=false,dpi=300)
xlabel!("Bayesian p-values")
savefig("ppc2.png")

using Soss

m = @model begin
    μ ~ Normal() |> iid(2)
    σ ~ HalfNormal() |> iid(3)
    x ~ For(1:2,1:3) do i,j
        Normal(μ[i], σ[j])
    end
end;

truth = rand(m())

post = dynamicHMC(m(), (x=truth.x,)) |> particles

pred = predictive(m,:μ,:σ)

predpost = pred(post)

rand(predpost)


text:
using Documenter
using DocumenterLaTeX
using DirectedAcyclicGraphs
using Literate

pages = [
    "Home" => "index.md",
    #"Quick Tutorial" => "generated/usage.md",
    "Installation" => "installation.md",
    "API" => "api.md",
    # "Development" => "development.md"
]

format = Documenter.HTML(
    prettyurls = !("local" in ARGS),
    canonical = "https://juice-jl.github.io/DirectedAcyclicGraphs.jl/stable/",
    assets = ["assets/favicon.ico"],
    analytics = "UA-136089579-2",
    highlights = ["yaml"],
    collapselevel = 1,
)

makedocs(
    sitename = "DirectedAcyclicGraphs.jl",
    pages    = pages,
    format   = format,
    doctest  = true,
    modules  = [DirectedAcyclicGraphs],
    linkcheck_ignore = [
        # We'll ignore links that point to GitHub's edit pages, as they redirect to the
        # login screen and cause a warning:
        r"https://github.com/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)/edit(.*)"
    ],
)

# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
deploydocs(
    target = "build",
    repo = "github.com/Juice-jl/DirectedAcyclicGraphs.jl.git",
    branch = "gh-pages",
    devbranch = "main",
    devurl = "dev",
    versions = ["stable" => "v^", "v#.#"],
)


text:
# -*- coding: utf-8 -*-
# ---
# jupyter:
#   jupytext:
#     formats: ipynb,jl:hydrogen
#     text_representation:
#       extension: .jl
#       format_name: hydrogen
#       format_version: '1.3'
#       jupytext_version: 1.11.2
#   kernelspec:
#     display_name: Julia 1.7.0-beta2
#     language: julia
#     name: julia-1.7
# ---

# %%
VERSION

# %%
valargmax(f, X) = (x = argmax(f, X); (f(x), x))
valindargmax(f, X) = valargmax(f∘last, pairs(X))
valargmin(f, X) = (x = argmin(f, X); (f(x), x))
valindargmin(f, X) = valargmin(f∘last, pairs(X))

# %%
using Plots

# %%
domain = range(0, 2; length=2001)
m, (i, x) = valindargmax(sinpi, domain)
@show m, (i, x)
plot(domain, sinpi; label="sin(πx)")
scatter!([x], [m]; label="maximum")
plot!(; size=(400, 250))

# %%
m, (i, x) = valindargmin(sinpi, range(0, 2; length=2001))
@show m, (i, x)
plot(domain, sinpi; label="sin(πx)")
scatter!([x], [m]; label="minimum")
plot!(; size=(400, 250))

# %%
f(x, y) = (1 - x)^2 + 100(y - x^2)^2

X = Y = range(-5, 5; length=1001)
@show m, (x, y) = valargmin(Base.splat(f), Iterators.product(X, Y))

surface(X, Y, log∘f; color=:rainbow, clim = (-7.5, 10), camera=(30, 60))
scatter!([x], [y], [-7.5]; label="minimum", color=:cyan)
plot!(; xtick = -5:5, ytick = -5:5, zlim=(-7.5, 10))

# %%
heatmap(X, Y, log∘f; color=:rainbow, clim=(-7.5, 10))
scatter!([x], [y]; label="", color=:cyan)
plot!(; xlim=extrema(X), ylim=extrema(Y), size=(500, 400))
plot!(; xtick = -5:5, ytick = -5:5)

# %%

max_stars_repo_path: 0008/valargmax and valindmax.jl

max_stars_repo_name: genkuroki/public

max_issues_repo_path: 0008/valargmax and valindmax.jl

max_issues_repo_name: genkuroki/public

max_forks_repo_path: 0008/valargmax and valindmax.jl

max_forks_repo_name: genkuroki/public


text:
import Base: +, -

abstract AbstractHistogram
"""`Histogram` is a type representing a histogram. It bundles up both the `x` and `y` information as well a running summs of all
seen event and all counted events. Counted events are those inside one of the bins, while seen events are any event at all
even with value outside any bin. `Histogram(r)` creates a new empty histogram with bin edges given by the range `r`.
`counts(h)[i]` is the number of events observed with value between `bin_edges(h)[i]` and `bin_edges(h)[i+1]`."""
type Histogram <: AbstractHistogram
	x::FloatRange{Float64}
	counts::Vector{Int}
	seen::Int # total events seen, including those not in counts
	counted::Int # running sum of counts
end
Histogram(x::Range) = Histogram(convert(FloatRange{Float64},x),zeros(Int, length(x)-1),0,0)
"""Return the bin edges of a Histogram as a FloatRange{Float64}."""
bin_edges(h::Histogram) = h.x
"""Return the bin edges of a Histogram as a FloatRange{Float64}."""
edges(h::Histogram) = h.x
"""Return the bin centers of a Histogram as a FloatRange{Float64}."""
bin_centers(h::Histogram) = midpoints(h.x)
"""Return the bin centers of a Histogram as a FloatRange{Float64}."""
Base.midpoints(h::Histogram) = midpoints(h.x)
"""Return the bin size of a Histogram as a Float64."""
binsize(h::Histogram) = step(h.x)
"""addcounts!(h::Histogram, events::Array)
Add events in the Vector `events` to `h`. If the value of the event is inside one of the bins, `counts` will increase at the corresponding index.
`seen` will increase by `length(events)` and `counted` will increase by the sum of the increase to `counts`. """
function addcounts!(h::Histogram, events::Vector)
	newcounts = hist(events,edges(h))[2]
	h.counts+=newcounts
	h.counted+=sum(newcounts)
	h.seen+=length(events)
end
"""addseen!(h::Histogram,n) Add seen events to `h`. Seen events are events whose value is outside of all bins of `h`."""
addseen!(h::Histogram,n)=h.seen+=n
"""counts(h::Histogram) Retrieve the `counts` from `h`."""
counts(h::Histogram) = h.counts
"""counted(h::Histogram) Return the total number of events whose value is inside a bin of `h`."""
counted(h::Histogram) = h.counted
"""misses(h::Histogram) Return the number of events whose value is outside all bins of `h`."""
misses(h::Histogram) = h.seen-counted(h)
"""seen(h::Histogram) Return the number of events seen, counted plus misses."""
seen(h::Histogram) = h.seen
donethru(h::Histogram) = h.seen
"""update_histogram!(h::Histogram, selection, x)
Add events to `h` whose values are in `events`. Only add events for which `selection` (a bit vector or Vector{Bool}) is true. Add
events for which `selection` is false to to `h.seen`."""
function update_histogram!(h::Histogram, selection, events)
	addcounts!(h,events[selection])
	addseen!(h,length(selection)-sum(selection))
end
function (+)(a::Histogram, b::Histogram)
	@assert edges(a)==edges(b) "adding histograms only supported if the x is the same, a has $(edges(a)), b has $(edges(b))"
	c = Histogram(edges(a), a.counts + b.counts, a.seen + b.seen, a.counted + b.counted)
end
function (-)(a::Histogram, b::Histogram)
	@assert edges(a)==edges(b) "subtracting histograms only supported if the x is the same, a has $(edges(a)), b has $(edges(b))"
	c = Histogram(edges(a), a.counts - b.counts, a.seen - b.seen, a.counted - b.counted)
end

function PyPlot.plot(h::Histogram)
	figure()
	plot(midpoints(h), counts(h))
end

# interface functions to KernelDensity, mainly to allow convoluation of Histogram with probability distributions like Distributions.Normal(μ=0.0, σ=1.0)
uvhist(edges, y) = UnivariateKDE(edges, convert(Array{Float64,1},hist(y,edges)[2]))
density(h::UnivariateKDE) = h.density
edges(h::UnivariateKDE) = h.x
Base.midpoints(h::UnivariateKDE) = midpoints(edges(h))
Base.conv(h::Histogram, y) = conv(UnivariateKDE(edges(h), convert(Vector{Float64},counts(h))), y)