text:
"""
    appear(s::Symbol)

Appear can be used inside a [`SubAction`](@ref)

# Example
```
Action(101:200, (args...)->house_of_nicholas(); subactions = [
    SubAction(1:20, appear(:fade)),
    SubAction(81:100, disappear(:fade))
])
```
In this case the `house_of_nicholas` will fade in during the first 20 frames
of the [`Action`](@ref) so `101-120`.

# Arguments
- `s::Symbol`: the symbol defines the animation of appearance
    The only symbols that are currently supported are:
    - `:fade_line_width` which increases the line width up to the default value
       or the value specified by [`setline`](@ref)
    - `:fade` which increases the opcacity up to the default value
       or the value specified by [`setopacity`](@ref)
    - `:scale` which increases the scale up to the default value `1`
       or the value specified by [`scale`](@ref)
    - `:draw_text` which only works for [`text`](@ref) and lets it appear from left to right.
"""
function appear(s::Symbol)
    (video, action, subaction, rel_frame) ->
        _appear(video, action, subaction, rel_frame, Val(s))
end

function _appear(video, action, subaction, rel_frame, symbol::Val{:fade_line_width})
    t = get_interpolation(subaction, rel_frame)
    action.current_setting.mul_line_width = t
end

function _appear(video, action, subaction, rel_frame, symbol::Val{:fade})
    t = get_interpolation(subaction, rel_frame)
    action.current_setting.mul_opacity = t
end

function _appear(video, action, subaction, rel_frame, symbol::Val{:scale})
    t = get_interpolation(subaction, rel_frame)
    action.current_setting.mul_scale = t
end

function _appear(video, action, subaction, rel_frame, symbol::Val{:draw_text})
    t = get_interpolation(subaction, rel_frame)
    action.opts[:draw_text_t] = t
end

"""
    disappear(s::Symbol)

Disappear can be used inside a [`SubAction`](@ref)

# Example
```
Action(101:200, (args...)->house_of_nicholas(); subactions = [
    SubAction(1:20, appear(:fade)),
    SubAction(81:100, disappear(:fade))
])
```
In this case the `house_of_nicholas` will fade out during the last 20 frames
of the [`Action`](@ref) so `181-200`.

# Arguments
- `s::Symbol`: the symbol defines the animation of disappearance
    The only symbols that are currently supported are:
    - `:fade_line_width` which decreases the line width down to `0`
    - `:fade` which decreases the opacity down to `0`
    - `:scale` which decreases the scale down to `0`
    - `:draw_text` which only works for text and let the text disappear from right to left.
"""
function disappear(s::Symbol)
    (video, action, subaction, rel_frame) ->
        _disappear(video, action, subaction, rel_frame, Val(s))
end

function _disappear(video, action, subaction, rel_frame, symbol::Val{:fade_line_width})
    t = get_interpolation(subaction, rel_frame)
    action.current_setting.mul_line_width = 1 - t
end

function _disappear(video, action, subaction, rel_frame, symbol::Val{:fade})
    t = get_interpolation(subaction, rel_frame)
    action.current_setting.mul_opacity = 1 - t
end

function _disappear(video, action, subaction, rel_frame, symbol::Val{:scale})
    t = get_interpolation(subaction, rel_frame)
    action.current_setting.mul_scale = 1 - t
end

function _disappear(video, action, subaction, rel_frame, symbol::Val{:draw_text})
    t = get_interpolation(subaction, rel_frame)
    action.opts[:draw_text_t] = 1 - t
end

"""
    translate()

Translate a function defined inside a [`SubAction`](@ref) using an Animation defined
with Animations.jl.

If you're used to working with Animations.jl this should feel quite natural.
Instead of defining each movement in its own subaction it's possible to define it in one
by using an Animation.

# Example
```
using Javis, Animations

function ground(args...)
    background("black")
    sethue("white")
end

video = Video(500, 500)
circle_anim = Animation(
    [0.0, 0.3, 0.6, 1.0], # must go from 0 to 1
    # the circle will move from the origin to `Point(150, 0)` then `Point(150, 150)`
    # and back to the origin `O`.
    [O, Point(150, 0), Point(150, 150), O],
    [sineio(), polyin(5), expin(8)],
)
javis(
    video, [
        BackgroundAction(1:150, ground),
        Action((args...)->circle(O, 25, :fill); subactions=[
            SubAction(1:150, circle_anim, translate())
        ])
    ], pathname="moving_a_circle.gif"
)
```

This notation uses the Animations.jl library very explicitly. It's also possible to do the
same with:

```
javis(
    video,
    [
        BackgroundAction(1:150, ground),
        Action((args...)->circle(O, 25, :fill); subactions = [
            SubAction(1:50, sineio(), Translation(150, 0)),
            SubAction(51:100, polyin(2), Translation(0, 150)),
            SubAction(101:150, expin(8), Translation(-150, -150))
        ])
    ],
    pathname = "moving_a_circle_javis.gif",
)
```

which uses the `SubAction` syntax three times and only uses easing functions instead of
specifying the `Animation` directly.

Here `circle_anim` defines the movement of the circle. The most important part is that the
time in animations has to be from `0.0` to `1.0`.
"""
function Luxor.translate()
    (video, action, subaction, rel_frame) -> _translate(video, action, subaction, rel_frame)
end

function _translate(video, action, subaction, rel_frame)
    p = get_interpolation(subaction, rel_frame)
    Luxor.translate(p)
end

"""
    rotate()

Rotate a function defined inside a [`SubAction`](@ref) using an Animation defined
with Animations.jl.

If you're used to working with Animations.jl this should feel quite natural.
Instead of defining each movement in its own subaction it's possible to define it in one
by using an Animation.

# Example
```
using Javis, Animations

video = Video(500, 500)
translate_anim = Animation(
    [0, 1], # must go from 0 to 1
    [O, Point(150, 0)],
    [sineio()],
)

translate_back_anim = Animation(
    [0, 1], # must go from 0 to 1
    [O, Point(-150, 0)],
    [sineio()],
)

rotate_anim = Animation(
    [0, 1], # must go from 0 to 1
    [0, 2π],
    [linear()],
)

javis(
    video,
    [
        BackgroundAction(1:150, ground),
        Action(
            (args...) -> circle(O, 25, :fill);
            subactions = [
                SubAction(1:10, sineio(), scale()),
                SubAction(11:50, translate_anim, translate()),
                SubAction(51:100, rotate_anim, rotate_around(Point(-150, 0))),
                SubAction(101:140, translate_back_anim, translate()),
                SubAction(141:150, rev(sineio()), scale())
            ],
        ),
    ],
    pathname = "animation.gif",
)
```

which uses the `SubAction` syntax five times with both easing functions directly and animation objects.
The `rev(sineio())` creates an `Animation` which goes from `1.0` to `0.0`.
"""
function Luxor.rotate()
    (video, action, subaction, rel_frame) -> _rotate(video, action, subaction, rel_frame)
end

function _rotate(video, action, subaction, rel_frame)
    p = get_interpolation(subaction, rel_frame)
    Luxor.rotate(p)
end

"""
    rotate_around(p::Point)

Rotate a function defined inside a [`SubAction`](@ref) using an Animation defined
with Animations.jl around the point `p`.

An example can be seen in [`rotate`](@ref).

# Arguments
- `p::Point`: the point to rotate around
"""
function rotate_around(p::Point)
    (video, action, subaction, rel_frame) ->
        _rotate_around(video, action, subaction, rel_frame, p)
end

function _rotate_around(video, action, subaction, rel_frame, p)
    i = get_interpolation(subaction, rel_frame)
    Luxor.translate(p)
    Luxor.rotate(i)
    Luxor.translate(-p)
end

"""
    scale()

Scale a function defined inside a [`SubAction`](@ref) using an Animation defined
with Animations.jl around the point `p`.

An example can be seen in [`rotate`](@ref).
"""
function scale()
    (video, action, subaction, rel_frame) -> _scale(video, action, subaction, rel_frame)
end

function _scale(video, action, subaction, rel_frame)
    p = get_interpolation(subaction, rel_frame)
    scale(p)
end

"""
    sethue()

Set the color of a function defined inside a [`SubAction`](@ref) using an Animation defined
with Animations.jl.

# Example
A possible animation would look like this:
```julia
color_anim = Animation(
    [0, 0.5, 1], # must go from 0 to 1
    [
        Lab(colorant"red"),
        Lab(colorant"cyan"),
        Lab(colorant"black"),
    ],
    [sineio(), sineio()],
)
```

An example on how to integrate this into a SubAction can be seen in [`rotate`](@ref).
Where this would be a valid SubAction: `SubAction(1:150, color_anim, sethue())`.
"""
function Luxor.sethue()
    (video, action, subaction, rel_frame) -> _sethue(video, action, subaction, rel_frame)
end

function _sethue(video, action, subaction, rel_frame)
    color = get_interpolation(subaction, rel_frame)
    Luxor.sethue(color)
end

"""
    follow_path(points::Vector{Point}; closed=true)

Can be applied inside a subaction such that the object defined in the parent action follows a path.
It takes a vector of points which can be created as an example by calling `circle(O, 50)` <- notice that the action is set to `:none` the default.

# Example
```julia
SubAction(1:150, follow_path(star(O, 300)))
```

# Arguments
- `points::Vector{Point}` - the vector of points the object should follow

# Keywords
- `closed::Bool` default: true, sets whether the path is a closed path as for example when
    using a circle, ellipse or any polygon. For a bezier path it should be set to false.
"""
function follow_path(points::Vector{Point}; closed = true)
    (video, action, subaction, rel_frame) ->
        _follow_path(video, action, subaction, rel_frame, points; closed = closed)
end

function _follow_path(video, action, subaction, rel_frame, points; closed = closed)
    isfirstframe = rel_frame == first(get_frames(subaction))
    t = get_interpolation(subaction, rel_frame)
    # if not closed it should be always between 0 and 1
    if !closed
        t = clamp(t, 0.0, 1.0)
    end
    # if t is discrete and not 0.0 take the last point or first if closed
    if !isfirstframe && isapprox_discrete(t)
        if closed
            translate(points[1])
        else
            translate(points[end])
        end
        return
    end
    # get only the fractional part to be between 0 and 1
    t -= floor(t)
    if isfirstframe
        # compute the distances only once for performance reasons
        subaction.defs[:p_dist] = polydistances(points, closed = closed)
    end
    if isapprox(t, 0.0, atol = 1e-4)
        translate(points[1])
        return
    end
    pdist = subaction.defs[:p_dist]
    ind, surplus = nearestindex(pdist, t * pdist[end])

    nextind = mod1(ind + 1, length(points))
    overshootpoint = between(
        points[ind],
        points[nextind],
        surplus / distance(points[ind], points[nextind]),
    )
    translate(overshootpoint)
end


text:
using MadelungConstant

MadelungConstant.plot()
println("終了するにはキーを押してください")
readline()

ext: jl

max_stars_repo_name: YIsoda/MadelungConstant

max_issues_repo_name: YIsoda/MadelungConstant

max_forks_repo_name: YIsoda/MadelungConstant


text:
immutable StaticBitSet
    chunks::NTuple{4, UInt64}
end

@inline _div64(l) = l >>> 6
@inline _mod64(l) = l & 63
@inline get_chunks_id(i::Integer) = _div64(Int(i)-1)+1, _mod64(Int(i)-1)

@inline function Base.in(x::UInt8, b::StaticBitSet)
    i1, i2 = get_chunks_id(x+1)
    (b.chunks[i1] & (UInt64(1) << i2)) != 0
end

function emit_level(leaf::IOTreeLeaf, args...)
    :(return $(leaf.value))
end

function emit_level(tree::Union{IOTreeRoot, IOTreeNode}, emasks, mask_idx, byte_reader, level)
    exprs = Expr(:block)
    b = gensym()
    push!(exprs.args, :($b = $(byte_reader(level))))
    cs = children(tree)
    accum_mask = copy(zeros_mask)
    for (i,c) in enumerate(cs)
        accum_mask .|= c.mask
        sm = StaticBitSet(tuple(c.mask.mask.chunks...))
        if i < length(cs)
          idx = mask_idx[sm]
          push!(exprs.args, quote
              if $b in $emasks[$idx]
                  $(emit_level(c, emasks, mask_idx, byte_reader, level+1))
              end
          end)
        else
          push!(exprs.args, emit_level(c, emasks, mask_idx, byte_reader, level+1))
        end
    end
    # Make sure the masks where exhaustive
    @assert accum_mask == ones_mask
    exprs
end

function generate_decoder_for_tree(tree, byte_reader)
    masks = Set{StaticBitSet}()
    for node in PreOrderDFS(tree)
        (node == tree) && continue
        push!(masks, StaticBitSet(tuple(node.mask.mask.chunks...)))
    end
    masks = tuple(collect(masks)...)
    mask_idx = Dict(x=>i for (i,x) in enumerate(masks))
    ret = Expr(:block)
    emasks = gensym()
    push!(ret.args, :($emasks = $masks))
    push!(ret.args, emit_level(tree, emasks, mask_idx, byte_reader, 1))
    ret
end


text:
#!/usr/bin/julia
using Pkg

using ArgParse
using JuliaFormatter

function parse_cmdline()
    s = ArgParseSettings()

    @add_arg_table! s begin
        "NEW_VERSION"
            help = "the new version number, in the format X.Y.Z"
            required = true
    end

    return parse_args(s)
end

function main()
    # Verify that we are on the right git branch.
    gitbranch = readchomp(`git rev-parse --abbrev-ref HEAD`)
    if gitbranch != "next"
        error("must be on the 'next' git branch." * "You're on '$(gitbranch)'.")
    end

    args = parse_cmdline()
    new_version = args["NEW_VERSION"]
    try
        # Update Project.toml version.
        projectfile = "$(@__DIR__)/../Project.toml"
        lines = readlines(projectfile, keep = true)
        open(projectfile, write = true) do io
            for line in lines
                if startswith(line, "version")
                    print(io, "version = \"$(new_version)\"")
                else
                    print(io, line)
                end
            end
        end

        # Update the local manifest.
        Pkg.activate("$(@__DIR__)/../")
        Pkg.update()

        # TODO: Run local tests, if available

        # Build docs to verify that `docs/make.jl` works.
        docbuilder = "$(@__DIR__)/../docs/make.jl"
        run(`julia $docbuilder`)

        # Auto-format the entire source tree
        format("$(@__DIR__)/../src/")
    catch e
        docs_manifest = "$(@__DIR__)/../docs/Manifest.toml"
        run(`git restore $projectfile $docs_manifest`)
        throw(e)
    end

    println("Finished release preparation for v$(new_version)")
    println("Remember to update the changelog and add a git tag before committing the release")
end

main()


text:
export COFFStrTab

"""
    COFFStrTab

COFF `StrTab` type, containing the metadata necessary to perform string table
lookups, via the `strtab_lookup()` method.
"""
struct COFFStrTab{H <: COFFHandle} <: StrTab{H}
    handle::COFFHandle
    offset::UInt32
end

StrTab(oh::H) where {H <: COFFHandle} = COFFStrTab{H}(oh, UInt32(strtab_offset(oh)))
handle(oh::COFFStrTab) = oh.handle

function strtab_lookup(strtab::COFFStrTab, index)
    seek(handle(strtab), strtab.offset + index)
    return strip(readuntil(handle(strtab), '\0'), '\0')
end


text:
Base.write(io::IO, ::MIME"text/plain", ::Void) = nothing
function Base.read(io::IO, ::MIME"text/plain", ::Type{Void})
    readline(io)
    return nothing
end

Base.write(io::IO, ::MIME"text/plain", i::Integer) = print(io, i)
Base.read{I<:Integer}(io::IO, ::MIME"text/plain", ::Type{I}) = parse(I, readline(io))


text:
@testset "A star" begin
    g3 = PathGraph(5)
    g4 = PathDiGraph(5)

    d1 = float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0])
    d2 = sparse(float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]))
    for g in testgraphs(g3), dg in testdigraphs(g4)
      @test @inferred(a_star(g, 1, 4, d1)) ==
          @inferred(a_star(dg, 1, 4, d1)) ==
          @inferred(a_star(g, 1, 4, d2))
      @test isempty(@inferred(a_star(dg, 4, 1)))
    end
end

max_stars_repo_name: AsileBcd/JohnsonCycles

max_issues_repo_name: AsileBcd/JohnsonCycles

max_forks_repo_name: AsileBcd/JohnsonCycles


text:
function RMP2{T}(refWfn::Fermi.HartreeFock.RHF,alg::Fermi.MollerPlesset.Conventional) where T <: AbstractFloat
    print_header()
    dmp2 = 0.0
    nocc = refWfn.ndocc
    @output "*  executing restricted MP2\n"
    @output "   nocc: {:>3}\n" nocc
    @output "   nvir: {:>3}\n" refWfn.nvir
    rocc = 1:1:nocc
    rvir = nocc+1:1:nocc+refWfn.nvir
    epsa = refWfn.eps
    @output "*  performing AO->MO integral transformation ... "
    t = @elapsed moeri = refWfn.ints["OOVV"]
    @output "done in {:>5.2f}s\n" t
    @output "*  Computing MP2 energy ... "
    t = @elapsed for b in rvir
        for a in rvir
            for j in rocc
                for i in rocc
                    aa = a - nocc
                    bb = b - nocc
                    dmp2 +=
                        (
                            moeri[i, j, aa, bb] *
                            (2 * moeri[i, j, aa, bb] - moeri[i, j, bb, aa])
                        ) / (epsa[i] + epsa[j] - epsa[a] - epsa[b])
                end
            end
        end
    end
    @output "done in {:>5.2f}s\n" t
    @output "   @RMP2 {:>20.17f} Eh\n" dmp2
    RMP2(dmp2,Fermi.MemTensor{T}(zeros(0,0,0,0)))
