text:
# This file contains various utility functions that don't belong anywhere else

"""
`update_env()`

Updates environment variables PATH and HOMEBREW_CACHE, and modifies DL_LOAD_PATH
to point to our Homebrew installation, allowing us to use things inside of
Homebrew transparently. This causes BinDeps to find the binaries during
Pkg.build() time, writing the absolute path into `deps/deps.jl`.  Because the
paths are written into `deps/deps.jl`, packages do not need to load in the entire
Homebrew package just to find their dependencies.

HOMEBREW_CACHE stores our bottle download cache in a separate place, separating
ourselves from other Homebrew installations so we don't conflict with anyone
"""
function update_env()
    if findfirst(joinpath(brew_prefix, "bin"), ENV["PATH"]) == nothing
        ENV["PATH"] = "$(abspath(joinpath(brew_prefix, "bin"))):$(abspath(joinpath(brew_prefix, "sbin"))):$(ENV["PATH"])"
    end

    if !(joinpath(brew_prefix,"lib") in Libdl.DL_LOAD_PATH)
        push!(Libdl.DL_LOAD_PATH, joinpath(brew_prefix, "lib") )
    end

    # We need to set our own, private, cache directory so that we don't conflict with
    # user-maintained Homebrew installations, and multiple users can use it at once
    ENV["HOMEBREW_CACHE"] = joinpath(ENV["HOME"],"Library/Caches/Homebrew.jl/")

    # We invoke `brew` a lot, let's disable automatic updates since we do those explicitly
    ENV["HOMEBREW_NO_AUTO_UPDATE"] = "1"

    # We opt out of analytics by default
    if !("HOMEBREW_NO_ANALYTICS" in keys(ENV))
        ENV["HOMEBREW_NO_ANALYTICS"] = "1"
    end

    # If we have `git` installed from Homebrew, add its environment variables
    if isfile(joinpath(brew_prefix,"bin","git"))
        git_core = joinpath(brew_prefix,"opt","git","libexec","git-core")
        ENV["PATH"] = ENV["PATH"] * ":" * git_core
        ENV["HOMEBREW_NO_ENV_FILTERING"] = "1"
        ENV["GIT_EXEC_PATH"] = git_core
        ENV["GIT_TEMPLATE_DIR"] = joinpath(brew_prefix,"opt","git","share","git-core")
    end
    return
end

"""
`add_flags(cmd::AbstractString, flags::Dict{String,Bool})`

Given a mapping of flags to Bools, return [cmd, flag1, flag2...] if the
respective Bools are true.  Useful for adding `--verbose` and `--force` flags
onto the end of commands
"""
function add_flags(cmd::Cmd, flags::Dict{Cmd,Bool})
    for flag in keys(flags)
        if flags[flag]
            cmd = `$cmd $flag`
        end
    end
    return cmd
end

"""
`download_and_unpack(url::AbstractString, target_dir::AbstractString)`

Download a tarball from `url` and unpack it into `target_dir`.
"""
function download_and_unpack(url::AbstractString, target_dir::AbstractString; strip=0)
    run(pipeline(`curl -\# -L $url`,
                         `tar xz -m --strip 1 -C $target_dir`))
end

"""
`clt_installed()`

Checks whether the command-line tools are installed, as reported by xcode-select
"""
function clt_installed()
    try
        !isempty(readchomp(pipeline(`/usr/bin/xcode-select -print-path`, stderr=devnull)))
    catch
        return false
    end
end

"""
`git_installed()`

Checks whether `git` is truly installed or not, dealing with stubs in /usr/bin
Also ensure that the version is new enough (e.g. >= 2.0.0.0) that it will work
with `git fetch --unshallow` on Homebrew.
"""
function git_installed()
    gitpath = readchomp(`which git`)

    # If there is no `git` executable at all, fail
    if isempty(gitpath)
        return false
    end

    # If we have a git from the CLT location, but the CLT isn't installed, fail
    if gitpath == "/usr/bin/git" && !clt_installed()
        return false
    end

    # check that the git version is at least 2.0.0.0.  We may end up
    # tightening these bounds a little bit in the future, so parse
    # out the full git version
    m = match(r"^git version ([\d\.]+) ", readchomp(`git --version`))
    if m === nothing
        return false
    end
    gitver = [parse(Int64, x) for x in split(m.captures[1], ".")]

    if gitver[1] < 2
        return false
    end

    # If we made it through the gauntlet, succeed!
    return true
end

"""
`formula_tap(name::AbstractString)`

Given a formula `name`, return the formula name and the tap it is from, replacing
"" for "Homebrew/core", as we don't care about that particular prefix.
"""
function formula_tap(name::AbstractString)
    tap_path = dirname(name)
    if isempty(tap_path) || lowercase(tap_path) == "homebrew/core"
        return basename(name), ""
    end
    return basename(name), tap_path
end


text:
include(joinpath("Occurrence", "logreg_chosenVariables_test.jl"))
include(joinpath("Occurrence", "logreg_research_test.jl"))

ext: jl

max_stars_repo_name: AlexLsn/CSO

max_issues_repo_name: AlexLsn/CSO

max_forks_repo_name: AlexLsn/CSO


text:
import Term: load_code_and_highlight, highlight_syntax, highlight, theme

@testset "\e[34mHIGHLIGHT" begin
    @test highlight("test 1 123 33.4 44,5 +1 -2 12 0.5, ,, ...") ==
          "test \e[38;2;144;202;249m1\e[39m \e[38;2;144;202;249m123\e[39m \e[38;2;144;202;249m33.4\e[39m \e[38;2;144;202;249m44\e[39m,\e[38;2;144;202;249m5\e[39m \e[38;2;239;83;80m+\e[39m\e[38;2;144;202;249m1\e[39m \e[38;2;239;83;80m-\e[39m\e[38;2;144;202;249m2\e[39m \e[38;2;144;202;249m12\e[39m \e[38;2;144;202;249m0.5\e[39m, ,, ..."

    @test highlight("this is ::Int64") == "this is \e[38;2;206;147;216m::Int64\e[39m"

    @test highlight("print", :func) == "\e[38;2;255;238;88mprint\e[39m"

    @test highlight("1 + 2", :code) == "\e[3m\e[38;2;255;238;88m1 + 2\e[23m\e[39m"

    @test highlight("this 1 + `test`") ==
          "this \e[38;2;144;202;249m1\e[39m \e[38;2;239;83;80m+\e[39m \e[3m\e[38;2;255;238;88m`test`\e[23m\e[39m"

    @test highlight(1) == "\e[38;2;144;202;249m1\e[39m"

    @test highlight([1, 2, 3]) == "\e[38;2;144;202;249m[1, 2, 3]\e[39m"

    @test highlight(Int32) == "\e[38;2;206;147;216mInt32\e[39m"

    @test highlight(print) == "\e[38;2;255;238;88mprint\e[39m"

    @test highlight("this :this :(x+y) 'a'") ==
          "this \e[38;2;255;167;38m:this\e[39m \e[38;2;255;202;40m:\e[38;2;255;245;157m(\e[39m\e[38;2;255;202;40mx\e[38;2;239;83;80m+\e[39m\e[38;2;255;202;40my\e[38;2;255;245;157m)\e[39m\e[38;2;255;202;40m\e[39m \e[38;2;100;181;101m'\e[39ma\e[38;2;100;181;101m'\e[39m"

    @test highlight(:x) == "\e[38;2;255;167;38mx\e[39m"

    @test highlight(:(x + y)) == "\e[38;2;255;202;40mx + y\e[39m"

    @test highlight_syntax("""
    This is ::Int64 my style
    print(x + 2)
    """) ==
          "\e[38;2;222;222;222mThis\e[39m\e[38;2;222;222;222m \e[39m\e[38;2;222;222;222mis\e[39m\e[38;2;222;222;222m \e[39m\e[38;2;222;109;89m::\e[39m\e[38;2;222;222;222mInt64\e[39m\e[38;2;222;222;222m \e[39m\e[38;2;222;222;222mmy\e[39m\e[38;2;222;222;222m \e[39m\e[38;2;222;222;222mstyle\e[39m\e[38;2;222;222;222m\n\e[39m\e[38;2;232;212;114mprint\e[39m\e[38;2;227;136;100m(\e[39m\e[38;2;222;222;222mx\e[39m\e[38;2;222;222;222m \e[39m\e[38;2;222;109;89m+\e[39m\e[38;2;222;222;222m \e[39m\e[38;2;144;202;249m2\e[39m\e[38;2;227;136;100m)\e[39m\e[38;2;222;222;222m\n\e[39m"

    @test load_code_and_highlight("02_test_ansi.jl", 7)[1:100] ==
          "{red bold}❯{/red bold} {white}7{/white}     get_color,\n  {grey39}8{/grey39}     NamedColor,\n  {gre"
    # end
end


text:
module Multroot

export multroot

using ..Polynomials
using LinearAlgebra

