text:
## http://docs.sympy.org/dev/modules/core.html

"""
    `Wild(:x)`: create a "wild card" for pattern matching
"""
Wild(x::AbstractString) = convert(Function, sympy[:Wild])(x)
Wild(x::Symbol) = Wild(string(x))
export Wild

"""
    `match(pattern, expression, ...)` match pattern against expression

returns a dictionary of matches.

If a match is unsuccesful, returns an *empty* dictionary. (SymPy returns "nothing")

The order of the arguments follows `Julia`'s `match` function, not `SymPy`'s. This may change.
"""
function Base.match(pat::Sym, ex::Sym, args...; kwargs...)
    out = ex[:match](pat, args...; kwargs...)
    out == nothing && return Dict()
    out
end

"""
     `func(ex)`: Return function head from an expression

```
func(sin(x))  # sin
func(x*y)     # Mul
func(x+y)     # Add
```
"""
func(ex::Sym) = Sym(ex.x[:func])
export func

"""
    `replace(expression, pattern, value, ...)`

From: [SymPy Docs](http://docs.sympy.org/dev/modules/core.html)

Traverses an expression tree and performs replacement of matching
subexpressions from the bottom to the top of the tree. The default
approach is to do the replacement in a simultaneous fashion so changes
made are targeted only once. If this is not desired or causes
problems, `simultaneous` can be set to `false`. In addition, if an
expression containing more than one `Wild` symbol is being used to match
subexpressions and the `exact` flag is `true`, then the match will only
succeed if non-zero values are received for each `Wild` that appears in
the match pattern.

Differences from SymPy:

* "types" are specified via calling `func` on the head of an expression: `func(sin(x))` -> `sin`
* functions are supported, but only partially so

Examples (from the SymPy docs)
```
x, y, z = symbols("x, y, z")
f = log(sin(x)) + tan(sin(x^2))
```

Types are specified through `func`:
```
replace(f, func(sin(x)), func(cos(x))) # log(cos(x)) + tan(cos(x^2));   type -> type
```

Wild terms are supported
```
a = Wild("a")
ex = sin(x)
replace(ex, sin(a), cos(a^2))  # cos(x^2)
```

Some patterns allow for functions, but there are subtleties.

The replacement pattern [type -> function](http://docs.sympy.org/dev/modules/core.html#sympy.core.basic.Basic.replace) is case 1.2 and works as expected:

```
ex = log(sin(x)) + tan(sin(x^2))
replace(ex, func(sin(x)), a -> sin(2a))  # log(sin(2x)) + tan(sin(2*x^2))
replace(x*y, func(x*y), (args...) -> sin(2*prod(args)))  # sin(2xy)
```

The pattern "pattern -> func" style requires two things: the function
uses keyword arguments to match the values in the pattern and *the*
return value must be wrapped in `SymPy.project` and the function
wrapped as a `PyObject`. (Yes, this should be better but for now
isn't)

```
a = Wild("a")
s2(;a=0) = SymPy.project(sin(2a))
replace(ex, sin(a), PyCall.PyObject(s2))
```

"""
function Base.replace(ex::Sym, query::Sym, fn::Function; kwargs...)
    replace(ex, query, PyCall.PyObject((args...) -> map(SymPy.project,fn(args...))); kwargs...)
end

function Base.replace(ex::Sym, query::Sym, value; kwargs...)
    ex[:replace](query, value; kwargs...)
end
## curried form
Base.replace(query::Sym, value; kwargs...) = ex -> replace(ex, query, value; kwargs...)

"""
    `rewrite(ex, f)`, `rewrite(ex, f, g)` rewrite named functions in an expression by others

Examples:
```
rewrite(sin(x), func(exp(x)))  # rewrite interms of exponentials
rewrite(sin(x), "exp")         # can use a string here
```
"""
function rewrite(ex::Sym,  args...; kwargs...)
    ex[:rewrite](args...; kwargs...)
end
export rewrite

"""

    `xreplace(ex, rule::Dict)` or `xreplace(ex, a=>b, c=>d, ...)`

Replace expressions in `ex` using replacements specified in a dictionary or as pairs.

```
x,y, z = symbols("x y z")
xreplace(x*y + x, x*y => PI)
xreplace(x*y*z, x*y => PI)   # entire node of expression tree is not matched
xreplace(2x, 2x => y, x => z)
xreplace(2*2*x, 2x=>y, x => z)
xreplace(Integral(sin(x), x), x=> y) # bound and unbound are replaced
```
"""
function xreplace(ex::Sym, rule::Dict, args...; kwargs...)
    d = Dict()
    for (k,v) in rule
        d[project(k)] = project(v)
    end
    ex[:xreplace](d, args...; kwargs...)
end
xreplace(ex::Sym, xs::Pair...; kwargs...) = xreplace(ex, Dict(xs...); kwargs...)

export xreplace


text:
export jacobian,  StabilityType

@with_kw struct jacobian
    ode
    jac_func
    u
    p
    t
end

"""
    StabilityType

Store the information about stability.
"""
@with_kw struct StabilityType
    stable ::Bool
    unstable ::Bool
    saddle  ::Bool
    damping ::Bool
end

"""
Construct the jacobian struct type

Argument
--------
- `ode` {ODE function}: with the form `f(du,u,p,t)`
- `u` {Array}: initial values
- `p` {Array}: parameters

Return
------
- `Jacobian` {struct}

Warning
-------
NameTuple definition of `ode` function is unrecommended. Due to the incompatibility with `ModelingToolkit.modelingtoolkitize`
"""
function jacobian(ode, u, p; t=nothing)
    prob = ODEProblem(ode, u, t, p)
    de =  ModelingToolkit.modelingtoolkitize(prob)

    jac_func = ModelingToolkit.generate_jacobian(de, expression=Val{false})[2]
    return jacobian(ode=ode, jac_func=jac_func, u=u, p=p, t=t)
end

"""Use DEmeta for jacobian generation"""
function jacobian(de::T; t= nothing) where T<:DEmeta
    return jacobian(de.func, de.u0, de.p; t=t)
end

"""
Calculate the jacobian of given initial valuables and parameters.
"""
function (self::jacobian)(u,p;t=nothing)
    l = length(u)
    j = zeros(l,l)
    self.jac_func(j, u, p, t)
    return j
end

"""
Get jacobian from state variable with default paramter set
"""
function (self::jacobian)(u;t=nothing)
    return self(u, self.p; t=t)
end

"""
Get jacobian from default state.
"""
function (self::jacobian)()
    return self(self.u, self.p; t=self.t)
end

function StabilityType(jac_matrix)
    es = eigvals(jac_matrix)

    return StabilityType(
    stable = is_stable(es),
    unstable = is_unstable(es),
    saddle = is_saddle(es),
    damping = is_damping(es)
    )
end

"""
Stability identification
"""
function is_stable(es) :: Bool
    method(e) = real(e) >= 0. ? true : false
    return judge_jac(es, method, true)
end

"""
Unstability identification
"""
function is_unstable(es) :: Bool
    method(e) = real(e) >= 0. ? true : false
    return judge_jac(es, method, false)
end

"""
Damping identification
"""
function is_damping(es) :: Bool
   method(e) = imag(e) != 0. ? true : false
   return judge_jac(es, method, false)
end

"""
Saddle point identification
"""
function is_saddle(es) :: Bool
    real_es = real.(es)
    if (maximum(real_es) > 0. ) & (minimum(real_es) < 0.)
        saddle = true
    else
        saddle = false
    end
    return saddle
end

"""
General method for judging jacobian
"""
function judge_jac(es, eigval_method, default_bool)
    feature = default_bool
    for e in es
        if eigval_method(e)
            feature = !feature
            break
        end
    end
    return feature
end

ext: jl


text:
using Test
using WaveToyDagger

WaveToyDagger.main()


text:
using Printf

function parse_map(s)
    lines = split(s, "\n")
    map_arr = zeros(Bool, length(lines), length(lines[1]))
    for (row_idx, l) in enumerate(lines)
        for (col_idx, c) in enumerate(l)
            map_arr[row_idx, col_idx] = (c == '#')
        end
    end
    return map_arr
end

function count_trees_on_slope(map_arr, right, down)
    tree_counter = 0
    x, y = 1, 1
    n_rows, n_cols = size(map_arr)
    while x <= n_rows
        if map_arr[x, y]
            tree_counter += 1
        end
        x += down
        y = (y + right) % n_cols
        if y == 0
            y = n_cols
        end
    end
    return tree_counter
end

function run(s)
    # Your code here
    map_arr = parse_map(s)
    slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
    results = map(x -> count_trees_on_slope(map_arr, x...), slopes)
    return reduce(*, results)
end

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

function main()
    res, time, memory = @timed run(ARGS[1])
    println("_duration:$(time * 1000)")
    println(res)
end

main()


text:
function ScriptLog(message)
    println("Log -> $message")
end

max_stars_repo_name: TapVM/Tap

max_issues_repo_name: TapVM/Tap

max_forks_repo_name: TapVM/Tap


text:
export varsindex, varsindices

"""
    varsindex(S, p::Symbol, [sp::Symbol...])

Return a range of indices corresponding to the property `p` and
(optionally) its subproperties `sp` based on the template type `S`.

# Examples
```julia-repl
julia> S = @vars(x::Float64, y::Float64)
julia> varsindex(S, :y)
2:2

julia> S = @vars(x::Float64, y::@vars(α::Float64, β::SVector{3, Float64}))
julia> varsindex(S, :y, :β)
3:5
```
"""
function varsindex(::Type{S}, insym::Symbol) where {S <: NamedTuple}
    offset = 0
    for varsym in fieldnames(S)
        T = fieldtype(S, varsym)
        if T <: Real
            offset += 1
            varrange = offset:offset
        elseif T <: SHermitianCompact
            LT = StaticArrays.lowertriangletype(T)
            N = length(LT)
            varrange = offset .+ (1:N)
            offset += N
        elseif T <: StaticArray
            N = length(T)
            varrange = offset .+ (1:N)
            offset += N
        else
            varrange = offset .+ (1:varsize(T))
            offset += varsize(T)
        end
        if insym == varsym
            return varrange
        end
    end
    error("symbol '$insym' not found")
end
Base.@propagate_inbounds function varsindex(
    ::Type{S},
    sym::Symbol,
    rest::Symbol...,
) where {S <: NamedTuple}
    varsindex(S, sym)[varsindex(fieldtype(S, sym), rest...)]
end

"""
    varsindices(S, ps::Tuple)
    varsindices(S, ps...)

Return a tuple of indices corresponding to the properties
specified by `ps` based on the template type `S`. Properties
can be specified using either symbols or strings.

# Examples
```julia-repl
julia> S = @vars(x::Float64, y::Float64, z::Float64)
julia> varsindices(S, (:x, :z))
(1, 3)

julia> S = @vars(x::Float64, y::@vars(α::Float64, β::SVector{3, Float64}))
julia> varsindices(S, "x", "y.β")
(1, 3, 4, 5)
```
"""
function varsindices(::Type{S}, vars::Tuple) where {S <: NamedTuple}
    indices = Int[]
    for var in vars
        splitvar = split(string(var), '.')
        append!(indices, collect(varsindex(S, map(Symbol, splitvar)...)))
    end
    Tuple(indices)
end
varsindices(::Type{S}, vars...) where {S <: NamedTuple} = varsindices(S, vars)


text:
using Rubin
using Tests
using Elliptic
using HypergeometricFunctions
using Polylogarithms
using SpecialFunctions