end


text:
dists = [
    "constraints",
    "expfam",
    "HMM",
    "matrixnormal",
    "LKJ"
]

for dname in dists
    include(joinpath("distributions", "$(dname).jl"))
end


text:
module ComputationManager
using DataStructures: OrderedDict

export savejob

const _JOBS = OrderedDict{String,Any}()

# TODO: this method is deprecated
function savejob(f, name::AbstractString)
    haskey(_JOBS, name) && @warn "Overwriting existing job: $(name)"
    _JOBS[name] = f(name)
    return name
end

function savejob(job::NamedTuple)
    @assert haskey(job, :name)
    @assert haskey(job, :f)
    haskey(_JOBS, job.name) && @warn "Overwriting existing job: $(job.name)"
    _JOBS[job.name] = job.f
    return job.name
end

function main(args)
    global _JOBS
    if isempty(args)
        for name in keys(_JOBS)
            println(name)
        end
        println()
    else
        names = ("--runall" in args) ? collect(keys(_JOBS)) : args
        hasnames = map(name -> haskey(_JOBS, name), names)
        if !all(hasnames)
            error("Invalid jobs names: $(names[hasnames])")
        end
        for name in names
            @info "Running: $(name)"
            _JOBS[name]()
        end
    end
end

end


text:
module Contractors
using ValidatedNumerics

export root, range_estimate, ShootingMethod, nthpreimage!, preimage, unique_sign, unique_increasing

"""
unique_sign(x)

Sign of an interval, but throws an error if it is not unique.
Used by various functions to compute orientations
"""
function unique_sign(x)
	s = sign(x)
	@assert isthin(s)
	return s.hi
end

"""
unique_increasing(a, b)

Given intervals a, b, returns `true` if a < b, `false` if b < a, and raises an error if it is not uniquely determined.
"""
function unique_increasing(a::Interval, b::Interval)
	if a.hi < b.lo
		return true
	elseif b.hi < a.lo
		return false
	else
		error("Insufficient precision to check the sign of this function")
	end
end
function unique_increasing(a, b) # Fallback for Float64
	if a < b
		return true
	elseif a > b
		return false
	else
		error("Could not determine sign")
	end
end

# this seems slower
#using TaylorSeries
#derivative(f) = x-> f(Taylor1([x,1.],1))[1]

using DualNumbers
derivative(f) = x->f(Dual(x, 1..1)).epsilon

"""
Compute a single root with (possibly multivariate) interval Newton

x must be an Interval (univariate) or IntervalBox (multivariate)

Stops when the interval reaches a fixed point, when the diameter is smaller than ε,
or when max_iter iterations are reached (with an error)
"""
root(f, x, ϵ; max_iter = 100) = root(f, derivative(f), x, ϵ; max_iter = max_iter)

function root(f, f′, x, ϵ; max_iter = 100)
	for i in 1:max_iter
		x_old = x
		x_mid = Interval(mid(x))
		x = intersect(x, x_mid - f′(x) \ f(x_mid))
		if x_old == x || isempty(x) || diam(x) < ϵ
			return x
		end
	end
	@info "Maximum iterates reached" max_iter, x, f(x)
	return x
end

preimage(y, f, X, ϵ; max_iter=100) = root(x -> f(x)-y, X, ϵ; max_iter)

# superseded by IntervalOptimisation.jl
function range_estimate(f, domain, recstep = 5)
	if recstep == 1
		return f(domain)
	else
		a, b = bisect(domain)
		Iₐ = range_estimate(f, a, recstep-1)
		Iᵦ = range_estimate(f, b, recstep-1)
		return Iₐ ∪ Iᵦ
	end
end

using LinearAlgebra

# this function generates the Jacobian for
# f(x_0)=x_1, f(x_1)=x_2, ..., f(x_{n-1})=y

coeff_interval(x::Array{Interval{T}, 1}) where {T} = T

function Jac(fprime, v::Vector{T}) where {T}
    dv = fprime.(v)
    ev = -ones(T, length(v)-1)
    return Bidiagonal{T}(dv, ev, :U)
end

# Used in InducedLSV; won't touch it to avoid breaking stuff --federico
function ShootingMethod(f, fprime, n, x, y, rigstep = 10)
	F = x->(f.(x)-[x[2:end]; y])

	for i in 1:rigstep
		x_mid = Interval{coeff_interval(x)}.(mid.(x))
		x = intersect.(x, x_mid-Jac(fprime, x)\F(x_mid))
	end
	return x
end

"""
Newer version of the 'shooting method' to compute the kth preimage of a point (or interval y)
fs contains k functions, X contains their domains. This computes a solution of
fk(f_{k-1}( ...  f1(x) ... )) = y.
Overwrites X with [x f1(x) f2(f1(x)) ... f_{k-1}(...)], so the
true solution is X[1].

Tries to avoid allocations and stuff.
"""
function nthpreimage!(y, fs, X; max_iter = 100)
	newX = zero(X)
	Xmid = zero(X)
	n = length(X)
	for i in 1:max_iter
		Xmid .= Interval.(mid.(X))
		newX[end] = (fs[end](Xmid[end]) - y) / derivative(fs[end])(X[end])
		for i = length(X)-1:-1:1
			newX[i] = (fs[i](Xmid[i]) - Xmid[i+1] + newX[i+1]) / derivative(fs[i])(X[i])
		end
		newX .= intersect.(Xmid - newX, X)
		if isempty(newX) || newX == X
			return newX
		end
		X .= newX
	end
	@info "Maximum iterates reached" max_iter
	return X
end

end #module