"""
    multroot(p; verbose=false, kwargs...)

Use `multroot` algorithm of
[Zeng](https://www.ams.org/journals/mcom/2005-74-250/S0025-5718-04-01692-8/S0025-5718-04-01692-8.pdf)
to identify roots of polynomials with suspected multiplicities over
`Float64` values, typically.

Example:

```
julia> using Polynomials

julia> p = fromroots([sqrt(2), sqrt(2), sqrt(2), 1, 1])
Polynomial(-2.8284271247461907 + 11.656854249492383*x - 19.07106781186548*x^2 + 15.485281374238573*x^3 - 6.242640687119286*x^4 + 1.0*x^5)

julia> roots(p)
5-element Array{Complex{Float64},1}:
  0.999999677417768 + 0.0im
 1.0000003225831504 + 0.0im
 1.4141705716005981 + 0.0im
 1.4142350577588885 - 3.72273772278647e-5im
 1.4142350577588885 + 3.72273772278647e-5im

julia> Polynomials.Multroot.multroot(p)
(values = [0.9999999999999993, 1.4142135623730958], multiplicities = [2, 3], κ = 5.218455674370636, ϵ = 2.8736226244218195e-16)
```

The algorithm has two stages. First it uses `pejorative_manifold` to
identify the number of distinct roots and their multiplicities. This
uses the fact if `p=Π(x-zᵢ)ˡⁱ`, `u=gcd(p, p′)`, and `u⋅v=p` then
`v=Π(x-zi)` is square free and contains the roots of `p` and `u` holds
the multiplicity details, which are identified by recursive usage of
`ncgd`, which identifies `u` and `v` above even if numeric
uncertainties are present.

Second it uses `pejorative_root` to improve a set of initial guesses
for the roots under the assumption the multiplicity structure is
correct using a Newton iteration scheme.

The following tolerances, passed through to `pejorative_manifold` by
`kwargs...`, are all used in the first stage, to identify the
multiplicity structure:

* `θ`: the singular value threshold, set to `1e-8`. This is used by
  `Polynomials.ngcd` to assess if a matrix is rank deficient by
  comparing the smallest singular value to `θ ⋅ ||p||₂`.

* `ρ`: the initial residual tolerance, set to `1e-10`. This is passed
  to `Polynomials.ngcd`, the GCD finding algorithm as a relative tolerance.

* `ϕ`: A scale factor, set to `100`. As the `ngcd` algorithm is called
  recursively, this allows the residual tolerance to scale up to match
  increasing numeric errors.

Returns a named tuple with

* `values`: the identified roots
* `multiplicities`: the corresponding multiplicities
* `κ`: the estimated condition number
* `ϵ`: the backward error, `||p̃ - p||_w`.

If the wrong multiplicity structure is identified in step 1, then
typically either `κ` or `ϵ` will be large. The estimated forward
error, `||z̃ - z||₂`, is bounded up to higher order terms by `κ ⋅ ϵ`.
This will be displayed if `verbose=true` is specified.

For polynomials of degree 20 or higher, it is often the case the `l`
is misidentified.

"""
function multroot(p::Polynomials.StandardBasisPolynomial{T}; verbose=false,
                  kwargs...) where {T}

    # degenerate case, constant
    degree(p) == 0 && return (values=T[], multiplicities=Int[], κ=NaN, ϵ=NaN)

    # degenerate case, all zeros
    if (nz = findfirst(!iszero, coeffs(p))) == length(coeffs(p))
        return (values=zeros(T,1), multiplicities=[nz-1], κ=NaN, ϵ=NaN)
    end

    z, l = pejorative_manifold(p; kwargs...)
    z̃ = pejorative_root(p, z, l)
    κ, ϵ = stats(p, z̃, l)

    verbose && show_stats(κ, ϵ)
    (values = z̃, multiplicities = l, κ = κ, ϵ = ϵ)

end

# The multiplicity structure, `l`, gives rise to a pejorative manifold `Πₗ = {Gₗ(z) | z∈ Cᵐ}`.
function pejorative_manifold(p::Polynomials.StandardBasisPolynomial{T};
                        ρ = 1e-10, # initial residual tolerance
                        θ = 1e-8,  # zero singular-value threshold
                        ϕ = 100)  where {T}

    zT = zero(float(real(T)))
    u, v, w, θ′, κ = Polynomials.ngcd(p, derivative(p),
                                       atol=ρ*norm(p), satol = θ*norm(p),
                                       rtol = zT, srtol = zT)
    zs = roots(v)
    nrts = length(zs)
    ls = ones(Int, nrts)

    while !Polynomials.isconstant(u)

        normp = 1 + norm(u, 2)
        ρ′ = max(ρ*normp, ϕ * θ′)  # paper uses just latter
        u, v, w, θ′, κ = Polynomials.ngcd(u, derivative(u),
                                          atol=ρ′, satol = θ*normp,
                                          rtol = zT, srtol = zT,
                                          minⱼ = degree(u) - nrts # truncate search
                                          )

        rts = roots(v)
        nrts = length(rts)

        for z in rts
            tmp, ind = findmin(abs.(zs .- z))
            ls[ind] = ls[ind] + 1
        end

    end

    zs, ls # estimate for roots, multiplicities

end

"""
    pejorative_root(p, zs, ls; kwargs...)

Find a *pejorative* *root* for `p` given multiplicity structure `ls` and initial guess `zs`.

The pejorative manifold for a multplicity structure `l` is denoted `{Gₗ(z) | z ∈ Cᵐ}`. A pejorative
root is a least squares minimizer of `F(z) = W ⋅ [Gₗ(z) - a]`. Here `a ~ (p_{n-1}, p_{n-2}, …, p_1, p_0) / p_n` and `W` are weights given by `min(1, 1/|aᵢ|)`. When `l` is the mathematically correct structure, then `F` will be `0` for a pejorative root. If `l` is not correct, then the backward error `||p̃ - p||_w` is typically large, where `p̃ = Π (x-z̃ᵢ)ˡⁱ`.

This follows Algorithm 1 of [Zeng](https://www.ams.org/journals/mcom/2005-74-250/S0025-5718-04-01692-8/S0025-5718-04-01692-8.pdf)
"""
function pejorative_root(p::Polynomials.StandardBasisPolynomial,
                         zs::Vector{S}, ls::Vector{Int}; kwargs...) where {S}
    ps = (reverse ∘ coeffs)(p)
    pejorative_root(ps, zs, ls; kwargs...)
end

# p is [1, a_{n-1}, a_{n-2}, ..., a_1, a_0]
function pejorative_root(p, zs::Vector{S}, ls::Vector{Int};
                 τ = eps(float(real(S)))^(2/3),
                 maxsteps = 100, # linear or quadratic
                 verbose=false
                 ) where {S}

    ## Solve WJ Δz = W(Gl(z) - a)
    ## using weights min(1/|aᵢ|), i ≠ 1

    m,n = sum(ls), length(zs)

    # storage
    a = p[2:end]./p[1]     # a ~ (p[n-1], p[n-2], ..., p[0])/p[n]
    W = Diagonal([min(1, 1/abs(aᵢ)) for aᵢ in a])
    J = zeros(S, m, n)
    G = zeros(S,  1 + m)
    Δₖ = zeros(S, n)
    zₖs = copy(zs)  # updated

    cvg = false
    δₖ₀ = -Inf
    for ctr in 1:maxsteps

        evalJ!(J, zₖs, ls)
        evalG!(G, zₖs, ls)
        Δₖ .= (W*J) \ (W*(view(G, 2:1+m) .- a)) # weighted least squares

        δₖ₁ = norm(Δₖ, 2)
        Δ = δₖ₀ - δₖ₁

        if ctr > 10 && δₖ₁ >= δₖ₀
            δₖ₀ < δₖ₁ && @warn "Increasing Δ, terminating search"
            cvg = true
            break
        end

        zₖs .-= Δₖ

        if δₖ₁^2 <= (δₖ₀ - δₖ₁) * τ
            cvg = true
            break
        end

        δₖ₀ = δₖ₁
    end
    verbose && show_stats(stats(p, zₖs, ls)...)

    if cvg
        return zₖs
    else
        @info ("""
The multiplicity count may be in error: the initial guess for the roots failed
to converge to a pejorative root.
""")
        return(zₖs)
    end

end

# Helper: compute Π (x-zᵢ)^lᵢ directly
function evalG!(G, zs::Vector{T}, ls::Vector) where {T}

    G .= zero(T)
    G[1] = one(T)

    ctr = 1
    for (z,l) in zip(zs, ls)
        for _ in 1:l
            for j in length(G)-1:-1:1#ctr
                G[1 + j] -= z * G[j]
            end
            ctr += 1
        end
    end

    nothing
end

# For eachcolumn, computes (3.8)
# -lⱼ * (x - xⱼ)^(lⱼ-1) * Π_{k ≠ j} (x - zₖ)^lₖ
function evalJ!(J, zs::Vector{T}, ls::Vector) where {T}

    J .= 0
    n, m = sum(ls), length(zs)

    evalG!(view(J, 1:1+n-m, 1), zs, ls .- 1)
    for (j′, lⱼ) in enumerate(reverse(ls))
        for i in 1+n-m:-1:1
            J[i, m - j′ + 1] = -lⱼ * J[i, 1]
        end
    end

    for  (j, lⱼ) in enumerate(ls)
        for (k, zₖ) in enumerate(zs)
            k == j && continue
            for i in n-1:-1:1
                J[1+i,j] -= zₖ * J[i,j]
            end
        end
    end
    nothing
end