@test integrate((1+2x)^(1/2), x) == :(1//3*(1+2x)^3//2)
@test integrate(x*(1+3x)^(1/2), x) == :(-2//27*(1+3x)^3//2+2//45*(1+3x)^5//2)
@test integrate(x^2*(1+x)^(1/2), x) == :(-4//5*(1+x)^5//2+2//3*(1+x)^3//2+2//7*(1+x)^7//2)
@test integrate(x*(2+-3x)^-1//2, x) == :(-4//9*(2+-3x)^(1/2)+2//27*(2+-3x)^3//2)
@test integrate((2+x^2+2x)^-3*(1+x), x) == :(-1//4*(2+x^2+2x)^-2)
@test integrate(sin(x)^3, x) == :(-1*cos(x)+1//3*cos(x)^3)
@test integrate(z*(-1+z)^1//3, z) == :(3//4*(-1+z)^4//3+3//7*(-1+z)^7//3)
@test integrate(sin(x)^-3*cos(x), x) == :(-1//2*csc(x)^2)
@test integrate((4+-1*sin(2x))^(1/2)*cos(2x), x) == :(-1//3*(4+-1*sin(2x))^3//2)
@test integrate((3+cos(x))^-2*sin(x), x) == :((3+cos(x))^-1)
@test integrate((cos(x)^3)^-1//2*sin(x), x) == :(2*(cos(x)^3)^-1//2*cos(x))
@test integrate((1+x)^-1//2*sin((1+x)^(1/2)), x) == :(-2*cos((1+x)^(1/2)))
@test integrate(x^(-1+n)*sin(x^n), x) == :(-1*n^-1*cos(x^n))
@test integrate(x^5*(1+-1*x^6)^-1//2, x) == :(-1//3*(1+-1*x^6)^(1/2))
@test integrate(t*(1+t)^1//4, t) == :(-4//5*(1+t)^5//4+4//9*(1+t)^9//4)
@test integrate((1+x^2)^-3//2, x) == :(x*(1+x^2)^-1//2)
@test integrate(x^2*(27+8*x^3)^2//3, x) == :(1//40*(27+8*x^3)^5//3)
@test integrate((-1*cos(x)+sin(x))^-1//3*(cos(x)+sin(x)), x) == :(3//2*(-1*cos(x)+sin(x))^2//3)
@test integrate(x*(1+x^2+(1+x^2)^3//2)^-1//2, x) == :(2*((1+x^2)*(1+(1+x^2)^(1/2)))^(1/2)*(1+x^2)^-1//2)
@test integrate(x*(1+x^2)^-1//2*(1+(1+x^2)^(1/2))^-1//2, x) == :(2*(1+(1+x^2)^(1/2))^(1/2))
@test integrate((1+-1x)^-1*(1+x^2+-2x)^1//5, x) == :(-5//2*(1+x^2+-2x)^1//5)
@test integrate(x*sin(x), x) == :(-1*x*cos(x)+sin(x))
@test integrate(x^2*sin(x), x) == :(2*cos(x)+-1*x^2*cos(x)+2*x*sin(x))
@test integrate(x^3*cos(x), x) == :(-6*cos(x)+x^3*sin(x)+-6*x*sin(x)+3*x^2*cos(x))
@test integrate(x^3*sin(x), x) == :(-6*sin(x)+-1*x^3*cos(x)+3*x^2*sin(x)+6*x*cos(x))
@test integrate(cos(x)*sin(x), x) == :((1/2)*sin(x)^2)
@test integrate(x*cos(x)*sin(x), x) == :(-1//4*x+(1/2)*x*sin(x)^2+1//4*cos(x)*sin(x))
@test integrate(sin(x)^2, x) == :((1/2)*x+-1//2*cos(x)*sin(x))
@test integrate(sin(x)^3, x) == :(-1*cos(x)+1//3*cos(x)^3)
@test integrate(sin(x)^4, x) == :(3//8*x+-3//8*cos(x)*sin(x)+-1//4*sin(x)^3*cos(x))
@test integrate(sin(x)^5, x) == :(-1*cos(x)+-1//5*cos(x)^5+2//3*cos(x)^3)
@test integrate(sin(x)^6, x) == :(5//16*x+-5//16*cos(x)*sin(x)+-5//24*sin(x)^3*cos(x)+-1//6*sin(x)^5*cos(x))
@test integrate(x*sin(x)^2, x) == :(1//4*x^2+1//4*sin(x)^2+-1//2*x*cos(x)*sin(x))
@test integrate(x*sin(x)^3, x) == :(1//9*sin(x)^3+2//3*sin(x)+-2//3*x*cos(x)+-1//3*x*sin(x)^2*cos(x))
@test integrate(x^2*sin(x)^2, x) == :(-1//4*x+1//6*x^3+(1/2)*x*sin(x)^2+1//4*cos(x)*sin(x)+-1//2*x^2*cos(x)*sin(x))
@test integrate(cos(x)^2, x) == :((1/2)*x+(1/2)*cos(x)*sin(x))
@test integrate(cos(x)^3, x) == :(-1//3*sin(x)^3+sin(x))
@test integrate(cos(x)^4, x) == :(3//8*x+1//4*cos(x)^3*sin(x)+3//8*cos(x)*sin(x))
@test integrate((a^2+-1*x^2)^5//2, x) == :(1//6*x*(a^2+-1*x^2)^5//2+5//16*a^6*arctan(x*(a^2+-1*x^2)^-1//2)+5//16*x*a^4*(a^2+-1*x^2)^(1/2)+5//24*x*a^2*(a^2+-1*x^2)^3//2)
@test integrate(x^5*(5+x^2)^-1//2, x) == :(25*(5+x^2)^(1/2)+-10//3*(5+x^2)^3//2+1//5*(5+x^2)^5//2)
@test integrate(t^3*(4+t^3)^-1//2, t) == :(2//5*t*(4+t^3)^(1/2)+-8//15*2^2//3*3^3//4*((t+2^2//3*(1+3^(1/2)))^-2*(t+2^2//3))^-1//2*((t+2^2//3*(1+3^(1/2)))^-2*(t^2+2*2^1//3+-1*t*2^2//3))^(1/2)*(2+3^(1/2))^(1/2)*(4+t^3)^-1//2*(t+2^2//3)*Elliptic.F(arcsin((t+2^2//3*(1+3^(1/2)))^-1*(t+2^2//3*(1+-1*3^(1/2)))),-7+-4*3^(1/2)))
@test integrate(tan(x)^2, x) == :(-1x+tan(x))
@test integrate(tan(x)^4, x) == :(x+-1*tan(x)+1//3*tan(x)^3)
@test integrate(cot(x)^2, x) == :(-1x+-1*cot(x))
@test integrate(cot(x)^4, x) == :(x+-1//3*cot(x)^3+cot(x))
@test integrate((2+3x)*sin(5x), x) == :(3//25*sin(5x)+(-2//5+-3//5*x)*cos(5x))
@test integrate(x*(1+x^2)^(1/2), x) == :(1//3*(1+x^2)^3//2)
@test integrate(x*(-1+x^2)^9, x) == :(1//20*(1+-1*x^2)^10)
@test integrate((7+6x)^-3*(3+2x), x) == :(-1//8*(3+2x)^2*(7+6x)^-2)
@test integrate(x^4*(1+x^5)^5, x) == :(1//30*(1+x^5)^6)
@test integrate(x^4*(1+-1x)^20, x) == :(-6//23*(1+-1x)^23+-1//21*(1+-1x)^21+-1//25*(1+-1x)^25+1//6*(1+-1x)^24+2//11*(1+-1x)^22)
@test integrate(x^-2*sin(x^-1), x) == :(cos(x^-1))
@test integrate(sin((-1+x)^1//4), x) == :(-24*sin((-1+x)^1//4)+-4*(-1+x)^3//4*cos((-1+x)^1//4)+12*(-1+x)^(1/2)*sin((-1+x)^1//4)+24*(-1+x)^1//4*cos((-1+x)^1//4))
@test integrate(x*cos(x^2)*sin(x^2), x) == :(1//4*sin(x^2)^2)
@test integrate((1+3*cos(x)^2)^(1/2)*sin(2x), x) == :(-2//9*(4+-3*sin(x)^2)^3//2)
@test integrate((2+3x)^-1, x) == :(1//3*log(2+3x))
@test integrate(log(x)^2, x) == :(2x+x*log(x)^2+-2*x*log(x))
@test integrate(x*log(x), x) == :(-1//4*x^2+(1/2)*x^2*log(x))
@test integrate(x*log(x)^2, x) == :(1//4*x^2+(1/2)*x^2*log(x)^2+-1//2*x^2*log(x))
@test integrate((1+t)^-1, t) == :(log(1+t))
@test integrate(cot(x), x) == :(log(sin(x)))
@test integrate(x^n*log(a*x), x) == :(-1*x^(1+n)*(1+n)^-2+x^(1+n)*(1+n)^-1*log(a*x))
@test integrate(x^2*log(x)^2, x) == :(2//27*x^3+-2//9*x^3*log(x)+1//3*x^3*log(x)^2)
@test integrate(x^-1*log(x)^-1, x) == :(log(log(x)))
@test integrate((1+-1t)^-1*log(1+-1t), t) == :(-1//2*log(1+-1t)^2)
@test integrate(x^-1*(1+log(x))^-1//2*log(x), x) == :(-2*(1+log(x))^(1/2)+2//3*(1+log(x))^3//2)
@test integrate(x^3*log(x)^3, x) == :(-3//128*x^4+-3//16*x^4*log(x)^2+1//4*x^4*log(x)^3+3//32*x^4*log(x))
@test integrate(x^2*exp(x^3), x) == :(1//3*exp(x^3))
@test integrate(2^(x^(1/2))*x^-1//2, x) == :(2^(1+x^(1/2))*log(2)^-1)
@test integrate(cos(x)*exp(2*sin(x)), x) == :((1/2)*exp(2*sin(x)))
@test integrate(exp(x)*sin(x), x) == :((1/2)*exp(x)*sin(x)+-1//2*cos(x)*exp(x))
@test integrate(cos(x)*exp(x), x) == :((1/2)*cos(x)*exp(x)+(1/2)*exp(x)*sin(x))
@test integrate((1+exp(x))^-1, x) == :(x+-1*log(1+exp(x)))
@test integrate(x*exp(x), x) == :(-1*exp(x)+x*exp(x))
@test integrate(x*exp(-1x), x) == :(-1*exp(-1x)+-1*x*exp(-1x))
@test integrate(x^2*exp(x), x) == :(2*exp(x)+x^2*exp(x)+-2*x*exp(x))
@test integrate(x^2*exp(-2x), x) == :(-1//4*exp(-2x)+-1//2*x*exp(-2x)+-1//2*x^2*exp(-2x))
@test integrate(exp(x^(1/2)), x) == :(-2*exp(x^(1/2))+2*x^(1/2)*exp(x^(1/2)))
@test integrate(x^3*exp(-1*x^2), x) == :(-1//2*exp(-1*x^2)+-1//2*x^2*exp(-1*x^2))
@test integrate(cos(b*x)*exp(a*x), x) == :(a*(a^2+b^2)^-1*cos(b*x)*exp(a*x)+b*(a^2+b^2)^-1*exp(a*x)*sin(b*x))
@test integrate(exp(a*x)*sin(b*x), x) == :(a*(a^2+b^2)^-1*exp(a*x)*sin(b*x)+-1*b*(a^2+b^2)^-1*cos(b*x)*exp(a*x))
@test integrate(arccot(x), x) == :((1/2)*log(1+x^2)+x*arccot(x))
@test integrate(arcsec(x), x) == :(-1*arctanh((1+-1*x^-2)^(1/2))+x*arcsec(x))
@test integrate(arccsc(x), x) == :(x*arccsc(x)+arctanh((1+-1*x^-2)^(1/2)))
@test integrate(arcsin(x)^2, x) == :(-2x+x*arcsin(x)^2+2*(1+-1*x^2)^(1/2)*arcsin(x))
@test integrate(x^-2*arcsin(x), x) == :(-1*arctanh((1+-1*x^2)^(1/2))+-1*x^-1*arcsin(x))
@test integrate((a^2+-1*x^2)^-1//2, x) == :(arctan(x*(a^2+-1*x^2)^-1//2))
@test integrate((1+-1*x^2+-2x)^-1//2, x) == :(arcsin((1/2)*2^(1/2)*(1+x)))
@test integrate((a^2+x^2)^-1, x) == :(a^-1*arctan(x*a^-1))
@test integrate((a+b*x^2)^-1, x) == :(a^-1//2*b^-1//2*arctan(x*a^-1//2*b^(1/2)))
@test integrate((2+x^2+-1x)^-1, x) == :(-2//7*7^(1/2)*arctan(1//7*7^(1/2)*(1+-2x)))
@test integrate(x*arctan(x), x) == :((1/2)*arctan(x)+-1//2*x+(1/2)*x^2*arctan(x))
@test integrate(x^2*arccos(x), x) == :(-1//3*(1+-1*x^2)^(1/2)+1//9*(1+-1*x^2)^3//2+1//3*x^3*arccos(x))
@test integrate(x*arctan(x)^2, x) == :((1/2)*arctan(x)^2+(1/2)*log(1+x^2)+(1/2)*x^2*arctan(x)^2+-1*x*arctan(x))
@test integrate(arctan(x^(1/2)), x) == :(-1*x^(1/2)+x*arctan(x^(1/2))+arctan(x^(1/2)))
@test integrate(x^-1//2*(1+x)^-1*arctan(x^(1/2)), x) == :(arctan(x^(1/2))^2)
@test integrate((1+-1*x^2)^(1/2), x) == :((1/2)*arcsin(x)+(1/2)*x*(1+-1*x^2)^(1/2))
@test integrate(x*(1+x^2)^-3//2*exp(arctan(x)), x) == :(-1//2*(1+x^2)^-1//2*(1+-1x)*exp(arctan(x)))
@test integrate((1+x^2)^-3//2*exp(arctan(x)), x) == :((1/2)*(1+x^2)^-1//2*(1+x)*exp(arctan(x)))
@test integrate(x^2*(1+x^2)^-2, x) == :((1/2)*arctan(x)+-1*x*(2+2*x^2)^-1)
@test integrate((1+exp(2x))^-1*exp(x), x) == :(arctan(exp(x)))
@test integrate(arccot(exp(x))*exp(-1x), x) == :((1/2)*log(1+exp(2x))+-1x+-1*arccot(exp(x))*exp(-1x))
@test integrate(((a+-1x)^-1*(a+x))^(1/2), x) == :(-1*((a+-1x)^-1*(a+x))^(1/2)*(a+-1x)+2*a*arctan(((a+-1x)^-1*(a+x))^(1/2)))
@test integrate(((b+-1x)*(x+-1a))^(1/2), x) == :((-1*x^2+x*(a+b)+-1*a*b)^(1/2)*((1/2)*x+-1//4*a+-1//4*b)+-1//8*(a+-1b)^2*arctan((1/2)*(-1*x^2+x*(a+b)+-1*a*b)^-1//2*(a+b+-2x)))
@test integrate(((b+-1x)*(x+-1a))^-1//2, x) == :(-1*arctan((1/2)*(-1*x^2+x*(a+b)+-1*a*b)^-1//2*(a+b+-2x)))
@test integrate((-3+x^2+2x)^-1*(3+5x), x) == :(2*log(1+-1x)+3*log(3+x))
@test integrate((-3+x^2+2x)^-1*(5+2x), x) == :(1//4*log(3+x)+7//4*log(1+-1x))
@test integrate((-3+x^2+-2x)^-1*(x^3+3x), x) == :((1/2)*x^2+2x+9*log(3+-1x)+log(1+x))
@test integrate((x^2+x^3+-2x)^-1*(-1+2*x^2+5x), x) == :((1/2)*log(x)+2*log(1+-1x)+-1//2*log(2+x))
@test integrate((1+x)^-2*(-1+x)^-1*(3+x^2+2x), x) == :((1+x)^-1+-1//2*log(1+x)+3//2*log(1+-1x))
@test integrate((-1+x^3)^-1*(-2+2x+3*x^2), x) == :(4//3*3^(1/2)*arctan(1//3*3^(1/2)*(1+2x))+log(1+-1*x^3))
@test integrate((-1+x)^-1*(2+x^2)^-2*(2+x^4+-1x+-1*x^3+2*x^2), x) == :((4+2*x^2)^-1+1//3*log(1+-1x)+1//3*log(2+x^2)+-1//6*2^(1/2)*arctan((1/2)*x*2^(1/2)))
@test integrate((cos(x)+sin(x))^-1, x) == :(-1//2*2^(1/2)*arctanh((1/2)*2^(1/2)*(-1*sin(x)+cos(x))))
@test integrate(x*(4+(4+-1*x^2)^(1/2)+-1*x^2)^-1, x) == :(-1*log(1+(4+-1*x^2)^(1/2)))
@test integrate((-2+x)^-1*(5+x)^-1*(3+2x), x) == :(log(2+-1x)+log(5+x))
@test integrate(x*(1+x)^-1*(2+x)^-1*(3+x)^-1, x) == :(2*log(2+x)+-3//2*log(3+x)+-1//2*log(1+x))
@test integrate(x*(2+x^3+-3x)^-1, x) == :((3+-3x)^-1+-2//9*log(2+x)+2//9*log(1+-1x))
@test integrate((x^2+x^3+-2x)^-1*(-6+x^4+2x), x) == :((1/2)*x^2+-1x+-1*log(1+-1x)+3*log(x)+log(2+x))
@test integrate((1+x)^-1*(1+2x)^-3*(7+8*x^3), x) == :(-3*(1+2x)^-2+3*(1+2x)^-1+log(1+x))
@test integrate((-1+x^3)^-1*(1+x+4*x^2), x) == :(2*log(1+-1x)+log(1+x+x^2))
@test integrate(x^4*(4+x^4+5*x^2)^-1, x) == :(x+-8//3*arctan((1/2)*x)+1//3*arctan(x))
@test integrate((x+x^2)^-1*(2+x), x) == :(-1*log(1+x)+2*log(x))
@test integrate(x^-1*(1+x^2)^-2, x) == :((2+2*x^2)^-1+-1//2*log(1+x^2)+log(x))
@test integrate((1+x)^-1*(2+x)^-2*(3+x)^-3, x) == :((2+x)^-1+2*log(2+x)+5*(12+4x)^-1+-17//8*log(3+x)+1//4*(3+x)^-2+1//8*log(1+x))
@test integrate(x*(1+x)^-2, x) == :((1+x)^-1+log(1+x))
@test integrate((x^3+-1x)^-1, x) == :((1/2)*log(1+-1*x^2)+-1*log(x))
@test integrate(x^2*(-6+x+x^2)^-1, x) == :(x+-9//5*log(3+x)+4//5*log(2+-1x))
@test integrate((4+x^2+-4x)^-1*(2+x), x) == :(4*(2+-1x)^-1+log(2+-1x))
@test integrate((4+x^2+-4x)^-1*(5+x^2+-4x)^-1, x) == :((2+-1x)^-1+arctan(2+-1x))
@test integrate((x^3+2x+3*x^2)^-1*(-3+x), x) == :(4*log(1+x)+-5//2*log(2+x)+-3//2*log(x))
@test integrate((-1+x^2)^-2, x) == :((1/2)*arctanh(x)+x*(2+-2*x^2)^-1)
@test integrate((-1+x^3)^-1*(1+x), x) == :(-1//3*log(1+x+x^2)+2//3*log(1+-1x))
@test integrate(x^-1*(1+x^2)^-2*(1+x^4), x) == :((1+x^2)^-1+log(x))
@test integrate((x^4+-2*x^3)^-1, x) == :(-1//8*log(x)+1//4*x^-1+1//4*x^-2+1//8*log(2+-1x))
@test integrate(x^-1*(1+x^2)^-1*(1+-1*x^3), x) == :(-1x+-1//2*log(1+x^2)+arctan(x)+log(x))
@test integrate((-1+x^4)^-1, x) == :(-1//2*arctan(x)+-1//2*arctanh(x))
@test integrate((1+x^4)^-1, x) == :(-1//4*2^(1/2)*arctan(1+-1*x*2^(1/2))+-1//8*2^(1/2)*log(1+x^2+-1*x*2^(1/2))+1//4*2^(1/2)*arctan(1+x*2^(1/2))+1//8*2^(1/2)*log(1+x^2+x*2^(1/2)))
@test integrate(x^2*(2+x^2+2x)^-2, x) == :(-1*x*(4+2*x^2+4x)^-1*(2+x)+arctan(1+x))
@test integrate((1+x+x^5)^-2*(-1+4*x^5), x) == :(-1*x*(1+x+x^5)^-1)
@test integrate((5+-1*cos(x)+2*sin(x))^-1, x) == :(1//5*5^(1/2)*arctan((5+-1*cos(x)+2*5^(1/2)+2*sin(x))^-1*(2*cos(x)+sin(x)))+1//10*x*5^(1/2))
@test integrate((1+a*cos(x))^-1, x) == :(2*(1+-1*a^2)^-1//2*arctan((1+a)^-1//2*(1+-1a)^(1/2)*tan((1/2)*x)))
@test integrate((1+2*cos(x))^-1, x) == :(-1//3*3^(1/2)*log(-1*sin((1/2)*x)+3^(1/2)*cos((1/2)*x))+1//3*3^(1/2)*log(3^(1/2)*cos((1/2)*x)+sin((1/2)*x)))
@test integrate((1+(1/2)*cos(x))^-1, x) == :(-4//3*3^(1/2)*arctan((2+3^(1/2)+cos(x))^-1*sin(x))+2//3*x*3^(1/2))
@test integrate((1+sin(x)^2)^-1*sin(x)^2, x) == :(x+-1//2*x*2^(1/2)+-1//2*2^(1/2)*arctan((1+2^(1/2)+sin(x)^2)^-1*cos(x)*sin(x)))
@test integrate((a^2*sin(x)^2+b^2*cos(x)^2)^-1, x) == :(a^-1*b^-1*arctan(a*b^-1*tan(x)))
@test integrate((a*sin(x)+b*cos(x))^-2, x) == :(b^-1*(a*sin(x)+b*cos(x))^-1*sin(x))
@test integrate((1+cos(x)+sin(x))^-1*sin(x), x) == :((1/2)*x+-1//2*log(1+tan((1/2)*x))+-1//2*log(1+cos(x)+sin(x)))
@test integrate((3+-1*x^2)^(1/2), x) == :(3//2*arcsin(1//3*x*3^(1/2))+(1/2)*x*(3+-1*x^2)^(1/2))
@test integrate(x*(3+-1*x^2)^-1//2, x) == :(-1*(3+-1*x^2)^(1/2))
@test integrate(x^-1*(3+-1*x^2)^(1/2), x) == :((3+-1*x^2)^(1/2)+-1*3^(1/2)*arctanh(1//3*3^(1/2)*(3+-1*x^2)^(1/2)))
@test integrate(x^-1*(x+x^2)^(1/2), x) == :((x+x^2)^(1/2)+arctanh(x*(x+x^2)^-1//2))
@test integrate((5+x^2)^(1/2), x) == :(5//2*arcsinh(1//5*x*5^(1/2))+(1/2)*x*(5+x^2)^(1/2))
@test integrate(x*(1+x+x^2)^-1//2, x) == :((1+x+x^2)^(1/2)+-1//2*arcsinh(1//3*3^(1/2)*(1+2x)))
@test integrate((x+x^2)^-1//2, x) == :(2*arctanh(x*(x+x^2)^-1//2))
@test integrate(x^-2*(2+-1x+-1*x^2)^(1/2), x) == :(-1*x^-1*(2+-1x+-1*x^2)^(1/2)+1//4*2^(1/2)*arctanh(1//4*2^(1/2)*(2+-1x+-1*x^2)^-1//2*(4+-1x))+arcsin(-1//3+-2//3*x))
@test integrate((1+t)^-1*log(t), t) == :(log(t)*log(1+t)+Polylogarithms.polylog(2,-1t))
@test integrate(log(exp(cos(x))), x) == :(x*log(exp(cos(x)))+-1*x*cos(x)+sin(x))
@test integrate(t^-1*exp(t), t) == :(expintegralei(t))
@test integrate(t^-1*exp(a*t), t) == :(expintegralei(a*t))
@test integrate(t^-2*exp(t), t) == :(-1*t^-1*exp(t)+expintegralei(t))
@test integrate(exp(t^-1), t) == :(-1*expintegralei(t^-1)+t*exp(t^-1))
@test integrate((-1+t+-1a)^-1*exp(-1t), t) == :(exp(-1+-1a)*expintegralei(1+a+-1t))
@test integrate(t*(1+t^2)^-1*exp(t^2), t) == :((1/2)*exp(-1)*expintegralei(1+t^2))
@test integrate((1+t)^-2*exp(t), t) == :(exp(-1)*expintegralei(1+t)+-1*(1+t)^-1*exp(t))
@test integrate(exp(t)*log(1+t), t) == :(exp(t)*log(1+t)+-1*exp(-1)*expintegralei(1+t))
@test integrate(t*exp(-1t), t) == :(-1*exp(-1t)+-1*t*exp(-1t))
@test integrate(t^2*exp(-1t), t) == :(-2*exp(-1t)+-1*t^2*exp(-1t)+-2*t*exp(-1t))
@test integrate(t^3*exp(-1t), t) == :(-6*exp(-1t)+-1*t^3*exp(-1t)+-6*t*exp(-1t)+-3*t^2*exp(-1t))
@test integrate((a*sin(x)+b*cos(x))^-1*(a1*sin(x)+b1*cos(x)), x) == :(x*(a^2+b^2)^-1*(a*a1+b*b1)+-1*(a^2+b^2)^-1*(a1*b+-1*a*b1)*log(a*sin(x)+b*cos(x)))
@test integrate(log(t)^-1, t) == :(logintegral(t))
@test integrate(log(t)^-2, t) == :(-1*t*log(t)^-1+logintegral(t))
@test integrate(log(t)^(-1+-1n), t) == :(-1*(-1*log(t))^n*log(t)^(-1n)*SpecialFunctions.gamma(-1n,-1*log(t)))
@test integrate((-1+t)^-1*exp(2t), t) == :(exp(2)*expintegralei(-2+2t))
@test integrate((2+x^2+-3x)^-1*exp(2x), x) == :(exp(4)*expintegralei(-4+2x)+-1*exp(2)*expintegralei(-2+2x))
@test integrate((1+t^3)^-1//2, t) == :(2//3*3^3//4*((1+t+3^(1/2))^-2*(1+t))^-1//2*((1+t+3^(1/2))^-2*(1+t^2+-1t))^(1/2)*(1+t^3)^-1//2*(2+3^(1/2))^(1/2)*(1+t)*Elliptic.F(arcsin((1+t+3^(1/2))^-1*(1+t+-1*3^(1/2))),-7+-4*3^(1/2)))

max_stars_repo_path: test/0 Independent test suites/Apostol Problems.jl


text:
###################################################
## network/iterative/greedy.jl
## Iterative state with fixed subse
###################################################

"""
    `GreedyEdges`, Iterative state optimizing on static trip list (subset of data)
    - each trip has a fixed max number of paths
    - Default number of paths per trip is infinite
    - Set of independent edges is updated at every iteration
"""
mutable struct GreedyEdges <: IterativeState
    # inherited attributes
    data::NetworkData
    timings::NetworkTimings
    trips::Vector{NetworkTrip}
    paths::Vector{Vector{Dict{Edge,Float64}}}  # for each trip, a vector of paths
    pathDiff::Float64

    "max number of paths per trip" #temporarily cannot be more than 1
    pathsPerTrip::Int64
    "independent edges"
    independent::Vector{Edge}
    "dependent edges"
    dependent::Vector{Edge}
    "original non-simplified paths"
    origPaths::Vector{Vector{Dict{Edge,Float64}}}
    "dependency matrix"
    dependencies::SparseMatrixCSC{Float64,Int}
    "edge map"
    edgeMap::Dict{Edge,Int}
    "number of edges to remove"
    numEdges::Int
    "number of iterations before removal"
    numIter::Int
    "minimum number of independent edges"
    minIndep::Int
    "state variable, remembers whether or not to update"
    state::Int
    "number of independent edges each dependent edge depends on"
    numDeps::Int
end

"""
    Creates initial fixed number of paths per trip state
    takes in NetworkData object, initial timings (as link times or full timings),
    and max number of paths per trip as integer
"""
function GreedyEdges(data::NetworkData, startSolution::NetworkTimings; pathsPerTrip::Int = typemax(Int), maxTrip::Int=1000, numEdges::Int = 10, numIter::Int = 3, minIndep::Int = 100, numDeps::Int = 3)
    if pathsPerTrip < 1
        error("Must have at least one path per trip")
    end
    # randomly select the trips
    Random.seed!(1991)
    trips = shuffle(data.trips)[1:min(maxTrip,length(data.trips))]
    # One path per trip: the initial shortest path
    paths = [Dict{Edge,Float64}[getFullPathEdges(t, startSolution)] for t in trips]
    println(typeof(paths))
    origPaths = [Dict{Edge,Float64}[getFullPathEdges(t, startSolution)] for t in trips]
    println(typeof(origPaths))
    independent = collect(edges(data.network.graph))
    dependent = Edge[]
    dependencies, edgeMap = findNetworkDependence(data.network, independent, dependent, numDeps = numDeps)
    return GreedyEdges(data,startSolution,trips,paths,Inf,pathsPerTrip,independent, dependent,origPaths,dependencies,edgeMap,numEdges, numIter, minIndep, 0, numDeps)
end

GreedyEdges(data::NetworkData, initTimes::AbstractArray{Float64, 2}; args...) =
    GreedyEdges(data, NetworkTimings(data.network, initTimes); args...)

"""
    Update paths of GreedyEdges object given new times
"""
function updateState!(s::GreedyEdges, times::AbstractArray{Float64, 2})
    # update state variable
    s.state += 1
    # update the timings and compute shortest paths
    newTimes = evaluateTimes(s.data.network, s.dependencies, times, s.independent, s.edgeMap)
    s.timings = NetworkTimings(s.data.network, newTimes)
    # update independent set and dependencies if necessary
    if s.state == s.numIter
        s.independent, s.dependent = updateIndependentEdges(s.paths, s.independent, s.dependent, s.numEdges, s.minIndep)
        s.dependencies, s.edgeMap = findNetworkDependence(s.data.network, s.independent, s.dependent, numDeps = s.numDeps)
        s.state = 0
        origPaths = [Dict{Edge,Float64}[getFullPathEdges(t, s.timings)] for t in s.trips]
        s.pathDiff = sum([length(symdiff(collect(keys(origPaths[d][1])), collect(keys(s.origPaths[d][1])))) for d=eachindex(s.trips)])/(2 * length(s.trips))
        s.origPaths = origPaths
    else
        s.pathDiff = 0.
        # update paths normally
        for (d,t) in enumerate(s.trips)
            sp = getFullPathEdges(t, s.timings)
            s.pathDiff += length(symdiff(collect(keys(sp)), collect(keys(s.origPaths[d][1]))))/2
            if s.pathsPerTrip == 1
                s.origPaths[d][1] = sp
            else
                index = findfirst(isequal(sp), s.origPaths[d])
                if index != nothing   # if so, put it in first position
                    s.origPaths[d][index], s.origPaths[d][1] = s.origPaths[d][1], s.origPaths[d][index] #swap
                elseif length(s.origPaths[d]) < s.pathsPerTrip # if not, and if enough room to add, add it in first position
                    pushfirst!(s.origPaths[d], sp)
                else        # replace least useful path
                    worstIndex = argmax([pathEdgesTime(s.timings, collect(keys(p))) for p in s.paths[d]])
                    s.origPaths[d][worstIndex] = s.origPaths[d][1]
                    s.origPaths[d][1] = sp
                end
            end
        end
        s.pathDiff /= length(s.trips)
    end
    s.paths = [[simplifyPath(p, s.independent, s.dependencies, s.edgeMap) for p in s.origPaths[d]] for d = eachindex(s.trips)]
end


text:
#=
  Copyright (c) 2021
  https://github.com/Ismael-VC/Varvara.jl/blob/main/CONTRIBUTORS.md

  Permission to use, copy, modify, and distribute this software for any
  purpose with or without fee is hereby granted, provided that the above
  copyright notice and this permission notice appear in all copies.

  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE.
=#

module UxnREPL

using ..Uxn: CPU
using ..VarvaraOS: uxn_boot

using ReplMaker: initrepl

#! format: off

function uxntal_repl_v1(s)
  c = CPU()
  address = c.ram.
  open("snarf.tmp", "w") do f
    ss = "|10 @Console [ &vector \$2 &read \$1 &pad \$5 &write \$1 &error \$1 ]" *
         " %EMIT { .Console/write DEO } %NL { #0a EMIT } |0100 " * s
    write(f, ss)
  end
  @info "file saved"
  read(`uxnasm snarf.tmp snarf.rom`)
  push!(ARGS, "snarf.rom")
  uxn_boot(c)
  c
end

if isdefined(Base, :active_repl)
  try
    initrepl(
      uxntal_repl_v1,
      prompt_text = "uxntal> ",
      prompt_color = :blue,
      start_key = ')',
      mode_name = "Uxntal"
    )
  catch e
    @show e
  end
end

#! format: on

end  # module


text:
import GitHub

auth = GitHub.authenticate(ENV["GITHUB_AUTH"])
repo = "JuliaLang/julia"
sha = GitHub.branch(repo, "master").commit.sha

message = """
          Executing the daily benchmark build, I will reply here when finished:

          @nanosoldier `runbenchmarks(ALL, isdaily = true)`
          """
GitHub.create_comment(repo, sha, :commit, auth=auth, params=Dict("body" => message))

message = """
          Executing the daily package evaluation, I will reply here when finished:

          @nanosoldier `runtests(ALL, isdaily = true)`
          """
GitHub.create_comment(repo, sha, :commit, auth=auth, params=Dict("body" => message))


text:
#!/opt/julia/bin/julia
using DataHandlers
using Documenter

makedocs()

# copy the resulting document to the README
fname = joinpath("build", "README.md")
if isfile(fname)
    info("Updating README...")
    cp(fname, joinpath("..", "README.md"), remove_destination=true)
end


text:
import Knet.Ops20: nll, accuracy
using Knet.KnetArrays: DevArray, KnetArray
using Knet.Ops20: findindices, logsoftmax

## Using GPU arrays for scores is inefficient

function nll(scores, labels::DevArray{<:Integer}; dims=1, average=true)
    @warn "nll(scores, answers::$(typeof(labels)) is inefficient, nll(scores, answers::Array{<:Integer}) is better." maxlog=1
    nll(scores, Array(labels); dims=dims, average=average)
end

function accuracy(scores, labels::DevArray{<:Integer}; dims=1, average=true)
    @warn "accuracy(scores, answers::$(typeof(labels)) is inefficient, nll(scores, answers::Array{<:Integer}) is better." maxlog=1
    accuracy(scores, Array(labels); dims=dims, average=average)
end


text:
using ClimateModels
using Test

@testset "ClimateModels.jl" begin
    (mm,gm,meta)=cmip()
    @test isapprox(gm["y"][end],285.71875)
end


text:
using Printf

function reportMinMax(varName::String,modelName::String,sol)
    y_min = findmin(sol.u)[1][1]
    t_min = sol.t[findmin(sol.u)[2]]
    y_max = findmax(sol.u)[1][1]
    t_max = sol.t[findmax(sol.u)[2]]
    print("$(varName): $(modelName)\n")
    print("var\ttime\tvalue\n")
    print("min\t$(t_min)\t$(y_min)\n")
    print("max\t$(t_max)\t$(y_max)\n\n")
    return y_min, t_min, y_max, t_max
end

function errorCheck(measured, predicted)
    error_abs = measured-predicted
    error_rel = (measured-predicted)/measured

    println("Measured\tPredicted\tM-P\t\t(M-P)/M")
    @printf("%.2e\t%.2e\t%.2e\t%.2e\n\n",measured,predicted,error_abs,error_rel)
end


text:
function lambda_arg_types(f::Function)
    [var for var in code_lowered(f)[1].specTypes.types[2:end]]
end

# Simple properties
function property(prop::Function, typs::Vector, ntests)
    arggens = [size -> generator(typ, size) for typ in typs]
    quantproperty(prop, typs, ntests, arggens...)
end
property(prop::Function, typs::Vector) = property(prop, typs, 100)
property(prop::Function, ntests) = property(prop, lambda_arg_types(prop), ntests)
property(prop::Function) = property(prop, 100)

# Conditional properties
function condproperty(prop::Function, typs::Vector, ntests, maxtests, argconds...)
    arggens = [size -> generator(typ, size) for typ in typs]
    check_property(prop, arggens, argconds, ntests, maxtests)
end
condproperty(prop::Function, args...) = condproperty(prop, lambda_arg_types(prop), args...)

# Quantified properties (custom generators)
function quantproperty(prop::Function, typs::Vector, ntests, arggens...)
    argconds = [(_...)->true for t in typs]
    check_property(prop, arggens, argconds, ntests, ntests)
end
quantproperty(prop::Function, args...) = quantproperty(prop, lambda_arg_types(prop), args...)

function check_property(prop::Function, arggens, argconds, ntests, maxtests)
    totalTests = 0
	counterexamples = false
    for i in 1:ntests
        goodargs = false
        args = []
        while !goodargs
            totalTests += 1
            if totalTests > maxtests
                println("Arguments exhausted after $i tests.")
                return
            end
            args = [arggen(div(i,2)+3) for arggen in arggens]
            goodargs = reduce(&,[cond(args...) for cond in argconds])
        end
        if !prop(args...)
		println("Falsifiable, after $i tests:\n$args")
		counterexamples = true
		return false
            #error("Falsifiable, after $i tests:\n$args")
        end
    end
	if !counterexamples
	    println("OK, passed $ntests tests.")
	return true
	end
end

function check_existence(prop::Function, arggens, argconds, ntests, maxtests)
    totalTests = 0
	findings = false
    for i in 1:ntests
        goodargs = false
        args = []
        while !goodargs
            totalTests += 1
            if totalTests > maxtests
                println("Arguments exhausted after $i tests.")
                return
            end
            args = [arggen(div(i,2)+3) for arggen in arggens]
            goodargs = reduce(&,[cond(args...) for cond in argconds])
        end
        if prop(args...)
            println("Found necessary value after $i tests:\n$args")
            findings = true
	     return true #break
        end
    end
     if !findings
		println("Could not prove existence after $ntests tests.")
		return false
	end
end

# Default generators for primitive types
generator{T<:Unsigned}(::Type{T}, size) = convert(T, rand(1:size))
generator{T<:Signed}(::Type{T}, size) = convert(T, rand(-size:size))
# Fima: replaced .* with * in the next line (was it typo?)
generator{T<:AbstractFloat}(::Type{T}, size) = convert(T, (rand()-0.5)*size)
# This won't generate interesting UTF-8, but doing that is a Hard Problem
generator{T<:AbstractString}(::Type{T}, size) = convert(T, randstring(size))

generator(::Type{Any}, size) = error("Property variables cannot by typed Any.")

# Generator for array types
function generator{T,n}(::Type{Array{T,n}}, size)
    dims = [rand(1:size) for i in 1:n]
    reshape([generator(T, size) for x in 1:prod(dims)], dims...)
end

# Generator for composite types
function generator{C}(::Type{C}, size)
    if C.types == ()
        error("No generator defined for type $C.")
    end
    C([generator(T, size) for T in C.types]...)
end

macro not(b)
	return :(!$b)
end


text:
"""
kagome lattice的相关功能
"""

module Kagome

using ..Fermi

export upperband_kagome_lattice
export wuxx_av3sb5_kagome_lattice
#export upperband_kagome_lattice2
export get_kagome_ν, get_kagome_U_mt
export get_wuxx_U_mt

"""
上面那个能带
"""
macro upperband(kx, ky)
    return esc(quote
        xval = $kx / 4
        yval = √3 * ($ky) / 4
        sqr = 2 * cos(2*xval - 2*yval)
        sqr += 2 * cos(2*xval + 2*yval)
        sqr += 2 * cos(4*xval) + 3
        if sqr < 0
            sqr = 0
        end
        eng = - 1 + sqrt(sqr)
    end)
end

"""
下面那个能带
"""
macro lowerband(kx, ky)
    return esc(quote
        xval = $kx / 4
        yval = √3 * ($ky) / 4
        sqr = 2 * cos(2*xval - 2*yval)
        sqr += 2 * cos(2*xval + 2*yval)
        sqr += 2 * cos(4*xval) + 3
        if sqr < 0
            sqr = 0
        end
        eng = - 1 - sqrt(sqr)
    end)
end

"""
上半个能带的kagome lattice
"""
function upperband_kagome_lattice(μ)
    disp(x, y) = (@upperband x y) + μ
    return TriangularSystem{:KAGOME}(
        [disp]
    )
end

"""
两个能带的A V_3 Sb_5
"""
function wuxx_av3sb5_kagome_lattice()
    disp1(x, y) = 0.5*(@upperband x y) - 0.055
    disp2(x, y) = (@lowerband x y) + 2.182
    return TriangularSystem{:WUXX}(
        [disp1, disp2]
    )
end

"""
获取nu变换的矩阵
"""
function get_kagome_ν(kx, ky)
    if kx == 0. && ky == 0.
        kx = 1e-10
        ky = -1e-10
    end
    x::BigFloat = kx / BigFloat(4)
    y::BigFloat = BigFloat(√3) * ky / BigFloat(4)
    sqr::BigFloat = 2 * cos(2*x - 2*y)
    sqr::BigFloat += 2 * cos(2*x + 2*y)
    sqr::BigFloat += 2 * cos(4*x) + 3
    if sqr < 0
        sqr = 0
    end
    #第一组
    nu1::Vector{BigFloat} = zeros(BigFloat, 3)
    nu1[1] = -cos(2*x)/2 + cos(2*y)/2
    nu1[2] = -cos(x-y)/2 + cos(3*x+y)/2
    nu1[3] = 1 - cos(x+y)^2
    #归一化
    n1 = nu1[1]^2 + nu1[2]^2 + nu1[3]^2
    n1 = 1.0 / sqrt(n1)
    #println(nu1)
    nu1 = n1 * nu1
    #println(nu1)
    #println("=======")
    #
    nu2::Vector{BigFloat} = zeros(BigFloat, 3)
    #第二组本征态
    lamb2::BigFloat = 1 - sqrt(sqr)
    nu2[1] = 0.5*(lamb2^2) - 2*(cos(x-y)^2)
    nu2[2] = 2*cos(2*x)*cos(x-y) + cos(x+y)*lamb2
    nu2[3] = cos(2*x)*lamb2 + 2*cos(x-y)*cos(x+y)
    #归一化
    #println(nu2)
    n2 = nu2[1]^2 + nu2[2]^2 + nu2[3]^2
    n2 = 1.0 / sqrt(n2)
    nu2 = n2 * nu2
    #println(nu2)
    #println("**********")
    #
    nu3::Vector{BigFloat} = zeros(BigFloat, 3)
    #第三组本征态
    lamb3::BigFloat = 1 + sqrt(sqr)
    nu3[1] = 0.5*(lamb3^2) - 2*(cos(x-y)^2)
    nu3[2] = 2*cos(2*x)*cos(x-y) + cos(x+y)*lamb3
    nu3[3] = cos(2*x)*lamb3 + 2*cos(x-y)*cos(x+y)
    #归一化
    #println(nu3)
    n3 = nu3[1]^2 + nu3[2]^2 + nu3[3]^2
    n3 = 1.0 / sqrt(n3)
    nu3 = n3 * nu3
    #println(nu3)
    #println("~~~~~~~~")
    return nu1, nu2, nu3
end

"""
获取相互作用在能带下的表示
"""
function get_kagome_U_mt(uval, pinfos)
    npat = length(pinfos)
    ret = zeros(npat, npat, npat)
    @Threads.threads for idxs in CartesianIndices(ret)
        k1i, k2i, k3i = Tuple(idxs)
        k1v = pinfos[k1i]
        k2v = pinfos[k2i]
        k3v = pinfos[k3i]
        k4v = Fermi.hexagon_kadd2(k1v, k2v)
        k4v = Fermi.hexagon_kadd2(k4v, -k3v)
        #p这个带只需要第二个
        _, k1nu, _ = get_kagome_ν(k1v.x, k1v.y)
        _, k2nu, _ = get_kagome_ν(k2v.x, k2v.y)
        _, k3nu, _ = get_kagome_ν(k3v.x, k3v.y)
        _, k4nu, _ = get_kagome_ν(k4v.x, k4v.y)
        #计算数值
        for sidx in 1:1:3
            ret[k1i, k2i, k3i] += uval * k1nu[sidx] *
            k2nu[sidx] * k3nu[sidx] * k4nu[sidx]
        end
    end
    return ret
end

"""
获取A V_3 Sb_5相互作用在能带下的表示
"""
function get_wuxx_U_mt(u1val, u2val, upval, pinfos1, pinfos2)
    npat = length(pinfos1)
    if length(pinfos2) != npat
        throw(error("pat数量对不上"))
    end
    #
    ret = zeros(2, 2, 2, 2, npat, npat, npat)
    place_holder = Array{Int8, 3}(undef, npat, npat, npat)
    #能带内的相互作用
    #第一条能带是靠上的能带
    @Threads.threads for idxs in CartesianIndices(place_holder)
        k1i, k2i, k3i = Tuple(idxs)
        k1v = pinfos1[k1i]
        k2v = pinfos1[k2i]
        k3v = pinfos1[k3i]
        k4v = Fermi.hexagon_kadd2(k1v, k2v)
        k4v = Fermi.hexagon_kadd2(k4v, -k3v)
        #p这个带只需要第二个
        _, k1nu, _ = get_kagome_ν(k1v.x, k1v.y)
        _, k2nu, _ = get_kagome_ν(k2v.x, k2v.y)
        _, k3nu, _ = get_kagome_ν(k3v.x, k3v.y)
        _, k4nu, _ = get_kagome_ν(k4v.x, k4v.y)
        #计算数值
        for sidx in 1:1:3
            ret[1, 1, 1, 1, k1i, k2i, k3i] += u1val * k1nu[sidx] *
            k2nu[sidx] * k3nu[sidx] * k4nu[sidx]
        end
    end
    #第二条是靠下的能带
    @Threads.threads for idxs in CartesianIndices(place_holder)
        k1i, k2i, k3i = Tuple(idxs)
        k1v = pinfos2[k1i]
        k2v = pinfos2[k2i]
        k3v = pinfos2[k3i]
        k4v = Fermi.hexagon_kadd2(k1v, k2v)
        k4v = Fermi.hexagon_kadd2(k4v, -k3v)
        #d这个带只需要第三个
        _, _, k1nu = get_kagome_ν(k1v.x, k1v.y)
        _, _, k2nu = get_kagome_ν(k2v.x, k2v.y)
        _, _, k3nu = get_kagome_ν(k3v.x, k3v.y)
        _, _, k4nu = get_kagome_ν(k4v.x, k4v.y)
        #计算数值
        for sidx in 1:1:3
            ret[2, 2, 2, 2, k1i, k2i, k3i] += u2val * k1nu[sidx] *
            k2nu[sidx] * k3nu[sidx] * k4nu[sidx]
        end
    end
    #能带之间的相互作用
    @Threads.threads for idxs in CartesianIndices(place_holder)
        k1i, k2i, k3i = Tuple(idxs)
        #第一个能带的patches
        k1v1 = pinfos1[k1i]
        k2v1 = pinfos1[k2i]
        k3v1 = pinfos1[k3i]
        k4v1 = Fermi.hexagon_kadd2(k1v1, k2v1)
        k4v1 = Fermi.hexagon_kadd2(k4v1, -k3v1)
        #第一个能带的系数
        _, k11nu, _ = get_kagome_ν(k1v1.x, k1v1.y)
        _, k21nu, _ = get_kagome_ν(k2v1.x, k2v1.y)
        _, k31nu, _ = get_kagome_ν(k3v1.x, k3v1.y)
        _, k41nu, _ = get_kagome_ν(k4v1.x, k4v1.y)
        #第二个能带的patches
        k1v2 = pinfos2[k1i]
        k2v2 = pinfos2[k2i]
        k3v2 = pinfos2[k3i]
        k4v2 = Fermi.hexagon_kadd2(k1v2, k2v2)
        k4v2 = Fermi.hexagon_kadd2(k4v2, -k3v2)
        #第二个能带的系数
        _, _, k12nu = get_kagome_ν(k1v2.x, k1v2.y)
        _, _, k22nu = get_kagome_ν(k2v2.x, k2v2.y)
        _, _, k32nu = get_kagome_ν(k3v2.x, k3v2.y)
        _, _, k42nu = get_kagome_ν(k4v2.x, k4v2.y)
        #计算数值
        #对于同能带U来说，自旋的求和up，dn和dn，up重复两次，再除2，正好一倍
        #对于不同能带U来说，自旋求和本来就有，能带指标1221,2112的重复刚好和除2抵消。
        for sidx in 1:1:3
            ret[1, 2, 2, 1, k1i, k2i, k3i] += upval * k11nu[sidx] *
            k22nu[sidx] * k32nu[sidx] * k41nu[sidx]
            ret[2, 1, 1, 2, k1i, k2i, k3i] += upval * k12nu[sidx] *
            k21nu[sidx] * k31nu[sidx] * k42nu[sidx]
        end
    end
    return ret
end

end # end module


text:
#################
# Magic Methods #
#################

# TODO: Implement magic methods

# Assume that this is mutating
# function Base.getproperty(fut::Future, sym::Symbol)
# end

# Mutating
# TODO: put this back in some way
# function Base.setproperty!(fut::Future, sym::Symbol, new_value)
# end

#############################
# Basic methods for futures #
#############################

function partitioned_computation(fut::AbstractFuture; destination, new_source=nothing)
    if isview(fut)
        error("Computing a view (such as a GroupedDataFrame) is not currently supported")
    end

    # NOTE: Right now, `compute` wil generally spill to disk (or write to some
    # remote location or download to the client). It will not just persist data
    # in memory. In Spark or Dask, it is recommended that you call persist or
    # compute or something like that in order to cache data in memory and then
    # ensure it stays there as you do logistic regression or some iterative
    # computation like that. With an iterative computation like logistic
    # regression in Banyan, you would only call `compute` on the result and we
    # would be using a same future for each iteration. Each iteration would
    # correspond to a separate stage with casting happening between them. And
    # the scheduler would try as hard as possible to keep the whole thing in
    # memory. This is because unlike Dask, we allow a Future to be reused
    # across tasks. If we need `compute` to only evaluate and persist in-memory
    # we should modify the way we schedule the final merging stage to not
    # require the last value to be merged simply because it is being evaluated.

    global jobs

    fut = convert(Future, fut)
    job_id = get_job_id()
    job = get_job()

    if fut.mutated || (destination.dst_name == "Client" && fut.stale) || destination.dst_name == "Remote"
        # TODO: Check to ensure that `fut` is annotated
        # This creates an empty final task that ensures that the future
        # will be scheduled to get sent to its destination.
        destined(fut, destination)
        mutated(fut)
        @partitioned fut begin end

        # Get all tasks to be recorded in this call to `compute`
        tasks = [req.task for req in job.pending_requests if req isa RecordTaskRequest]

        # Call `partitioned_using_func`s in 2 passes - forwards and backwards.
        # This allows sample properties to propagate in both directions. We
        # must also make sure to apply mutations in each task appropriately.
        for t in Iterators.reverse(tasks)
            apply_mutation(invert(t.mutation))
        end
        for t in tasks
            if !isnothing(t.partitioned_using_func)
                t.partitioned_using_func()
            end
            apply_mutation(t.mutation)
        end
        for t in Iterators.reverse(tasks)
            apply_mutation(invert(t.mutation))
            if !isnothing(t.partitioned_using_func)
                t.partitioned_using_func()
            end
        end

        # Do further processing on tasks now that all samples have been
        # computed and sample properties have been set up to share references
        # as needed to prevent expensive redundant computation of sample
        # properties like divisions
        for (i, t) in enumerate(tasks)
            apply_mutation(t.mutation)

            # Call `partitioned_with_func` to create additional PAs for each task
            set_task(t)
            if !isnothing(t.partitioned_with_func)
                t.partitioned_with_func()
            end

            # Cascade PAs backwards. In other words, if as we go from first to
            # last PA we come across one that's annotating a value not
            # annotated in a previous PA, we copy over the annotation (the
            # assigned PT stack) to the previous PA.
            for (j, pa) in enumerate(t.pa_union)
                # For each PA in this PA union for this task, we consider the
                # PAs before it
                for previous_pa in Iterators.reverse(t.pa_union[1:j-1])
                    for value_id in keys(pa.partitions.pt_stacks)
                        # Check if there is a previous PA where this value
                        # does not have a PT.
                        if !(value_id in keys(previous_pa.partitions.pt_stacks))
                            # Cascade the PT composition backwards
                            previous_pa.partitions.pt_stacks[value_id] =
                                deepcopy(pa.partitions.pt_stacks[value_id])

                            # Cascade backwards all constraints that mention the
                            # value. NOTE: If this is not desired, users should
                            # be explicit and assign different PT compositions for
                            # different values.
                            for constraint in pa.constraints.constraints
                                # Determine whether we should copy over this constraint
                                copy_constraint = false
                                if constraint isa PartitioningConstraintOverGroup
                                    for arg in constraint.args
                                        if arg isa PartitionTypeReference && first(arg) == value_id
                                            copy_constraint = true
                                        end
                                    end
                                elseif constraint isa PartitioningConstraintOverGroups
                                    for arg in constraint.args
                                        for subarg in arg
                                            if subarg isa PartitionTypeReference && first(subarg) == value_id
                                                copy_constraint = true
                                            end
                                        end
                                    end
                                end

                                # Copy over constraint
                                if copy_constraint
                                    push!(previous_pa.constraints.constraints, deepcopy(constraint))
                                end
                            end
                        end
                    end
                end
            end
        end

        # Switch back to a new task for next code region
        finish_task()

        # Iterate through tasks for further processing before recording them
        for t in tasks
            # Apply defaults to PAs
            for pa in t.pa_union
                apply_default_constraints!(pa)
                duplicate_for_batching!(pa)
            end

            # Destroy all closures so that all references to `Future`s are dropped
            t.partitioned_using_func = nothing
            t.partitioned_with_func = nothing

            # Handle
            empty!(t.mutation) # Drop references to `Future`s here as well
        end

        # Finalize (destroy) all `Future`s that can be destroyed
        GC.gc()

        # Destroy everything that is to be destroyed in this task
        for req in job.pending_requests
            # Don't destroy stuff where a `DestroyRequest` was produced just
            # because of a `mutated(old, new)`
            if req isa DestroyRequest && !any(req.value_id in values(t.mutation) for t in tasks)
                # If this value was to be downloaded to or uploaded from the
                # client side, delete the reference to its data. We do the
                # `GC.gc()` before this and store `futures_on_client` in a
                # `WeakKeyDict` just so that we can ensure that we can actually
                # garbage-collect a value if it's done and only keep it around if
                # a later call to `collect` it may happen and in that call to
                # `collect` we will be using `partitioned_computation` to
                # communicate with the executor and fill in the value for that
                # future as needed and then return `the_future.value`.
                if req.value_id in keys(job.futures_on_client)
                    delete!(job.futures_on_client, req.value_id)
                end

                # Remove information about the value's location including the
                # sample taken from it
                delete!(job.locations, req.value_id)
            end
        end

        # Send evaluation request
        is_merged_to_disk = false
        try
            response = send_evaluation(fut.value_id, job_id)
            is_merged_to_disk = response["is_merged_to_disk"]
        catch
            destroy_job(failed=true)
            rethrow()
        end

        # Get queues for moving data between client and cluster
        scatter_queue = get_scatter_queue(job_id)
        gather_queue = get_gather_queue(job_id)

        # Read instructions from gather queue
        # @info "Computing result with ID $(fut.value_id)"
        @debug "Waiting on running job $job_id, listening on $gather_queue, and computing value with ID $(fut.value_id)"
        p = ProgressUnknown("Computing value with ID $(fut.value_id)", spinner=true)
        if get_job_status(job_id) != "running"
            wait_for_job(job_id)
        end
        while true
            # TODO: Use to_jl_value and from_jl_value to support Client
            message = receive_next_message(gather_queue, p)
            message_type = message["kind"]
            if message_type == "JOB_READY"
                # @debug "Job $job_id is ready"
            elseif message_type == "SCATTER_REQUEST"
                # Send scatter
                value_id = message["value_id"]
                f = job.futures_on_client[value_id]
                # @debug "Received scatter request for value with ID $value_id and value $(f.value) with location $(get_location(f))"
                send_message(
                    scatter_queue,
                    JSON.json(
                        Dict{String,Any}(
                            "value_id" => value_id,
                            "contents" => to_jl_value_contents(f.value)
                        ),
                    ),
                )
                # sourced(f, None())
                # TODO: Update stale/mutated here to avoid costly
                # call to `send_evaluation`
            elseif message_type == "GATHER"
                # Receive gather
                value_id = message["value_id"]
                # @debug "Received gather request for $value_id"
                if value_id in keys(job.futures_on_client)
                    value = from_jl_value_contents(message["contents"])
                    f::Future = job.futures_on_client[value_id]
                    f.value = value
                    # @debug "Received $(f.value)"
                    # TODO: Update stale/mutated here to avoid costly
                    # call to `send_evaluation`
                end
            elseif message_type == "EVALUATION_END"
                # @debug "End of evaluation"
                if message["end"] == true
                    break
                end
            end
        end

        # Update `mutated` and `stale` for the future that is being evaluated
        fut.mutated = false
        # TODO: See if there are more cases where you a `compute` call on a future
        # makes it no longer stale
        if get_dst_name(fut) == "Client"
            fut.stale = false
        end

        # This is where we update the location source.
        if is_merged_to_disk
            sourced(fut, Disk())
        else
            # TODO: If not still merged to disk, we need to lazily set the location source to something else
            if !isnothing(new_source)
                sourced(fut, new_source)
            else
                # TODO: Maybe suppress this warning because while it may be
                # useful for large datasets, it is going to come up for
                # every aggregateion result value that doesn't have a source
                # but is being computed with the Client as its location.
                if destination.src_name == "None"
                    # It is not guaranteed that this data can be used again.
                    # In fact, this data - or rather, this value - can only be
                    # used again if it is in memory. But because it is up to
                    # the schedule to determine whether it is possible for the
                    # data to fit in memory, we can't be sure that it will be
                    # in memory. So this data should have first been written to
                    # disk with `write_to_disk` and then only written to this
                    # unreadable location.
                    @warn "Value with ID $(fut.value_id) has been written to a location that cannot be used as a source and it is not on disk. Please do not attempt to use this value again. If you wish to use it again, please write it to disk with `write_to_disk` before writing it to a location."
                end
                sourced(fut, destination)
            end
        end

        # Reset the location destination to its default. This is where we
        # update the location destination.
        destined(fut, None())
    end

    # Reset the annotation for this partitioned computation
    set_task(DelayedTask())

    # NOTE: One potential room for optimization is around the fact that
    # whenever we compute something we fully merge it. In fully merging it,
    # we spill it out of memory. Maybe it might be kept in memory and we don't
    # need to set the new source of something being `collect`ed to `Client`.

    fut
end

# Scheduling options
report_schedule = false
encourage_parallelism = false
encourage_parallelism_with_batches = false
exaggurate_size = false

function configure_scheduling(;kwargs...)
    global report_schedule
    global encourage_parallelism
    global encourage_parallelism_with_batches
    global exaggurate_size
    report_schedule = get(kwargs, :report_schedule, false) || haskey(kwargs, :name)
    if get(kwargs, :encourage_parallelism, false) || get(kwargs, :name, "") == "parallelism encouraged"
        encourage_parallelism = true
    end
    if haskey(kwargs, :encourage_parallelism_with_batches) || get(kwargs, :name, "") == "parallelism and batches encouraged"
        encourage_parallelism = true
        encourage_parallelism_with_batches = true
    end
    if get(kwargs, :exaggurate_size, false) || get(kwargs, :name, "") == "size exaggurated"
        exaggurate_size = true
    end
end

function send_evaluation(value_id::ValueId, job_id::JobId)
    global encourage_parallelism
    global encourage_parallelism_with_batches
    global exaggurate_size

    # Note that we do not need to check if the job is running here, because
    # `evaluate` will check if the job has failed. If the job is still creating,
    # we will proceed with the eval request, but the client side will wait
    # for the job to be ready when reading from the queue.

    @debug "Sending evaluation request"

    # Get list of the modules used in the code regions here
    used_packages = union(vcat([req.task.used_modules for req in get_job().pending_requests if req isa RecordTaskRequest]...))

    # Submit evaluation request
    response = send_request_get_response(
        :evaluate,
        Dict{String,Any}(
            "value_id" => value_id,
            "job_id" => job_id,
            "requests" => [to_jl(req) for req in get_job().pending_requests],
            "options" => Dict(
                "report_schedule" => report_schedule,
                "encourage_parallelism" => encourage_parallelism,
                "encourage_parallelism_with_batches" => encourage_parallelism_with_batches,
                "exaggurate_size" => exaggurate_size
            ),
            "num_bang_values_issued" => get_num_bang_values_issued(),
            "main_modules" => get_loaded_packages(),
            "partitioned_using_modules" => used_packages,
            "benchmark" => get(ENV, "BANYAN_BENCHMARK", "0") == "1"
        ),
    )
    if isnothing(response)
        throw(ErrorException("The evaluation request has failed. Please contact support"))
    end

    # Update counters for generating unique values
    set_num_bang_values_issued(response["num_bang_values_issued"])

    # Clear global state and return response
    empty!(get_job().pending_requests)
    response
end

function Base.collect(fut::AbstractFuture)
    fut = convert(Future, fut)

    # NOTE: We might be in the middle of an annotation when this is called so
    # we need to avoid partitioned computation (which will reset the task)

    # # Fast case for where the future has not been mutated and isn't stale
    if !fut.mutated && !fut.stale
        return fut.value
    end

    # # This function collects the given future on the client side

    # # NOTE: If the value was already replicated and has never been written to disk, then this
    # # might send it to the client and never allow the value to be used again since it hasn't been saved.
    # # By computing it now, we can ensure that its saved to disk. This is one of the things we should address when we
    # # clean up locations.
    # compute(fut)

    # # Set the future's destination location to Client
    # destined(fut, Client())
    # mutated(fut)

    # pt(fut, Replicated())
    # @partitioned fut begin
    #     # This code region is empty but it ensures that something is run
    #     # and so the data is partitioned and then re-merged back up to its new
    #     # destination location, the client
    # end

    # # Evaluate the future so that its value is downloaded to the client
    # compute(fut)
    # destined(fut, None())
    # @show fut.value
    # fut.value

    # We don't need to specify a `source_after` since it should just be
    # `Client()` and the sample won't change at all. Also, we should already
    # have a sample since we are merging it to the client.

    pt(fut, Replicated())
    partitioned_computation(fut, destination=Client(), new_source=Client(nothing))

    # NOTE: We can't use `new_source=fut->Client(fut.value)` because
    # `new_source` is for locations that require expensive sample collection
    # and so we would only want to compute that location if we really need to
    # use it as a source. Instead in this case, we really just know initially
    # that this is a destination with _some_ value (so we default it to `nothing`)
    # and then right after when we have actually computed, we will set it to the right
    # location using the computed `fut.value`.
    sourced(fut, Client(fut.value))

    fut.value
end

function write_to_disk(fut::AbstractFuture)
    fut = convert(Future, fut)

    pt(fut, Replicated())
    partitioned_computation(fut, destination=Disk())
end

###############################################################
# Other requests to be sent with request to evaluate a Future #
###############################################################

struct RecordTaskRequest
    task::DelayedTask
end

struct RecordLocationRequest
    value_id::ValueId
    location::Location
end

struct DestroyRequest
    value_id::ValueId
end

const Request = Union{RecordTaskRequest,RecordLocationRequest,DestroyRequest}

to_jl(req::RecordTaskRequest) = Dict("type" => "RECORD_TASK", "task" => to_jl(req.task))

to_jl(req::RecordLocationRequest) =
    Dict(
        "type" => "RECORD_LOCATION",
        "value_id" => req.value_id,
        "location" => to_jl(req.location),
    )

to_jl(req::DestroyRequest) = Dict("type" => "DESTROY", "value_id" => req.value_id)

function record_request(request::Request)
    push!(get_job().pending_requests, request)
end

max_stars_repo_name: banyan-team/banyan-julia

max_issues_repo_name: banyan-team/banyan-julia

max_forks_repo_name: banyan-team/banyan-julia


text:
function loadone(name::AbstractString)
    data, f = wavread(name, format="native")
    @assert f == 16000
    vec(data)
end

loaddir(dir::AbstractString) = cd(joinpath(@__DIR__, "..", "dataset")) do
    map(loadone, filter(s -> endswith(s, ".wav"), readdir(dir, join=true, sort=true)))
end

dirs2labels = ["yes" => :yes, "no" => :no, "up" => :up, "down" => :down, "left" => :left, "right" => :right, "on" => :on, "off" => :off, "stop" => :stop, "go" => :go, "bed" => :unknown, "bird" => :unknown, "cat" => :unknown, "dog" => :unknown, "eight" => :unknown, "five" => :unknown, "four" => :unknown, "happy" => :unknown, "house" => :unknown, "marvin" => :unknown, "nine" => :unknown, "one" => :unknown, "seven" => :unknown, "sheila" => :unknown, "six" => :unknown, "three" => :unknown, "tree" => :unknown, "two" => :unknown, "wow" => :unknown, "zero" => :unknown]

gettrain() = reduce(vcat, map(pair -> map(data -> (data = data, label = pair.second), loaddir("train/audio/$(pair.first)")), dirs2labels))
getbgnoise() = loaddir("train/audio/_background_noise_")
gettest() = loaddir("test/audio")

max_stars_repo_name: kpmrozowski/wut-mini-deep-learning

max_issues_repo_name: kpmrozowski/wut-mini-deep-learning

max_forks_repo_name: kpmrozowski/wut-mini-deep-learning


text:
module LazyTrees

import Base: getindex, setindex!, show, delete!, convert

using CoordinateTransformations: AffineMap
using StaticArrays: SMatrix, SVector

mutable struct LazyTree{K, T}
    data::T
    children::Dict{K, LazyTree{K, T}}

    LazyTree{K, T}() where {K, T} = new{K, T}(T(), Dict{K, LazyTree{K, T}}())
    LazyTree{K, T}(data::T) where {K, T} = new{K, T}(data, Dict{K, LazyTree{K, T}}())
end

function show(io::IO, t::LazyTree)
    print(io, "LazyTree: $(t.data)")
    if length(t.children) > 0
        print(io, " with children: $(t.children)")
    end
end

children(t::LazyTree) = t.children
data(t::LazyTree) = t.data

convert(::Type{LazyTree{K, T}}, x::T) where {K, T} = LazyTree{K, T}(x)
convert(::Type{LazyTree{K, T}}, x) where {K, T} = LazyTree{K, T}(convert(T, x))
convert(::Type{LT}, x::LT) where {LT<:LazyTree} = x

setindex!(t::LazyTree, child, childname) = t.children[childname] = child

function setindex!(t::LazyTree{K}, child, path::Union{<:AbstractVector{K}, <:(NTuple{N, K} where N)}) where {K}
    for i in 1:(length(path) - 1)
        t = t[path[i]]
    end
    t[path[end]] = child
end

setindex!(t::LazyTree, child, path...) = setindex!(t, child, path)

function getindex(t::T, childname) where T <: LazyTree
    if haskey(children(t), childname)
        children(t)[childname]
    else
        child = T()
        t[childname] = child
        child
    end
end

function getindex(t::LazyTree{K}, path::Union{<:AbstractVector{K}, <:(NTuple{N, K} where N)}) where {K}
    for childname in path
        t = t[childname]
    end
    t
end

getindex(t::LazyTree{K}, path...) where {K} = getindex(t, path)

delete!(t::LazyTree{K}, childname::K) where {K} = delete!(t.children, childname)
function delete!(t::LazyTree, path::Union{Tuple, AbstractVector})
    if length(path) == 0
        for child in keys(children(t))
            delete!(t, child)
        end
    else
        for p in path[1:end-1]
            t = t[p]
        end
        delete!(t, path[end])
    end
end

function descendants(t::LazyTree{K}, prefix=K[]) where K
    result = Vector{Vector{K}}()
    for (childname, child) in children(t)
        childpath = vcat(prefix, childname)
        push!(result, childpath)
        append!(result, descendants(child, childpath))
    end
    result
end

end


text:
push!(LOAD_PATH, pwd())
println(LOAD_PATH);

import Sockets
import Spirit

p = Spirit.pipe()
conn = Sockets.listen(5000)

server = Spirit.HTTPServer(conn, p)

f = @async run(server)

println("Server is running")

wait(f)


text:
import .Basic: gather

# gpu gather
gather(w::CuMatrix{T}, xs::OneHotArray) where T = gather(w, onehot2indices(xs))
function gather(w::CuMatrix{T}, xs::CuArray{Int}) where T
    ys = CuArray{T}(undef, size(w, 1), size(xs)...)

    function kernel!(ys::CuDeviceArray{T}, w::CuDeviceArray{T}, xs)
        li = threadIdx().y + (blockIdx().y - 1) * blockDim().y
        i = threadIdx().x + (blockIdx().x - 1) * blockDim().x

        @inbounds if li <= length(xs)
            ind = Tuple(CartesianIndices(xs)[li])
            ys[i, ind...] = w[i, xs[li]]
        end

        return
    end

    max_threads = 256
    threads_x = min(max_threads, size(ys,1))
    threads_y = min(max_threads ÷ threads_x, length(xs))
    threads = (threads_x, threads_y)
    blocks = ceil.(Int, (size(ys,1), length(xs)) ./ threads)

    CuArrays.@cuda blocks=blocks threads=threads kernel!(ys, w, xs)
    return ys
end

function gather(W::CuArray{T}, xs::CuArray{<:Tuple}) where T
    ys = CuArray{T}(undef, size(W, 1), size(xs)...)

    function kernel!(ys::CuDeviceArray{T}, w::CuDeviceArray{T}, xs)
        li = threadIdx().y + (blockIdx().y - 1) * blockDim().y
        i = threadIdx().x + (blockIdx().x - 1) * blockDim().x

        @inbounds if li <= length(xs)
            ind = Tuple(CartesianIndices(xs)[li])
            ys[i, ind...] = w[i, xs[li]...]
        end

        return
    end

    max_threads = 256
    threads_x = min(max_threads, size(ys,1))
    threads_y = min(max_threads ÷ threads_x, length(xs))
    threads = (threads_x, threads_y)
    blocks = ceil.(Int, (size(ys,1), length(xs)) ./ threads)

    CuArrays.@cuda blocks=blocks threads=threads kernel!(ys, W, xs)
    return ys
end


text:
#=
see description in native.jl
=#

using SparseArrays

struct MatrixCompletionJuMP{T <: Real} <: ExampleInstanceJuMP{T}
    size_ratio::Int
    num_rows::Int
end

function build(inst::MatrixCompletionJuMP{T}) where {T <: Float64}
    (size_ratio, num_rows) = (inst.size_ratio, inst.num_rows)
    @assert size_ratio >= 1
    num_cols = size_ratio * num_rows

    (rows, cols, Avals) = findnz(sprandn(num_rows, num_cols, 0.8))
    is_known = vec(Matrix(sparse(rows, cols,
        trues(length(Avals)), num_rows, num_cols)))

    model = JuMP.Model()
    JuMP.@variable(model, X[1:length(is_known)])
    JuMP.@variable(model, t)
    JuMP.@objective(model, Min, t)
    JuMP.@constraint(model, vcat(t, X) in
        MOI.NormSpectralCone(num_rows, num_cols))
    X_unknown = X[.!is_known]
    JuMP.@constraint(model, vcat(1, X_unknown) in
        MOI.GeometricMeanCone(1 + length(X_unknown)))
    JuMP.@constraint(model, X[is_known] .== Avals)

    return model
end


text:
function mean(h::Histogram{T1, 1}) where {T1 <: Real}
    mean(midpoints(h.edges[1]), FrequencyWeights(h.weights))
end

function std(h::Histogram{T1, 1}, μ = mean(h)) where {T1 <: Real}
    std(midpoints(h.edges[1]), FrequencyWeights(h.weights), mean = μ, corrected = true)
end

function mean_and_std(h::Histogram{T1, 1}) where {T1 <: Real}
    μ = mean(h)
    σ = std(h, μ = μ)
    return μ, σ
end


text:
using PolyharmonicSplines
using Test

@testset "PolyharmonicSplines.jl" begin
    # Write your tests here.
end


text:
module Data

using ..PSCOPFio
using ..Networks

export
    pscopfdata2network

#################
# from pscopf_
#################

"""
    pscopfdata2network(data::String)::Network

reads the input files and construct a `PSCOPF.Network`

# Arguments
    - `data::String` : path to the directory containing PSCOPF's input files

# Returns
    The Network representing the input files
"""
function pscopfdata2network(data::String)::Network
    # Init network
    network = Networks.Network(data)

    #from pscopf_ptdf
    PSCOPFio.read_buses!(network, data)
    #from pscopf_ptdf and pscopf_limits
    PSCOPFio.read_branches!(network, data)
    #from pscopf_ptdf
    PSCOPFio.read_ptdf!(network, data)

    #from pscopf_units
    PSCOPFio.read_generators!(network, data)

    # Return built network
    return network
end

end

max_stars_repo_name: klorel/pscopf

max_issues_repo_name: klorel/pscopf

max_forks_repo_name: klorel/pscopf


text:
"Normalize logical storage path"
function normalize_path(p::AbstractString)
    # \ to / since normpath on linux won't handle it
    p = replace(p, '\\'=>'/')
    p = normpath(p)
    # \ to / again since normpath on windows creates \
    p = replace(p, '\\'=>'/')
    p == "/" ? p : rstrip(p, '/')
end

# Stores files in a regular file system
struct DirectoryStore <: AbstractStore
    folder::String
    function DirectoryStore(p)
      mkpath(normalize_path(p))
      new(normalize_path(p))
    end
end

function Base.getindex(d::DirectoryStore, i::String)
  fname=joinpath(d.folder,i)
  if isfile(fname)
    read(fname)
  else
    nothing
  end
end

function Base.setindex!(d::DirectoryStore,v,i::String)
  fname=joinpath(d.folder,i)
  write(fname,v)
  v
end

getsub(s::DirectoryStore, d::String) = DirectoryStore(joinpath(s.folder,d))

function newsub(s::DirectoryStore, d::String)
  p = mkpath(joinpath(s.folder,d))
  DirectoryStore(p)
end

storagesize(d::DirectoryStore) = sum(filter(i->i ∉ (".zattrs",".zarray"),readdir(d.folder))) do f
  filesize(joinpath(d.folder,f))
end

zname(s::DirectoryStore) = splitdir(s.folder)[2]

subdirs(s::DirectoryStore) = filter(i -> isdir(joinpath(s.folder, i)), readdir(s.folder))
Base.keys(s::DirectoryStore) = filter(i -> isfile(joinpath(s.folder, i)), readdir(s.folder))
Base.delete!(s::DirectoryStore, k::String) = isfile(joinpath(s.folder, k)) && rm(joinpath(s.folder, k))

path(s::DirectoryStore) = s.folder


text:
using ImageMetadata, FixedPointNumbers, Colors, ColorVectorSpace, Test

@testset "operations" begin
    function checkmeta(A, B)
        @test isa(A, ImageMeta)
        @test A == B
        if isa(B, ImageMeta)
            @test properties(A) == properties(B)
        end
        nothing
    end
    for A in (rand(Bool, 3, 5), rand(3, 5),
              rand(Gray{N0f8}, 3, 5), rand(RGB{N0f8}, 3, 5))
        M = ImageMeta(A)
        M2 = similar(M)
        checkmeta(-M, -A)
        checkmeta(M .+ zero(eltype(M)), M)
        checkmeta(zero(eltype(M)) .+ M, M)
        checkmeta(M .- zero(eltype(M)), M)
        checkmeta(zero(eltype(M)) .- M, -M)
        B = falses(size(M))
        if !(eltype(A) <: RGB)
            checkmeta(M + B, M)
            checkmeta(M .+ B, M)
            checkmeta((B .+ M .+ B), M)
            checkmeta(B + M, M)
            checkmeta(B .+ M, M)
            @test_throws ErrorException M + M2
            @test_throws ErrorException M .+ M2
            checkmeta(A + M, A+A)
            checkmeta(A .+ M, A+A)
            checkmeta(M + A, A+A)
            checkmeta(M .+ A, A+A)
            checkmeta(M - B, M)
            checkmeta(M .- B, M)
            checkmeta(B - M, -M)
            checkmeta(B .- M, -M)
            @test_throws ErrorException M - M2
            @test_throws ErrorException M .- M2
            checkmeta(A - M, 0*M)
            checkmeta(A .- M, 0*M)
            checkmeta(M - A, 0*M)
            checkmeta(M .- A, 0*M)
            checkmeta(A .- M .+ A, M)
            checkmeta(M .- A .+ M, M)
        end
        checkmeta(M*2, 2*M)
        checkmeta(2 .* M, 2*M)
        checkmeta(M .* 2, 2*M)
        checkmeta(M/2, M/2)
        checkmeta(M./2, M/2)
        checkmeta(M.*B, 0*M)
        checkmeta(B.*M, 0*M)
        if !(eltype(A) <: RGB)
            @test_throws ErrorException M.*M2
            checkmeta(A.*M, A.*A)
            checkmeta(M.*A, A.*A)
            checkmeta(M.^1, M)
        end
        B1 = trues(size(M))
        checkmeta(M./B1, M)
        @test_throws Union{MethodError,ErrorException} M./M2
        if !(eltype(A) <: RGB)
            checkmeta(M .+ false, M)
            checkmeta(false .+ M, M)
            checkmeta(M .+ 0.0, M)
            checkmeta(0.0 .+ M, M)
            if eltype(A) == Float64
                checkmeta(M./A, ones(size(M)))
            end
            @test (M .< 0.5) == (A .< 0.5)
            @test (M .> 0.5) == (A .> 0.5)
            @test (M .< A) == B
            @test (M .> A) == B
            @test (M .== 0.5) == (A .== 0.5)
            @test (M .== A) == B1
        end
    end
end

M = ImageMeta([1,2,3,4])
@test minimum(M) == 1
@test maximum(M) == 4
Mp = M'
@test ndims(Mp) == 2
Ms = dropdims(Mp, dims=1)
@test Ms == M

img = convert(ImageMeta{Gray{N0f16}}, [0.01164 0.01118; 0.01036 0.01187])
@test all((1 .- img) .== (1 .- img))

nothing


text:
function test_helpers()
    test_build_uri()
    test_days()
end

function test_build_uri()
    test_config = {
        "protocol" => "http",
        "host" => "dev.staffjoy.com",
        "api_key" => "staffjoydev", # This should be from a sudo user
        "pagerduty" => false, # Alert on issues?
        "pagerduty_key" => "", # API key for triggering an alert
        "sleep" => 10, # Seconds between fetching
    }

    path = "/home"
    expected = "http://staffjoydev:@dev.staffjoy.com/home"
    actual = build_uri(test_config, path)
    @test actual == expected
end

function test_days()
    # Given a start day, get days in the correct order
    input = {"day_week_starts" => "tuesday"}
    expected = [
        "tuesday",
        "wednesday",
        "thursday",
        "friday",
        "saturday",
        "sunday",
        "monday",
    ]

    actual = days(input)
    @test expected == actual
end

max_stars_repo_name: shdann/autoshift

max_issues_repo_name: shdann/autoshift

max_forks_repo_name: shdann/autoshift


text:
import POMDPModelTools: obs_weight
import POMDPs: observation

struct P <: POMDP{Nothing, Nothing, Nothing} end

@test !@implemented obs_weight(::P, ::Nothing, ::Nothing, ::Nothing, ::Nothing)
@test !@implemented obs_weight(::P, ::Nothing, ::Nothing, ::Nothing)
@test !@implemented obs_weight(::P, ::Nothing, ::Nothing)

obs_weight(::P, ::Nothing, ::Nothing, ::Nothing) = 1.0
@test @implemented obs_weight(::P, ::Nothing, ::Nothing, ::Nothing)
@test @implemented obs_weight(::P, ::Nothing, ::Nothing, ::Nothing, ::Nothing)
@test !@implemented obs_weight(::P, ::Nothing, ::Nothing)

@test obs_weight(P(), nothing, nothing, nothing, nothing) == 1.0

observation(::P, ::Nothing) = nothing
@test @implemented obs_weight(::P, ::Nothing, ::Nothing)


text:
using CuArrays
using Distributions: pdf
using Random

RLBase.get_prob(p::AbstractPolicy, obs, ::RLBase.AbstractActionStyle, a) =
    pdf(get_prob(p, obs), a)

Random.rand(s::MultiContinuousSpace{<:CuArray}) = rand(CuArrays.CURAND.generator(), s)


text:
using MOOSE

include("CoupledConvection.jl")

# Create the Mesh
mesh = buildSquare(0, 1, 0, 1, 20, 20)

# Create the System to hold the equations
diffusion_system = System{Float64}(mesh)

# Add some variables
u = addVariable!(diffusion_system, "u")
v = addVariable!(diffusion_system, "v")

# Apply the Laplacian operator to the "u" variable
addKernel!(diffusion_system, Diffusion(u))

# Apply the Coupled Convection operator
addKernel!(diffusion_system, CoupledConvection(u, v))

# Apply the Laplacian operator to the "v" variable
addKernel!(diffusion_system, Diffusion(v))

# u = 0 on the Left
addBC!(diffusion_system, DirichletBC(u, [4], 0.0))

# u = 1 on the Right
addBC!(diffusion_system, DirichletBC(u, [2], 1.0))

# v = 0 on the Left
addBC!(diffusion_system, DirichletBC(v, [4], 0.0))

# v = 1 on the Right
addBC!(diffusion_system, DirichletBC(v, [2], 1.0))

# Initialize the system of equations
initialize!(diffusion_system)

# Create a solver and solve
solver = JuliaDenseNonlinearImplicitSolver(diffusion_system)
solve!(solver, nl_max_its=5)

# Output
out = VTKOutput()
output(out, solver, "coupled_convection_out")


text:
using InteractiveUtils # 0.7 之后需要调用这个标准库

function view_tree(T, depth=0)
    println("  "^depth, T)
    for each in subtypes(T)
        view_tree(each, depth+1)
    end
end

abstract type AbstractAnimal end

abstract type AbstractBird <: AbstractAnimal end
abstract type AbstractDog <: AbstractAnimal end
abstract type AbstractCat <: AbstractAnimal end

struct Sparrow <: AbstractBird end
struct Kitty <: AbstractCat end
struct Snoope <: AbstractDog end

view_tree(AbstractAnimal)

max_stars_repo_name: liushooter/OneDayOneCommit

max_issues_repo_name: liushooter/OneDayOneCommit

max_forks_repo_name: liushooter/OneDayOneCommit


text:
module D3Trees

using JSON
#using Blink
using Random
using AbstractTrees

import AbstractTrees: printnode

export
    D3Tree,
    D3TreeNode,
    D3TreeView,

    blink,
    inchrome,
    inbrowser,
	tofile

struct D3Tree
    children::Vector{Vector{Int}}
    text::Vector{String}
    tooltip::Vector{String}
    style::Vector{String}
    link_style::Vector{String}
    title::String
	fontsize::Number
	noder::Number
    options::Dict{Symbol, Any}
end

"""
    D3Tree(node; detect_repeat=true, kwargs...)

Construct a tree to be displayed using D3 in a browser or ipython notebook with any object, `node`, that implements the AbstractTrees interface.

The style may be controlled by implementing the following functions, which should return `String`s for the nodes:
```@docs
D3Trees.text(node)
D3Trees.tooltip(node)
D3Trees.style(node)
D3Trees.link_style(node)
```

# Arguments

## Required

- `node`: an object that has AbstractTrees.children(node) and AbstractTrees.printnode(io::IO, node)

## Keyword

- `detect_repeat`: if true, uses a dictionary to detect whether a node has appeared previously
- Also supports, the non-vector arguments of the vector-of-vectors `D3Tree` constructor, i.e. `title`, `init_expand`, `init_duration`, `svg_height`.
"""
function D3Tree(node; detect_repeat::Bool=true, kwargs...)

    t = D3Tree(Vector{Int}[]; kwargs...)

    if detect_repeat
        node_dict = Dict{Any, Int}()
        push_node!(t, node, node_dict)
    else
        push_node!(t, node)
    end
    return t
end

"""
    D3Tree(children, <keyword arguments>)

Construct a tree to be displayed using D3 in a browser or ipython notebook, specifying structure with lists of children indices.

# Arguments

## Required

- `children::Vector{Vector{Int}}`: List of children for each node. E.g.
  ```julia
  D3Tree([[2,3], [], [4], []])
  ```
  creates a tree with four nodes. Nodes 2 and 3 are children of node 1, and node 4 is the only child of node 3. Nodes 2 and 4 are childless.

## Keyword:
- `text::Vector{String}` - text to appear under each node.
- `tooltip::Vector{String}` - text to appear when hovering over each node.
- `style::Vector{String}` - html style for each node.
- `link_style::Vector{String}` - html style for each link.
- `title::String` - html title.
- `init_expand::Integer` - levels to expand initially.
- `init_duration::Number` - duration of the initial animation in ms.
- `svg_height::Number` - height of the svg containing the tree in px.
- `fontsize::Number` - size of text, defaults to 12.
- `noder::Number` - radius of the nodes, defaults to 10.
"""
function D3Tree(children::AbstractVector{<:AbstractVector}; kwargs...)
    kwd = Dict(kwargs)
    n = length(children)
    return D3Tree(children,
                  get(kwd, :text, collect(string(i) for i in 1:n)),
                  get(kwd, :tooltip, fill("", n)),
                  get(kwd, :style, fill("", n)),
                  get(kwd, :link_style, fill("", n)),
                  get(kwd, :title, "Julia D3Tree"),
				  get(kwd, :fontsize, 12),
				  get(kwd, :noder, 10),
                  convert(Dict{Symbol, Any}, kwd)
                 )
end

"""
    D3Trees.text(n)

Return the text to be displayed at the D3Trees node corresponding to AbstractTrees node `n`
"""
text(node) = sprint(printnode, node)

"""
    D3Trees.tooltip(n)

Return the text to be displayed in the tooltip for the D3Trees node corresponding to AbstractTrees node `n`
"""
tooltip(node) = sprint(printnode, node)

"""
    D3Trees.style(n)

Return the html style for the D3Trees node corresponding to AbstractTrees node `n`
"""
style(node) = ""

"""
    D3Trees.link_style(n)

Return the html style for the link leading to the D3Trees node corresponding to AbstractTrees node `n`
"""
link_style(node) = ""

struct D3TreeNode
    tree::D3Tree
    index::Int
end

AbstractTrees.children(n::D3TreeNode) = (D3TreeNode(n.tree, c) for c in n.tree.children[n.index])
AbstractTrees.children(t::D3Tree) = children(D3TreeNode(t, 1))
n_children(n::D3TreeNode) = length(n.tree.children[n.index])
AbstractTrees.printnode(io::IO, n::D3TreeNode) = print(io, n.tree.text[n.index])
AbstractTrees.printnode(io::IO, t::D3Tree) = print(io, t.text[1])
tooltip(n::D3TreeNode) = n.tree.tooltip[n.index]
tooltip(t::D3Tree) = t.tooltip[1]
style(n::D3TreeNode) = n.tree.style[n.index]
style(t::D3Tree) = t.style[1]
link_style(n::D3TreeNode) = n.tree.link_style[n.index]
link_style(t::D3Tree) = t.link_style[1]

struct D3TreeView
    root::D3TreeNode
    depth::Int
end

function push_node!(t, node, node_dict=nothing)
    if !(node_dict == nothing) && haskey(node_dict, node)
        return node_dict[node]
    end

    ind = length(t.children) + 1
    if !(node_dict == nothing)
        node_dict[node] = ind
    end
    if length(t.children) < ind
        push!(t.children, Int[])
        push!(t.text, text(node))
        push!(t.tooltip, tooltip(node))
        push!(t.style, style(node))
        push!(t.link_style, link_style(node))
    end
    for c in children(node)
        c_ind = push_node!(t, c, node_dict)
        push!(t.children[ind], c_ind)
    end
    return ind
end

include("show.jl")
include("displays.jl")
include("text.jl")

end # module


text:
function fixedpointmap(f, x_0, tolerance, maxiter)
    D(f) = x -> ForwardDiff.derivative(f, x)
    f_prime = D(f)
    x_old = x_0
    normdiff = Inf
    iter = 1
    while normdiff > tolerance && iter <= maxiter
        x_new = x_old - f(x_old)/f_prime(x_old)
        normdiff = norm(x_new - x_old)
        x_old = x_new
        iter = iter + 1
    end
    return (value = x_old, normdiff = normdiff, iter = iter)
end

# define a map and parameters
f(x) = (x-1)^2

sol = fixedpointmap(f, 0, 1.0E-8, 1000)
println("Fixed point = $(sol.value), and |x_t+1 - x_t| = $(sol.normdiff) in $(sol.iter) iterations")


text:
using SafeTestsets, Pkg

const GROUP = get(ENV, "GROUP", "All")
const is_APPVEYOR = Sys.iswindows() && haskey(ENV,"APPVEYOR")
const is_TRAVIS = haskey(ENV,"TRAVIS")

function activate_downstream_env()
    Pkg.activate("downstream")
    Pkg.develop(PackageSpec(path=dirname(@__DIR__)))
    Pkg.instantiate()
end

@time begin
if GROUP == "All" || GROUP == "Core"
    @safetestset "Rosenbrock" begin include("rosenbrock.jl") end
    @safetestset "AD Tests" begin include("ADtests.jl") end
    @safetestset "Mini batching" begin include("minibatch.jl") end
    @safetestset "DiffEqFlux" begin include("diffeqfluxtests.jl") end
end

if !is_APPVEYOR && GROUP == "GPU"
    activate_downstream_env()
    @safetestset "DiffEqFlux GPU" begin include("downstream/gpu_neural_ode.jl") end
end
end


text:
using Distributions, FreqTables, DataFrames

function MvInv_slow(u, a, κ, γ, M)
    N(x) =  a*κ^γ/SpecialFunctions.gamma(1-γ)*Γ(-γ,κ*x)
    ξ = cumsum(rand(Exponential(1), M))
    J = Array{Float64}(undef, M)
    higherbound = 10^3
    for i in eachindex(J)
        obj(x) = N(x) - ξ[i]
        # println((higherbound, obj.((8eps(), higherbound))))
        J[i] = find_zero(obj, (8eps(), higherbound))
        higherbound = J[i]
    end
    return J
end

function MvInv_slow_arb(u, a, κ, γ, M)
    N(x) =  a*κ^γ*Float64(real(1/gamma(CC(1-γ))*gamma(CC(-γ), CC(κ*x))))
    ξ = cumsum(rand(Exponential(1), M))
    J = Array{Float64}(undef, M)
    higherbound = 10
    for i in eachindex(J)
        obj(x) = N(x) - ξ[i]
        J[i] = find_zero(obj, (8eps(), higherbound))
        higherbound = J[i]
    end
    return J
end

function MvInv_simple(u, a, kappa, gama, N, M)
    J = Array{Float64}(undef, M)
    x = -log.(range(exp(-1e-05), exp(-10), length = N))
    f =  a/ Float64(real(gamma(CC(1- gama)))) * (x.^(-(1+gama)).*exp.( - (u+kappa)*x))
    dx = diff(x)
    h = (f[2:end] + f[1:(end-1)])/2
    Mv = zeros(N)
    ξ = cumsum(rand(Exponential(1), M))
    for i in (N-1):-1:1
        Mv[i] = Mv[i+1] + dx[i]*h[i]
    end
    for i in eachindex(J)
        J[i] = x[argmin(Mv .> ξ[i])]
    end
    return J
end

function fill_v2(M, Mv, W,N, x)
    v = Array{Float64}(undef, M)
    iMv = N
    for i in 1:M
        while iMv > 0 && Mv[iMv] < W[i]
            iMv = iMv -1
        end
        v[i] = x[iMv + 1]
    end
    return(v)
end

function MvInv_D(u, a, kappa, gama, N, M)
    x = -log.(range(exp(-1e-05),exp(-10), length=N))
    f =  a/ Float64(real(gamma(GibbsTypePriors.CC(1- gama)))) * (x.^(-(1+gama)).*exp.( - (u+kappa)*x))
    dx = diff(x)
    h = (f[2:end] + f[1:(end-1)]) / 2
    Mv = append!(reverse(cumsum(reverse(dx.* h))),[0])
    dist = Exponential(1)
    W = rand(dist, M)
    W = cumsum(W)
    return fill_v2(M,Mv,W,N,x)
end

## functions to compute weights pk for different approximations (FK, stick-breaking)

function NGG_FK_weights_fast(β, σ, M)
    a = 1
    κ = (σ*a*β)^(1/σ)
    γ = σ
    # Js = MvInv_slow(0, a, κ, γ, M)
    Js = MvInv_simple(0, a, κ, γ, 10^4, M)
    # Js = MvInv_D(0, a, κ, γ, 10^4, M)
    # println(Js[end]/sum(Js))
    return Js ./ sum(Js)
end

function Pkn_NGG_FK_fast(n, β, σ, M; runs=10^4)
    array_clust_num = Array{Int64}(undef, runs)
    for i in 1:runs
        weights_NGG = NGG_FK_weights_fast(β, σ, M)
        c = wsample(1:M, weights_NGG, n, replace=true)
        n_c =  length(unique(c))
        array_clust_num[i] = n_c
    end
    return proportions(array_clust_num, n)
end

## slow version

function NGG_FK_weights(β, σ, M)
    a = 1
    #a =σ*β
    #println(a)
    κ = (σ*a*β)^(1/σ)
    γ = σ
    Js = MvInv_slow(0, a, κ, γ, M)
    # Js = MvInv_simple(0, a, κ, γ, 10^4, M)
    # Js = MvInv_D(0, a, κ, γ, 10^4, M)
    # println(Js[end]/sum(Js))
    return Js ./ sum(Js)
end

function Pkn_NGG_FK(n, β, σ, M; runs=10^4)
    array_clust_num = Array{Int64}(undef, runs)
    for i in 1:runs
        weights_NGG = NGG_FK_weights(β, σ, M)
        c = wsample(1:M, weights_NGG, n, replace=true)
        n_c =  length(unique(c))
        array_clust_num[i] = n_c
    end
    return proportions(array_clust_num, n)
end

max_stars_repo_name: konkam/approximatingBNPpriors

max_issues_repo_name: konkam/approximatingBNPpriors

max_forks_repo_name: konkam/approximatingBNPpriors


text:
"""
    grind_ripserer(b::Benchmark; extras=false, sparse=false, kwargs...)

Run `valgrind --tool=massif` on Ripserer.

!!! warning
    If you get `ERROR: Unable to find compatible target in system image.`, see:
    https://github.com/JuliaLang/julia/issues/27131
"""
function grind_ripserer(b::Benchmark; extras=false, sparse=false, kwargs...)
    if !isnothing(b.threshold)
        complex_kwargs = (;threshold=b.threshold)
    else
        complex_kwargs = (;)
    end
    if !isnothing(sparse)
        complex_kwargs = (;complex_kwargs..., sparse=sparse)
    end
    kwargs = (;kwargs..., b.kwargs...)
    project_dir = joinpath(@__DIR__, "..")
    if !isnothing(sparse) && sparse
        outfile = joinpath(
            @__DIR__, "../results/massif", "ripserer-sparse-" * b.name * ".massif.out"
        )
    else
        outfile = joinpath(
            @__DIR__, "../results/massif", "ripserer-" * b.name * ".massif.out"
        )
    end

    f = b.filename
    c = string(b.complex)
    ca = string(complex_kwargs)
    a = string(kwargs)

    cmd = `valgrind --tool=massif --massif-out-file=$outfile
           --smc-check=all-non-file julia -O3 --project=$project_dir -e
           'using RipsererBenchmarks;
            using Ripserer;
            RipsererBenchmarks._ripserer("'$f'", '$c', '$ca', '$a')
          '
          `
    run(cmd)
end

"""
    grind_ripser(b::Benchmark)

Run `valgrind --tool=massif` on (Cubical) Ripser.
"""
function grind_ripser(b::Benchmark)
    @info "grinding ripser for $filename"
    outfile = joinpath(
        @__DIR__, "../results/massif", "ripser-" * b.name * ".massif.out"
    )
    infile = joinpath(@__DIR__, "../datasets/", filename)
    ripser = ripsers_cmd(b.filename, true; b.kwargs..., threshold=b.threshold)
    cmd = `valgrind --tool=massif --massif-out-file=$outfile $ripser`
    run(cmd)
end


text:
using Documenter, HighDimPDE
# push!(LOAD_PATH,"/Users/victorboussange/ETHZ/projects/EvoId/") # not sure this is necessary
pathsrc = joinpath(@__DIR__,"src")
makedocs(sitename="HighDimPDE.jl",
        format = Documenter.HTML(prettyurls = false),
        authors = "Victor Boussange",
        pages = [
            "Home" => "index.md",
            "Getting started" => "getting_started.md",
            "Solver Algorithms" => ["MLP.md",
                        "DeepSplitting.md",
                        ],
            "Feynman Kac formula" => "Feynman_Kac.md",
        ],)

deploydocs(repo = "github.com/vboussange/HighDimPDE.jl", devbranch="main")


text:
# *****************************************************************************
# Written by Ritchie Lee, ritchie.lee@sv.cmu.edu
# *****************************************************************************
# Copyright ã 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.  The Reinforcement Learning Encounter Simulator (RLES)
# platform is licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. You
# may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable
# law or agreed to in writing, software distributed under the License is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
# _____________________________________________________________________________
# Reinforcement Learning Encounter Simulator (RLES) includes the following
# third party software. The SISLES.jl package is licensed under the MIT Expat
# License: Copyright (c) 2014: Youngjun Kim.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED
# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# *****************************************************************************

module TrajSaveReplay

export trajReplay, fill_replay

using AdaptiveStressTesting
using RLESUtils, Obj2Dict, Observers
using CPUTime

using ..Config_ACASX_GM
using ..ConfigAST
using ..ConfigMCTS
using ..DefineSave
using ..SaveHelpers
using ..TrajSaveCommon
using ..Fill_To_Max_Time
using ..DefineLog
using ..SaveTypes

function trajReplay(savefile::AbstractString; fileroot::AbstractString="")
    d = trajLoad(savefile)
    if isempty(fileroot)
        fileroot = string(getSaveFileRoot(savefile), "_replay")
    end
    trajReplay(d; fileroot=fileroot)
end

function trajReplay(d::TrajLog; fileroot::AbstractString="")
    sim_params = get_sim_params(d)
    ast_params = get_ast_params(d)
    reward = get_reward(d)
    action_seq = get_action_seq(d)

    sim = defineSim(sim_params)
    ast = defineAST(sim, ast_params)
    compute_info = get_compute_info(d)
    study_params = get_study_params(d)

    d2 = trajLoggedPlay(ast, reward, action_seq, compute_info, sim_params, ast_params)

    copy!(d, d2)
    outfile = trajSave(fileroot, d)

    outfile
end

function fill_replay(filename::AbstractString; overwrite::Bool=false)
    fillfile = fill_to_max_time(filename)
    if overwrite
        outfile = trajReplay(fillfile, fileroot=getSaveFileRoot(filename))
    else
        outfile = trajReplay(fillfile)
    end
    rm(fillfile) #delete intermediate fill file
    outfile
end

fill_replay{T<:AbstractString}(filenames::Vector{T}) = map(fill_replay, filenames)

end #module

max_stars_repo_name: sisl/RLESCAS

max_issues_repo_name: sisl/RLESCAS

max_forks_repo_name: sisl/RLESCAS