text:
@testset "5.3.3 (d+e x)^m (a+b arctan(c x^n))^p" begin
    (a, b, c, d, e, x, ) = @variables a b c d e x

    #= ::Package:: =#

    #= ::Title:: =#
    #=Integrands*of*the*form*(d+e*x)^m*(a+b*atan(c*x^n))^p=#

    #= ::Section::Closed:: =#
    #=Integrands*of*the*form*(d+e*x)^m*(a+b*atan(c*x^1))^p=#

    @test_int [(d + e*x)^4*(a + b*atan(c*x)), x, 6, -((b*d*e*(2*c^2*d^2 - e^2)*x)/c^3) - (b*e^2*(10*c^2*d^2 - e^2)*x^2)/(10*c^3) - (b*d*e^3*x^3)/(3*c) - (b*e^4*x^4)/(20*c) - (b*d*(c^4*d^4 - 10*c^2*d^2*e^2 + 5*e^4)*atan(c*x))/(5*c^4*e) + ((d + e*x)^5*(a + b*atan(c*x)))/(5*e) - (b*(5*c^4*d^4 - 10*c^2*d^2*e^2 + e^4)*log(1 + c^2*x^2))/(10*c^5)]
    @test_int [(d + e*x)^3*(a + b*atan(c*x)), x, 6, -(b*e*(6*c^2*d^2 - e^2)*x)/(4*c^3) - (b*d*e^2*x^2)/(2*c) - (b*e^3*x^3)/(12*c) - (b*(c^4*d^4 - 6*c^2*d^2*e^2 + e^4)*atan(c*x))/(4*c^4*e) + ((d + e*x)^4*(a + b*atan(c*x)))/(4*e) - (b*d*(c*d - e)*(c*d + e)*log(1 + c^2*x^2))/(2*c^3)]
    @test_int [(d + e*x)^2*(a + b*atan(c*x)), x, 6, -((b*d*e*x)/c) - (b*e^2*x^2)/(6*c) - (b*d*(d^2 - (3*e^2)/c^2)*atan(c*x))/(3*e) + ((d + e*x)^3*(a + b*atan(c*x)))/(3*e) - (b*(3*c^2*d^2 - e^2)*log(1 + c^2*x^2))/(6*c^3)]
    @test_int [(d + e*x)^1*(a + b*atan(c*x)), x, 6, -(b*e*x)/(2*c) - (b*(d^2 - e^2/c^2)*atan(c*x))/(2*e) + ((d + e*x)^2*(a + b*atan(c*x)))/(2*e) - (b*d*log(1 + c^2*x^2))/(2*c)]
    @test_int [(a + b*atan(c*x))/(d + e*x)^1, x, 4, -(((a + b*atan(c*x))*log(2/(1 - im*c*x)))/e) + ((a + b*atan(c*x))*log((2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/e + (im*b*PolyLog(2, 1 - 2/(1 - im*c*x)))/(2*e) - (im*b*PolyLog(2, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(2*e)]
    @test_int [(a + b*atan(c*x))/(d + e*x)^2, x, 6, (b*c^2*d*atan(c*x))/(e*(c^2*d^2 + e^2)) - (a + b*atan(c*x))/(e*(d + e*x)) + (b*c*log(d + e*x))/(c^2*d^2 + e^2) - (b*c*log(1 + c^2*x^2))/(2*(c^2*d^2 + e^2))]
    @test_int [(a + b*atan(c*x))/(d + e*x)^3, x, 7, -(b*c)/(2*(c^2*d^2 + e^2)*(d + e*x)) + (b*c^2*(c*d - e)*(c*d + e)*atan(c*x))/(2*e*(c^2*d^2 + e^2)^2) - (a + b*atan(c*x))/(2*e*(d + e*x)^2) + (b*c^3*d*log(d + e*x))/(c^2*d^2 + e^2)^2 - (b*c^3*d*log(1 + c^2*x^2))/(2*(c^2*d^2 + e^2)^2)]
    @test_int [(a + b*atan(c*x))/(d + e*x)^4, x, 7, -(b*c)/(6*(c^2*d^2 + e^2)*(d + e*x)^2) - (2*b*c^3*d)/(3*(c^2*d^2 + e^2)^2*(d + e*x)) + (b*c^4*d*(c^2*d^2 - 3*e^2)*atan(c*x))/(3*e*(c^2*d^2 + e^2)^3) - (a + b*atan(c*x))/(3*e*(d + e*x)^3) + (b*c^3*(3*c^2*d^2 - e^2)*log(d + e*x))/(3*(c^2*d^2 + e^2)^3) - (b*c^3*(3*c^2*d^2 - e^2)*log(1 + c^2*x^2))/(6*(c^2*d^2 + e^2)^3)]

    @test_int [(d + e*x)^3*(a + b*atan(c*x))^2, x, 19, (b^2*d*e^2*x)/c^2 - (a*b*e*(6*c^2*d^2 - e^2)*x)/(2*c^3) + (b^2*e^3*x^2)/(12*c^2) - (b^2*d*e^2*atan(c*x))/c^3 - (b^2*e*(6*c^2*d^2 - e^2)*x*atan(c*x))/(2*c^3) - (b*d*e^2*x^2*(a + b*atan(c*x)))/c - (b*e^3*x^3*(a + b*atan(c*x)))/(6*c) + (im*d*(c*d - e)*(c*d + e)*(a + b*atan(c*x))^2)/c^3 - ((c^4*d^4 - 6*c^2*d^2*e^2 + e^4)*(a + b*atan(c*x))^2)/(4*c^4*e) + ((d + e*x)^4*(a + b*atan(c*x))^2)/(4*e) + (2*b*d*(c*d - e)*(c*d + e)*(a + b*atan(c*x))*log(2/(1 + im*c*x)))/c^3 - (b^2*e^3*log(1 + c^2*x^2))/(12*c^4) + (b^2*e*(6*c^2*d^2 - e^2)*log(1 + c^2*x^2))/(4*c^4) + (im*b^2*d*(c*d - e)*(c*d + e)*PolyLog(2, 1 - 2/(1 + im*c*x)))/c^3]
    @test_int [(d + e*x)^2*(a + b*atan(c*x))^2, x, 15, (-2*a*b*d*e*x)/c + (b^2*e^2*x)/(3*c^2) - (b^2*e^2*atan(c*x))/(3*c^3) - (2*b^2*d*e*x*atan(c*x))/c - (b*e^2*x^2*(a + b*atan(c*x)))/(3*c) + ((im/3)*(3*c^2*d^2 - e^2)*(a + b*atan(c*x))^2)/c^3 - (d*(d^2 - (3*e^2)/c^2)*(a + b*atan(c*x))^2)/(3*e) + ((d + e*x)^3*(a + b*atan(c*x))^2)/(3*e) + (2*b*(3*c^2*d^2 - e^2)*(a + b*atan(c*x))*log(2/(1 + im*c*x)))/(3*c^3) + (b^2*d*e*log(1 + c^2*x^2))/c^2 + ((im/3)*b^2*(3*c^2*d^2 - e^2)*PolyLog(2, 1 - 2/(1 + im*c*x)))/c^3]
    @test_int [(d + e*x)^1*(a + b*atan(c*x))^2, x, 12, -((a*b*e*x)/c) - (b^2*e*x*atan(c*x))/c + (im*d*(a + b*atan(c*x))^2)/c - ((d^2 - e^2/c^2)*(a + b*atan(c*x))^2)/(2*e) + ((d + e*x)^2*(a + b*atan(c*x))^2)/(2*e) + (2*b*d*(a + b*atan(c*x))*log(2/(1 + im*c*x)))/c + (b^2*e*log(1 + c^2*x^2))/(2*c^2) + (im*b^2*d*PolyLog(2, 1 - 2/(1 + im*c*x)))/c]
    @test_int [(a + b*atan(c*x))^2/(d + e*x)^1, x, 1, -(((a + b*atan(c*x))^2*log(2/(1 - im*c*x)))/e) + ((a + b*atan(c*x))^2*log((2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/e + (im*b*(a + b*atan(c*x))*PolyLog(2, 1 - 2/(1 - im*c*x)))/e - (im*b*(a + b*atan(c*x))*PolyLog(2, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/e - (b^2*PolyLog(3, 1 - 2/(1 - im*c*x)))/(2*e) + (b^2*PolyLog(3, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(2*e)]
    @test_int [(a + b*atan(c*x))^2/(d + e*x)^2, x, 13, (im*c*(a + b*atan(c*x))^2)/(c^2*d^2 + e^2) + (c^2*d*(a + b*atan(c*x))^2)/(e*(c^2*d^2 + e^2)) - (a + b*atan(c*x))^2/(e*(d + e*x)) - (2*b*c*(a + b*atan(c*x))*log(2/(1 - im*c*x)))/(c^2*d^2 + e^2) + (2*b*c*(a + b*atan(c*x))*log(2/(1 + im*c*x)))/(c^2*d^2 + e^2) + (2*b*c*(a + b*atan(c*x))*log((2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(c^2*d^2 + e^2) + (im*b^2*c*PolyLog(2, 1 - 2/(1 - im*c*x)))/(c^2*d^2 + e^2) + (im*b^2*c*PolyLog(2, 1 - 2/(1 + im*c*x)))/(c^2*d^2 + e^2) - (im*b^2*c*PolyLog(2, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(c^2*d^2 + e^2)]
    @test_int [(a + b*atan(c*x))^2/(d + e*x)^3, x, 19, (b^2*c^3*d*atan(c*x))/(c^2*d^2 + e^2)^2 - (b*c*(a + b*atan(c*x)))/((c^2*d^2 + e^2)*(d + e*x)) + (im*c^3*d*(a + b*atan(c*x))^2)/(c^2*d^2 + e^2)^2 + (c^2*(c*d - e)*(c*d + e)*(a + b*atan(c*x))^2)/(2*e*(c^2*d^2 + e^2)^2) - (a + b*atan(c*x))^2/(2*e*(d + e*x)^2) - (2*b*c^3*d*(a + b*atan(c*x))*log(2/(1 - im*c*x)))/(c^2*d^2 + e^2)^2 + (2*b*c^3*d*(a + b*atan(c*x))*log(2/(1 + im*c*x)))/(c^2*d^2 + e^2)^2 + (b^2*c^2*e*log(d + e*x))/(c^2*d^2 + e^2)^2 + (2*b*c^3*d*(a + b*atan(c*x))*log((2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(c^2*d^2 + e^2)^2 - (b^2*c^2*e*log(1 + c^2*x^2))/(2*(c^2*d^2 + e^2)^2) + (im*b^2*c^3*d*PolyLog(2, 1 - 2/(1 - im*c*x)))/(c^2*d^2 + e^2)^2 + (im*b^2*c^3*d*PolyLog(2, 1 - 2/(1 + im*c*x)))/(c^2*d^2 + e^2)^2 - (im*b^2*c^3*d*PolyLog(2, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(c^2*d^2 + e^2)^2]

    @test_int [(d + e*x)^3*(a + b*atan(c*x))^3, x, 29, (3*a*b^2*d*e^2*x)/c^2 - (b^3*e^3*x)/(4*c^3) + (b^3*e^3*atan(c*x))/(4*c^4) + (3*b^3*d*e^2*x*atan(c*x))/c^2 + (b^2*e^3*x^2*(a + b*atan(c*x)))/(4*c^2) - (3*b*d*e^2*(a + b*atan(c*x))^2)/(2*c^3) + ((im/4)*b*e^3*(a + b*atan(c*x))^2)/c^4 - (((3*im)/4)*b*e*(6*c^2*d^2 - e^2)*(a + b*atan(c*x))^2)/c^4 - (3*b*e*(6*c^2*d^2 - e^2)*x*(a + b*atan(c*x))^2)/(4*c^3) - (3*b*d*e^2*x^2*(a + b*atan(c*x))^2)/(2*c) - (b*e^3*x^3*(a + b*atan(c*x))^2)/(4*c) + (im*d*(c*d - e)*(c*d + e)*(a + b*atan(c*x))^3)/c^3 - ((c^4*d^4 - 6*c^2*d^2*e^2 + e^4)*(a + b*atan(c*x))^3)/(4*c^4*e) + ((d + e*x)^4*(a + b*atan(c*x))^3)/(4*e) + (b^2*e^3*(a + b*atan(c*x))*log(2/(1 + im*c*x)))/(2*c^4) - (3*b^2*e*(6*c^2*d^2 - e^2)*(a + b*atan(c*x))*log(2/(1 + im*c*x)))/(2*c^4) + (3*b*d*(c*d - e)*(c*d + e)*(a + b*atan(c*x))^2*log(2/(1 + im*c*x)))/c^3 - (3*b^3*d*e^2*log(1 + c^2*x^2))/(2*c^3) + ((im/4)*b^3*e^3*PolyLog(2, 1 - 2/(1 + im*c*x)))/c^4 - (((3*im)/4)*b^3*e*(6*c^2*d^2 - e^2)*PolyLog(2, 1 - 2/(1 + im*c*x)))/c^4 + ((3*im)*b^2*d*(c*d - e)*(c*d + e)*(a + b*atan(c*x))*PolyLog(2, 1 - 2/(1 + im*c*x)))/c^3 + (3*b^3*d*(c*d - e)*(c*d + e)*PolyLog(3, 1 - 2/(1 + im*c*x)))/(2*c^3)]
    @test_int [(d + e*x)^2*(a + b*atan(c*x))^3, x, 20, (a*b^2*e^2*x)/c^2 + (b^3*e^2*x*atan(c*x))/c^2 - ((3*im)*b*d*e*(a + b*atan(c*x))^2)/c^2 - (b*e^2*(a + b*atan(c*x))^2)/(2*c^3) - (3*b*d*e*x*(a + b*atan(c*x))^2)/c - (b*e^2*x^2*(a + b*atan(c*x))^2)/(2*c) + ((im/3)*(3*c^2*d^2 - e^2)*(a + b*atan(c*x))^3)/c^3 - (d*(d^2 - (3*e^2)/c^2)*(a + b*atan(c*x))^3)/(3*e) + ((d + e*x)^3*(a + b*atan(c*x))^3)/(3*e) - (6*b^2*d*e*(a + b*atan(c*x))*log(2/(1 + im*c*x)))/c^2 + (b*(3*c^2*d^2 - e^2)*(a + b*atan(c*x))^2*log(2/(1 + im*c*x)))/c^3 - (b^3*e^2*log(1 + c^2*x^2))/(2*c^3) - ((3*im)*b^3*d*e*PolyLog(2, 1 - 2/(1 + im*c*x)))/c^2 + (im*b^2*(3*c^2*d^2 - e^2)*(a + b*atan(c*x))*PolyLog(2, 1 - 2/(1 + im*c*x)))/c^3 + (b^3*(3*c^2*d^2 - e^2)*PolyLog(3, 1 - 2/(1 + im*c*x)))/(2*c^3)]
    @test_int [(d + e*x)^1*(a + b*atan(c*x))^3, x, 14, (((-3*im)/2)*b*e*(a + b*atan(c*x))^2)/c^2 - (3*b*e*x*(a + b*atan(c*x))^2)/(2*c) + (im*d*(a + b*atan(c*x))^3)/c - ((d^2 - e^2/c^2)*(a + b*atan(c*x))^3)/(2*e) + ((d + e*x)^2*(a + b*atan(c*x))^3)/(2*e) - (3*b^2*e*(a + b*atan(c*x))*log(2/(1 + im*c*x)))/c^2 + (3*b*d*(a + b*atan(c*x))^2*log(2/(1 + im*c*x)))/c - (((3*im)/2)*b^3*e*PolyLog(2, 1 - 2/(1 + im*c*x)))/c^2 + ((3*im)*b^2*d*(a + b*atan(c*x))*PolyLog(2, 1 - 2/(1 + im*c*x)))/c + (3*b^3*d*PolyLog(3, 1 - 2/(1 + im*c*x)))/(2*c)]
    @test_int [(a + b*atan(c*x))^3/(d + e*x)^1, x, 1, -(((a + b*atan(c*x))^3*log(2/(1 - im*c*x)))/e) + ((a + b*atan(c*x))^3*log((2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/e + (3*im*b*(a + b*atan(c*x))^2*PolyLog(2, 1 - 2/(1 - im*c*x)))/(2*e) - (3*im*b*(a + b*atan(c*x))^2*PolyLog(2, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(2*e) - (3*b^2*(a + b*atan(c*x))*PolyLog(3, 1 - 2/(1 - im*c*x)))/(2*e) + (3*b^2*(a + b*atan(c*x))*PolyLog(3, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(2*e) - (3*im*b^3*PolyLog(4, 1 - 2/(1 - im*c*x)))/(4*e) + (3*im*b^3*PolyLog(4, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(4*e)]
    @test_int [(a + b*atan(c*x))^3/(d + e*x)^2, x, 10, (im*c*(a + b*atan(c*x))^3)/(c^2*d^2 + e^2) + (c^2*d*(a + b*atan(c*x))^3)/(e*(c^2*d^2 + e^2)) - (a + b*atan(c*x))^3/(e*(d + e*x)) - (3*b*c*(a + b*atan(c*x))^2*log(2/(1 - im*c*x)))/(c^2*d^2 + e^2) + (3*b*c*(a + b*atan(c*x))^2*log(2/(1 + im*c*x)))/(c^2*d^2 + e^2) + (3*b*c*(a + b*atan(c*x))^2*log((2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(c^2*d^2 + e^2) + (3*im*b^2*c*(a + b*atan(c*x))*PolyLog(2, 1 - 2/(1 - im*c*x)))/(c^2*d^2 + e^2) + (3*im*b^2*c*(a + b*atan(c*x))*PolyLog(2, 1 - 2/(1 + im*c*x)))/(c^2*d^2 + e^2) - (3*im*b^2*c*(a + b*atan(c*x))*PolyLog(2, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(c^2*d^2 + e^2) - (3*b^3*c*PolyLog(3, 1 - 2/(1 - im*c*x)))/(2*(c^2*d^2 + e^2)) + (3*b^3*c*PolyLog(3, 1 - 2/(1 + im*c*x)))/(2*(c^2*d^2 + e^2)) + (3*b^3*c*PolyLog(3, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(2*(c^2*d^2 + e^2))]
    @test_int [(a + b*atan(c*x))^3/(d + e*x)^3, x, 23, (3*b*c^3*d*(a + b*atan(c*x))^2)/(2*(c^2*d^2 + e^2)^2) + (3*im*b*c^2*e*(a + b*atan(c*x))^2)/(2*(c^2*d^2 + e^2)^2) - (3*b*c*(a + b*atan(c*x))^2)/(2*(c^2*d^2 + e^2)*(d + e*x)) + (im*c^3*d*(a + b*atan(c*x))^3)/(c^2*d^2 + e^2)^2 + (c^2*(c*d - e)*(c*d + e)*(a + b*atan(c*x))^3)/(2*e*(c^2*d^2 + e^2)^2) - (a + b*atan(c*x))^3/(2*e*(d + e*x)^2) - (3*b^2*c^2*e*(a + b*atan(c*x))*log(2/(1 - im*c*x)))/(c^2*d^2 + e^2)^2 - (3*b*c^3*d*(a + b*atan(c*x))^2*log(2/(1 - im*c*x)))/(c^2*d^2 + e^2)^2 + (3*b^2*c^2*e*(a + b*atan(c*x))*log(2/(1 + im*c*x)))/(c^2*d^2 + e^2)^2 + (3*b*c^3*d*(a + b*atan(c*x))^2*log(2/(1 + im*c*x)))/(c^2*d^2 + e^2)^2 + (3*b^2*c^2*e*(a + b*atan(c*x))*log((2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(c^2*d^2 + e^2)^2 + (3*b*c^3*d*(a + b*atan(c*x))^2*log((2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(c^2*d^2 + e^2)^2 + (3*im*b^3*c^2*e*PolyLog(2, 1 - 2/(1 - im*c*x)))/(2*(c^2*d^2 + e^2)^2) + (3*im*b^2*c^3*d*(a + b*atan(c*x))*PolyLog(2, 1 - 2/(1 - im*c*x)))/(c^2*d^2 + e^2)^2 + (3*im*b^3*c^2*e*PolyLog(2, 1 - 2/(1 + im*c*x)))/(2*(c^2*d^2 + e^2)^2) + (3*im*b^2*c^3*d*(a + b*atan(c*x))*PolyLog(2, 1 - 2/(1 + im*c*x)))/(c^2*d^2 + e^2)^2 - (3*im*b^3*c^2*e*PolyLog(2, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(2*(c^2*d^2 + e^2)^2) - (3*im*b^2*c^3*d*(a + b*atan(c*x))*PolyLog(2, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(c^2*d^2 + e^2)^2 - (3*b^3*c^3*d*PolyLog(3, 1 - 2/(1 - im*c*x)))/(2*(c^2*d^2 + e^2)^2) + (3*b^3*c^3*d*PolyLog(3, 1 - 2/(1 + im*c*x)))/(2*(c^2*d^2 + e^2)^2) + (3*b^3*c^3*d*PolyLog(3, 1 - (2*c*(d + e*x))/((c*d + im*e)*(1 - im*c*x))))/(2*(c^2*d^2 + e^2)^2)]

    #= ::Section::Closed:: =#
    #=Integrands*of*the*form*(d+e*x)^m*(a+b*atan(c*x^2))^p=#

    #= ::Subsection::Closed:: =#
    #=Integrands*of*the*form*(d+e*x)^m*(a+b*atan(c*x^2))^p=#

    @test_int [(d + e*x)^2*(a + b*atan(c*x^2)), x, 17, -((2*b*e^2*x)/(3*c)) - (b*d^3*atan(c*x^2))/(3*e) + ((d + e*x)^3*(a + b*atan(c*x^2)))/(3*e) + (b*(3*c*d^2 - e^2)*atan(1 - sqrt(2)*sqrt(c)*x))/(3*sqrt(2)*c^(3/2)) - (b*(3*c*d^2 - e^2)*atan(1 + sqrt(2)*sqrt(c)*x))/(3*sqrt(2)*c^(3/2)) - (b*(3*c*d^2 + e^2)*log(1 - sqrt(2)*sqrt(c)*x + c*x^2))/(6*sqrt(2)*c^(3/2)) + (b*(3*c*d^2 + e^2)*log(1 + sqrt(2)*sqrt(c)*x + c*x^2))/(6*sqrt(2)*c^(3/2)) - (b*d*e*log(1 + c^2*x^4))/(2*c)]
    @test_int [(d + e*x)^1*(a + b*atan(c*x^2)), x, 16, -((b*d^2*atan(c*x^2))/(2*e)) + ((d + e*x)^2*(a + b*atan(c*x^2)))/(2*e) + (b*d*atan(1 - sqrt(2)*sqrt(c)*x))/(sqrt(2)*sqrt(c)) - (b*d*atan(1 + sqrt(2)*sqrt(c)*x))/(sqrt(2)*sqrt(c)) - (b*d*log(1 - sqrt(2)*sqrt(c)*x + c*x^2))/(2*sqrt(2)*sqrt(c)) + (b*d*log(1 + sqrt(2)*sqrt(c)*x + c*x^2))/(2*sqrt(2)*sqrt(c)) - (b*e*log(1 + c^2*x^4))/(4*c)]
    @test_int [(a + b*atan(c*x^2))/(d + e*x)^1, x, 19, ((a + b*atan(c*x^2))*log(d + e*x))/e + (b*c*log((e*(1 - (-c^2)^(1/4)*x))/((-c^2)^(1/4)*d + e))*log(d + e*x))/(2*sqrt(-c^2)*e) + (b*c*log(-((e*(1 + (-c^2)^(1/4)*x))/((-c^2)^(1/4)*d - e)))*log(d + e*x))/(2*sqrt(-c^2)*e) - (b*c*log((e*(1 - sqrt(-sqrt(-c^2))*x))/(sqrt(-sqrt(-c^2))*d + e))*log(d + e*x))/(2*sqrt(-c^2)*e) - (b*c*log(-((e*(1 + sqrt(-sqrt(-c^2))*x))/(sqrt(-sqrt(-c^2))*d - e)))*log(d + e*x))/(2*sqrt(-c^2)*e) + (b*c*PolyLog(2, ((-c^2)^(1/4)*(d + e*x))/((-c^2)^(1/4)*d - e)))/(2*sqrt(-c^2)*e) - (b*c*PolyLog(2, (sqrt(-sqrt(-c^2))*(d + e*x))/(sqrt(-sqrt(-c^2))*d - e)))/(2*sqrt(-c^2)*e) + (b*c*PolyLog(2, ((-c^2)^(1/4)*(d + e*x))/((-c^2)^(1/4)*d + e)))/(2*sqrt(-c^2)*e) - (b*c*PolyLog(2, (sqrt(-sqrt(-c^2))*(d + e*x))/(sqrt(-sqrt(-c^2))*d + e)))/(2*sqrt(-c^2)*e)]
    @test_int [(a + b*atan(c*x^2))/(d + e*x)^2, x, 18, (b*c^2*d^3*atan(c*x^2))/(e*(c^2*d^4 + e^4)) - (a + b*atan(c*x^2))/(e*(d + e*x)) + (b*sqrt(c)*(c*d^2 - e^2)*atan(1 - sqrt(2)*sqrt(c)*x))/(sqrt(2)*(c^2*d^4 + e^4)) - (b*sqrt(c)*(c*d^2 - e^2)*atan(1 + sqrt(2)*sqrt(c)*x))/(sqrt(2)*(c^2*d^4 + e^4)) - (2*b*c*d*e*log(d + e*x))/(c^2*d^4 + e^4) - (b*sqrt(c)*(c*d^2 + e^2)*log(1 - sqrt(2)*sqrt(c)*x + c*x^2))/(2*sqrt(2)*(c^2*d^4 + e^4)) + (b*sqrt(c)*(c*d^2 + e^2)*log(1 + sqrt(2)*sqrt(c)*x + c*x^2))/(2*sqrt(2)*(c^2*d^4 + e^4)) + (b*c*d*e*log(1 + c^2*x^4))/(2*(c^2*d^4 + e^4))]

    #= [(d + e*x)^2*(a + b*atan(c*x^2))^2, x, 163, a^2*d^2*x - (4*a*b*e^2*x)/(3*c) + (2/9)*im*a*b*e^2*x^3 - (2*(-1)^(3/4)*a*b*d^2*atan((-1)^(3/4)*sqrt(c)*x))/sqrt(c) + (4*(-1)^(3/4)*b^2*e^2*atan((-1)^(3/4)*sqrt(c)*x))/(3*c^(3/2)) + ((-1)^(3/4)*b^2*d^2*atan((-1)^(3/4)*sqrt(c)*x)^2)/sqrt(c) + ((-1)^(1/4)*b^2*e^2*atan((-1)^(3/4)*sqrt(c)*x)^2)/(3*c^(3/2)) + (im*d*e*(a + b*atan(c*x^2))^2)/c + d*e*x^2*(a + b*atan(c*x^2))^2 + (2*(-1)^(3/4)*a*b*d^2*atanh((-1)^(3/4)*sqrt(c)*x))/sqrt(c) - (2*(-1)^(1/4)*a*b*e^2*atanh((-1)^(3/4)*sqrt(c)*x))/(3*c^(3/2)) - (4*(-1)^(3/4)*b^2*e^2*atanh((-1)^(3/4)*sqrt(c)*x))/(3*c^(3/2)) - ((-1)^(1/4)*b^2*d^2*atanh((-1)^(3/4)*sqrt(c)*x)^2)/sqrt(c) - ((-1)^(3/4)*b^2*e^2*atanh((-1)^(3/4)*sqrt(c)*x)^2)/(3*c^(3/2)) + (2*(-1)^(1/4)*b^2*d^2*atan((-1)^(3/4)*sqrt(c)*x)*log(2/(1 - (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) - (2*(-1)^(3/4)*b^2*e^2*atan((-1)^(3/4)*sqrt(c)*x)*log(2/(1 - (-1)^(1/4)*sqrt(c)*x)))/(3*c^(3/2)) - (2*(-1)^(1/4)*b^2*d^2*atan((-1)^(3/4)*sqrt(c)*x)*log(2/(1 + (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) + (2*(-1)^(3/4)*b^2*e^2*atan((-1)^(3/4)*sqrt(c)*x)*log(2/(1 + (-1)^(1/4)*sqrt(c)*x)))/(3*c^(3/2)) + ((-1)^(1/4)*b^2*d^2*atan((-1)^(3/4)*sqrt(c)*x)*log((sqrt(2)*((-1)^(1/4) + sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) - ((-1)^(3/4)*b^2*e^2*atan((-1)^(3/4)*sqrt(c)*x)*log((sqrt(2)*((-1)^(1/4) + sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/(3*c^(3/2)) + (2*(-1)^(1/4)*b^2*d^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(2/(1 - (-1)^(3/4)*sqrt(c)*x)))/sqrt(c) + (2*(-1)^(3/4)*b^2*e^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(2/(1 - (-1)^(3/4)*sqrt(c)*x)))/(3*c^(3/2)) - (2*(-1)^(1/4)*b^2*d^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(2/(1 + (-1)^(3/4)*sqrt(c)*x)))/sqrt(c) - (2*(-1)^(3/4)*b^2*e^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(2/(1 + (-1)^(3/4)*sqrt(c)*x)))/(3*c^(3/2)) + ((-1)^(1/4)*b^2*d^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(-((sqrt(2)*((-1)^(3/4) + sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x))))/sqrt(c) + ((-1)^(3/4)*b^2*e^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(-((sqrt(2)*((-1)^(3/4) + sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x))))/(3*c^(3/2)) + ((-1)^(1/4)*b^2*d^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(((1 + im)*(1 + (-1)^(1/4)*sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x)))/sqrt(c) + ((-1)^(3/4)*b^2*e^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(((1 + im)*(1 + (-1)^(1/4)*sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x)))/(3*c^(3/2)) + ((-1)^(1/4)*b^2*d^2*atan((-1)^(3/4)*sqrt(c)*x)*log(((1 - im)*(1 + (-1)^(3/4)*sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) - ((-1)^(3/4)*b^2*e^2*atan((-1)^(3/4)*sqrt(c)*x)*log(((1 - im)*(1 + (-1)^(3/4)*sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/(3*c^(3/2)) + im*a*b*d^2*x*log(1 - im*c*x^2) - (2*im*b^2*e^2*x*log(1 - im*c*x^2))/(3*c) - (1/9)*b^2*e^2*x^3*log(1 - im*c*x^2) + ((-1)^(1/4)*b^2*d^2*atan((-1)^(3/4)*sqrt(c)*x)*log(1 - im*c*x^2))/sqrt(c) - ((-1)^(1/4)*b^2*d^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(1 - im*c*x^2))/sqrt(c) - ((-1)^(3/4)*b^2*e^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(1 - im*c*x^2))/(3*c^(3/2)) - (1/4)*b^2*d^2*x*log(1 - im*c*x^2)^2 - (1/9)*im*b*e^2*x^3*(2*a + im*b*log(1 - im*c*x^2)) - ((-1)^(1/4)*b*e^2*atan((-1)^(3/4)*sqrt(c)*x)*(2*a + im*b*log(1 - im*c*x^2)))/(3*c^(3/2)) + (1/12)*e^2*x^3*(2*a + im*b*log(1 - im*c*x^2))^2 + (2*b*d*e*(a + b*atan(c*x^2))*log(2/(1 + im*c*x^2)))/c - im*a*b*d^2*x*log(1 + im*c*x^2) + (2*im*b^2*e^2*x*log(1 + im*c*x^2))/(3*c) - (1/3)*im*a*b*e^2*x^3*log(1 + im*c*x^2) - ((-1)^(1/4)*b^2*d^2*atan((-1)^(3/4)*sqrt(c)*x)*log(1 + im*c*x^2))/sqrt(c) + ((-1)^(3/4)*b^2*e^2*atan((-1)^(3/4)*sqrt(c)*x)*log(1 + im*c*x^2))/(3*c^(3/2)) + ((-1)^(1/4)*b^2*d^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(1 + im*c*x^2))/sqrt(c) + ((-1)^(3/4)*b^2*e^2*atanh((-1)^(3/4)*sqrt(c)*x)*log(1 + im*c*x^2))/(3*c^(3/2)) + (1/2)*b^2*d^2*x*log(1 - im*c*x^2)*log(1 + im*c*x^2) + (1/6)*b^2*e^2*x^3*log(1 - im*c*x^2)*log(1 + im*c*x^2) - (1/4)*b^2*d^2*x*log(1 + im*c*x^2)^2 - (1/12)*b^2*e^2*x^3*log(1 + im*c*x^2)^2 + ((-1)^(3/4)*b^2*d^2*PolyLog(2, 1 - 2/(1 - (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) + ((-1)^(1/4)*b^2*e^2*PolyLog(2, 1 - 2/(1 - (-1)^(1/4)*sqrt(c)*x)))/(3*c^(3/2)) + ((-1)^(3/4)*b^2*d^2*PolyLog(2, 1 - 2/(1 + (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) + ((-1)^(1/4)*b^2*e^2*PolyLog(2, 1 - 2/(1 + (-1)^(1/4)*sqrt(c)*x)))/(3*c^(3/2)) - ((-1)^(3/4)*b^2*d^2*PolyLog(2, 1 - (sqrt(2)*((-1)^(1/4) + sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/(2*sqrt(c)) - ((-1)^(1/4)*b^2*e^2*PolyLog(2, 1 - (sqrt(2)*((-1)^(1/4) + sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/(6*c^(3/2)) + ((-1)^(1/4)*b^2*d^2*PolyLog(2, 1 - 2/(1 - (-1)^(3/4)*sqrt(c)*x)))/sqrt(c) + ((-1)^(3/4)*b^2*e^2*PolyLog(2, 1 - 2/(1 - (-1)^(3/4)*sqrt(c)*x)))/(3*c^(3/2)) + ((-1)^(1/4)*b^2*d^2*PolyLog(2, 1 - 2/(1 + (-1)^(3/4)*sqrt(c)*x)))/sqrt(c) + ((-1)^(3/4)*b^2*e^2*PolyLog(2, 1 - 2/(1 + (-1)^(3/4)*sqrt(c)*x)))/(3*c^(3/2)) - ((-1)^(1/4)*b^2*d^2*PolyLog(2, 1 + (sqrt(2)*((-1)^(3/4) + sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x)))/(2*sqrt(c)) - ((-1)^(3/4)*b^2*e^2*PolyLog(2, 1 + (sqrt(2)*((-1)^(3/4) + sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x)))/(6*c^(3/2)) - ((-1)^(1/4)*b^2*d^2*PolyLog(2, 1 - ((1 + im)*(1 + (-1)^(1/4)*sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x)))/(2*sqrt(c)) - ((-1)^(3/4)*b^2*e^2*PolyLog(2, 1 - ((1 + im)*(1 + (-1)^(1/4)*sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x)))/(6*c^(3/2)) - ((-1)^(3/4)*b^2*d^2*PolyLog(2, 1 - ((1 - im)*(1 + (-1)^(3/4)*sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/(2*sqrt(c)) - ((-1)^(1/4)*b^2*e^2*PolyLog(2, 1 - ((1 - im)*(1 + (-1)^(3/4)*sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/(6*c^(3/2)) + (im*b^2*d*e*PolyLog(2, 1 - 2/(1 + im*c*x^2)))/c] =#
    @test_int [(d + e*x)^1*(a + b*atan(c*x^2))^2, x, 77, a^2*d*x - (2*(-1)^(3/4)*a*b*d*atan((-1)^(3/4)*sqrt(c)*x))/sqrt(c) + ((-1)^(3/4)*b^2*d*atan((-1)^(3/4)*sqrt(c)*x)^2)/sqrt(c) + (im*e*(a + b*atan(c*x^2))^2)/(2*c) + (1/2)*e*x^2*(a + b*atan(c*x^2))^2 + (2*(-1)^(3/4)*a*b*d*atanh((-1)^(3/4)*sqrt(c)*x))/sqrt(c) - ((-1)^(1/4)*b^2*d*atanh((-1)^(3/4)*sqrt(c)*x)^2)/sqrt(c) + (2*(-1)^(1/4)*b^2*d*atan((-1)^(3/4)*sqrt(c)*x)*log(2/(1 - (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) - (2*(-1)^(1/4)*b^2*d*atan((-1)^(3/4)*sqrt(c)*x)*log(2/(1 + (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) + ((-1)^(1/4)*b^2*d*atan((-1)^(3/4)*sqrt(c)*x)*log((sqrt(2)*((-1)^(1/4) + sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) + (2*(-1)^(1/4)*b^2*d*atanh((-1)^(3/4)*sqrt(c)*x)*log(2/(1 - (-1)^(3/4)*sqrt(c)*x)))/sqrt(c) - (2*(-1)^(1/4)*b^2*d*atanh((-1)^(3/4)*sqrt(c)*x)*log(2/(1 + (-1)^(3/4)*sqrt(c)*x)))/sqrt(c) + ((-1)^(1/4)*b^2*d*atanh((-1)^(3/4)*sqrt(c)*x)*log(-((sqrt(2)*((-1)^(3/4) + sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x))))/sqrt(c) + ((-1)^(1/4)*b^2*d*atanh((-1)^(3/4)*sqrt(c)*x)*log(((1 + im)*(1 + (-1)^(1/4)*sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x)))/sqrt(c) + ((-1)^(1/4)*b^2*d*atan((-1)^(3/4)*sqrt(c)*x)*log(((1 - im)*(1 + (-1)^(3/4)*sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) + im*a*b*d*x*log(1 - im*c*x^2) + ((-1)^(1/4)*b^2*d*atan((-1)^(3/4)*sqrt(c)*x)*log(1 - im*c*x^2))/sqrt(c) - ((-1)^(1/4)*b^2*d*atanh((-1)^(3/4)*sqrt(c)*x)*log(1 - im*c*x^2))/sqrt(c) - (1/4)*b^2*d*x*log(1 - im*c*x^2)^2 + (b*e*(a + b*atan(c*x^2))*log(2/(1 + im*c*x^2)))/c - im*a*b*d*x*log(1 + im*c*x^2) - ((-1)^(1/4)*b^2*d*atan((-1)^(3/4)*sqrt(c)*x)*log(1 + im*c*x^2))/sqrt(c) + ((-1)^(1/4)*b^2*d*atanh((-1)^(3/4)*sqrt(c)*x)*log(1 + im*c*x^2))/sqrt(c) + (1/2)*b^2*d*x*log(1 - im*c*x^2)*log(1 + im*c*x^2) - (1/4)*b^2*d*x*log(1 + im*c*x^2)^2 + ((-1)^(3/4)*b^2*d*PolyLog(2, 1 - 2/(1 - (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) + ((-1)^(3/4)*b^2*d*PolyLog(2, 1 - 2/(1 + (-1)^(1/4)*sqrt(c)*x)))/sqrt(c) - ((-1)^(3/4)*b^2*d*PolyLog(2, 1 - (sqrt(2)*((-1)^(1/4) + sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/(2*sqrt(c)) + ((-1)^(1/4)*b^2*d*PolyLog(2, 1 - 2/(1 - (-1)^(3/4)*sqrt(c)*x)))/sqrt(c) + ((-1)^(1/4)*b^2*d*PolyLog(2, 1 - 2/(1 + (-1)^(3/4)*sqrt(c)*x)))/sqrt(c) - ((-1)^(1/4)*b^2*d*PolyLog(2, 1 + (sqrt(2)*((-1)^(3/4) + sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x)))/(2*sqrt(c)) - ((-1)^(1/4)*b^2*d*PolyLog(2, 1 - ((1 + im)*(1 + (-1)^(1/4)*sqrt(c)*x))/(1 + (-1)^(3/4)*sqrt(c)*x)))/(2*sqrt(c)) - ((-1)^(3/4)*b^2*d*PolyLog(2, 1 - ((1 - im)*(1 + (-1)^(3/4)*sqrt(c)*x))/(1 + (-1)^(1/4)*sqrt(c)*x)))/(2*sqrt(c)) + (im*b^2*e*PolyLog(2, 1 - 2/(1 + im*c*x^2)))/(2*c)]
    @test_int [(a + b*atan(c*x^2))^2/(d + e*x)^1, x, 0, Unintegrable((a + b*atan(c*x^2))^2/(d + e*x), x)]
    @test_int [(a + b*atan(c*x^2))^2/(d + e*x)^2, x, 0, Unintegrable((a + b*atan(c*x^2))^2/(d + e*x)^2, x)]

    #= ::Section::Closed:: =#
    #=Integrands*of*the*form*(d+e*x)^m*(a+b*atan(c*x^3))^p=#

    #= ::Subsection::Closed:: =#
    #=Integrands*of*the*form*(d+e*x)^m*(a+b*atan(c*x^3))^p=#

    @test_int [(d + e*x)^2*(a + b*atan(c*x^3)), x, 24, -((b*d*e*atan(c^(1/3)*x))/c^(2/3)) - (b*d^3*atan(c*x^3))/(3*e) + ((d + e*x)^3*(a + b*atan(c*x^3)))/(3*e) + (b*d*e*atan(sqrt(3) - 2*c^(1/3)*x))/(2*c^(2/3)) - (b*d*e*atan(sqrt(3) + 2*c^(1/3)*x))/(2*c^(2/3)) + (sqrt(3)*b*d^2*atan((1 - 2*c^(2/3)*x^2)/sqrt(3)))/(2*c^(1/3)) + (b*d^2*log(1 + c^(2/3)*x^2))/(2*c^(1/3)) - (sqrt(3)*b*d*e*log(1 - sqrt(3)*c^(1/3)*x + c^(2/3)*x^2))/(4*c^(2/3)) + (sqrt(3)*b*d*e*log(1 + sqrt(3)*c^(1/3)*x + c^(2/3)*x^2))/(4*c^(2/3)) - (b*d^2*log(1 - c^(2/3)*x^2 + c^(4/3)*x^4))/(4*c^(1/3)) - (b*e^2*log(1 + c^2*x^6))/(6*c)]
    @test_int [(d + e*x)^1*(a + b*atan(c*x^3)), x, 22, -((b*e*atan(c^(1/3)*x))/(2*c^(2/3))) - (b*d^2*atan(c*x^3))/(2*e) + ((d + e*x)^2*(a + b*atan(c*x^3)))/(2*e) + (b*e*atan(sqrt(3) - 2*c^(1/3)*x))/(4*c^(2/3)) - (b*e*atan(sqrt(3) + 2*c^(1/3)*x))/(4*c^(2/3)) + (sqrt(3)*b*d*atan((1 - 2*c^(2/3)*x^2)/sqrt(3)))/(2*c^(1/3)) + (b*d*log(1 + c^(2/3)*x^2))/(2*c^(1/3)) - (sqrt(3)*b*e*log(1 - sqrt(3)*c^(1/3)*x + c^(2/3)*x^2))/(8*c^(2/3)) + (sqrt(3)*b*e*log(1 + sqrt(3)*c^(1/3)*x + c^(2/3)*x^2))/(8*c^(2/3)) - (b*d*log(1 - c^(2/3)*x^2 + c^(4/3)*x^4))/(4*c^(1/3))]
    @test_int [(a + b*atan(c*x^3))/(d + e*x)^1, x, 25, ((a + b*atan(c*x^3))*log(d + e*x))/e + (b*c*log((e*(1 - (-c^2)^(1/6)*x))/((-c^2)^(1/6)*d + e))*log(d + e*x))/(2*sqrt(-c^2)*e) - (b*c*log(-((e*(1 + (-c^2)^(1/6)*x))/((-c^2)^(1/6)*d - e)))*log(d + e*x))/(2*sqrt(-c^2)*e) + (b*c*log(-((e*((-1)^(1/3) + (-c^2)^(1/6)*x))/((-c^2)^(1/6)*d - (-1)^(1/3)*e)))*log(d + e*x))/(2*sqrt(-c^2)*e) - (b*c*log(-((e*((-1)^(2/3) + (-c^2)^(1/6)*x))/((-c^2)^(1/6)*d - (-1)^(2/3)*e)))*log(d + e*x))/(2*sqrt(-c^2)*e) + (b*c*log(((-1)^(2/3)*e*(1 + (-1)^(1/3)*(-c^2)^(1/6)*x))/((-c^2)^(1/6)*d + (-1)^(2/3)*e))*log(d + e*x))/(2*sqrt(-c^2)*e) - (b*c*log(((-1)^(1/3)*e*(1 + (-1)^(2/3)*(-c^2)^(1/6)*x))/((-c^2)^(1/6)*d + (-1)^(1/3)*e))*log(d + e*x))/(2*sqrt(-c^2)*e) - (b*c*PolyLog(2, ((-c^2)^(1/6)*(d + e*x))/((-c^2)^(1/6)*d - e)))/(2*sqrt(-c^2)*e) + (b*c*PolyLog(2, ((-c^2)^(1/6)*(d + e*x))/((-c^2)^(1/6)*d + e)))/(2*sqrt(-c^2)*e) + (b*c*PolyLog(2, ((-c^2)^(1/6)*(d + e*x))/((-c^2)^(1/6)*d - (-1)^(1/3)*e)))/(2*sqrt(-c^2)*e) - (b*c*PolyLog(2, ((-c^2)^(1/6)*(d + e*x))/((-c^2)^(1/6)*d + (-1)^(1/3)*e)))/(2*sqrt(-c^2)*e) - (b*c*PolyLog(2, ((-c^2)^(1/6)*(d + e*x))/((-c^2)^(1/6)*d - (-1)^(2/3)*e)))/(2*sqrt(-c^2)*e) + (b*c*PolyLog(2, ((-c^2)^(1/6)*(d + e*x))/((-c^2)^(1/6)*d + (-1)^(2/3)*e)))/(2*sqrt(-c^2)*e)]
    @test_int [(a + b*atan(c*x^3))/(d + e*x)^2, x, 34, -((b*c^(2/3)*d*e^3*atan(c^(1/3)*x))/(c^2*d^6 + e^6)) + (b*c^2*d^5*atan(c*x^3))/(e*(c^2*d^6 + e^6)) - (a + b*atan(c*x^3))/(e*(d + e*x)) + (b*c^(2/3)*d*(sqrt(3)*c*d^3 + e^3)*atan(sqrt(3) - 2*c^(1/3)*x))/(2*(c^2*d^6 + e^6)) + (b*c^(2/3)*d*(sqrt(3)*c*d^3 - e^3)*atan(sqrt(3) + 2*c^(1/3)*x))/(2*(c^2*d^6 + e^6)) + (sqrt(3)*b*c^(5/3)*e*(sqrt(-c^2)*d^3 + e^3)*atan((1 + (2*c^(2/3)*x)/(-c^2)^(1/6))/sqrt(3)))/(2*(-c^2)^(2/3)*(c^2*d^6 + e^6)) - (sqrt(3)*b*c^(5/3)*e*(sqrt(-c^2)*d^3 - e^3)*atan((c^(4/3) + 2*(-c^2)^(5/6)*x)/(sqrt(3)*c^(4/3))))/(2*(-c^2)^(2/3)*(c^2*d^6 + e^6)) + (b*c^(5/3)*e*(sqrt(-c^2)*d^3 + e^3)*log((-c^2)^(1/6) - c^(2/3)*x))/(2*(-c^2)^(2/3)*(c^2*d^6 + e^6)) - (b*c^(5/3)*e*(sqrt(-c^2)*d^3 - e^3)*log((-c^2)^(1/6) + c^(2/3)*x))/(2*(-c^2)^(2/3)*(c^2*d^6 + e^6)) + (3*b*c*d^2*e^2*log(d + e*x))/(c^2*d^6 + e^6) + (b*c^(5/3)*d^4*log(1 + c^(2/3)*x^2))/(2*(c^2*d^6 + e^6)) - (b*c^(2/3)*d*(c*d^3 - sqrt(3)*e^3)*log(1 - sqrt(3)*c^(1/3)*x + c^(2/3)*x^2))/(4*(c^2*d^6 + e^6)) - (b*c^(2/3)*d*(c*d^3 + sqrt(3)*e^3)*log(1 + sqrt(3)*c^(1/3)*x + c^(2/3)*x^2))/(4*(c^2*d^6 + e^6)) + (b*c^(5/3)*e*(sqrt(-c^2)*d^3 - e^3)*log((-c^2)^(1/3) - c^(2/3)*(-c^2)^(1/6)*x + c^(4/3)*x^2))/(4*(-c^2)^(2/3)*(c^2*d^6 + e^6)) - (b*c^(5/3)*e*(sqrt(-c^2)*d^3 + e^3)*log((-c^2)^(1/3) + c^(2/3)*(-c^2)^(1/6)*x + c^(4/3)*x^2))/(4*(-c^2)^(2/3)*(c^2*d^6 + e^6)) - (b*c*d^2*e^2*log(1 + c^2*x^6))/(2*(c^2*d^6 + e^6))]
    end

max_stars_repo_path: test/5 Inverse trig functions/5.3 Inverse tangent/5.3.3 (d+e x)^m (a+b arctan(c x^n))^p.jl


text:
# Inverse fields

struct InverseField{F} <: Field
  original::F
end

inverse_map(a::Field) = InverseField(a)
inverse_map(a::InverseField) = a.original

function return_cache(a::InverseField,x::Point)
  y₀ = [zero(x)...]             # initial guess and solution
  F₀ = [zero(x)...]             # error
  return return_cache(a.original,x), return_cache(∇(a.original),x), y₀, F₀
end

function evaluate!(caches,a::InverseField,x::Point)
  P = typeof(x)
  D = length(x)
  cache,∇cache,y₀,F₀ = caches
  # Initial guess
  # We cannot use an SVector here; nlsolve expects a mutable object.
  # We're keeping the vector in the cache to avoid allocations.
  y₀ .= Tuple(zero(x))
  # Function and its derivative
  f!(F,y) = F .= SVector{D}(Tuple(evaluate!(cache,a.original,P(y)) - x))
  j!(J,y) = J .= SMatrix{D,D}(Tuple(evaluate!(∇cache,∇(a.original),P(y))))
  df = OnceDifferentiable(f!,j!,y₀,F₀)
  # Solve
  res = nlsolve(df,y₀,method=:newton,linesearch=BackTracking())
  @check converged(res) "InverseField evaluation did not converge"
  # Extract solution
  y = res.zero
  return P(y)
end

function return_cache(a::InverseField,xs::AbstractVector{<:Point})
  return return_cache(a,testitem(xs))
end
function evaluate!(cache,a::InverseField,xs::AbstractVector{<:Point})
  map(x->evaluate!(cache,a,x), xs)
end


text:
"""
    struct LSBasis <: BasisSet

Represent a basis of ``L^2`` and ``S^2`` eigenstates, for an integer orbital angular
momentum ``ℓ``.
"""
struct LSBasis <: BasisSet
    b :: TensorProductBasis{AngularBasis,AngularBasis}
    function LSBasis(ℓ::Integer)
        new(TensorProductBasis(AngularBasis(ℓ), AngularBasis(1//2)))
    end
end
Base.length(b::LSBasis) = length(b.b)

ℓ(b::LSBasis) = convert(Int, b.b.b1.j)
ml(b::LSBasis, idx) = m(b.b.b1, leftindex(b.b, idx))
ms(b::LSBasis, idx) = m(b.b.b2, rightindex(b.b, idx))

struct LOperator{K} <: LinearOperator{LSBasis}
    b :: LSBasis
    op :: ProductExtensionOperator{AngularBasis,AngularBasis,JOperator{K},IdentityOperator{AngularBasis}}
    function LOperator(b::LSBasis, kind::Symbol)
        op = ProductExtensionOperator(b.b, JOperator(b.b.b1, kind), IdentityOperator(b.b.b2))
        new{kind}(b, op)
    end
end
basis(op::LOperator) = op.b
apply(i::Integer, op::LOperator, j::Integer) = apply(i, op.op, j)

struct SOperator{K} <: LinearOperator{LSBasis}
    b :: LSBasis
    op :: ProductExtensionOperator{AngularBasis,AngularBasis,IdentityOperator{AngularBasis},JOperator{K}}
    function SOperator(b::LSBasis, kind::Symbol)
        op = ProductExtensionOperator(b.b, IdentityOperator(b.b.b1), JOperator(b.b.b2, kind))
        new{kind}(b, op)
    end
end
basis(op::SOperator) = op.b
apply(i::Integer, op::SOperator, j::Integer) = apply(i, op.op, j)

# LS to J transformation
struct LStoJTransform <: BasisTransformation{LSBasis,TensorSumBasis{AngularBasis,AngularBasis}}
    lsb :: LSBasis
    jjb :: TensorSumBasis{AngularBasis,AngularBasis}
    function LStoJTransform(lsb::LSBasis)
        ℓ(lsb) == 0 && error("ℓ=0 is trivial")
        jjb = TensorSumBasis(AngularBasis(ℓ(lsb) - 1//2), AngularBasis(ℓ(lsb) + 1//2))
        @assert length(lsb) == length(jjb)
        new(lsb, jjb)
    end
end
basisfrom(ls2j::LStoJTransform) = ls2j.lsb
basisto(ls2j::LStoJTransform) = ls2j.jjb
function transform(i::Integer, ls2j::LStoJTransform, j::Integer)
    Nj1 = length(ls2j.jjb.b1)
    _j, _m = if i <= Nj1
        ls2j.jjb.b1.j, m(ls2j.jjb.b1, i)
    else
        ls2j.jjb.b2.j, m(ls2j.jjb.b2, i - Nj1)
    end
    clebschgordan(ℓ(ls2j.lsb), ml(ls2j.lsb, j), HalfInteger(1, 2), ms(ls2j.lsb, j), _j, _m)
end


text:
function add_source_to_ref(sys::PSY.System, X_th::Float64)
    for g in PSY.get_components(StaticInjection, sys)
        isa(g, ElectricLoad) && continue
        g.bus.bustype == BusTypes.REF &&
            error("A device is already attached to the REF bus")
    end

    slack_bus = [b for b in PSY.get_components(Bus, sys) if b.bustype == BusTypes.REF][1]
    inf_source = Source(
        name = "InfBus", #name
        available = true, #availability
        activepower = 0.0,
        reactivepower = 0.0,
        bus = slack_bus, #bus
        R_th = 0.0,
        X_th = X_th, #Xth
    )
    PSY.add_component!(sys, inf_source)
    return
end

function add_source_to_ref(sys::PSY.System)
    for g in PSY.get_components(StaticInjection, sys)
        isa(g, ElectricLoad) && continue
        g.bus.bustype == BusTypes.REF &&
            error("A device is already attached to the REF bus")
    end

    slack_bus = [b for b in PSY.get_components(Bus, sys) if b.bustype == BusTypes.REF][1]
    inf_source = Source(
        name = "InfBus", #name
        available = true, #availability
        active_power = 0.0,
        reactive_power = 0.0,
        bus = slack_bus, #bus
        R_th = 0.0,
        X_th = 5e-6, #Xth
    )
    PSY.add_component!(sys, inf_source)
    return
end


text:
include("PDEstruct.jl")
include("MsFEMutility.jl")
include("FEMutility.jl")
using Logging
using ForwardDiff
# using BenchmarkTools
using PyPlot

## PDE parameters
function afun(t,s)
    epsilon1 = 1/5;
    epsilon2 = 1/13;
    epsilon3 = 1/17;
    epsilon4 = 1/31;
    epsilon5 = 1/65;
    return 1/6*((1.1+sin(2*pi*t/epsilon1))/(1.1+sin(2*pi*s/epsilon1))+
            (1.1+sin(2*pi*s/epsilon2))/(1.1+cos(2*pi*t/epsilon2))+
            (1.1+cos(2*pi*t/epsilon3))/(1.1+sin(2*pi*s/epsilon3))+
            (1.1+sin(2*pi*s/epsilon4))/(1.1+cos(2*pi*t/epsilon4))+
            (1.1+cos(2*pi*t/epsilon5))/(1.1+sin(2*pi*s/epsilon5))+
            sin(4*s^2*t^2)+1);
    # return 1.0
end

function u(x)
    return sin(2*π*x[1])*sin(π*x[2])*exp(x[1]+2*x[2])
end

function rhs(t,s)
    x = [t,s]
    result = -sum(ForwardDiff.gradient(x -> afun(x[1],x[2]), x).*ForwardDiff.gradient(u, x)) - afun(x[1],x[2])*tr(ForwardDiff.hessian(u,x))

    return result
    # return t^4-s^3+1;
end

function bdy_Diri(t,s)
    return u([t,s])
end

function bdy_Neum(t,s)
    return ForwardDiff.derivative(t->u([t,s]),t)
end

function bdy_Robin(t,s)
    function bdy_Robin1(t,s)
        return 1
    end
    return bdy_Robin1(t,s), -ForwardDiff.derivative(t->u([t,s]),t) + bdy_Robin1(t,s)*u([t,s])
end

function bdy_type(t,s)
    Type = nothing
    # Neuman and Robin boundary condition should be on open intervals
    if t == 0 && 0<s<1
        Type = 1
    elseif t == 1 && 0<s<1
        Type = 1
    else
        Type = 1
    end
    return Type
end

none() = nothing

PDEparam = VarElliptic(afun,rhs,bdy_type, bdy_Diri, bdy_Neum, bdy_Robin)

## MsFEM parameters
Nce = 2^5 # Ne elements each dimension
Nfe = 2^5
MsFEMparam = MsFEM_2d2ScaleUnifQuadMesh(Nce,Nfe)

## Solver:
@time coarse_sol, sol_bubble, MsFEMstore = MsFEM_CoarseSolver(MsFEMparam,PDEparam)
# subsequent linear solve; rhs and bdy can be different
@time coarse_sol, sol_bubble = MsFEM_SubsequentSolve(MsFEMparam,PDEparam,MsFEMstore)

## error calculation: can use when truth exists
# coarse accuracy
Nce = MsFEMparam.Nce
x = MsFEMparam.CGrid_x
y = MsFEMparam.CGrid_y

FEMparam = FEM_2dUnifQuadMesh(Nce)
FEMstore = FEM_StiffnMassAssembly(FEMparam,PDEparam)

truth = [u([x[i],y[j]]) for j in 1:Nce+1 for i in 1:Nce+1]
Linf = maximum(abs.(truth - coarse_sol)) / maximum(abs.(truth))
L2 = sqrt((truth - coarse_sol)'*FEMstore.M*(truth - coarse_sol) / (truth'*FEMstore.M*truth))
energy = sqrt((truth - coarse_sol)'*FEMstore.A*(truth - coarse_sol) / (truth'*FEMstore.A*truth))
@info "[Error] Coarse solution: Relative energy err $energy, Relative L2 $L2, Linf $Linf"

# fine accuracy
@time fine_sol = MsFEM_FineConstruct(coarse_sol, sol_bubble, MsFEMstore)

Ne = Nce*Nfe
FEMparam = FEM_2dUnifQuadMesh(Ne)
FEMstore = FEM_StiffnMassAssembly(FEMparam,PDEparam)
x = FEMparam.Grid_x
y = FEMparam.Grid_y

truth = [u([x[i],y[j]]) for j in 1:Ne+1 for i in 1:Ne+1]
Linf = maximum(abs.(truth - fine_sol)) / maximum(abs.(truth))
L2 = sqrt((truth - fine_sol)'*FEMstore.M*(truth - fine_sol) / (truth'*FEMstore.M*truth))
energy = sqrt((truth - fine_sol)'*FEMstore.A*(truth - fine_sol) / (truth'*FEMstore.A*truth))
@info "[Error] Fine solution: Relative energy err $energy, Relative L2 $L2, Linf $Linf"

# ## plot
function meshgrid(x,y)
    xx = repeat(x',length(y),1)
    yy = repeat(y,1,length(x))
    return xx,yy
end
xx, yy = meshgrid(x, y)

result=reshape(truth - fine_sol,Ne+1,Ne+1)'
figure()
plt.contourf(xx,yy,abs.(result))
colorbar()
display(gcf())


text:
NAME_EQUALS(s::State) = if length(s.name) >= 2
  push!(s.boolean, pop!(s.name) == pop!(s.name))
end

NAME_DUP(s::State) = if !isempty(s.name)
  push!(s.name, peek(s.name))
end

NAME_FLUSH(s::State) = empty!(s.name)

NAME_POP(s::State) = !isempty(s.name) && pop!(s.name)

NAME_QUOTE(s::State) = s.flag_quote_name = true

NAME_RAND(s::State) = push!(s.name, random_name(s))

NAME_RAND_BOUND_NAME(s::State) = push!(s.name, random_bound_name(s))

NAME_ROT(s::State) = if length(s.name) > 2
  s.name[end], s.name[end-1], s.name[end-2] =
    s.name[end-1], s.name[end-2], s.name[end]
end

NAME_SHOVE(s::State) = if !isempty(s.integer) && !isempty(s.name)
  shove!(s.name, pop!(s.integer))
end

NAME_STACK_DEPTH(s::State) = push!(s.integer, length(s.name))

NAME_SWAP(s::State) = if length(s.name) >= 2
  s.name[end], s.name[end-1] = s.name[end-1], s.name[end]
end

NAME_YANK(s::State) = if !isempty(s.integer) && !isempty(s.name)
  yank!(s.name, pop!(s.integer))
end

NAME_YANKDUP(s::State) = if !isempty(s.integer) && !isempty(s.name)
  yankdup!(s.name, pop!(s.integer))
end

NAME_ERC(s::State) = return

Push.register("NAME.=",              NAME_EQUALS)
Push.register("NAME.DUP",            NAME_DUP)
Push.register("NAME.FLUSH",          NAME_FLUSH)
Push.register("NAME.POP",            NAME_POP)
Push.register("NAME.QUOTE",          NAME_QUOTE)
Push.register("NAME.RAND",           NAME_RAND)
Push.register("NAME.RANDBOUNDNAME",  NAME_RAND_BOUND_NAME)
Push.register("NAME.ROT",            NAME_ROT)
Push.register("NAME.SHOVE",          NAME_SHOVE)
Push.register("NAME.STACKDEPTH",     NAME_STACK_DEPTH)
Push.register("NAME.SWAP",           NAME_SWAP)
Push.register("NAME.YANK",           NAME_YANK)
Push.register("NAME.YANKDUP",        NAME_YANKDUP)
Push.register("NAME.ERC",            NAME_ERC)


text:
using Mimi
include("../src/getpagefunction.jl")

m = getpage()
run(m)
explore(m)

max_stars_repo_name: jkikstra/PAGE-VAR

max_issues_repo_name: jkikstra/PAGE-VAR

max_forks_repo_name: jkikstra/PAGE-VAR


text:
function dlyap(A,Q)

	# Solving Discrete LYAPunov equation using Silvester equation
	#
	# Sylvester equation A*X + X*B + C = 0
	# if B = -(A')^(-1), C = Q*(A')^(-1)
	# => A*X - X*(A')^(-1) + Q*(A')^(-1) = 0
	# => A*X*A' - X + Q = 0  -> Discrete Lyapunov equation

	Atinv = inv(A')
	B = -Atinv
	C = Q*Atinv
	X = sylvester(A, B, C)

	return X

end

# ======================================================
function dlyap_test()

	# example from
	# Barraud, A.Y., "A numerical algorithm to solve A'XA - X = Q",
	# IEEE Trans. Auto. Contr., AC-22, pp. 883-885, 1977.

	A = [1.5 2.5 3.5 4.5 5.5 6.5 7.5;
		1 -1.5 2.5 3.5 4.5 5.5 6.5;
		0 0 1.5 -2.5 3.5 4.5 5.5;
		0 0 0 1.5 2.5 -3.5 4.5;
		0 0 0 1 1.5 2.5 -3.5;
		0 0 0 0 0 1.5 -2.5;
		0 0 0 0 0 1 1.5]

	q = [5.25 1.5 19.25 22.5 55.75 60 49.25;
		0 0 3.25 -0.25 -6 -11 11.25;
		0 0 62.75 83 183.25 222.75 129.75;
		0 0 0 56.5 208.25 232.25 250.75;
		0 0 0 0 532.25 739.5 476.75;
		0 0 0 0 0 631 745.75;
		0 0 0 0 0 0 133.75]

	Q = (q + q') - diagm(diag(q))

	x = [1 1 1 1 1 1 1;
		0 1 2 3 4 5 6;
		0 0 1 3 6 10 15;
		0 0 0 1 4 10 20;
		0 0 0 0 1 5 15;
		0 0 0 0 0 1 6;
		0 0 0 0 0 0 1];

	X = (x + x') - diagm(diag(x))

	A = A'
	Q = -Q

	X1 = dlyap(A,Q)

	return X,X1

end


text:
module Thrift

using Distributed
using Sockets
using ThriftJuliaCompiler_jll

import Sockets: TCPServer, listen, accept
import Base: open, close, isopen, read, read!, write, flush, skip, show, copy!, hasproperty, getproperty, setproperty!, propertynames

export open, close, isopen, read, read!, write, flush, skip, listen, accept, show, copy!

# from base.jl
export TSTOP, TVOID, TBOOL, TBYTE, TI08, TDOUBLE, TI16, TI32, TI64, TSTRING, TUTF7, TSTRUCT, TMAP, TSET, TLIST, TUTF8, TUTF16
export TType, TProcessor, TTransport, TServerTransport, TServer, TProtocol
export writeMessageBegin, writeMessageEnd, writeStructBegin, writeStructEnd, writeFieldBegin, writeFieldEnd, writeFieldStop, writeMapBegin, writeMapEnd, writeListBegin, writeListEnd, writeSetBegin, writeSetEnd, writeBool, writeByte, writeI16, writeI32, writeI64, writeDouble, writeString
export readMessageBegin, readMessageEnd, readStructBegin, readStructEnd, readFieldBegin, readFieldEnd, readMapBegin, readMapEnd, readListBegin, readListEnd, readSetBegin, readSetEnd, readBool, readByte, readI16, readI32, readI64, readDouble, readString
export ApplicationExceptionType, MessageType, TException, TApplicationException
export ThriftMetaAttribs, ThriftMeta, meta
export isinitialized, set_field!, get_field, clear, has_field, fillunset, isfilled, thriftbuild, enumstr

# from transports.jl
export TFramedTransport, TSASLClientTransport, TSocket, TServerSocket, TSocketBase, TMemoryTransport, TFileTransport
export TransportExceptionTypes, TTransportException

# from sasl.jl
export SASL_MECH_PLAIN, SASL_MECH_KERB, SASL_MECH_LDAP, SASLException

# from protocols.jl
export TBinaryProtocol, TCompactProtocol

# from processor.jl
export ThriftProcessor, ThriftHandler, process, handle, extend, distribute

# from server.jl
export TSimpleServer, TTaskServer, TProcessPoolServer, serve

function generate(idl_file::String; dir::String=pwd())
    thrift() do thrift_cmd
        run(Cmd(`$thrift_cmd -gen jl $idl_file`; dir=dir))
    end
end

include("base.jl")
include("codec.jl")
include("sasl.jl")
include("transports.jl")
include("protocols.jl")
include("processor.jl")
include("server.jl")

end # module


text:
const yosb1 = [8.44e-1, 9.08e-1, 9.32e-1, 9.36e-1, 9.25e-1, 9.08e-1,
               8.81e-1, 8.50e-1, 8.18e-1, 7.84e-1, 7.51e-1, 7.18e-1,
               6.85e-1, 6.58e-1, 6.28e-1, 6.03e-1, 5.80e-1, 5.58e-1,
               5.38e-1, 5.22e-1, 5.06e-1, 4.90e-1, 4.78e-1, 4.67e-1,
               4.57e-1, 4.48e-1, 4.38e-1, 4.31e-1, 4.24e-1, 4.20e-1,
               4.14e-1, 4.11e-1, 4.06e-1]

const osborne1 = let res_init=zeros(33), jac_init=zeros(33,5), x_init=[.5, 1.5, -1.0, .01, .02]

    function res(x, r)
        for i = 1:33
            ti = 1.0e1 * Float64(1-i)
            r[i] = yosb1[i] - (x[1] + x[2] * exp(x[4] * ti) + x[3] * exp(x[5] * ti))
        end
        return r
    end

    function jac(x, j)
        for i = 1:33
            ti = 1.0e1 * Float64(1-i)
            j[i, 1] = -1.e0
            j[i, 2] = -exp(x[4] * ti)
            j[i, 3] = -exp(x[5] * ti)
            j[i, 4] = ti * x[2] * j[i, 2]
            j[i, 5] = ti * x[3] * j[i, 3]
        end
        return j
    end

    f(;scale=1, verbose=false, print_steps=false) = testone("osborne", res, jac,
                                                            res_init, jac_init, x_init;
                                                            scale=scale, verbose=verbose,
                                                            print_steps=print_steps)
end

const yosb2 = [ 1.366e0, 1.191e0, 1.112e0, 1.013e0, 9.91e-1, 8.85e-1,
                8.31e-1, 8.47e-1, 7.86e-1, 7.25e-1, 7.46e-1, 6.79e-1,
                6.08e-1, 6.55e-1, 6.16e-1, 6.06e-1, 6.02e-1, 6.26e-1,
                6.51e-1, 7.24e-1, 6.49e-1, 6.49e-1, 6.94e-1, 6.44e-1,
                6.24e-1, 6.61e-1, 6.12e-1, 5.58e-1, 5.33e-1, 4.95e-1,
                5.00e-1, 4.23e-1, 3.95e-1, 3.75e-1, 3.72e-1, 3.91e-1,
                3.96e-1, 4.05e-1, 4.28e-1, 4.29e-1, 5.23e-1, 5.62e-1,
                6.07e-1, 6.53e-1, 6.72e-1, 7.08e-1, 6.33e-1, 6.68e-1,
                6.45e-1, 6.32e-1, 5.91e-1, 5.59e-1, 5.97e-1, 6.25e-1,
                7.39e-1, 7.10e-1, 7.29e-1, 7.20e-1, 6.36e-1, 5.81e-1,
                4.28e-1, 2.92e-1, 1.62e-1, 9.8e-2, 5.4e-2]

# uftolg is a machine-dependent constant.  it is just slightly
# larger than the log of the smallest positive machine number.
const uftolg = 1.999e0 * log(sqrt(1.001 * 2.2250738585072014e-308))

const osborne2 = let res_init=zeros(65), jac_init=zeros(65,11),
                     x_init=[1.3, .65, .65, .7, .6, 3., 5., 7., 2., 4.5, 5.5]

    function res(x, r)
        for i = 1:65
            ti = 0.1e0 * Float64(1-i)
            ri = x[1] * exp(x[5] * ti)
            for j = 2:4
                t = 0.e0
                theta = -x[j+4] * (ti + x[j+7]) ^ 2
                if theta > uftolg
                    t = exp(theta)
                end
                ri = ri + x[j] * t
            end
            r[i] = yosb2[i] - ri
        end
        return r
    end

    function jac(x, j)
        for i = 1:65
            ti = Float64(1 - i) * 1.e-1
            j[i, 1] = -exp(x[5] * ti)
            j[i, 5] = x[1] * ti * j[i,1]
            for k = 2:4
                t = x[k + 7] + ti
                theta = -x[k+4]*t*t
                r2 = theta > uftolg ? -exp(theta) : 0.e0
                j[i, k] = r2
                r2 = -t * r2 * x[k]
                j[i, k+4] = r2*t
                j[i, k+7] = 2.e0 * x[k+4] * r2
            end
        end
        return j
    end

    f(;scale=1, verbose=false, print_steps=false) = testone("osborne2", res, jac,
                                                            res_init, jac_init, x_init;
                                                            scale=scale, verbose=verbose,
                                                            print_steps=print_steps)
end


text:
function myplot(fn, func)
    x = 0:0.1:2π
    plt = func(scatter(x=x, y=sin.(x)))
    savefig(plt, fn)
end

@testset "kaleido" begin
    for func in [Plot, plot]
        for ext in [PlotlyJS.ALL_FORMATS..., "html"]
            if ext === "eps"
                continue
            end
            fn = tempname() * "." * ext
            @show func, fn
            myplot(fn, func) == fn
            @test isfile(fn)
            rm(fn)
        end
    end
end


text:
# ---------------------------------------------------------------------------- #
#
#   basisFuncTriangleLag.jl
#
#   Get Lagrangian basis functions for Triangle
#
#   λυτέος
#   Fall 2017
#
#   Max Opgenoord
#
# ---------------------------------------------------------------------------- #

function basisFuncTriangleLag( P::P1, s::Vector{Float64}, t::Vector{Float64} )

  dim = 2
  nx  = length( s )

  # Linear

  nphi = 3
  phi  = Array{Float64}(nphi, nx)
  dphi = Array{Float64}(nphi, nx, dim)

  # value
  phi[1,:] = -s -t + 1.0
  phi[2,:] =  s
  phi[3,:] =  t

  # derivative in x
  dphi[1,:,1] =  -1.0
  dphi[2,:,1] =   1.0
  dphi[3,:,1] =   0.0

  # derivative in y
  dphi[1,:,2] =  -1.0
  dphi[2,:,2] =   0.0
  dphi[3,:,2] =   1.0

  return phi, dphi

end

function basisFuncTriangleLag( P::P2, s::Vector{Float64}, t::Vector{Float64} )

  dim = 2
  nx  = length( s )

  # Quadratric

  nphi = 6
  phi  = Array{Float64}(nphi, nx)
  dphi = Array{Float64}(nphi, nx, dim)

  # value
  phi[1,:] = s.*-3.0-t.*3.0+s.*t.*4.0+(s.*s).*2.0+(t.*t).*2.0+1.0
  phi[2,:] = -s+(s.*s).*2.0
  phi[3,:] = -t+(t.*t).*2.0
  phi[4,:] = s.*t.*4.0
  phi[5,:] = t.*(s+t-1.0).*-4.0
  phi[6,:] = -s.*(s.*4.0+t.*4.0-4.0)

  # derivative in x
  dphi[1,:,1] = s.*4.0+t.*4.0-3.0
  dphi[2,:,1] = s.*4.0-1.0
  dphi[3,:,1] = 0.0
  dphi[4,:,1] = t.*4.0
  dphi[5,:,1] = t.*-4.0
  dphi[6,:,1] = s.*-8.0-t.*4.0+4.0

  # derivative in y
  dphi[1,:,2] = s.*4.0+t.*4.0-3.0
  dphi[2,:,2] = 0.0
  dphi[3,:,2] = t.*4.0-1.0
  dphi[4,:,2] = s.*4.0
  dphi[5,:,2] = s.*-4.0-t.*8.0+4.0
  dphi[6,:,2] = s.*-4.0

  return phi, dphi

end

function basisFuncTriangleLag( P::P3, s::Vector{Float64}, t::Vector{Float64} )

  dim = 2
  nx  = length( s )

  nphi = 10
  phi  = Array{Float64}(nphi, nx)
  dphi = Array{Float64}(nphi, nx, dim)

  # value
  phi[1,:] = s.*(-1.1E1/2.0)-t.*(1.1E1/2.0)+s.*t.*1.8E1-s.*(t.*t).*(2.7E1/2.0)-(s.*s).*t.*(2.7E1/2.0)+(s.*s).*9.0-
              (s.*s.*s).*(9.0/2.0)+(t.*t).*9.0-(t.*t.*t).*(9.0/2.0)+1.0
  phi[2,:] = s-(s.*s).*(9.0/2.0)+(s.*s.*s).*(9.0/2.0)
  phi[3,:] = t-(t.*t).*(9.0/2.0)+(t.*t.*t).*(9.0/2.0)
  phi[4,:] = s.*t.*(-9.0/2.0)+(s.*s).*t.*(2.7E1/2.0)

  phi[5,:] =  s.*t.*(-9.0/2.0)+s.*(t.*t).*(2.7E1/2.0)

  phi[6,:] =  t.*(-9.0/2.0)+s.*t.*(9.0/2.0)-s.*(t.*t).*(2.7E1/2.0)+(t.*t).*1.8E1-(t.*t.*t).*(2.7E1/2.0)

  phi[7,:] =  t.*9.0-s.*t.*(4.5E1/2.0)+s.*(t.*t).*2.7E1+(s.*s).*t.*(2.7E1/2.0)-(t.*t).*(4.5E1/2.0)+(t.*t.*t).*(2.7E1/2.0)

  phi[8,:] =  s.*9.0-s.*t.*(4.5E1/2.0)+s.*(t.*t).*(2.7E1/2.0)+(s.*s).*t.*2.7E1-(s.*s).*(4.5E1/2.0)+(s.*s.*s).*(2.7E1/2.0)

  phi[9,:] =  s.*(-9.0/2.0)+s.*t.*(9.0/2.0)-(s.*s).*t.*(2.7E1/2.0)+(s.*s).*1.8E1-(s.*s.*s).*(2.7E1/2.0)

  phi[10,:] =  s.*t.*2.7E1-s.*(t.*t).*2.7E1-(s.*s).*t.*2.7E1

  # derivative in x
  dphi[1,:,1] =  s.*1.8E1+t.*1.8E1-s.*t.*2.7E1-(s.*s).*(2.7E1/2.0)-(t.*t).*(2.7E1/2.0)-1.1E1/2.0

  dphi[2,:,1] =  s.*-9.0+(s.*s).*(2.7E1/2.0)+1.0

  dphi[3,:,1] =  0.0

  dphi[4,:,1] =  t.*(-9.0/2.0)+s.*t.*2.7E1

  dphi[5,:,1] =  t.*(-9.0/2.0)+(t.*t).*(2.7E1/2.0)

  dphi[6,:,1] =  t.*(9.0/2.0)-(t.*t).*(2.7E1/2.0)

  dphi[7,:,1] =  t.*(-4.5E1/2.0)+s.*t.*2.7E1+(t.*t).*2.7E1

  dphi[8,:,1] =  s.*-4.5E1-t.*(4.5E1/2.0)+s.*t.*5.4E1+(s.*s).*(8.1E1/2.0)+(t.*t).*(2.7E1/2.0)+9.0

  dphi[9,:,1] =  s.*3.6E1+t.*(9.0/2.0)-s.*t.*2.7E1-(s.*s).*(8.1E1/2.0)-9.0/2.0

  dphi[10,:,1] =  t.*2.7E1-s.*t.*5.4E1-(t.*t).*2.7E1

  # dphi/dy
  dphi[1,:,2] =  s.*1.8E1+t.*1.8E1-s.*t.*2.7E1-(s.*s).*(2.7E1/2.0)-(t.*t).*(2.7E1/2.0)-1.1E1/2.0
  dphi[2,:,2] =  0.0
  dphi[3,:,2] =  t.*-9.0+(t.*t).*(2.7E1/2.0)+1.0
  dphi[4,:,2] =  s.*(-9.0/2.0)+(s.*s).*(2.7E1/2.0)
  dphi[5,:,2] =  s.*(-9.0/2.0)+s.*t.*2.7E1
  dphi[6,:,2] =  s.*(9.0/2.0)+t.*3.6E1-s.*t.*2.7E1-(t.*t).*(8.1E1/2.0)-9.0/2.0
  dphi[7,:,2] =  s.*(-4.5E1/2.0)-t.*4.5E1+s.*t.*5.4E1+(s.*s).*(2.7E1/2.0)+(t.*t).*(8.1E1/2.0)+9.0
  dphi[8,:,2] =  s.*(-4.5E1/2.0)+s.*t.*2.7E1+(s.*s).*2.7E1
  dphi[9,:,2] =  s.*(9.0/2.0)-(s.*s).*(2.7E1/2.0)
  dphi[10,:,2] =  s.*2.7E1-s.*t.*5.4E1-(s.*s).*2.7E1

  return phi, dphi

end

function basisFuncTriangleLag( P::P4, s::Vector{Float64}, t::Vector{Float64} )

  dim = 2
  nx  = length( s )

  nphi = 15
  phi  = Array{Float64}(nphi, nx)
  dphi = Array{Float64}(nphi, nx, dim)

  # value
  phi[1,:] =  (s.*s).*(t.*t).*6.4E1-(1./3).*s.*2.5E1-(1./3).*t.*2.5E1+(1./3).*(s.*s).*7.0E1-(1./3).*(s.*s.*s).*8.0E1+
      (1./3).*(s.*s.*s.*s).*3.2E1+(1./3).*(t.*t).*7.0E1-(1./3).*(t.*t.*t).*8.0E1+(1./3).*(t.*t.*t.*t).*3.2E1-s.*(t.*t).*
      8.0E1-(s.*s).*t.*8.0E1+(1./3).*s.*t.*1.4E2+(1./3).*s.*(t.*t.*t).*1.28E2+(1./3).*(s.*s.*s).*t.*1.28E2+1.0

  phi[2,:] =  -s+(1./3).*(s.*s).*2.2E1+(1./3).*(s.*s.*s.*s).*3.2E1-(s.*s.*s).*1.6E1

  phi[3,:] =  -t+(1./3).*(t.*t).*2.2E1+(1./3).*(t.*t.*t.*t).*3.2E1-(t.*t.*t).*1.6E1

  phi[4,:] =  (s.*s).*t.*-3.2E1+(1./3).*s.*t.*1.6E1+(1./3).*(s.*s.*s).*t.*1.28E2

  phi[5,:] =  (s.*s).*(t.*t).*6.4E1+s.*t.*4.0-s.*(t.*t).*1.6E1-(s.*s).*t.*1.6E1

  phi[6,:] =  s.*(t.*t).*-3.2E1+(1./3).*s.*t.*1.6E1+(1./3).*s.*(t.*t.*t).*1.28E2

  phi[7,:] =  (1./3).*t.*1.6E1-(1./3).*(t.*t).*1.12E2+(1./3).*(t.*t.*t).*2.24E2-(1./3).*(t.*t.*t.*t).*1.28E2+s.*
      (t.*t).*3.2E1-(1./3).*s.*t.*1.6E1-(1./3).*s.*(t.*t.*t).*1.28E2

  phi[8,:] =  t.*-1.2E1+(s.*s).*(t.*t).*6.4E1+s.*t.*2.8E1-s.*(t.*t).*1.44E2-(s.*s).*t.*1.6E1+s.*(t.*t.*t).*1.28E2+(t.*t).*7.6E1-
      (t.*t.*t).*1.28E2+(t.*t.*t.*t).*6.4E1

  phi[9,:] =  t.*1.6E1-(s.*s).*(t.*t).*1.28E2-(1./3).*(t.*t).*2.08E2-(1./3).*(t.*t.*t.*t).*1.28E2+s.*(t.*t).*1.92E2+(s.*
      s).*t.*9.6E1-s.*(t.*t.*t).*1.28E2+(t.*t.*t).*9.6E1-(1./3).*s.*t.*2.08E2-(1./3).*(s.*s.*s).*t.*1.28E2

  phi[10,:] =  s.*1.6E1-(s.*s).*(t.*t).*1.28E2-(1./3).*(s.*s).*2.08E2-(1./3).*(s.*s.*s.*s).*1.28E2+s.*(t.*t).*9.6E1+(s.*
      s).*t.*1.92E2-(s.*s.*s).*t.*1.28E2+(s.*s.*s).*9.6E1-(1./3).*s.*t.*2.08E2-(1./3).*s.*(t.*t.*t).*1.28E2

  phi[11,:] =  s.*-1.2E1+(s.*s).*(t.*t).*6.4E1+s.*t.*2.8E1-s.*(t.*t).*1.6E1-(s.*s).*t.*1.44E2+(s.*s.*s).*t.*1.28E2+(s.*s).*7.6E1-
      (s.*s.*s).*1.28E2+(s.*s.*s.*s).*6.4E1

  phi[12,:] =  (1./3).*s.*1.6E1-(1./3).*(s.*s).*1.12E2+(1./3).*(s.*s.*s).*2.24E2-(1./3).*(s.*s.*s.*s).*1.28E2+(s.*
      s).*t.*3.2E1-(1./3).*s.*t.*1.6E1-(1./3).*(s.*s.*s).*t.*1.28E2

  phi[13,:] =  (s.*s).*(t.*t).*2.56E2+s.*t.*9.6E1-s.*(t.*t).*2.24E2-(s.*s).*t.*2.24E2+s.*(t.*t.*t).*1.28E2+(s.*s.*s).*t.*1.28E2

  phi[14,:] =  (s.*s).*(t.*t).*-1.28E2-s.*t.*3.2E1+s.*(t.*t).*3.2E1+(s.*s).*t.*1.6E2-(s.*s.*s).*t.*1.28E2

  phi[15,:] =  (s.*s).*(t.*t).*-1.28E2-s.*t.*3.2E1+s.*(t.*t).*1.6E2+(s.*s).*t.*3.2E1-s.*(t.*t.*t).*1.28E2

  # derivative in x
  dphi[1,:,1] =  (1./3).*-2.5E1+(1./3).*s.*1.4E2+(1./3).*t.*1.4E2-s.*t.*1.6E2-(1./3).*(s.*s).*2.4E2+(1./3).*
      (s.*s.*s).*1.28E2+(1./3).*(t.*t.*t).*1.28E2+s.*(t.*t).*1.28E2-(t.*t).*8.0E1+(1./3).*(s.*s).*t.*3.84E2

  dphi[2,:,1] =  (1./3).*s.*4.4E1+(1./3).*(s.*s.*s).*1.28E2-(s.*s).*4.8E1-1.0

  dphi[3,:,1] =  0.0

  dphi[4,:,1] =  (1./3).*t.*1.6E1-s.*t.*6.4E1+(1./3).*(s.*s).*t.*3.84E2

  dphi[5,:,1] =  t.*4.0-s.*t.*3.2E1+s.*(t.*t).*1.28E2-(t.*t).*1.6E1

  dphi[6,:,1] =  (1./3).*t.*1.6E1+(1./3).*(t.*t.*t).*1.28E2-(t.*t).*3.2E1

  dphi[7,:,1] =  (1./3).*t.*-1.6E1-(1./3).*(t.*t.*t).*1.28E2+(t.*t).*3.2E1

  dphi[8,:,1] =  t.*2.8E1-s.*t.*3.2E1+s.*(t.*t).*1.28E2-(t.*t).*1.44E2+(t.*t.*t).*1.28E2

  dphi[9,:,1] =  (1./3).*t.*-2.08E2+s.*t.*1.92E2-s.*(t.*t).*2.56E2+(t.*t).*1.92E2-(t.*t.*t).*1.28E2-(1./3).*(s.*s).*t.*
      3.84E2

  dphi[10,:,1] =  (1./3).*s.*-4.16E2-(1./3).*t.*2.08E2+s.*t.*3.84E2-(1./3).*(s.*s.*s).*5.12E2-(1./3).*(t.*t.*t).*1.28E2-
      s.*(t.*t).*2.56E2-(s.*s).*t.*3.84E2+(s.*s).*2.88E2+(t.*t).*9.6E1+1.6E1

  dphi[11,:,1] =  s.*1.52E2+t.*2.8E1-s.*t.*2.88E2+s.*(t.*t).*1.28E2+(s.*s).*t.*3.84E2-(s.*s).*3.84E2+(s.*s.*s).*2.56E2-(t.*
      t).*1.6E1-1.2E1

  dphi[12,:,1] =  (1./3).*1.6E1-(1./3).*s.*2.24E2-(1./3).*t.*1.6E1+s.*t.*6.4E1+(1./3).*(s.*s).*6.72E2-(1./3).*
      (s.*s.*s).*5.12E2-(1./3).*(s.*s).*t.*3.84E2

  dphi[13,:,1] =  t.*9.6E1-s.*t.*4.48E2+s.*(t.*t).*5.12E2+(s.*s).*t.*3.84E2-(t.*t).*2.24E2+(t.*t.*t).*1.28E2

  dphi[14,:,1] =  t.*-3.2E1+s.*t.*3.2E2-s.*(t.*t).*2.56E2-(s.*s).*t.*3.84E2+(t.*t).*3.2E1

  dphi[15,:,1] =  t.*-3.2E1+s.*t.*6.4E1-s.*(t.*t).*2.56E2+(t.*t).*1.6E2-(t.*t.*t).*1.28E2

  # derivative in y
  dphi[1,:,2] =  (1./3).*-2.5E1+(1./3).*s.*1.4E2+(1./3).*t.*1.4E2-s.*t.*1.6E2+(1./3).*(s.*s.*s).*1.28E2-(1./3).*
      (t.*t).*2.4E2+(1./3).*(t.*t.*t).*1.28E2+(s.*s).*t.*1.28E2-(s.*s).*8.0E1+(1./3).*s.*(t.*t).*3.84E2

  dphi[2,:,2] =  0.0

  dphi[3,:,2] =  (1./3).*t.*4.4E1+(1./3).*(t.*t.*t).*1.28E2-(t.*t).*4.8E1-1.0

  dphi[4,:,2] =  (1./3).*s.*1.6E1+(1./3).*(s.*s.*s).*1.28E2-(s.*s).*3.2E1

  dphi[5,:,2] =  s.*4.0-s.*t.*3.2E1+(s.*s).*t.*1.28E2-(s.*s).*1.6E1

  dphi[6,:,2] =  (1./3).*s.*1.6E1-s.*t.*6.4E1+(1./3).*s.*(t.*t).*3.84E2

  dphi[7,:,2] =  (1./3).*1.6E1-(1./3).*s.*1.6E1-(1./3).*t.*2.24E2+s.*t.*6.4E1+(1./3).*(t.*t).*6.72E2-(1./3).*
      (t.*t.*t).*5.12E2-(1./3).*s.*(t.*t).*3.84E2

  dphi[8,:,2] =  s.*2.8E1+t.*1.52E2-s.*t.*2.88E2+s.*(t.*t).*3.84E2+(s.*s).*t.*1.28E2-(s.*s).*1.6E1-(t.*t).*3.84E2+(t.*t.*t).*
      2.56E2-1.2E1

  dphi[9,:,2] =  (1./3).*s.*-2.08E2-(1./3).*t.*4.16E2+s.*t.*3.84E2-(1./3).*(s.*s.*s).*1.28E2-(1./3).*(t.*t.*t).*5.12E2-
      s.*(t.*t).*3.84E2-(s.*s).*t.*2.56E2+(s.*s).*9.6E1+(t.*t).*2.88E2+1.6E1

  dphi[10,:,2] =  (1./3).*s.*-2.08E2+s.*t.*1.92E2-(s.*s).*t.*2.56E2+(s.*s).*1.92E2-(s.*s.*s).*1.28E2-(1./3).*s.*(t.*t).*
      3.84E2

  dphi[11,:,2] =  s.*2.8E1-s.*t.*3.2E1+(s.*s).*t.*1.28E2-(s.*s).*1.44E2+(s.*s.*s).*1.28E2

  dphi[12,:,2] =  (1./3).*s.*-1.6E1-(1./3).*(s.*s.*s).*1.28E2+(s.*s).*3.2E1

  dphi[13,:,2] =  s.*9.6E1-s.*t.*4.48E2+s.*(t.*t).*3.84E2+(s.*s).*t.*5.12E2-(s.*s).*2.24E2+(s.*s.*s).*1.28E2

  dphi[14,:,2] =  s.*-3.2E1+s.*t.*6.4E1-(s.*s).*t.*2.56E2+(s.*s).*1.6E2-(s.*s.*s).*1.28E2

  dphi[15,:,2] =  s.*-3.2E1+s.*t.*3.2E2-s.*(t.*t).*3.84E2-(s.*s).*t.*2.56E2+(s.*s).*3.2E1

  return phi, dphi

end


text:
# Find the dimension with the largest spread.
function find_largest_spread(data::AbstractVector{V}, indices, low, high) where {V}
    T = eltype(V)
    n_points = high - low + 1
    n_dim = length(V)
    split_dim = 1
    max_spread = zero(T)
    for dim in 1:n_dim
        xmin = typemax(T)
        xmax = typemin(T)
        # Find max and min in this dim
        for coordinate in 1:n_points
            xmin = min(xmin, data[indices[coordinate + low - 1]][dim])
            xmax = max(xmax, data[indices[coordinate + low - 1]][dim])
        end

        if xmax - xmin > max_spread # Found new max_spread, update split dimension
            max_spread = xmax - xmin
            split_dim = dim
        end
    end
    return split_dim
end

# Taken from https://github.com/JuliaLang/julia/blob/v0.3.5/base/sort.jl
# and modified to compare against a matrix
@inline function select_spec!(v::Vector{Int}, k::Int, lo::Int,
                              hi::Int, data::AbstractVector, dim::Int)
    lo <= k <= hi || error("select index $k is out of range $lo:$hi")
    @inbounds while lo < hi
        if hi - lo == 1
            if data[v[hi]][dim] < data[v[lo]][dim]
                v[lo], v[hi] = v[hi], v[lo]
            end
            return
        end
        pivot = v[(lo + hi) >>> 1]
        i, j = lo, hi
        while true
            while data[v[i]][dim] < data[pivot][dim]; i += 1; end
            while data[pivot][dim] < data[v[j]][dim]; j -= 1; end
            i <= j || break
            v[i], v[j] = v[j], v[i]
            i += 1; j -= 1
        end
        if k <= j
            hi = j
        elseif i <= k
            lo = i
        else
            return
        end
    end
    return
end

# In place heap sort
@inline function heap_sort_inplace!(xs, xis)
    @inbounds for i in length(xs):-1:2
        xs[i], xs[1] = xs[1], xs[i]
        xis[i], xis[1] = xis[1], xis[i]
        percolate_down!(xs, xis, xs[1], xis[1], i - 1)
    end
    return
end

# Binary max-heap percolate down.
@inline function percolate_down!(xs::AbstractArray,
                         xis::AbstractArray,
                         dist::Number,
                         index::Int,
                         len::Int=length(xs))
    i = 1
    @inbounds while (l = getleft(i)) <= len
        r = getright(i)
        j = ifelse(r > len || (xs[l] > xs[r]), l, r)
        if xs[j] > dist
            xs[i] = xs[j]
            xis[i] = xis[j]
            i = j
        else
            break
        end
    end
    xs[i] = dist
    xis[i] = index
    return
end

# Default skip function, always false
@inline function always_false(::Int)
    false
end

# Instead of ReinterpretArray wrapper, copy an array, interpreting it as a vector of SVectors
copy_svec(::Type{T}, data, ::Val{dim}) where {T, dim} =
        [SVector{dim,T}(ntuple(i -> data[n+i], Val(dim))) for n in 0:dim:(length(data)-1)]


text:
###Test the trait types
for args in [(:mhrunner,MHRunnerType,[:standard,:generalized]),
            (:initialize,InitializeFrom,[:default,:prior]),
            (:propose,ProposeFrom,[:indicator,:auxiliary]),
            (:indicator,IndicatorType,[:stationary,:cyclical]),
            (:jobsegments,JobSegments,[:procs,:workers,:test]),
            (:chain,ChainType,[:standard,:gradient]),
            (:store,StoreDuring,[:burnin,:main,:all])]
    for j in args[3]
        t = trait(args[1],j)
        @test typeof(t) == args[2]
        @test traitvalue(t) == j
        @test traittype(t) == Val{j}
    end
end

###Test MHRuntimePolicy
@test traitvalue(GeneralizedMetropolisHastings._num2propose(1)) == :indicator
@test traitvalue(GeneralizedMetropolisHastings._num2propose(2)) == :auxiliary
@test_throws AssertionError GeneralizedMetropolisHastings._num2propose(0)

@test traitvalue(GeneralizedMetropolisHastings._num2runner(1)) == :standard
@test traitvalue(GeneralizedMetropolisHastings._num2runner(2)) == :generalized
@test_throws AssertionError GeneralizedMetropolisHastings._num2runner(0)

@test traitvalue(GeneralizedMetropolisHastings._num2segments(1,:test)) == :none
@test traitvalue(GeneralizedMetropolisHastings._num2segments(2,:workers)) == :workers
@test_throws AssertionError GeneralizedMetropolisHastings._num2segments(0,:none)

p1 = policy(:mh,10)
p2 = policy(:mh,1,initialize=:default,indicator=:cyclical,chain=:gradient,store=:all,sampletype=Int,calculationtype=Float32)

for args in [(p1,(:generalized,:prior,:auxiliary,:stationary,:workers,:standard,:main,Float64,Float64)),
             (p2,(:standard,:default,:indicator,:cyclical,:none,:gradient,:all,Int,Float32))]
    for (i,f) in enumerate([:runner,:initialize,:propose,:indicator,:jobsegments,:chain,:store])
        @test traittype(getfield(args[1],f)) == Val{args[2][i]}
    end
    @test args[1].sampletype == args[2][end-1]
    @test args[1].calculationtype == args[2][end]
end

println("====================")
println("Test show() function")
show(p1)
show(p2)
println("End  show() function")
println("====================")
println()

nothing


text:
module RegressionBenchmarks

using StatsBase, Distributions, SubsetSelection, SubsetSelectionCIO,
      MLDataUtils, JuMP, Gurobi, CPLEX, MathProgBase, TimerOutputs
using Gadfly, DataFrames
import Base.rand #, Base.normalize!
import Base.mkdir

export BinChoice, NoNoise, MatrixCorrelation, NoCorrelation,
    getw, getX, getdata, BenchmarkData, XData,
    # Methods
    RegressionMethod, ExactPrimalCuttingPlane, PrimalWithHeuristics,
    RelaxDualSubgradient, RelaxDualCutting, NoWarmStart,
    # Parts of methods
    ConstantStepping, PolyakStepping,
    # Validate and solve
    validate_params!,
    solve_problem,
    # Utilities
    isRsquared, oosRsquared, accuracy, falsepositive, predict_sparse,
    # Results
    benchmark, makeplot,
    data2str, method2str #,
    # normalize!

const YVector = Union{Vector{Float64},SubArray{Float64,1}}
const TimeStats = TimerOutput()

include("datatypes.jl")
include("data.jl")
include("methods/methods.jl")
include("utils.jl")
include("validation.jl")
include("benchmark.jl")
include("plots.jl")

# TODO keyword argument in sort function type unstable make it sort -ax

# TODO try cutting plane with user heuristic. cache subgradient in extension dictionary
# TODO lagrangian relaxation relaxing knapsack constraint

end # module


text:
module SpringCollab2020RetractSpinner

using ..Ahorn, Maple

@mapdef Entity "SpringCollab2020/RetractSpinner" RetractSpinner(x::Integer, y::Integer, attachToSolid::Bool=false)

const placements = Ahorn.PlacementDict(
    "Retract Spinner (Spring Collab 2020)" => Ahorn.EntityPlacement(
        RetractSpinner
    )
)

sprite = "danger/SpringCollab2020/retractspinner/urchin_harm00.png"

function Ahorn.selection(entity::RetractSpinner)
    x, y = Ahorn.position(entity)
    return Ahorn.Rectangle(x - 8, y - 8, 16, 16)
end

Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::RetractSpinner, room::Maple.Room) = Ahorn.drawSprite(ctx, sprite, 0, 0)

end


text:
function OC_getIntegratedTemperature(
    ocn      :: Ocean,
    i        :: Integer,
    j        :: Integer;
    target_z :: Float64,
)

    return getIntegratedQuantity(
        zs       = ocn.cols.zs[i, j],
        qs       = ocn.cols.Ts[i, j],
        q_ML     = ocn.T_ML[i, j],
        h_ML     = ocn.h_ML[i, j],
        Nz       = ocn.Nz[i, j],
        target_z = target_z,
    )
end

function OC_getIntegratedSalinity(
    ocn      :: Ocean,
    i        :: Integer,
    j        :: Integer;
    target_z :: Float64,
)

    return getIntegratedQuantity(
        zs       = ocn.cols.zs[i, j],
        qs       = ocn.cols.Ss[i, j],
        q_ML     = ocn.S_ML[i, j],
        h_ML     = ocn.h_ML[i, j],
        Nz       = ocn.Nz[i, j],
        target_z = target_z,
    )
end

function OC_getIntegratedBuoyancy(
    ocn      :: Ocean,
    i        :: Integer,
    j        :: Integer;
    target_z :: Float64,
)

    return getIntegratedQuantity(
        zs       = ocn.cols.zs[i, j],
        qs       = ocn.cols.bs[i, j],
        q_ML     = ocn.b_ML[i, j],
        h_ML     = ocn.h_ML[i, j],
        Nz       = ocn.Nz[i, j],
        target_z = target_z,
    )
end

function getIntegratedQuantity(;
    zs       :: AbstractArray{Float64,1},
    qs       :: AbstractArray{Float64,1},
    q_ML     :: Float64,
    h_ML     :: Float64,
    Nz       :: Integer,
    target_z :: Float64,
)

    if target_z < zs[Nz+1]
        throw(ErrorException(
            format("target_z ({:f}) cannot be deeper than the minimum of zs ({:f}).", target_z, zs[Nz])
        ))
    end

    # Integrate mixed layer
    if -target_z < h_ML
        return q_ML * ( - target_z )
    end

    sum_q = 0.0
    sum_q += h_ML * q_ML

    # Test if entire ocean column is mixed layer
    FLDO = getFLDO(zs=zs, h_ML=h_ML, Nz=Nz)
    if FLDO == -1
        return sum_q
    end

    # Integrate FLDO
    if target_z > zs[FLDO+1]
        sum_q += qs[FLDO] * ( (-h_ML) - target_z)
        return sum_q
    end

    sum_q += qs[FLDO] * ( (-h_ML) - zs[FLDO+1])

    # Integrate rest layers
    if FLDO < Nz
        for i = FLDO+1 : Nz
            if target_z < zs[i+1]
                sum_q += qs[i] * (zs[i] - zs[i+1])
            else
                sum_q += qs[i] * (zs[i] - target_z)
                return sum_q
            end
        end
    else
        return sum_q
    end

end

max_stars_repo_name: meteorologytoday/IOM

max_issues_repo_name: meteorologytoday/IOM

max_forks_repo_name: meteorologytoday/IOM


text:
################################################################################
# Copyright (c) 2009-2014: Jeff Bezanson, Stefan Karpinski, Viral B. Shah,
# and other contributors:
#
# https://github.com/JuliaLang/julia/contributors
#
# Copyright (C) 2015, Tommy Hofmann
#
# 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.

if v"0.4" <= VERSION < v"0.5-"
  import Base: precision

  precision(::Type{BigFloat}) = Base.MPFR.DEFAULT_PRECISION[end]

  function setprecision(::Type{BigFloat}, precision::Int)
    if precision < 2
      throw(DomainError())
    end
    Base.MPFR.DEFAULT_PRECISION[end] = precision
  end

  setprecision(precision::Int) = setprecision(BigFloat, precision)

  function setprecision{T}(f::Function, ::Type{T}, prec::Integer)
    old_prec = precision(T)
    setprecision(T, prec)
    try
      return f()
    finally
      setprecision(T, old_prec)
    end
  end

  setprecision(f::Function, precision::Integer) = setprecision(f, BigFloat, precision)

else
  import Base: precision, setprecision
end


text:
function render(buffer, this::Section)
    if this.layout == "auto"
        layout = auto_layout(this)
    else
        layout = Tokenizer(this.layout) |> parse_layout
    end

    render(buffer, this, layout)
end

function render(buffer, this, Row)
end

function render(buffer, this, Col)

end

function render(buffer, this, Element)

end

function auto_layout(this::Section)
    error("TODO")
end

function get_width_hint(x::Row)
    sum(get_width_hint.(x.children)) + length(x.children) - 1
end

function get_width_hint(x::Col)
    maximum(get_width_hint.(x.children))
end

function get_width_hint(x::Element)

end


text:
function getos()::String
    if Sys.iswindows()
        "windows"
    elseif Sys.islinux()
        "linux"
    else
        lowercase(string(Sys.KERNEL))
    end
end

const DATA_DIR = joinpath(pwd(), "..", "data", "matrix_market")
const OUTPUT_DIR = mkpath(joinpath(pwd(), "output"))

max_stars_repo_name: saiteki-kai/direct-methods

max_issues_repo_name: saiteki-kai/direct-methods

max_forks_repo_name: saiteki-kai/direct-methods


text:
# Used in `feed.yml`
function parse_env(env=ENV; verbose=true)
    pr_url = string("https://github.com/", env["GITHUB_REPOSITORY"], "/pull/", env["PR_NUMBER"])
    body = env["PR_BODY"]

    name = r"(?:^|\n|\r\n)(?:\-|\*) Registering package: (\w*?)(?:$|\n|\r\n)"
    repo = r"(?:^|\n|\r\n)(?:\-|\*) Repository: (.*?)(?:$|\n|\r\n)"
    description = r"(?:^|\n|\r\n)(?:\-|\*) Description: (.*?)(?:$|\n|\r\n)"
    release_notes = r"(?:^|\n|\r\n)(?:\-|\*) Release notes:(?:\s*?)(?:$|\n|\r\n)<!-- BEGIN RELEASE NOTES -->((?s).*)<!-- END RELEASE NOTES -->"

    text = sprint() do io
        match_name = match(name, body)
        has_name = match_name !== nothing
        match_description = match(description, body)
        has_description = match_description !== nothing

        match_release = match(release_notes, body)
        has_release = match_release !== nothing

        match_repo = match(repo, body)
        has_repo = match_repo !== nothing

        if has_description && has_name
            println(io, match_name[1], ": ", strip(match_description[1]))
        elseif has_description
            println(io, strip(match_description[1]))
        end

        if has_release
            # Leave a gap if we've just printed something
            has_description && println(io)
            println(io, "Release notes:")
            println(io, strip(match_release[1]))
        end

        # Leave a gap if we've just printed something
        if has_description || has_release
            println(io)
        end
        println(io, "Registration: ", pr_url)
        if has_repo
            println(io, "Repository:   ", strip(match_repo[1]))
        end
        # Nothing? Just print the `pr_url`
        if match_description === match_release === match_repo === nothing
            println(io, pr_url)
        end
    end

    verbose && @info "" pr_url text
    return (; text, pr_url)
end

env = Dict("GITHUB_REPOSITORY" => "JuliaRegistries/General",
           "PR_NUMBER" => "43765",
           "PR_BODY" =>
            """
            - Registering package: Fastnet
            - Repository: https://github.com/bridgewalker/Fastnet.jl
            - Version: v0.1.0
            - Description: This is a test description.
            - Commit: 976c26fc6165d5501fb765048fd18d2e30181a94
            - Git reference: v0.1.0
            - Release notes:
            <!-- BEGIN RELEASE NOTES -->
            > Fastnet is a Julia package that allows very fast (linear-time) simulation of discrete-state dynamical processes on networks, such as commonly studied models of epidemics
            <!-- END RELEASE NOTES -->
            """)

using Test
p = parse_env(env; verbose=false)

@testset "parse_env" begin
    @test p.text == "Fastnet: This is a test description.\n\nRelease notes:\n> Fastnet is a Julia package that allows very fast (linear-time) simulation of discrete-state dynamical processes on networks, such as commonly studied models of epidemics\n\nRegistration: https://github.com/JuliaRegistries/General/pull/43765\nRepository:   https://github.com/bridgewalker/Fastnet.jl\n"
    @test p.pr_url == "https://github.com/JuliaRegistries/General/pull/43765"
end

max_stars_repo_name: ErikQQY/General

max_issues_repo_name: ErikQQY/General

max_forks_repo_name: ErikQQY/General


text:
# loss functions
function loss(w, s, visual, captions, masks; o=Dict(), values=[])
    finetune = get(o, :finetune, false)
    atype = get(o, :atype, AutoGrad.getval(typeof(w["wdec"])))
    atype = atype<:Array?Array:KnetArray
    visual = convert(atype, visual)
    if finetune
        visual = vgg19(w["wcnn"], visual; o=o)
        visual = transpose(visual)
    end

    lossval, nwords = decoder(w, s, visual, captions, masks; o=o)
    push!(values, AutoGrad.getval(lossval), AutoGrad.getval(nwords))
    return lossval/nwords
end

# loss gradient functions
lossgradient = grad(loss)

# loss function for decoder network
function decoder(w, sd, vis, seq, masks; o=Dict())
    total, count = 0, 0
    atype = get(o, :atype, AutoGrad.getval(typeof(w["wdec"])))

    # set dropouts
    vembdrop = get(o, :vembdrop, 0.0)
    wembdrop = get(o, :wembdrop, 0.0)
    softdrop = get(o, :softdrop, 0.0)
    fc7drop  = get(o, :fc7drop, 0.0)

    h = sum(vis, 2) / size(vis, 2)
    h = reshape(h, size(h,1), size(h,3))
    c = copy(h)

    # textual features
    for t = 1:length(seq)-1
        # make input
        x = w["wemb"][seq[t],:]
        x = dropout(x, wembdrop)

        # get context vector
        ctx = att(w,vis,h,o)

        # make input
        x = hcat(ctx,wemb)

        # lstm
        h,c = lstm(w["wdec"], w["bdec"], h, c, x)

        # prediction
        ht = dropout(h, softdrop)
        ypred = ht * w["wsoft"] .+ w["bsoft"]
        ygold = seq[t+1]

        # loss calculcation
        total += logprob(ygold,ypred,masks[t])
        count += length(ygold)
        x = ygold
    end

    return (-total,count)
end

# generate
function generate(w, s, vis, vocab; maxlen=20, beamsize=1)
    atype = typeof(AutoGrad.getval(w["wdec"])) <: KnetArray ? KnetArray : Array
    wcnn = get(w, "wcnn", nothing)
    vis = convert(atype, vis)
    if wcnn != nothing
        vis = vgg19(wcnn, vis; o=Dict(:featuremaps=>true))
    end
    vis = reshape(vis, 1, size(vis,1)*size(vis,2), size(vis,3))

    h = sum(vis, 2) / size(vis, 2)
    h = reshape(h, size(h,1), size(h,3))
    c = copy(h)

    # language generation with (sentence, state, probability) array
    sentences = Any[(Any[SOS],h,c,0.0)]
    while true
        changed = false
        for i = 1:beamsize
            # get current sentence
            curr = shift!(sentences)
            sentence, ht, ct, prob = curr

            # get last word
            word = sentence[end]
            if word == EOS || length(sentence) >= maxlen
                push!(sentences, curr)
                continue
            end

            # get probabilities
            x = w["wemb"][word2index(vocab,word),:]
            x = reshape(x, 1, length(x))
            ctx = att(w,vis,ht)
            (ht,ct) = lstm(w["wdec"], w["bdec"], ht, ct, x, ctx)
            ypred = ht * w["wsoft"] .+ w["bsoft"]
            ypred = logp(ypred, 2)
            ypred = convert(Array{Float32}, ypred)[:]

            # add most probable predictions to array
            maxinds = sortperm(ypred, rev=true)
            for j = 1:beamsize
                ind = maxinds[j]
                new_word = index2word(vocab, ind)
                new_sentence = copy(sentence)
                new_probability = prob + ypred[ind]
                push!(new_sentence, new_word)
                push!(sentences, (new_sentence, copy(ht), copy(ct), new_probability))
            end
            changed = true

            # skip first loop
            if word == SOS
                break
            end
        end

        orders = sortperm(map(x -> x[4], sentences), rev=true)
        sentences = sentences[orders[1:beamsize]]

        if !changed
            break
        end
    end

    sentence = first(sentences)[1]
    if sentence[end] == EOS
        pop!(sentence)
    end
    push!(sentence, ".")
    output = join(filter(word -> word != UNK, sentence[2:end]), " ")
end

max_stars_repo_name: ilkerkesen/show-attend-and-tell

max_issues_repo_name: ilkerkesen/show-attend-and-tell

max_forks_repo_name: ilkerkesen/show-attend-and-tell


text:
using RDatasets
iris_dataset = dataset("datasets", "iris")
head(iris_dataset)

max_stars_repo_path: Chapter 2/3.jl

max_stars_repo_name: PacktPublishing/Julia-for-data-science

max_issues_repo_path: Chapter 2/3.jl

max_issues_repo_name: PacktPublishing/Julia-for-data-science

max_forks_repo_path: Chapter 2/3.jl

max_forks_repo_name: PacktPublishing/Julia-for-data-science


text:
# This file is a part of ROOTFramework.jl, licensed under the MIT License (MIT).

__precompile__(false)

module ROOTFramework

using Cxx
using ROOT

using Cxx.CxxCore: CppValue, CppPtr, CppRef, CxxBuiltinTs

macro rcpp_str(s,args...)
    CppRef{Cxx.CxxCore.simpleCppType(s),Cxx.CxxCore.NullCVR}
end

include("pointers.jl")
include("tstring.jl")
include("tobject.jl")
include("tcanvas.jl")
include("tbrowser.jl")
include("tcolor.jl")
include("json.jl")
include("taxis.jl")
include("tdirectory.jl")
include("tfitresult.jl")
include("thxx.jl")
include("ttree.jl")
include("ttree_bindings.jl")

end # module


text:
data_size(data::Array{Ts}) where Ts <: StructVector = sum(length.(data))
data_size(data::Ts) where Ts <: StructVector = length(data)

# Unpacking vectors of arrays into dataframes
function all_indices_comb(A::AbstractMatrix)
    m, n = size(A)
    M = repeat(1:m, inner=n)
    N = repeat(1:n, outer=m)
    v = [(i,j) for (i,j) in zip(M,N)]
    return v
end

function unpack(V::Vector{T}, name) where T <: Number
    DataFrames.DataFrame(reshape(V, length(V), 1), [name])
end

function unpack(V::Vector{T}, name) where T <: AbstractVector
    df = DataFrames.DataFrame([V], [name])
    return select(df, name => ByRow(vec) => [Symbol(name,"[$i]") for i in eachindex(V[1])])
end

function unpack(V::Vector{T}, name) where T <: AbstractMatrix
    all_indices = all_indices_comb(V[1])
    df = DataFrames.DataFrame([V], [name])
    return select(df, name => ByRow(vec) => [Symbol(name,"[$i, $j]") for (i,j) in all_indices])
end

function unpack(S::StructVector{T}) where T <: NamedTuple
    tmp = DataFrames.DataFrame(S)
    df = DataFrames.DataFrame()
    for n in keys(S[1])
        df = hcat(df, unpack(tmp[!,n], n))
    end
    return df
end

# Convert Dataframes into a StructVector with named fields s, a, and r
repack(df::DataFrames.DataFrame, val) = fill(val, nrow(df))
repack(df::DataFrames.DataFrame, name::Symbol) = Vector(df[!,name])
repack(df::DataFrames.DataFrame, names::Vector{Symbol}) = [(;df[!,names][i,:]...) for i in 1:nrow(df)]
function build_history(df::DataFrames.DataFrame; states=missing, actions, feedbacks=missing, hidden=missing)
    return StructVector(s = repack(df, states),
                        a = repack(df, actions),
                        r = repack(df, feedbacks),
                        h = repack(df, hidden))
end

max_stars_repo_name: sqwayer/AnimalBehavior

max_issues_repo_name: sqwayer/AnimalBehavior