# Defn (3.5) condition number of z with respect to the multiplicity l and weight W
cond_zl(p::AbstractPolynomial, zs::Vector{S}, ls) where {S}  = cond_zl(reverse(coeffs(p)), zs, ls)
function cond_zl(p, zs::Vector{S}, ls) where {S}
    J = zeros(S, sum(ls), length(zs))
    W = diagm(0 => [min(1, 1/abs(aᵢ)) for aᵢ in p[2:end]])
    evalJ!(J, zs, ls)
    F = qr(W*J)
    _, σ, _ = Polynomials.NGCD.smallest_singular_value(F.R)
    1 / σ
end

backward_error(p::AbstractPolynomial, zs::Vector{S}, ls) where {S}  =
    backward_error(reverse(coeffs(p)), zs, ls)
function backward_error(p, z̃s::Vector{S}, ls) where {S}
    # || ã - a ||w
    G = zeros(S,  1 + sum(ls))
    evalG!(G, z̃s, ls)
    a = p[2:end]./p[1]
    W = Diagonal([min(1, 1/abs(aᵢ)) for aᵢ in a])
    u = G[2:end] .- a
    norm(W*u,2)
end

function stats(p, zs, ls)
    cond_zl(p, zs, ls), backward_error(p, zs, ls)
end

function show_stats(κ, ϵ)
    println("")
    println("Condition number κ(z; l) = ", κ)
    println("Backward error ||ã - a||w = ", ϵ)
    println("Estimated forward root error ||z̃ - z||₂ = ", κ * ϵ)
    println("")
end

end


text:
using Test, MLToolkit

@testset "Utility" begin
    @testset "count_leadingzeros" begin
        @test count_leadingzeros([0,0,1,0]) == 2
        @test count_leadingzeros([0,0,0,0]) == 4
        @test count_leadingzeros([1,0,0,0]) == 0
    end
end


text:
@testset "Language Model..." begin
        @time d = ZhuXian()
        lm = KongYiji.LM(d; epochs=100)
        #Knet.save(KongYiji.dir("lm.jld2"), "zx", lm)
        #r = generate!(lm, 1; words=d.postags, len=100)
        #println(r)
end


text:
function deconstruct(ordered_marker_bodies::AbstractVector{<:RigidBody}, q::AbstractVector,
        marker_positions_body::AbstractDict{<:RigidBody, <:AbstractVector{<:Point3D}})
    x = Vector(q)
    for body in ordered_marker_bodies
        positions = marker_positions_body[body]
        for j = 1 : length(positions)
            append!(x, positions[j].v)
        end
    end
    x
end

function reconstruct!(ordered_marker_bodies::AbstractVector{<:RigidBody}, q::AbstractVector,
        marker_positions_body::AbstractDict{<:RigidBody, <:AbstractVector{<:Point3D}}, x...)
    index = 1
    for i = 1 : length(q)
        q[i] = x[index]
        index += 1
    end
    for body in ordered_marker_bodies
        positions = marker_positions_body[body]
        frame = default_frame(body)
        for j = 1 : length(positions)
            positions[j] = Point3D(frame, x[index], x[index + 1], x[index + 2])
            index += 3
        end
    end
end


text:
# Weave readme
using Pkg
cd("c:/git/JDF/readme-build")
Pkg.activate("c:/git/JDF/readme-build")
Pkg.update()
upcheck()

using Weave

weave("../README.jmd", out_path="c:/git/JDF/", doctype="github")

if false
    # debug
    tangle("../README.jmd")
end

using ThreadPools: @bthreads
using DataFrames
using SortingLab: sorttwo!

mutable struct InProgressVector{T}  <: AbstractVector{T}
    v::Vector{T}
    isready::ReentrantLock
    parent::DataFrame
    name::String
end

Base.length(v::InProgressVector) = length(v.v)
Base.size(v::InProgressVector) = size(v.v)
Base.getindex(v::InProgressVector, args...) = begin
    lock(v.isready)
    vv = getindex(v.v, args...)
    unlock(v.isready)
    vv
end

# function barrier for assigining values
function assignreplace!(v::InProgressVector, idx)
    # to be taken
    lock(v.isready)
    v.v .= v.v[idx]
    v.parent[!, v.name] = v.v
    unlock(v.isready)
end

function fsort!(dataframe, by)
    idx = collect(1:nrow(dataframe))
    sorttwo!(dataframe[!, by], idx)

    all_except_by = setdiff(names(dataframe), [by])
    for n in all_except_by
        inprogressv = InProgressVector(dataframe[!, n], ReentrantLock(), dataframe, n)
        dataframe[!, n] = inprogressv
    end

    return dataframe

    @bthreads for n in all_except_by
        assignreplace!(dataframe[!, n], idx)
    end

    dataframe
end

@time df = DataFrame([rand(Int, 1_000_000) for i = 1:30]);
@time df1 = sort!(copy(df), "x1")
@time df2 = fsort!(copy(df), "x1") # takes 1 seconds

df2.x1

df1 == df2

[v1==v2 for (v1, v2) in zip(eachcol(df1), eachcol(df2))]

# faster sort of dataframe
function fsort!(dataframe, by)
    _, idx = sorttwo!(dataframe[!, by], collect(1:nrow(dataframe)))

    all_except_by = setdiff(names(dataframe), [by])
     @bthreads for n in all_except_by
        assignreplace!(dataframe[!, n], idx)
    end
    dataframe
end

# generate a dataframe with 300 columns
@time df = DataFrame([rand(Int, 1_000_000) for i = 1:300])
sort_time = @elapsed sort!(df, "x1") # takes 14 seconds

@time df = DataFrame([rand(Int, 1_000_000) for i = 1:300])
df = fsort2!(df, "x1") # takes 1 seconds

fsort2_time = @elapsed fsort2!(df, "x1") # takes 1 seconds

# sorting
@time df = DataFrame([rand(Int, 1_000_000) for i = 1:300])
fsort_time = @elapsed fsort!(df, "x1") # takes 1 seconds

using Plots
plot(
    ["DataFrames.jl sort", "New Sort", "New Sort with SortingLab.jl"],
    [sort_time, fsort2_time, fsort_time]; title = "Sorting DataFrames", seriestype=:bar)

savefig("perf.png")

function abc()
    cc = []
    for i in 1:3
        c = Channel{Bool}(1)
        push!(cc, c)
        put!(c, true)
        fetch(c) # wait for it
    end

    for i in 1:3
        println(i)
        take!(cc[i])
    end
end

@time abc()

using DataFrames

mutable struct IsReadyVector{T} <: AbstractVector{T}
    v::AbstractVector{T}
    isready::Channel{Bool}
end

Base.size(v::IsReadyVector) = size(v.v)

function def(n)
    df = DataFrame([rand(Int, 1_000_000) for i = 1:n])

    cc = []
    for i in names(df)
        newv = IsReadyVector(df[!, i], Channel{Bool}(1))
        df[!, i] = newv
        put!(newv.isready, true)
        fetch(newv.isready) # wait for it
    end

    for i in names(df)
        println(i)
        take!(df[!, i].isready)
    end
end

@time def(30)


text:
export ShowIterations,
	ShowNewLine,
	ShowTime,
	NoLog,
	CacheFuncVal,
	StoreFuncVal,
	ShowFuncVal,
	StoreLogIterations,
	ShowAlgState,
	StoreAlgState

export initialize!,
	finalize!,
	stagelog!,
	log!

################################################################################
# Loggers
################################################################################
abstract type AbstractLogger end

initialize!(l::AbstractLogger) = nothing
finalize!(l::AbstractLogger) = nothing

log!(l::AbstractLogger) = nothing
log!(l::AbstractLogger, iter) = log!(l::AbstractLogger)
log!(l::AbstractLogger, iter, stage) = log!(l::AbstractLogger, iter)
log!(l::AbstractLogger, alg, iter, stage) = log!(l::AbstractLogger, iter, stage)

# Make it possible to package multiple loggers in a tuple.
Loggers = NTuple{N,AbstractLogger} where N

initialize!(tl::Loggers) = unrolled_foreach(initialize!, tl)
finalize!(tl::Loggers) = unrolled_foreach(finalize!, tl)

log!(tl::Loggers, alg, iter, stage) =
	unrolled_foreach(l -> log!(l, alg, iter, stage), tl)

################################################################################
struct NoLog <: AbstractLogger end

################################################################################
struct ShowIterations <: AbstractLogger end
log!(l::ShowIterations, iter, stage) =
	@printf("Stage: %5d, Iteration: %7d, ", stage, iter)

################################################################################
struct ShowNewLine{S} <: AbstractLogger
	s::S
end
ShowNewLine() = ShowNewLine("")
log!(l::ShowNewLine) = println(l.s)

################################################################################
struct ShowTime{F} <: AbstractLogger
	t0::Base.RefValue{F}
	function ShowTime()
		t0 = time()
		new{typeof(t0)}(Ref(t0))
	end
end
initialize!(l::ShowTime) = l.t0[] = time()
finalize!(l::ShowTime) = @printf("Total time elapsed: %.5g\n", time() - l.t0[])
log!(l::ShowTime) = @printf("Time: %5.f, ", time() - l.t0[])

################################################################################
struct CacheFuncVal{F,T} <: AbstractLogger
	f::F
	val::Base.RefValue{T}
	CacheFuncVal(f::F,T=Float64) where {F} = new{F,T}(f,Ref(zero(T)))
end
log!(l::CacheFuncVal,alg,iter,stage) =
	l.val[] = l.f(primiterates(alg),dualiterates(alg))
(l::CacheFuncVal)(x,y) = l.val[]

################################################################################
struct ShowFuncVal{F,L} <: AbstractLogger
	f::F
	label::L
end
log!(l::ShowFuncVal, alg, iter, stage) =
	@printf("%s: %g, ", l.label, l.f(primiterates(alg), dualiterates(alg)))

################################################################################
struct ShowAlgState{F,L} <: AbstractLogger
	f::F
	label::L
end
log!(l::ShowAlgState, alg, iter, stage) = print(l.label, ": ", l.f(alg), ", ")

################################################################################
struct LogStorage{V}
	vals::V
	idx::Base.RefValue{Int}
	LogStorage(v::V) where {V} = new{V}(v,Ref(1))
end
initialize!(ls::LogStorage) = ls.idx[] = 1
function store!(ls::LogStorage, val)
	i = ls.idx[]
	i > length(ls.vals) && return
	ls.vals[i] = val
	ls.idx[] += 1
end
function finalize!(ls::LogStorage)
	# Zero out unused space
	last = ls.idx[]
	padding = zero(eltype(ls.vals))
	for i = last:length(ls.vals)
		ls.vals[i] = padding
	end
end

################################################################################
struct StoreFuncVal{F,V} <: AbstractLogger
	f::F
	ls::LogStorage{V}
	StoreFuncVal(f::F, fv::V) where {F,V} = new{F,V}(f,LogStorage(fv))
end
initialize!(l::StoreFuncVal) = initialize!(l.ls)
function log!(l::StoreFuncVal, alg, iter, stage)
	val = l.f(primiterates(alg), dualiterates(alg))
	store!(l.ls, val)
end
finalize!(l::StoreFuncVal) = finalize!(l.ls)

################################################################################
struct StoreLogIterations{VI<:AbstractArray{Int}} <: AbstractLogger
	ls::LogStorage{VI}
	StoreLogIterations(iters::VI) where {VI} = new{VI}(LogStorage(iters))
end
initialize!(l::StoreLogIterations) = initialize!(l.ls)
log!(l::StoreLogIterations, alg, iter, stage) = store!(l.ls, iter)
finalize!(l::StoreLogIterations) = finalize!(l.ls)

################################################################################
struct StoreAlgState{F,V} <: AbstractLogger
	f::F
	ls::LogStorage{V}
	StoreAlgState(f::F, fv::V) where {F,V} = new{F,V}(f,LogStorage(fv))
end
initialize!(l::StoreAlgState) = initialize!(l.ls)
function log!(l::StoreAlgState, alg, iter, stage)
	val = l.f(alg)
	store!(l.ls, val)
end
finalize!(l::StoreAlgState) = finalize!(l.ls)


text:
using BenchmarkTools, StatsBase

##### function definitions #####

# for BenchmarkTools.jl results
function summarize(::Val{true}, fname)
  # retrieve the Trial objects for the test suite
  results = BenchmarkTools.load(fname)[1]

  for (b_info, trial) in leaves(results)
    # convert results from ns to ms
    times = [ t * 1e-6 for t in trial.times ]

    b_mean   = mean(times)
    b_std    = std(times)
    b_median = median(times)
    b_q1     = quantile(times, 0.25)
    b_q3     = quantile(times, 0.75)

    # benchmark info string
    str = [ "$(s) " for s in b_info ]

    println("----- $(str...)-----")
    println("trials: $(length(times))")
    println("  mean: $(b_mean) ms")
    println("   std: $(b_std) ms")
    println("median: $(b_median) ms")
    println("    Q1: $(b_q1) ms")
    println("    Q3: $(b_q3) ms")
    println()
  end
end

function summarize(::Val{false}, fname)
  # retrieve data from Python benchmarks
  results = map(x -> parse(Float64, x), readlines(fname))

  # convert results from s to ms
  times = [ t * 1e3 for t in results ]

  b_mean   = mean(times)
  b_std    = std(times)
  b_median = median(times)
  b_q1     = quantile(times, 0.25)
  b_q3     = quantile(times, 0.75)

  println("----- $(fname) ------")
  println("trials: $(length(results))")
  println("  mean: $(b_mean) ms")
  println("   std: $(b_std) ms")
  println("median: $(b_median) ms")
  println("    Q1: $(b_q1) ms")
  println("    Q3: $(b_q3) ms")
  println()
end

##### command-line tool #####

fname = ARGS[1]
ftype = split(fname, ".")[end]

is_json = ftype == "json"

summarize(Val(is_json), fname)


text:
using AbstractGPs
using AbstractGPs: AbstractGP, MeanFunction, FiniteGP, ConstMean, GP, ZeroMean,
    ConstMean, CustomMean, Xt_A_X, Xt_A_Y, Xt_invA_Y, Xt_invA_X, diag_At_A, diag_At_B,
    diag_Xt_A_X, diag_Xt_A_Y, diag_Xt_invA_X, diag_Xt_invA_Y, Xtinv_A_Xinv, tr_At_A,
    mean_and_cov_diag

using Documenter
using ChainRulesCore
using Distributions: MvNormal, PDMat
using FiniteDifferences
using FiniteDifferences: j′vp, to_vec
using LinearAlgebra
using LinearAlgebra: AbstractTriangular
using Plots
using Random
using Statistics
using Test
using Turing
using Zygote

include("test_util.jl")

@testset "AbstractGPs" begin
    @testset "util" begin
        include(joinpath("util", "common_covmat_ops.jl"))
        include(joinpath("util", "plotting.jl"))
    end
    @info "Ran util tests"

    @testset "abstract_gp" begin
        include(joinpath("abstract_gp", "abstract_gp.jl"))
        include(joinpath("abstract_gp", "finite_gp.jl"))
    end
    @info "Ran abstract_gp tests"

    @testset "gp" begin
        include(joinpath("gp", "mean_functions.jl"))
        include(joinpath("gp", "gp.jl"))
    end
    @info "Ran gp tests"

    @testset "posterior_gp" begin
        include(joinpath("posterior_gp", "posterior_gp.jl"))
        include(joinpath("posterior_gp", "approx_posterior_gp.jl"))
    end
    @info "Ran posterior_gp tests"

    include(joinpath("latent_gp", "latent_gp.jl"))
    @info "Ran latent_gp tests"

    include("turing.jl")
    @info "Ran Turing tests"

    @testset "doctests" begin
        DocMeta.setdocmeta!(
            AbstractGPs,
            :DocTestSetup,
            :(using AbstractGPs, Random, Documenter, LinearAlgebra);
            recursive=true,
        )
        doctest(AbstractGPs)
    end
end


text:
module DOT

using GraphIO.ParserCombinator.Parsers
using LightGraphs
using LightGraphs: AbstractGraphFormat

import LightGraphs: loadgraph, loadgraphs, savegraph

export DOTFormat

struct DOTFormat <: AbstractGraphFormat end

function savedot(io::IO, g::LightGraphs.AbstractGraph, gname::String = "")
    isdir = LightGraphs.is_directed(g)
    println(io,(isdir ? "digraph " : "graph ") * gname * " {")
    for i in LightGraphs.vertices(g)
         println(io,"\t" * string(i))
    end
    if isdir
        for u in LightGraphs.vertices(g)
            out_nbrs = LightGraphs.outneighbors(g, u)
            length(out_nbrs) == 0 && continue
            println(io, "\t" * string(u) * " -> {" * join(out_nbrs,',') * "}")
        end
    else
        for e in LightGraphs.edges(g)
            source = string(LightGraphs.src(e))
            dest = string(LightGraphs.dst(e))
            println(io, "\t" * source * " -- " * dest)
        end
    end
    println(io,"}")
    return 1
end

function savedot_mult(io::IO, graphs::Dict)
    ng = 0
    for (gname, g) in graphs
        ng += savedot(io, g, gname)
    end
    return ng
end

function _dot_read_one_graph(pg::Parsers.DOT.Graph)
    isdir = pg.directed
    nvg = length(Parsers.DOT.nodes(pg))
    nodedict = Dict(zip(collect(Parsers.DOT.nodes(pg)), 1:nvg))
    if isdir
        g = LightGraphs.DiGraph(nvg)
    else
        g = LightGraphs.Graph(nvg)
    end
    for es in Parsers.DOT.edges(pg)
        s = nodedict[es[1]]
        d = nodedict[es[2]]
        add_edge!(g, s, d)
    end
    return g
end

function loaddot(io::IO, gname::String)
    p = Parsers.DOT.parse_dot(read(io, String))
    for pg in p
        isdir = pg.directed
        possname = isdir ? Parsers.DOT.StringID("digraph") : Parsers.DOT.StringID("graph")
        name = get(pg.id, possname).id
        name == gname && return _dot_read_one_graph(pg)
    end
    error("Graph $gname not found")
end

function loaddot_mult(io::IO)
    p = Parsers.DOT.parse_dot(read(io, String))

    graphs = Dict{String,AbstractGraph}()

    for pg in p
        isdir = pg.directed
        possname = isdir ? Parsers.DOT.StringID("digraph") : Parsers.DOT.StringID("graph")
        name = get(pg.id, possname).id
        graphs[name] = _dot_read_one_graph(pg)
    end
    return graphs
end

loadgraph(io::IO, gname::String, ::DOTFormat) = loaddot(io, gname)
loadgraphs(io::IO, ::DOTFormat) = loaddot_mult(io)
savegraph(io::IO, g::AbstractGraph, gname::String, ::DOTFormat) = savedot(io, g, gname)
savegraph(io::IO, d::Dict, ::DOTFormat) = savedot_mult(io, d)

end #module


text:
using Mill, JsonGrinder

metadata = fill("metadata", 4)
a = BagNode(ArrayNode(rand(3,4)),[1:4], metadata)
b = BagNode(ArrayNode(rand(3,4)),[1:2,3:4], metadata)
c = BagNode(ArrayNode(rand(3,4)),[1:1,2:2,3:4], metadata)
d = BagNode(ArrayNode(rand(3,4)),[1:4,0:-1], metadata)
wa = WeightedBagNode(ArrayNode(rand(3,4)),[1:4], rand(1:4, 4), metadata)
wb = WeightedBagNode(ArrayNode(rand(3,4)),[1:2,3:4], rand(1:4, 4), metadata)
wc = WeightedBagNode(ArrayNode(rand(3,4)),[1:1,2:2,3:4], rand(1:4, 4), metadata)
wd = WeightedBagNode(ArrayNode(rand(3,4)),[1:4,0:-1], rand(1:4, 4), metadata)
e = ArrayNode(rand(2, 2))

f = ProductNode((wb,b))
g = ProductNode([c, wc])
h = ProductNode((wc,c))
i = ProductNode((
              b,
              ProductNode((
                        b,
                        BagNode(
                                BagNode(
                                        ArrayNode(rand(2,4)),
                                        [1:1, 2:2, 3:3, 4:4]
                                       ),
                                [1:3, 4:4]
                               )
                       ))
             ))
k = ProductNode((a = wb, b = b))
l = ProductNode((a = wc, b = c))

ext1 = ExtractDict(Dict("a" => ExtractScalar(Float64,2,3),"b" => ExtractScalar(Float64), "c" => ExtractArray(ExtractScalar(Float64,2,3))))
ext2 = ExtractDict(Dict("a" => ExtractScalar(Float64,2,3)))

@testset "testing terseprint on - Mill" begin
    PrintTypesTersely.with_state(true) do
        @test repr(typeof([h,i])) == "Array{…}"
        @test repr(typeof(h)) == "ProductNode{…}"
    end
end

@testset "testing terseprint off - Mill" begin
    PrintTypesTersely.with_state(false) do
        @test repr(typeof([h,i])) == (VERSION < v"1.6.0-" ? "Array{ProductNode{T,Nothing} where T,1}" : "Vector{ProductNode{T, Nothing} where T}")
        # because there are metadata in Mill 2.4 but not in 2.3
        if :metadata ∈ fieldnames(LazyNode)
            @test repr(typeof(h)) ==  (VERSION < v"1.6.0-" ?
                "ProductNode{Tuple{WeightedBagNode{ArrayNode{Array{Float64,2},Nothing},AlignedBags{Int64},Int64,Array{String,1}},BagNode{ArrayNode{Array{Float64,2},Nothing},AlignedBags{Int64},Array{String,1}}},Nothing}" :
                "ProductNode{Tuple{WeightedBagNode{ArrayNode{Matrix{Float64}, Nothing}, AlignedBags{Int64}, Int64, Vector{String}}, BagNode{ArrayNode{Matrix{Float64}, Nothing}, AlignedBags{Int64}, Vector{String}}}, Nothing}")
        else
            @test repr(typeof(h)) ==  (VERSION < v"1.6.0-" ?
                "ProductNode{Tuple{WeightedBagNode{ArrayNode{Array{Float64,2},Nothing},AlignedBags,Int64,Array{String,1}},BagNode{ArrayNode{Array{Float64,2},Nothing},AlignedBags,Array{String,1}}},Nothing}" :
                "ProductNode{Tuple{WeightedBagNode{ArrayNode{Matrix{Float64}, Nothing}, AlignedBags{Int64}, Int64, Vector{String}}, BagNode{ArrayNode{Matrix{Float64}, Nothing}, AlignedBags{Int64}, Vector{String}}}, Nothing}")
        end
    end
end

@testset "testing terseprint on - JsonGrinder" begin
    PrintTypesTersely.with_state(true) do
        @test repr(typeof([ext1, ext2])) == "Array{…}"
        @test repr(typeof(ext1)) == "ExtractDict{…}"
    end
end

@testset "testing terseprint off - JsonGrinder" begin
    PrintTypesTersely.with_state(false) do
        @test repr(typeof([ext1, ext2])) == (VERSION < v"1.6.0-" ? "Array{ExtractDict,1}" : "Vector{ExtractDict}")
        @test repr(typeof(ext1)) == (VERSION < v"1.6.0-" ?
            "ExtractDict{Dict{String,JsonGrinder.AbstractExtractor}}" :
            "ExtractDict{Dict{String, JsonGrinder.AbstractExtractor}}")
    end
end

@testset "testing obscure terseprint things" begin
    function experiment(ds::LazyNode{T}) where {T<:Symbol}
        @show ds
        @show T
    end
    a = methods(experiment)
    a_method = a.ms[1]
    b = getfield(a_method.sig, 2)
    c = getfield(b, 3)
    d = c[2]
    e = d.body

    t = UnionAll(TypeVar(:t), LazyNode)
    u = typeof(LazyNode(:oh_hi, ["Mark"]))

    orig_terse = PrintTypesTersely._terseprint[]

    v = UnionAll(TypeVar(:T, AbstractMillModel), BagModel)

    PrintTypesTersely.with_state(true) do
        @test occursin("(ds::LazyNode{…}) where T<:Symbol", repr(methods(experiment)))
        @test repr(t) == "LazyNode{…}"
        @test repr(u) == "LazyNode{…}"
        @test repr(d) == "LazyNode{…}"
        @test repr(e) == "LazyNode{…}"
        @test repr(v) == "BagModel{…}"
    end

    PrintTypesTersely.with_state(false) do
        # because there are metadata in Mill 2.4 but not in 2.3
        if :metadata ∈ fieldnames(LazyNode)
            expected = (VERSION < v"1.6.0-" ? "(ds::LazyNode{T,D,C} where C where D) where T<:Symbol" :
            "(ds::LazyNode{T, D, C} where {D, C}) where T<:Symbol")
            @test occursin(expected, repr(methods(experiment)))
            @test repr(u) == (VERSION < v"1.6.0-" ? "LazyNode{:oh_hi,Array{String,1},Nothing}" : "LazyNode{:oh_hi, Vector{String}, Nothing}")
            @test repr(d) == (VERSION < v"1.6.0-" ? "LazyNode{T<:Symbol,D,C} where C where D" : "LazyNode{T<:Symbol, D, C} where {D, C}")
            @test repr(e) == (VERSION < v"1.6.0-" ? "LazyNode{T<:Symbol,D,C} where C" : "LazyNode{T<:Symbol, D, C} where C")
        else
            expected = (VERSION < v"1.6.0-" ? "(ds::LazyNode{T,D} where D) where T<:Symbol" :
            "(ds::LazyNode{T, D} where D) where T<:Symbol")
            @test occursin("(ds::LazyNode{T,D} where D) where T<:Symbol", repr(methods(experiment)))
            @test repr(u) == (VERSION < v"1.6.0-" ? "LazyNode{:oh_hi,Array{String,1}}" : "LazyNode{:oh_hi, Vector{String}}")
            @test repr(d) == "LazyNode{T<:Symbol,D} where D"
            @test repr(e) == (VERSION < v"1.6.0-" ? "LazyNode{T<:Symbol,D}" : "LazyNode{T<:Symbol, D}")
        end
        @test repr(t) == "LazyNode"
        @test repr(v) == "BagModel"
    end
end


text:
include("runtests_preamble.jl")
include("run_script.jl")

@testset "Examples" begin
    #####
    ##### Free convection example
    #####

    free_convection_filepath = joinpath(@__DIR__, "..", "examples", "free_convection.jl")

    replace_strings = [
        ("size=(32, 32, 32)", "size=(1, 1, 1)"),
        ("TimeInterval(4hour)", "TimeInterval(2minute)"),
        ("AveragedTimeInterval(1hour, window=15minute)", "AveragedTimeInterval(2minute, window=1minute)"),
        ("IterationInterval(100)", "IterationInterval(1)"),
        ("stop_time=8hour", "stop_time=1")
    ]

    @test run_script(replace_strings, "free_convection", free_convection_filepath)

    push!(replace_strings, ("CPU()", "GPU()"))
    @test_skip run_script(replace_strings, "free_convection", free_convection_filepath)
end

max_stars_repo_name: ali-ramadhan/LESbrary

max_issues_repo_name: ali-ramadhan/LESbrary

max_forks_repo_name: ali-ramadhan/LESbrary


text:
using Test
using OrdinaryDiffEq

@testset "KdV equation (Single Solition)" begin
    N,M = 100,5000
    Δx = 1/(N-1)
    Δt = 1/(M-1)
    a = 1

    x = collect(-π : Δx : π)
    ϕ(x,t,a) = sin.((x-a*t)) # solution of the single forward moving wave, a is the speed of wave
    u0 = ϕ(x,0,a);
    oriu = zeros(x);

    A = DiffEqUpwindOperator{Float64}(1,2,Δx,length(x),.~BitVector(length(x)),:Dirichlet0,:nothing);

    function advection(t, u, du)
       A(t,u,du)
       # scale!(du,-1)
    end

    single_solition = ODEProblem(advection, u0, (0.,5.));
    soln = solve(single_solition,SSPRK22(),dense=false,saveat=0.001,dt=Δt);

    for t in 0:0.5:5
        @test soln(t) ≈ ϕ(x,t,a) atol = 0.01;
    end
end


text:
include("../bike/bike.jl")

mutable struct Simulation
    bikes :: Vector{Bike}
    current_time :: Int
    timed_bike_positions
    simulation_run_time :: Int
end


text:
using Test, YaoBlocks, LuxurySparse, YaoBase
using YaoBlocks.ConstGate
import YaoBlocks: u1mat, unmat, cunmat, unij!

@testset "dense-u1mat-unmat" begin
    nbit = 4
    mmm = Rx(0.5) |> mat
    m1 = u1mat(nbit, mmm, 2)
    m2 = linop2dense(v -> instruct!(v, mmm, (2,)), nbit)
    m3 = unmat(nbit, mmm, (2,))
    @test m1 ≈ m2
    @test m1 ≈ m3

    # test control not
    ⊗ = kron
    res = mat(I2) ⊗ mat(I2) ⊗ mat(P1) ⊗ mat(I2) + mat(I2) ⊗ mat(I2) ⊗ mat(P0) ⊗ mat(Rx(0.5))
    m3 = cunmat(nbit, (2,), (0,), mmm, (1,))
    @test m3 ≈ res
end

@testset "sparse-u1mat-unmat" begin
    nbit = 4
    # test control not
    ⊗ = kron
    res = mat(I2) ⊗ mat(I2) ⊗ mat(P1) ⊗ mat(I2) + mat(I2) ⊗ mat(I2) ⊗ mat(P0) ⊗ mat(P1)
    m3 = cunmat(nbit, (2,), (0,), mat(P1), (1,))
    @test m3 ≈ res
end

@testset "perm-unij-unmat" begin
    perm = PermMatrix([1, 2, 3, 4], [1, 1, 1, 1.0])
    pm = unij!(copy(perm), [2, 3, 4], PermMatrix([3, 1, 2], [0.1, 0.2, 0.3]))
    @test pm ≈ PermMatrix([1, 4, 2, 3], [1, 0.1, 0.2, 0.3])
    pm = unij!(copy(perm), [2, 3, 4], PermMatrix([3, 1, 2], [0.1, 0.2, 0.3]) |> staticize)
    @test pm ≈ PermMatrix([1, 4, 2, 3], [1, 0.1, 0.2, 0.3])

    nbit = 4
    mmm = X |> mat
    m1 = unmat(nbit, mmm, (2,))
    m2 = linop2dense(v -> instruct!(v, mmm, (2,)), nbit)
    @test m1 ≈ m2
end

@testset "identity-unmat" begin
    nbit = 4
    mmm = Z |> mat
    m1 = unmat(nbit, mmm, (2,))
    m2 = linop2dense(v -> instruct!(v, mmm, (2,)), nbit)
    @test m1 ≈ m2
end

@testset "fix-static and adjoint for mat" begin
    G1 = matblock(rand_unitary(2))
    G6 = matblock(rand_unitary(1 << 6))
    @test mat(put(3, 2 => G1')) ≈ mat(put(3, 2 => matblock(G1)))'
    @test mat(put(7, (3, 2, 1, 5, 4, 6) => G6')) ≈ mat(put(7, (3, 2, 1, 5, 4, 6) => G6))'
end

max_stars_repo_name: QuantumBFS/YaoStdCircuit

max_issues_repo_name: QuantumBFS/YaoStdCircuit


text:
int main() {
    // Arithmetic operations
    int x;
    x++;
    printInt(x);
    x--;
    printInt(x);
    x--;
    printInt(x);
    printInt(x+x);

    return 0;
}

max_stars_repo_name: carlostome/Javalette-Compiler

max_issues_repo_name: carlostome/Javalette-Compiler

max_forks_repo_name: carlostome/Javalette-Compiler


text:
function event_occurred(obj::EventDetector, arg0::SpacecraftState, arg1::jboolean)
    return jcall(obj, "eventOccurred", Action, (SpacecraftState, jboolean), arg0, arg1)
end

function g(obj::EventDetector, arg0::SpacecraftState)
    return jcall(obj, "g", jdouble, (SpacecraftState,), arg0)
end

function get_max_check_interval(obj::EventDetector)
    return jcall(obj, "getMaxCheckInterval", jdouble, ())
end

function get_max_iteration_count(obj::EventDetector)
    return jcall(obj, "getMaxIterationCount", jint, ())
end

function get_threshold(obj::EventDetector)
    return jcall(obj, "getThreshold", jdouble, ())
end

function init(obj::EventDetector, arg0::SpacecraftState, arg1::AbsoluteDate)
    return jcall(obj, "init", void, (SpacecraftState, AbsoluteDate), arg0, arg1)
end

function reset_state(obj::EventDetector, arg0::SpacecraftState)
    return jcall(obj, "resetState", SpacecraftState, (SpacecraftState,), arg0)
end


text:
function sumlengths(points)
    result = zeros(eltype(points[1]), length(points))
    for i=1:length(points)
        i0 = max(i-1,1)
        result[i] = result[i0] + norm(points[i0]-points[i])
    end
    result
end


text:
function func(x)
    return x-cos(x)
end

function bisection(func,xleft,xright,eps)
    y_left = func(xleft)
    y_right = func(xright)
    num_iter = 0
    iteration = 100000000
    if y_left == 0
        return xleft, num_iter
    elseif y_right == 0
        return xright, num_iter
    elseif y_left*y_right > 0
        return nothing, nothing
    else
        for n in 1:iteration
            x_mid = (xleft+xright)/2
            y_mid = func(x_mid)
            if y_mid == 0
                num_iter = n
                return x_mid, num_iter
            end
            if y_left*y_mid < 0
                xright = x_mid
            else
                xleft = x_mid
            end
            if(abs(xright-xleft) < eps)
                num_iter = n
                return x_mid, num_iter
            end
        end
        return nothing, num_iter
    end
end

function main()
    xleft, xright = 0, 3.14
    eps = 1e-7
    solution, num_iter = bisection(func, xleft, xright, eps)
    if solution != nothing
        print("X=$(solution) $(func(solution)), $(num_iter)")
    elseif num_iter == nothing
        print("f(x1)*f(x2) must be less than 0")
    else
        print("No Convergence")
    end
end

main()

max_stars_repo_name: terasakisatoshi/juliaExer

max_issues_repo_name: terasakisatoshi/juliaExer

max_forks_repo_name: terasakisatoshi/juliaExer


text:
export iauC2t06a
"""
Form the celestial to terrestrial matrix given the date, the UT1 and
the polar motion, using the IAU 2006 precession and IAU 2000A
nutation models.

This function is part of the International Astronomical Union's
SOFA (Standards Of Fundamental Astronomy) software collection.

Status:  support function.

Given:
   tta,ttb  double         TT as a 2-part Julian Date (Note 1)
   uta,utb  double         UT1 as a 2-part Julian Date (Note 1)
   xp,yp    double         coordinates of the pole (radians, Note 2)

Returned:
   rc2t     double[3][3]   celestial-to-terrestrial matrix (Note 3)

Notes:

   1. The TT and UT1 dates tta+ttb and uta+utb are Julian Dates,
   apportioned in any convenient way between the arguments uta and
   utb.  For example, JD(UT1)=2450123.7 could be expressed in any of
   these ways, among others:

            uta            utb

      2450123.7           0.0       (JD method)
      2451545.0       -1421.3       (J2000 method)
      2400000.5       50123.2       (MJD method)
      2450123.5           0.2       (date & time method)

   The JD method is the most natural and convenient to use in
   cases where the loss of several decimal digits of resolution is
   acceptable.  The J2000 and MJD methods are good compromises
   between resolution and convenience.  In the case of uta,utb, the
   date & time method is best matched to the Earth rotation angle
   algorithm used:  maximum precision is delivered when the uta
   argument is for 0hrs UT1 on the day in question and the utb
   argument lies in the range 0 to 1, or vice versa.

   2. The arguments xp and yp are the coordinates (in radians) of the
   Celestial Intermediate Pole with respect to the International
   Terrestrial Reference System (see IERS Conventions 2003),
   measured along the meridians to 0 and 90 deg west respectively.

   3. The matrix rc2t transforms from celestial to terrestrial
   coordinates:

      [TRS] = RPOM * R_3(ERA) * RC2I * [CRS]

            = rc2t * [CRS]

   where [CRS] is a vector in the Geocentric Celestial Reference
   System and [TRS] is a vector in the International Terrestrial
   Reference System (see IERS Conventions 2003), RC2I is the
   celestial-to-intermediate matrix, ERA is the Earth rotation
   angle and RPOM is the polar motion matrix.

Called:
   iauC2i06a    celestial-to-intermediate matrix, IAU 2006/2000A
   iauEra00     Earth rotation angle, IAU 2000
   iauSp00      the TIO locator s', IERS 2000
   iauPom00     polar motion matrix
   iauC2tcio    form CIO-based celestial-to-terrestrial matrix

Reference:

   McCarthy, D. D., Petit, G. (eds.), 2004, IERS Conventions (2003),
   IERS Technical Note No. 32, BKG

This revision:  2013 June 18

SOFA release 2018-01-30

Copyright (C) 2018 IAU SOFA Board.  See notes at end.
"""

# void iauC2t06a(double tta, double ttb, double uta, double utb,
#                double xp, double yp, double rc2t[3][3])

function iauC2t06a(tta::Real, ttb::Real, uta::Real, utb::Real, xp::Real, yp::Real)

   # Allocate return value
   rc2t = zeros(Float64, 3, 3)

   ccall((:iauC2t06a, libsofa_c), Cvoid,
         (Cdouble, Cdouble, Cdouble,
         Cdouble, Cdouble, Cdouble,
         Ptr{Cdouble}),
         convert(Float64, tta), convert(Float64, ttb),
         convert(Float64, uta), convert(Float64, utb),
         convert(Float64, xp), convert(Float64, yp),
         rc2t)

   return SMatrix{3,3}(rc2t')
end


text:
module MakeCshared

using Printf

export printout, calc, hello

import Libdl
const depsjl_path = joinpath(dirname(@__FILE__), "..", "deps", "deps.jl")
if !isfile(depsjl_path)
    error("shared library not installed properly; run Pkg.build(\"MakeCshared\"), restart Julia, and try again.")
end

include(depsjl_path)

function __init__()
    check_deps()
end

function printout()
    ccall((:display, libextrac), Nothing, ())
end

function calc(x)
    ccall((:calc, libextrac), Int32, (Int32,), x)
end

function hello(s::AbstractString)
    v = ccall((:hello, libextrac), Cstring, (Cstring,), s)
    unsafe_string(v)
end

end # module


text:
int main()
{
  int x, y;
  for (x = 1; x < 5; x++)
    for (y = 1; y < 5; y++)
    {
      int z = -17;
      for (z = 1; z < 5; z++)
        printInt(x * y * z);
      printString("");
    }
  return 0;
}

/* vim:set ts=2 sts=2 sw=2 et ft=c: */

max_stars_repo_name: jwilk/jtc

max_issues_repo_name: jwilk/jtc

max_forks_repo_name: jwilk/jtc


text:
function vtkCG(c,CG,Param,vtkGrid,vtk)
OrdPoly=CG.OrdPoly;
nz=Param.Grid.nz;
NF=Param.Grid.NumFaces;
NumV=size(c,3);
ivtkc=0;
vtkc=zeros(nz*NF*OrdPoly*OrdPoly,NumV);
for iF=1:Param.Grid.NumFaces
  for iz=1:Param.Grid.nz
    cLoc=reshape(c[CG.Faces[iF].Glob,iz,:],OrdPoly+1,OrdPoly+1,NumV);
    dd=2/OrdPoly;
    eta0=-1;
    for jRef=1:OrdPoly
      ksi0=-1;
      eta1=eta0+dd;
      for iRef=1:OrdPoly
        ksi1=ksi0+dd;
        cc=zeros(NumV,1);
        for j=1:OrdPoly+1
          for i=1:OrdPoly+1
            cc[:]=cc[:]+reshape(Lagrange(0.5*(ksi0+ksi1),CG.xw,i)*
              Lagrange(0.5*(eta0+eta1),CG.xw,j)*
              cLoc[i,j,:],NumV,1);
          end
        end
        ivtkc=ivtkc+1;
        vtkc[ivtkc,:]=cc[:];
        ksi0=ksi1;
      end
      eta0=eta1;
    end
  end
end

vtkS=num2str(vtk);
vtkWriteHex(strcat(Param.vtkFileName,vtkS,".vtk"),
  vtkGrid.vtkP,
  vtkGrid.ConnectivityList,vtkc,Param.cNames)
vtk=vtk+1;
return vtk
end


text:
#
# This file is part of the DiscreteEvents.jl Julia package, MIT license
#
# Paul Bayer, 2020
#
# This is a Julia package for discrete event simulation
#

"""
```
event!([clk], ex, t; <keyword arguments>)
event!([clk], ex, t, cy; <keyword arguments>)
event!([clk], ex, T, t; <keyword arguments>)
```
Schedule an event for a given time `t`.

If `t` is a `Distribution`, event time is evaluated as `rand(t)`.
If `cy` is a `Distribution`, the event is repeated after a random
interval `rand(cy)`. If the evaluated time ≤ clk.time, the event
is scheduled at `clk.time`.

# Arguments
- `clk<:AbstractClock`: clock, it not supplied, the event is scheduled to 𝐶,
- `ex<:Action`: an expression or function or a tuple of them,
- `T::Timing`: a timing, one of `at`, `after` or `every`,
- `t`: event time, `Number` or `Distribution`,
- `cy`: repeat cycle, `Number` or `Distribution`.

# Keyword arguments
- `n::Int=typemax(Int)`: number of repeating events,
- `cid::Int=clk.id`: if cid ≠ clk.id, assign the event to the parallel clock
    with id == cid. This overrides `spawn`,
- `spawn::Bool=false`: if true, spawn the event at other available threads,

# Examples
```jldoctest
julia> using DiscreteEvents, Distributions, Random

julia> Random.seed!(123);

julia> c = Clock()
Clock 1: state=:idle, t=0.0, Δt=0.01, prc:0
  scheduled ev:0, cev:0, sampl:0

julia> f(x) = x[1] += 1
f (generic function with 1 method)

julia> a = [0]
1-element Array{Int64,1}:
 0

julia> event!(c, fun(f, a), 1)                     # 1st event at 1

julia> event!(c, fun(f, a), at, 2)                 # 2nd event at 2

julia> event!(c, fun(f, a), after, 3)              # 3rd event after 3

julia> event!(c, fun(f, a), every, Exponential(3)) # Poisson process with λ=1/3

julia> run!(c, 50)
"run! finished with 26 clock events, 0 sample steps, simulation time: 50.0"

julia> a
1-element Array{Int64,1}:
 26
```
"""
function event!(clk::CL, ex::A, t::U; # 1st case, t isa Number
                cid::Int=clk.id, spawn::Bool=false) where {CL<:AbstractClock,A<:Action,U<:Number}
    t = _tadjust(clk, t)
    t = max(t, _tadjust(clk, tau(clk)))
    _assign(clk, DiscreteEvent(ex, t, nothing, 1), _cid(clk,cid,spawn))
end

# 2nd case, x isa Distribution
function event!(clk::CL, ex::A, x::X;
    cid::Int=clk.id, spawn::Bool=false) where {CL<:AbstractClock,A<:Action,X<:Distribution}
    t = max(rand(x), _tadjust(clk, tau(clk)))
    _assign(clk, DiscreteEvent(ex, t, nothing, 1), _cid(clk,cid,spawn))
end

# 3rd case, t and cy are Numbers
function event!(clk::CL, ex::A, t::U, cy::V;
    n::Int=typemax(Int), cid::Int=clk.id, spawn::Bool=false) where {CL<:AbstractClock,A<:Action,U<:Number,V<:Number}
    t = _tadjust(clk, t)
    cy = _tadjust(clk, cy)
    t = max(t, _tadjust(clk, tau(clk)))
    _assign(clk, DiscreteEvent(ex, t, cy, n), _cid(clk,cid,spawn))
end

# 4th case, t isa Number, cy isa Distribution
function event!(clk::CL, ex::A, t::U, cy::V;
    n::Int=typemax(Int), cid::Int=clk.id, spawn::Bool=false) where {CL<:AbstractClock,A<:Action,U<:Number,V<:Distribution}
    t = _tadjust(clk, t)
    t = max(t, _tadjust(clk, tau(clk)))
    _assign(clk, DiscreteEvent(ex, t, cy, n), _cid(clk,cid,spawn))
end

# 5th case, t and cy are both Distributions
function event!(clk::CL, ex::A, t::U, cy::V;
    n::Int=typemax(Int), cid::Int=clk.id, spawn::Bool=false) where {CL<:AbstractClock,A<:Action,U<:Distribution,V<:Distribution}
    t = max(rand(t), _tadjust(clk, tau(clk)))
    _assign(clk, DiscreteEvent(ex, t, cy, n), _cid(clk,cid,spawn))
end

# 6th case, Timing and Number
function event!(clk::CL, ex::A, T::Timing, t::U; kw...) where {CL<:AbstractClock,A<:Action,U<:Number}
    t = _tadjust(clk, t)
    if T == after
        event!(clk, ex, clk.time+t; kw...)
    elseif T == every
        event!(clk, ex, t, t; kw...)
    else
        event!(clk, ex, t; kw...)
    end
end

# 7th case, Timing and Distribution
function event!(clk::CL, ex::A, T::Timing, x::X; kw...) where {CL<:AbstractClock,A<:Action,X<:Distribution}
    if T == after
        event!(clk, ex, clk.time+rand(x); kw...)
    elseif T == every
        event!(clk, ex, rand(x), x; kw...)
    else
        event!(clk, ex, rand(x); kw...)
    end
end
# 7 cases to default clock
event!(ex::A, t::U; kw...) where {A<:Action,U<:Number} = event!(𝐶, ex, t; kw...)
event!(ex::A, x::X; kw...) where {A<:Action,X<:Distribution} = event!(𝐶, ex, x; kw...)
event!(ex::A, t::U, cy::V; kw...) where {A<:Action,U<:Number,V<:Number} = event!(𝐶, ex, t, cy; kw...)
event!(ex::A, t::U, cy::V; kw...) where {A<:Action,U<:Number,V<:Distribution} = event!(𝐶, ex, t, cy; kw...)
event!(ex::A, t::U, cy::V; kw...) where {A<:Action,U<:Distribution,V<:Distribution} = event!(𝐶, ex, t, cy; kw...)
event!(ex::A, T::Timing, t::U; kw...) where {A<:Action,U<:Number} = event!(𝐶, ex, T, t; kw...)
event!(ex::A, T::Timing, X::Distribution; kw...) where A<:Action = event!(𝐶, ex, T, X; kw...)

"""
    event!([clk], ex, cond; <keyword arguments>)

Schedule `ex` as a conditional event, conditions `cond` get evaluated at each clock tick.

# Arguments
- `clk<:AbstractClock`: if no clock is supplied, the event is scheduled to 𝐶,
- `ex<:Action`: an expression or function or a tuple of them,
- `cond<:Action`: a condition is true if all functions or expressions therein return true,

# Keyword arguments
- `cid::Int=clk.id`: if cid ≠ clk.id, assign the event to the parallel clock
    with id == cid. This overrides `spawn`,
- `spawn::Bool=false`: if true, spawn the event at other available threads.

# Examples
```jldoctest
julia> using DiscreteEvents

julia> c = Clock()   # create a new clock
Clock 1: state=:idle, t=0.0, Δt=0.01, prc:0
  scheduled ev:0, cev:0, sampl:0

julia> event!(c, fun((x)->println(tau(x), ": now I'm triggered"), c), fun(>=, fun(tau, c), 5))

julia> run!(c, 10)   # sampling is not exact, so it takes 502 sample steps to fire the event
5.009999999999938: now I'm triggered
"run! finished with 0 clock events, 502 sample steps, simulation time: 10.0"
```
"""
function event!(clk::T, ex::A, cond::C;
                cid::Int=clk.id, spawn=false) where {T<:AbstractClock,A<:Action,C<:Action}
    if _busy(clk) && all(_evaluate(cond))   # all conditions met
        _evaluate(ex)                      # execute immediately
    else
        _assign(clk, DiscreteCond(cond, ex), _cid(clk,cid,spawn))
    end
    return nothing
end
event!( ex::A, cond::C; kw...) where {A<:Action,C<:Action} = event!(𝐶, ex, cond; kw...)

"""
```
periodic!([clk], ex, Δt; <keyword arguments>)
periodic!(clk, ex; <keyword arguments>)
```

Register an Action `ex` for periodic execution at the clock`s sample rate.

# Arguments
- `clk<:AbstractClock`: if not supplied, it registers on 𝐶,
- `ex<:Action`: an expression or function or a tuple of them,
- `Δt<:Number=clk.Δt`: set the clock's sampling rate, if no Δt is given, it takes
    the current sampling rate, if ≤ 0, it calculates a positive one,

# Keyword arguments
- `cid::Int=clk.id`: if cid ≠ clk.id, sample at the parallel clock
    with id == cid. This overrides `spawn`,
- `spawn::Bool=false`: if true, spawn the periodic event to other available threads.
"""
function periodic!(clk::Clock, ex::T, Δt::U=clk.Δt;
                cid::Int=clk.id, spawn=false) where {T<:Action,U<:Number}
   if Δt ≤ 0  # pick a positive sample rate
       clk.Δt = clk.evcount == 0 ? 0.01 : _scale(clk.time/clk.evcount)/100
   end
    _assign(clk, Sample(ex), _cid(clk,cid,spawn))
end
periodic!(ex::T, Δt::U=𝐶.Δt; kw...) where {T<:Action,U<:Number} = periodic!(𝐶, ex, Δt; kw...)
periodic!(ac::ActiveClock, ex::T, Δt::U=ac.clock.Δt; kw...) where {T<:Action,U<:Number} = periodic!(ac.clock, ex, Δt; kw...)
periodic!(rtc::RTClock, ex::T) where T<:Action = _assign(rtc, Sample(ex))

# Return a random number out of the thread ids of all available parallel clocks
function _spawnid(c::Clock)
    if c.id == 1
        return isempty(c.ac) ? 1 : rand(rng, 1:(length(c.ac)+1))
    elseif isempty(c.ac)
        return c.id
    else
        return _spawnid(c.ac[])
    end
end
_spawnid(ac::ActiveClock) = _spawnid(ac.master[])

# return a valid clock id
function _cid(c::Clock, cid::Int, spawn::Bool)
    if c.id == cid
        return spawn ? _spawnid(c) : cid
    elseif c.id == 1
        isempty(c.ac) && return 1
        cid ∈ (eachindex(c.ac).+1) && return cid
        return spawn ? _spawnid(c) : 1
    else
        _cid(c.ac[], cid, spawn)
    end
end
function _cid(ac::ActiveClock, cid::Int, spawn::Bool)
    if ac.id == cid
        return spawn ? _spawnid(ac.master[]) : cid
    else
        cid ∈ 1:(length(ac.master[].ac).+1) && return cid
        return spawn ? _spawnid(ac.master[]) : ac.id
    end
end
_cid(rtc::RTClock, cid::Int, spawn::Bool) = rtc.id

# calculate the scale from a given number
function _scale(n::T)::Float64 where {T<:Number}
    if n > 0
        i = 1.0
        while !(10^i ≤ n < 10^(i+1))
            n < 10^i ? i -= 1 : i += 1
        end
        return 10^i
    else
        return 1.0
    end
end

# ---------------------------------------------------------------
# assign and register events and samples to a clock
# ---------------------------------------------------------------
# There are several ways to do it:
# 1. assign it directly to a clock or
# 2. assign it via a channel to another one, if given a different id.
#    In this case the event is sent over the channel to the target clock.
#    - The master clock (id=0) can directly send to an active clock.
#    - An active clock can send directly to master.
#    - An active clock can only send via master to another active clock.
_assign(c::S, ev::T) where {S<:AbstractClock, T<:AbstractEvent} = _register!(c, ev)
function _assign(c::S, ev::T, id::Int) where {S<:AbstractClock, T<:AbstractEvent}
    if id == c.id
        _register!(c, ev)       # 1: register it to yourself
    else
        _register(c, ev, id)    # 2: register it to another clock
    end
end

# function barrier: register an event directly to a clock.
function _register!(c::Clock, ev::DiscreteEvent)
    t = ev.t
    while any(i->i==t, values(c.sc.events)) # in case an event at that time exists
        t = nextfloat(float(t))                  # increment scheduled time
    end
    c.sc.events[ev] = t
    return
end
function _register!(c::Clock, cond::DiscreteCond)
    # (c.Δt == 0) && (c.Δt = _scale(c.end_time - c.time)/100)
    if c.Δt ≤ 0  # pick a sample rate
        c.Δt = c.evcount == 0 ? 0.01 : _scale(c.time/c.evcount)/100
    end
    push!(c.sc.cevents, cond)
    return
end
_register!(c::Clock, sp::Sample) = ( push!(c.sc.samples, sp); nothing )
_register!(ac::ActiveClock, ev::T) where {T<:AbstractEvent} = _register!(ac.clock, ev)
_register!(rtc::RTClock, ev::T) where {T<:AbstractEvent} = put!(rtc.cmd, Register(ev))

# Register an event to another clock via a channel.
# - c::Clock: a master clock can forward events to active clocks,
#             a local clock needs to access the wrapping active clock,
# - ac::ActiveClock: active clocks can forward events only through master,
#                    he then does the distribution for them,
# - ev<:AbstractEvent: the event to register,
# - id::Int: the id of the clock it should get registered to.
function _register(c::Clock, ev::T, id::Int) where {T<:AbstractEvent}
    if c.id == id
        _register!(c, ev)
    elseif c.id == 1
        i = findfirst(x->x.thread==id, c.ac)
        i === nothing ? _register!(c, ev) : put!(c.ac[i].forth, Register(ev))
    else
        _register(c.ac[], ev, id)  # let the active clock do it
    end
end
function _register(ac::ActiveClock, ev::T, id::Int) where {T<:AbstractEvent}
    if ac.id == id
        _register!(ac.clock, ev)
    else
        if ac.master[].state == Busy()      # uses shared variable ↯↯↯
             put!(ac.back, Forward(ev, id)) # shouldn't happen often
        else                                # but still can go wrong !!!
            _register(ac.master[], ev, id)  # needs responsive master
        end                                 # to be solved !!!
    end
end