text:
using PortAudio, SampledSignals, LibSndFile
using HTTP
using WAV
using Statistics
using Plots
using Images
using PyCall
using DSP

function spectronew(val)
    fs = 16000
    audio_test = SampleBuf(val, 16000)
    n = length(audio_test.data)
    nw = n÷25
    spec = DSP.spectrogram(audio_test.data[:], nw, nw÷10; fs=fs)
    png(
        Plots.heatmap(spec.time, spec.freq, pow2db.(spec.power), xaxis = false, yaxis=false, legend = :none, ticks=false, margins = -1.2Plots.cm, size=(28.5,29)),
        "testcase",
    )
    img = load("testcase.png")
    img = imresize(img, (28,28))
    img = reshape(convert(Array{Float32}, Gray.(img)), (28, 28, 1));
    return img
end
function senddataup(data)
    batch = map(x->data[16000*(x-1)+1:16000*x] ,1:5)
    batch = map(x->spectronew(x), batch)
    for i in batch
        r  = HTTP.post("http://localhost:8003/adddata", [], string(i))
        # println(String(r.body))
    end
end

function sendfileup(filename)
    splited = split(filename, "/")
    label = splited[end-1]
    label2 = splited[end]
    img =  convert(Array{Float32}, Gray.(load("./datasetspectro2/"*label*"#"*label2)))
    println(size(img))
    batch = map(x->img , 1:5)
    #batch = map(x->spectronew(x), batch)
    for i in batch
        r  = HTTP.post("http://localhost:8003/adddata", [], string(i))
        # println(String(r.body))
    end
end

function sendsingledataup(data)
   r  = HTTP.post("http://localhost:8003/adddata", [], string(spectronew(data)))
   # println(String(r.body))
end

labeldict = Dict("left" => 0, "right" => 1, "up" => 2,  "down" => 3,""=>4)

function makeamove(mode)
    println(mode)
    py"""
    import pyautogui as autogui
    def makemode(mode):
        if mode == 3:
            autogui.press('left')
        elif mode == 4:
            autogui.press('right')
        elif mode == 5:
            autogui.press('up')
        elif mode == 6:
            autogui.press('down')
        else:
            print(mode)
            print("mode not yet made")
    """
    py"makemode"(mode)
end

py"""
import collections
import contextlib
import sys
import wave

import webrtcvad

def read_wave(path):
    with contextlib.closing(wave.open(path, 'rb')) as wf:
        num_channels = wf.getnchannels()
        assert num_channels == 1
        sample_width = wf.getsampwidth()
        assert sample_width == 2
        sample_rate = wf.getframerate()
        assert sample_rate in (8000, 16000, 32000, 48000)
        pcm_data = wf.readframes(wf.getnframes())
        return pcm_data, sample_rate

def write_wave(path, audio, sample_rate):
    with contextlib.closing(wave.open(path, 'wb')) as wf:
        wf.setnchannels(1)
        wf.setsampwidth(2)
        wf.setframerate(sample_rate)
        wf.writeframes(audio)

class Frame(object):
    def __init__(self, bytes, timestamp, duration):
        self.bytes = bytes
        self.timestamp = timestamp
        self.duration = duration

def frame_generator(frame_duration_ms, audio, sample_rate):
    n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)
    offset = 0
    timestamp = 0.0
    duration = (float(n) / sample_rate) / 2.0
    while offset + n < len(audio):
        yield Frame(audio[offset:offset + n], timestamp, duration)
        timestamp += duration
        offset += n

def vad_collector(sample_rate, frame_duration_ms,
                  padding_duration_ms, vad, frames):
    num_padding_frames = int(padding_duration_ms / frame_duration_ms)
    ring_buffer = collections.deque(maxlen=num_padding_frames)
    triggered = False

    voiced_frames = []
    for frame in frames:
        is_speech = vad.is_speech(frame.bytes, sample_rate)

        sys.stdout.write('1' if is_speech else '0')
        if not triggered:
            ring_buffer.append((frame, is_speech))
            num_voiced = len([f for f, speech in ring_buffer if speech])
            if num_voiced > 0.9 * ring_buffer.maxlen:
                triggered = True
                # sys.stdout.write('+(%s)' % (ring_buffer[0][0].timestamp,))
                for f, s in ring_buffer:
                    voiced_frames.append(f)
                ring_buffer.clear()
        else:
            voiced_frames.append(frame)
            ring_buffer.append((frame, is_speech))
            num_unvoiced = len([f for f, speech in ring_buffer if not speech])
            if num_unvoiced > 0.9 * ring_buffer.maxlen:
                # sys.stdout.write('-(%s)' % (frame.timestamp + frame.duration))
                triggered = False
                yield b''.join([f.bytes for f in voiced_frames])
                ring_buffer.clear()
                voiced_frames = []
    # if triggered:
        # print("Here I arrive")
        # sys.stdout.write('-(%s)' % (frame.timestamp + frame.duration))
    #sys.stdout.write('\n')
    if voiced_frames:
        yield b''.join([f.bytes for f in voiced_frames])

def doyourvaejobplease(path):
    audio, sample_rate = read_wave(path)
    vad = webrtcvad.Vad(int(1))
    frames = frame_generator(30, audio, sample_rate)
    frames = list(frames)
    segments = vad_collector(sample_rate, 30, 300, vad, frames)
    for i, segment in enumerate(segments):
        path = './audios/chunk-%002d.wav' % (i,)
        # print(' Writing %s' % (path,))
        write_wave(path, segment, sample_rate)
"""

function dealwithmyissue(results)
	for i in results
		if sign(i[1]) == -1
			lowval =  abs(i[1])
			i[1] = 0
			i[2] = i[2] + lowval
		elseif i[2] > 88200
			highval = i[2]-88200
			i[2] = 88200
			i[1] = i[1] - highval
		end
	end
	return results
end
function findislands(arr)
	startindices = []
	finalindices = []
	for (i,val) in enumerate(arr)
		if i == 1
			continue
		elseif arr[i] == 0 && arr[i-1] == 1
			push!(finalindices, i-1)
		elseif arr[i-1] == 0 && arr[i] == 1
			push!(startindices, i)
		end
	end
	lengths = finalindices .- startindices .+1
	centeralpoints = round.(Int, (startindices .+ finalindices)/2)
	results = map(x-> [x-8000,x+7999], centeralpoints)
	results = dealwithmyissue(results)
	return results
end
using Glob
while true
    stream = PortAudioStream("default", 1, 0)
    buf = read(stream, 2s).data[:]
    # #binarymask = abs.(buf .-0.02) .> 0.1
    # #islanddetails = findislands(binarymask)
    # #interestingdata = map(x->buf[x[1]:x[2]], islanddetails)
    wavwrite(buf,  "test8final.wav", Fs=48000, nbits=16,  compression=WAVE_FORMAT_PCM)
    # mkdir("audios")
    py"doyourvaejobplease"("test8final.wav")
    close(stream)
    # y, fs = wavread("./mini_speech_commands/down/00b01445_nohash_1.wav") # works for down
    # y, fs = wavread("./mini_speech_commands/left/012c8314_nohash_0.wav") # works for left
    # y, fs = wavread("./mini_speech_commands/up/0132a06d_nohash_2.wav") # works for up
    # y, fs = wavread("./mini_speech_commands/right/ffd2ba2f_nohash_4.wav ") # works for right
    #senddataup(vec(buf.data))
    #senddataup(repeat(y, 6))
    listofwavs = glob("*.wav","./audios")
    # println(listofwavs)
    interestingdata = map(x->wavread(x)[1][:], listofwavs)
    # println(typeof(interestingdata[1]))
    for i in interestingdata
        datara = ceil(Int, length(i)/16000)
        zerosadd =  datara*16000 - length(i)
        println(zerosadd)
        zeroestobeadded = zeros(Float64, zerosadd)
        i = vcat(i, zeroestobeadded)
        batch = map(x->i[16000*(x-1)+1:16000*x] ,1:datara)
    	for j in batch
            sendsingledataup(j)
        end
    end

    # # rm("audios")
    map(x->rm(x), listofwavs)
    interestingdata = nothing
    listofwavs = nothing
    buf = nothing
    # #sendfileup("./mini_speech_commands/up/0132a06d_nohash_2.wav.png")
    # #down#00b01445_nohash_1.wav.png # for down
    # #./datasetspectro2/left#ffd2ba2f_nohash_4.wav.png" # for left
    # #./datasetspectro2/up#0132a06d_nohash_2.wav.png # for up
    # #./datasetspectro2/right#ffd2ba2f_nohash_4.wav.png for right
    r = HTTP.get("http://localhost:8003/digitreg", [])
    mode = labeldict[String(r.body)]
    makeamove(mode)
    sleep(0.1)
end

max_stars_repo_name: ashwani-rathee/Sardor

max_issues_repo_name: ashwani-rathee/Sardor

max_forks_repo_name: ashwani-rathee/Sardor


text:
module Player

import GL

type State
	position::GL.Vec3
	orientation::GL.Vec3   # pitch, yaw, and roll in degrees
	look_velocity::GL.Vec3
	move_velocity::GL.Vec3
	speed::Real
	last_think::Real
end
State() = State(GL.Vec3(0,0,0), GL.Vec3(0,0,0), GL.Vec3(0,0,0), GL.Vec3(0,0,0), 100, 0)

function lookdir!(player::State, delta::GL.Vec3, apply::Bool)
	if apply
		player.look_velocity += delta
	else
		player.look_velocity -= delta
	end
end

function lookdir!(player::State, pitch::Real, yaw::Real)
	pitch = player.orientation[1] + pitch
	pitch = clamp(pitch, -89, 89)
	yaw = (player.orientation[2] + yaw) % 360
	player.orientation = GL.Vec3(pitch, yaw, 0)
end

export sphere2cartesian # TODO: put this in a better spot
function sphere2cartesian(orientation::GL.Vec3)
	orientation = degrees2radians(orientation)
	x = cos(orientation[1]) * cos(orientation[2])
	y = cos(orientation[1]) * sin(orientation[2])
	z = sin(orientation[1])
	eyedir = GL.Vec3(x, y, z)
	eyedir /= norm(eyedir)
	updir = GL.Vec3(0, 0, 1)
	rightdir = cross(eyedir, updir)
	rightdir /= norm(rightdir)
	return eyedir, updir, rightdir
end

function movedir!(player::State, delta::GL.Vec3, apply::Bool)
	if apply
		player.move_velocity += delta
	else
		player.move_velocity -= delta
	end
end

# update position using eyedir, move_velocity, and speed
function move!(player::State)
	now = time_ns()
	time = (now - player.last_think) / 1000000000
	dist = player.speed * time
	lookdir!(player, player.look_velocity[1] * time, player.look_velocity[2] * time)
	eyedir, updir, rightdir = sphere2cartesian(player.orientation)
	player.position += dist * player.move_velocity[1] * eyedir
	player.position += dist * player.move_velocity[2] * rightdir
	player.position += dist * player.move_velocity[3] * updir
	player.last_think = now
end

self = State()

export forward, back, moveleft, moveright, moveup, movedown, speed, left, right, lookup, lookdown

forward(apply::Bool)   = movedir!(self, GL.Vec3( 1,  0,  0), apply)
back(apply::Bool)      = movedir!(self, GL.Vec3(-1,  0,  0), apply)
moveleft(apply::Bool)  = movedir!(self, GL.Vec3( 0, -1,  0), apply)
moveright(apply::Bool) = movedir!(self, GL.Vec3( 0,  1,  0), apply)
moveup(apply::Bool)    = movedir!(self, GL.Vec3( 0,  0,  1), apply)
movedown(apply::Bool)  = movedir!(self, GL.Vec3( 0,  0, -1), apply)

function speed(apply::Bool)
	if apply
		self.speed *= 5
	else
		self.speed /= 5
	end
end

left(apply::Bool)     = lookdir!(self, GL.Vec3(  0,  60,  0), apply)
right(apply::Bool)    = lookdir!(self, GL.Vec3(  0, -60,  0), apply)
lookup(apply::Bool)   = lookdir!(self, GL.Vec3( 60,   0,  0), apply)
lookdown(apply::Bool) = lookdir!(self, GL.Vec3(-60,   0,  0), apply)

end

ext: jl


text:
using BSplineKit.DifferentialOps
using BSplineKit.DifferentialOps:
    DerivativeUnitRange

using LinearAlgebra: ⋅

@testset "DifferentialOps" begin
    D2 = Derivative(2)
    D3 = Derivative(3)
    @test max_order(D2) == 2
    @test max_order(D3) == 3

    @test D2^2 === Derivative(4)
    @test D2^3 === Derivative(6)
    @test Derivative() === Derivative(1)
    @test Derivative()^3 === Derivative(3)

    @inferred (() -> Derivative())()
    @inferred (() -> Derivative()^3)()
    @inferred (() -> Derivative(3))()

    S = D2 + 5 * D3
    S′ = 5 * D3 + D2
    @test S == S′
    @test max_order(S) == max_order(S′) == 3

    @testset "Projections" begin
        @test LeftNormal() ⋅ D2 == D2 == 1 * D2
        @test RightNormal() ⋅ D2 == D2 == 1 * D2

        # Odd-order derivatives are flipped on the left boundary.
        @test LeftNormal() ⋅ D3 == -D3 == -1 * D3
        @test RightNormal() ⋅ D3 == D3 == 1 * D3

        @test LeftNormal() ⋅ S == D2 - 5 * D3
        @test RightNormal() ⋅ S == D2 + 5 * D3
    end

    @testset "Ranges" begin
        @inferred (() -> Derivative(2:5))()
        @inferred (() -> Derivative(2):Derivative(5))()
        r = Derivative(2:5)
        @test typeof(r) === DerivativeUnitRange{2, 5}
        @test repr(r) == "Derivative(2:5)"
        @test r === Derivative(2):Derivative(5)
    end
end

max_stars_repo_name: jipolanco/BasisSplines

max_issues_repo_name: jipolanco/BasisSplines

max_forks_repo_name: jipolanco/BasisSplines


text:
export
    AbstractSimplex,
    orientation,
    intersect,
    radius,
    volume,
    centroid

import LinearAlgebra: det
import .Simplices: centroid
import .Simplices: radius
import .Simplices: orientation
import .Simplices: volume

abstract type AbstractSimplex{D, T} end

# Return the i-th point as column vector
Base.getindex(s::AbstractSimplex, i) = s.vertices[i]
Base.getindex(s::AbstractSimplex, i, j) = s.vertices[i][j]
Base.getindex(s::AbstractSimplex, i::Colon, j) = hcat(s.vertices[j]...,)
Base.getindex(s::AbstractSimplex, i::Colon, j::Colon) = hcat(s.vertices...,)

Base.length(s::AbstractSimplex) = length(s.vertices)
Base.size(s::AbstractSimplex) = length(s[1]), length(s)
Base.size(s::AbstractSimplex, i) = size(s)[i]
Base.IteratorSize(s::AbstractSimplex) = Base.HasLength()

Base.firstindex(s::AbstractSimplex) = 1
Base.lastindex(s::AbstractSimplex) = length(s)
Base.eachindex(s::AbstractSimplex) = Base.OneTo(length(s))
Base.iterate(s::AbstractSimplex, state = 1) = iterate(s.vertices, state)

###########################################################
# Vector{vertex} representation => Array representation
###########################################################
Base.Array(s::AbstractSimplex) = hcat(s.vertices...,)

"""
    dimension(s::AbstractSimplex)

Get the dimension of a simplex.
"""
dimension(s::AbstractSimplex) = length(s[1])
npoints(s::AbstractSimplex) = length(s)

"""
    nvertices(s::AbstractSimplex)

Get the number of vertices of a simplices.
"""
nvertices(s::AbstractSimplex) = length(s)

"""
    orientation(s::AbstractSimplex)

Compute the orientation of a simplex. *Convention: append rows of ones at top of vertex matrix*.
"""
function Simplices.orientation(s::AbstractSimplex)
    det([ones(1, dimension(s) + 1); s[:, :]])
end

"""
    volume(s::AbstractSimplex)

Compute the unscaled volume of the simplex. Divide by factorial(dim) to get the true volume.
"""
Simplices.volume(s::AbstractSimplex) = abs(orientation(s))

function Simplices.centroid(s::AbstractSimplex)
    D = dimension(s)
    # Results in a dim-by-1 matrix, but we just want a vector, so drop the last dimension
    centroid = dropdims(s[:, :] * (ones(D + 1, 1) / (D + 1)), dims = 2)
end

"""
    radius(s::AbstractSimplex)

Compute the radius of a simplex.
"""
function Simplices.radius(s::AbstractSimplex)
    D = dimension(s)
    centroidmatrix = repeat(centroid(s), 1, D + 1)
    radius = sqrt(maximum(ones(1, D) * ((s[:, :] .- centroidmatrix) .^ 2)))
end

function Base.intersect(s1::AbstractSimplex, s2::AbstractSimplex)
    Simplices.simplexintersection(s1[:, :], s2[:, :])
end

"""
    ∩(s1::AbstractSimplex, s2::AbstractSimplex)

Compute the volume intersection between two simplices.
"""
∩(s1::AbstractSimplex, s2::AbstractSimplex) = intersect(s1, s2)


text:
using Test
using TropicalNumbers

@testset "counting tropical" begin
    ct1 = CountingTropical(2.0, 4.0)
    ct2 = CountingTropical(2.0, 3.0)
    @test ct1 * true == ct1
    @test ct1 * false == CountingTropical(-Inf, 1.0)
    @test one(ct1) == CountingTropical(0.0, 1.0)
    @test zero(ct1) == CountingTropical(-Inf, 1.0)
    res1 = ct1 + ct2
    @test res1.n == 2
    @test res1.c == 7
    res2 = ct1 * ct2
    @test res2.n == 4
    @test res2.c == 12
    @test res2 ≈ CountingTropical(4, 12)
    println(CountingTropical{Float64}(3))

    ct1 = CountingTropical(2, 4)
    ct2 = CountingTropical(2.0, 3.0)
    @test CountingTropicalF64(ct1) === CountingTropical(2.0, 4.0)
    @test promote(ct1, ct2) === (CountingTropical(2.0, 4.0), ct2)

    @test CountingTropical{Float64}(2) === CountingTropical{Float64,Float64}(2.0, 1.0)
    @test CountingTropical{Int64, Float64}(2) === CountingTropical{Int64,Float64}(2, 1.0)
    @test CountingTropical{Int64, Float64}(TropicalF64(2)) === CountingTropical{Int64,Float64}(2, 1.0)
    @test CountingTropical{Int64, Float64}(CountingTropicalF64(2)) === CountingTropical{Int64,Float64}(2, 1.0)
    @test zero(CountingTropical{Int64,Float64}) === CountingTropical{Int64,Float64}(-999999, 0.0)
    @test one(CountingTropical{Int64,Float64}) === CountingTropical{Int64,Float64}(0, 1.0)

    @test promote(CountingTropical{Float64,Float32}(1, 2), CountingTropical{Int64,Int32}(1, 2)) == (CountingTropical{Float64,Float32}(1, 2), CountingTropical{Float64,Float32}(1, 2))
    @test promote(CountingTropical{Float64,Float32}(1, 2)) == (CountingTropical{Float64,Float32}(1, 2),)
    @test promote_type(CountingTropical{Float64,Float32}, CountingTropicalF32, CountingTropical{Int32,Int32}) == CountingTropical{Float64,Float32}

    @test one(CountingTropical{Float64}) == one(CountingTropicalF64)
    @test isnan(CountingTropical(NaN))
    @test !isnan(CountingTropical(-Inf))
end


text:
insts = OrderedDict()
insts["minimal"] = [
    ((2, false, true, true, true),),
    ((2, false, false, true, true),),
    ((2, true, true, true, true),),
    ((2, true, false, true, true),),
    ((2, false, true, true, false),),
    ((2, false, false, true, false),),
    ((2, true, true, true, false),),
    ((2, true, false, true, false),),
    ((2, false, false, false, false),),
    ((2, true, false, false, false),),
    ]
insts["fast"] = [
    ((5, false, true, true, true),),
    ((5, false, false, true, false),),
    ((5, true, true, true, false),),
    ((5, true, false, true, true),),
    ((5, false, true, false, false),),
    ((5, false, false, false, false),),
    ((5, true, true, false, false),),
    ((5, true, false, false, false),),
    ((20, false, true, true, false),),
    ((20, false, false, true, true),),
    ((20, true, true, true, true),),
    ((20, true, false, true, false),),
    ((20, false, true, false, false),),
    ((20, false, false, false, false),),
    ((20, true, true, false, false),),
    ((20, true, false, false, false),),
    ((100, false, true, false, false),),
    ((100, false, false, false, false),),
    ]
insts["various"] = [
    ((50, false, true, true, true),),
    ((50, false, false, true, true),),
    ((50, true, true, true, false),),
    ((50, true, false, true, false),),
    ((50, false, true, false, false),),
    ((50, false, false, false, false),),
    ((50, true, true, false, false),),
    ((50, true, false, false, false),),
    ((100, false, true, true, true),),
    ((100, false, false, true, false),),
    ((100, true, true, true, false),),
    ((100, true, false, true, true),),
    ((100, false, true, false, false),),
    ((100, false, false, false, false),),
    ((100, true, true, false, false),),
    ((100, true, false, false, false),),
    ((200, false, true, false, false),),
    ((200, false, false, false, false),),
    ((200, false, true, true, false),),
    ((200, false, false, true, false),),
    ((200, true, true, true, true),),
    ((200, true, false, true, true),),
    ((400, false, true, false, false),),
    ((400, false, false, false, false),),
    ((400, false, true, true, false),),
    ((400, false, false, true, true),),
    ((400, true, true, true, true),),
    ((400, true, false, true, false),),
    ]
return (NearestPSDJuMP, insts)


text:
"""
    B_SplineFFT{T, order} <: AbstractInterpolation{T, CircEdge, order}
    B_SplineFFT( order::Int, n::Int, T::DataType=Float64)

Type containing spline coefficients for b-spline interpolation based on fft, using the fact that b-spline matrix is a circulant matrix

# Type parameters
- `T` : the type of data that is interpolate
- `order::Int`: order of lagrange interpolation

# Implementation :
- `c_fft::Vector{Complex{T}}` : fft transform of coefficients
- `parfft::PrepareFftBig` : fft precomputed data
- `tabfct::Vector{Polynomial{T}}` : function table for interpolation

# Arguments :
- `n` : size of the matrix
- `order` : the order of interpolation
- `[T::DataType=Float64]` : The type values to interpolate

"""
struct B_SplineFFT{T,order} <: B_Spline{T,CircEdge,order}
    c_fft::Vector{Complex{T}}
    parfft::PrepareFftBig
    tabfct::Vector{Polynomial{T}}
    function B_SplineFFT(order::Int, n::Int, T::DataType = Float64)
        bspline = getbspline(order, 0)
        tabfct_rat = map(x -> bspline[order-x](Polynomial([order - x, 1])), 0:order)
        kl, ku = get_kl_ku(order)
        c = zeros(T, n)
        parfft = PrepareFftBig(n, T)
        tab_coef = convert.(T, bspline.(1:order))
        dec = n - kl - 1
        for i = 1:order
            c[(dec+i)%n+1] = tab_coef[i]
        end
        c_fft = fftgen(parfft, c)
        return new{T,order}(c_fft, parfft, convert.(Polynomial{T}, tabfct_rat))
    end
    B_SplineFFT(o::Int, n::Int, _::T) where {T} = B_SplineFFT(o, n, T)
end
function sol(bsp::B_SplineFFT{T}, b::AbstractVector{T}) where {T}
    return real(ifftgen(bsp.parfft, fftgen(bsp.parfft, b) ./ bsp.c_fft))
end
function sol!(Y::AbstractVector{T}, bsp::B_SplineFFT{T}, b::AbstractVector{T}) where {T}
    Y .= real(ifftgen(bsp.parfft, fftgen(bsp.parfft, b) ./ bsp.c_fft))
end


text:
using MPI
using Test
function run_mpi_driver(;procs,file)
  mpidir = @__DIR__
  testdir = joinpath(mpidir,"..")
  repodir = joinpath(testdir,"..")
  mpiexec() do cmd
    run(`$cmd -n $procs $(Base.julia_cmd()) --project=$repodir $(joinpath(mpidir,file))`)
    @test true
  end
end


text:
module ExtendableGrids

using DocStringExtensions
using ElasticArrays
using AbstractTrees

using InteractiveUtils
using SparseArrays
using Printf
using Random
using Dates
using LinearAlgebra

include("adjacency.jl")
export Adjacency,VariableTargetAdjacency,FixedTargetAdjacency
export atranspose,num_targets,num_sources,num_links,append!, max_num_targets_per_source
export asparse,tryfix,makevar

include("serialadjacency.jl")
export SerialVariableTargetAdjacency

include("vectorofconstants.jl")
export VectorOfConstants

include("typehierarchy.jl")
export AbstractExtendableGridApexType
export typehierarchy

include("elementgeometry.jl")
export AbstractElementGeometry, ElementInfo
export elementgeometries

export AbstractElementGeometry0D
export Vertex0D

export AbstractElementGeometry1D
export Edge1D

export AbstractElementGeometry2D
export Polygon2D,Triangle2D,Quadrilateral2D,Pentagon2D,Hexagon2D,Parallelogram2D,Circle2D

export AbstractElementGeometry3D
export Polyhedron3D,Tetrahedron3D, Hexahedron3D,Parallelepiped3D,Prism3D,TrianglePrism3D,Sphere3D

export AbstractElementGeometry4D
export Polychoron4D,HyperCube4D

export dim_element

include("coordinatesystem.jl")
export coordinatesystems
export AbstractCoordinateSystem
export Cartesian1D,Cartesian2D,Cartesian3D
export Cylindrical2D,Cylindrical3D
export Polar2D,Polar1D ,Spherical3D,Spherical1D

include("extendablegrid.jl")
export ExtendableGrid
export instantiate, veryform
export AbstractGridComponent
export AbstractGridAdjacency,AbstractElementGeometries,AbstractElementRegions
export Coordinates, CellNodes, BFaceNodes
export CellGeometries, BFaceGeometries
export CellRegions, BFaceRegions, BEdgeRegions
export NumCellRegions, NumBFaceRegions, NumBEdgeRegions
export CoordinateSystem
export AbstractGridFloatArray1D,AbstractGridFloatArray2D
export AbstractGridIntegerArray1D,AbstractGridIntegerArray2D
export index_type, coord_type
export dim_space, dim_grid
export num_nodes, num_cells, num_bfaces, num_bedges
export num_cellregions, num_bfaceregions, num_bedgeregions
export gridcomponents
export seemingly_equal

include("subgrid.jl")
export subgrid

include("shape_specs.jl")
export refcoords_for_geometry
export num_nodes
export num_faces
export num_edges
export local_cellfacenodes
export local_celledgenodes
export facetype_of_cellface
export Volume4ElemType
export Normal4ElemType!
export Tangent4ElemType!
export xrefFACE2xrefCELL
export xrefFACE2xrefOFACE

include("derived.jl")
export Coordinates
export CellVolumes, CellFaces, CellEdges, CellFaceSigns, CellFaceOrientations, CellEdgeSigns
export FaceNodes, FaceGeometries, FaceVolumes, FaceRegions, FaceCells, FaceEdges, FaceNormals
export EdgeNodes, EdgeGeometries, EdgeVolumes, EdgeRegions, EdgeCells, EdgeTangents
export BFaceFaces, BFaceCellPos, BFaceVolumes
export BEdgeNodes, BEdgeEdges, BEdgeVolumes, BEdgeGeometries
export NodePatchGroups
export unique, UniqueCellGeometries, UniqueFaceGeometries, UniqueBFaceGeometries, UniqueEdgeGeometries, UniqueBEdgeGeometries
export GridComponent4TypeProperty
export ITEMTYPE_CELL, ITEMTYPE_FACE, ITEMTYPE_BFACE, ITEMTYPE_EDGE, ITEMTYPE_BEDGE
export PROPERTY_NODES, PROPERTY_REGION, PROPERTY_VOLUME, PROPERTY_UNIQUEGEOMETRY, PROPERTY_GEOMETRY
export get_facegrid, get_bfacegrid, get_edgegrid
export GridEGTypes
export GridRegionTypes

include("more.jl")
# export EdgeNodes, CellEdges, EdgeCells,
export BFaceCells, BFaceNormals, BFaceEdges, BEdgeNodes

include("voronoi.jl")
export tricircumcenter!,VoronoiFaceCenters

include("meshrefinements.jl")
export split_grid_into
export uniform_refine
export barycentric_refine
export CellParents

include("adaptive_meshrefinements.jl")
export bulk_mark
export RGB_refine

include("assemblytypes.jl");
export AssemblyType
export AT_NODES, ON_CELLS, ON_FACES, ON_IFACES, ON_BFACES, ON_EDGES, ON_BEDGES
export ItemType4AssemblyType
export GridComponentNodes4AssemblyType
export GridComponentVolumes4AssemblyType
export GridComponentGeometries4AssemblyType
export GridComponentRegions4AssemblyType
export GridComponentUniqueGeometries4AssemblyType

include("l2gtransformations.jl");
export L2GTransformer, update_trafo!, eval_trafo!, mapderiv!

include("cellfinder.jl")
export CellFinder
export gFindLocal!, gFindBruteForce!

include("commongrids.jl")
export reference_domain
export grid_unitcube
export grid_lshape
export grid_unitsquare, grid_unitsquare_mixedgeometries
export grid_triangle

include("regionedit.jl")
export cellmask!, bfacemask!, bedgemask!

include("arraytools.jl")
export glue,geomspace,linspace

include("simplexgrid.jl")
export simplexgrid, geomspace, glue
export XCoordinates, YCoordinates, ZCoordinates
export writefile

include("tokenstream.jl")
export TokenStream, gettoken, expecttoken,trytoken

end # module


text:
export FT_Description, FT_SerialNumber, ft_openex

#Flags (see ft_openex)
const FT_OPEN_BY_SERIAL_NUMBER = 1
const FT_OPEN_BY_DESCRIPTION = 2
const FT_OPEN_BY_LOCATION = 4

immutable FT_Description
  d :: Array{UInt8,1}
  function FT_Description(s :: ASCIIString)
    description = Array(UInt8,64)
    if length(s) < 64
      for (pos,character) in enumerate(s)
        description[pos] = Int(character)
      end
      description[length(s)+1] = 0
    else
      error("length(desctiption) must be < 64")
    end
    new(description)
  end
end

immutable FT_SerialNumber
  sn :: Array{UInt8,1}
  function FT_SerialNumber(s :: ASCIIString)
    serialnumber = Array(UInt8,16)
    if length(s) < 16
      for (pos,character) in enumerate(s)
        serialnumber[pos] = Int(character)
      end
      serialnumber[length(s)+1] = 0
    else
      error("length(serialnumber) must be < 16")
    end
    new(serialnumber)
  end
end

function ft_openex(location :: Unsigned)
  ft_handle = Ref{Culong}()
  ft_status = ccall((:FT_OpenEx, d2xx),
                      Cuint,
                      (Cuint,Cuint,Ref{Culong}),
                      location,FT_OPEN_BY_LOCATION,ft_handle)
  checkstatus(ft_status)
  return ft_handle[]
end

function ft_openex(serialnumber :: FT_SerialNumber)
  ft_handle = Ref{Culong}()
  ft_status = ccall((:FT_OpenEx, d2xx),
                      Cuint,
                      (Ptr{UInt8},Cuint,Ref{Culong}),
                      serialnumber.sn,FT_OPEN_BY_SERIAL_NUMBER,ft_handle)
  checkstatus(ft_status)
  return ft_handle[]
end

function ft_openex(description :: FT_Description)
  ft_handle = Ref{Culong}()
  ft_status = ccall((:FT_OpenEx, d2xx),
                      Cuint,
                      (Ptr{UInt8},Cuint,Ref{Culong}),
                      description.d,FT_OPEN_BY_DESCRIPTION,ft_handle)
  checkstatus(ft_status)
  return ft_handle[]
end


text:
""
function constraint_variable_transformer_y_from(pm::GenericPowerModel, i::Int; nw::Int = pm.cnw, cnd::Int = pm.ccnd)
    branch = PowerModels.ref(pm, nw, :branch, i)
    f_bus = branch["f_bus"]
    t_bus = branch["t_bus"]
    f_idx = (i, f_bus, t_bus)
    t_idx = (i, t_bus, f_bus)

    g, b = PowerModels.calc_branch_y(branch)
    c = branch["br_b"]
    g_shunt = branch["g_shunt"]
    tap_min = branch["tap_fr_min"]
    tap_max = branch["tap_fr_max"]

    return constraint_variable_transformer_y_from(pm, nw, cnd, f_bus, t_bus, f_idx, t_idx, g, b, c, g_shunt, tap_min, tap_max)
end

""
function constraint_variable_transformer_y_to(pm::GenericPowerModel, i::Int;  nw::Int = pm.cnw, cnd::Int = pm.ccnd)
    branch = PowerModels.ref(pm, nw, :branch, i)
    f_bus = branch["f_bus"]
    t_bus = branch["t_bus"]
    f_idx = (i, f_bus, t_bus)
    t_idx = (i, t_bus, f_bus)

    g, b = PowerModels.calc_branch_y(branch)
    c = branch["br_b"]
    g_shunt = branch["g_shunt"]
    tap_min = branch["tap_to_min"]
    tap_max = branch["tap_to_max"]

    return constraint_variable_transformer_y_to(pm, nw, cnd, f_bus, t_bus, f_idx, t_idx, g, b, c, g_shunt, tap_min, tap_max)
end

""
function constraint_link_voltage_magnitudes(pm::GenericPowerModel, i::Int; nw::Int = pm.cnw, cnd::Int = pm.ccnd)
    branch = PowerModels.ref(pm, nw, :branch, i)
    f_bus = branch["f_bus"]
    t_bus = branch["t_bus"]
    f_idx = (i, f_bus, t_bus)
    t_idx = (i, t_bus, f_bus)

    tap_fr = branch["tap_fr"]
    tap_to = branch["tap_to"]

    return constraint_link_voltage_magnitudes(pm, nw, cnd, f_bus, t_bus, f_idx, t_idx, tap_fr, tap_to)
end

# function constraint_link_voltage_magnitudes(pm::GenericPowerModel, n::Int, i::Int)
#     branch = PowerModels.ref(pm, n, :branch, i)
#     f_bus = branch["f_bus"]
#     t_bus = branch["t_bus"]
#     f_idx = (i, f_bus, t_bus)
#     t_idx = (i, t_bus, f_bus)
#
#     tap_fr = branch["tap_fr"]
#     tap_to = branch["tap_to"]
#
#     return constraint_link_voltage_magnitudes(pm, n, f_bus, t_bus, f_idx, t_idx, tap_fr, tap_to)
# end
# constraint_link_voltage_magnitudes(pm::GenericPowerModel, i::Int) = constraint_link_voltage_magnitudes(pm::GenericPowerModel, pm.cnw, i::Int)

""
function constraint_kcl_shunt_aggregated(pm::GenericPowerModel, i::Int; nw::Int=pm.cnw, cnd::Int=pm.ccnd)
    bus = PowerModels.ref(pm, nw, :bus, i)
    bus_arcs = PowerModels.ref(pm, nw, :bus_arcs, i)
    bus_arcs_dc = PowerModels.ref(pm, nw, :bus_arcs_dc, i)

    bus_loads = ref(pm, nw, :bus_loads, i)
    bus_shunts = ref(pm, nw, :bus_shunts, i)

    bus_gs = Dict(k => ref(pm, nw, :shunt, k, "gs", cnd) for k in bus_shunts)
    bus_bs = Dict(k => ref(pm, nw, :shunt, k, "bs", cnd) for k in bus_shunts)

    return constraint_kcl_shunt_aggregated(pm, nw, cnd, i, bus_arcs, bus_arcs_dc, bus_gs, bus_bs)
end

""
function constraint_load_gen_aggregation(pm, nw::Int, i::Int)
        constraint_active_load_gen_aggregation(pm, nw, i)
        constraint_reactive_load_gen_aggregation(pm, nw, i)
end
constraint_load_gen_aggregation(pm::GenericPowerModel, i::Int) = constraint_load_gen_aggregation(pm::GenericPowerModel, pm.cnw, i::Int)

function constraint_active_load_gen_aggregation(pm, nw::Int, i::Int)
    bus = PowerModels.ref(pm, nw, :bus, i)
    bus_gens = PowerModels.ref(pm, nw, :bus_gens, i)

    return constraint_active_load_gen_aggregation(pm, nw, i, bus_gens, bus["pd"])
end
constraint_active_load_gen_aggregation(pm::GenericPowerModel, i::Int) = constraint_active_load_gen_aggregation(pm::GenericPowerModel, pm.cnw, i::Int)

function constraint_reactive_load_gen_aggregation(pm, nw::Int, i::Int)
    bus = PowerModels.ref(pm, nw, :bus, i)
    bus_gens = PowerModels.ref(pm, nw, :bus_gens, i)

    return constraint_reactive_load_gen_aggregation(pm, nw, i, bus_gens, bus["qd"])
end
constraint_reactive_load_gen_aggregation(pm::GenericPowerModel, i::Int) = constraint_reactive_load_gen_aggregation(pm::GenericPowerModel, pm.cnw, i::Int)

""
function constraint_load_gen_aggregation_sheddable(pm, i::Int; nw::Int = pm.cnw, cnd::Int = pm.ccnd)
    constraint_active_load_gen_aggregation_sheddable(pm, nw, cnd, i)
    constraint_reactive_load_gen_aggregation_sheddable(pm, nw, cnd, i)
end
#constraint_load_gen_aggregation_sheddable(pm::GenericPowerModel, i::Int) = constraint_load_gen_aggregation_sheddable(pm::GenericPowerModel, pm.cnw, i::Int)

function constraint_active_load_gen_aggregation_sheddable(pm, nw::Int, cnd::Int, i::Int)
    bus = PowerModels.ref(pm, nw, :bus, i)
    bus_gens = PowerModels.ref(pm, nw, :bus_gens, i)
    bus_loads = PowerModels.ref(pm, nw, :bus_loads, i)

    return constraint_active_load_gen_aggregation_sheddable(pm, nw, cnd, i, bus_gens, bus_loads)
end
#constraint_active_load_gen_aggregation_sheddable(pm::GenericPowerModel, i::Int) = constraint_active_load_gen_aggregation_sheddable(pm::GenericPowerModel, pm.cnw, i::Int)

function constraint_reactive_load_gen_aggregation_sheddable(pm, nw::Int, cnd::Int, i::Int)
    bus = PowerModels.ref(pm, nw, :bus, i)
    bus_gens = PowerModels.ref(pm, nw, :bus_gens, i)
    bus_loads = PowerModels.ref(pm, nw, :bus_loads, i)

    return constraint_reactive_load_gen_aggregation_sheddable(pm, nw, cnd, i, bus_gens, bus_loads)
end
#constraint_reactive_load_gen_aggregation_sheddable(pm::GenericPowerModel, i::Int) = constraint_reactive_load_gen_aggregation_sheddable(pm::GenericPowerModel, pm.cnw, i::Int)

""
function constraint_flexible_load(pm, i::Int; nw::Int = pm.cnw, cnd::Int = pm.ccnd)
        constraint_flexible_active_load(pm, nw, cnd, i)
        constraint_flexible_reactive_load(pm, nw, cnd, i)
end

function constraint_flexible_active_load(pm, nw::Int, cnd::Int, i::Int)
    load = PowerModels.ref(pm, nw, :load, i)
    return constraint_flexible_active_load(pm, nw, cnd, load["index"], load["prated"], load["pref"])
end

function constraint_flexible_reactive_load(pm, nw::Int, cnd::Int, i::Int)
    load = PowerModels.ref(pm, nw, :load, i)
    return constraint_flexible_reactive_load(pm, nw, cnd, load["index"], load["qrated"], load["qref"])
end
# function constraint_flexible_load(pm::GenericPowerModel, n::Int, i::Int)
#         constraint_flexible_active_load(pm, n, i)
#         constraint_flexible_reactive_load(pm, n, i)
# end
# constraint_flexible_load(pm::GenericPowerModel, i::Int) = constraint_flexible_load(pm::GenericPowerModel, pm.cnw, i::Int)
#
# function constraint_flexible_active_load(pm, n::Int, i::Int)
#     load = PowerModels.ref(pm, n, :load, i)
#     return constraint_flexible_active_load(pm, n, load["index"], load["prated"], load["pref"])
# end
# constraint_flexible_active_load(pm::GenericPowerModel, i::Int) = constraint_flexible_active_load(pm::GenericPowerModel, pm.cnw, i::Int)
#
#
# function constraint_flexible_reactive_load(pm, n::Int, i::Int)
#     load = PowerModels.ref(pm, n, :load, i)
#     return constraint_flexible_reactive_load(pm, n, load["index"], load["qrated"], load["qref"])
# end
# constraint_flexible_reactive_load(pm::GenericPowerModel, i::Int) = constraint_flexible_reactive_load(pm::GenericPowerModel, pm.cnw, i::Int)

""
function constraint_flexible_gen(pm, i::Int; nw::Int = pm.cnw, cnd::Int = pm.ccnd)
        constraint_flexible_active_gen(pm, nw, cnd, i)
        constraint_flexible_reactive_gen(pm, nw, cnd, i)
end

function constraint_flexible_active_gen(pm, nw::Int, cnd::Int, i::Int)
    gen = PowerModels.ref(pm, nw, :gen, i)
    return constraint_flexible_active_gen(pm, nw, cnd, gen["index"], gen["prated"], gen["pref"])
end

function constraint_flexible_reactive_gen(pm, nw::Int, cnd::Int, i::Int)
    gen = PowerModels.ref(pm, nw, :gen, i)
    return constraint_flexible_reactive_gen(pm, nw, cnd, gen["index"], gen["qrated"], gen["qref"])
end

# function constraint_flexible_gen(pm::GenericPowerModel, n::Int, i::Int)
#         constraint_flexible_active_gen(pm, n, i)
#         constraint_flexible_reactive_gen(pm, n, i)
# end
# constraint_flexible_gen(pm::GenericPowerModel, i::Int) = constraint_flexible_gen(pm::GenericPowerModel, pm.cnw, i::Int)
#
#
# function constraint_flexible_active_gen(pm, n::Int, i::Int)
#     gen = PowerModels.ref(pm, n, :gen, i)
#     return constraint_flexible_active_gen(pm, n, gen["index"], gen["prated"], gen["pref"])
# end
# constraint_flexible_active_gen(pm::GenericPowerModel, i::Int) = constraint_flexible_active_gen(pm::GenericPowerModel, pm.cnw, i::Int)
#
# function constraint_flexible_reactive_gen(pm, n::Int, i::Int)
#     gen = PowerModels.ref(pm, n, :gen, i)
#     return constraint_flexible_reactive_gen(pm, n, gen["index"], gen["qrated"], gen["qref"])
# end
# constraint_flexible_reactive_gen(pm::GenericPowerModel, i::Int) = constraint_flexible_reactive_gen(pm::GenericPowerModel, pm.cnw, i::Int)

""
function constraint_redispatch_power_gen(pm, i::Int; nw::Int = pm.cnw, cnd::Int = pm.ccnd)
    constraint_redispatch_active_power_gen(pm, nw, cnd, i)
    constraint_redispatch_reactive_power_gen(pm, nw, cnd, i)
end

function constraint_redispatch_active_power_gen(pm, nw::Int, cnd::Int, i::Int)
    gen = PowerModels.ref(pm, nw, :gen, i)
    return constraint_redispatch_active_power_gen(pm, nw, cnd, gen["index"], gen["pref"])
end

function constraint_redispatch_reactive_power_gen(pm, nw::Int, cnd::Int, i::Int)
    gen = PowerModels.ref(pm, nw, :gen, i)
    return constraint_redispatch_reactive_power_gen(pm, nw, cnd, gen["index"], gen["qref"])
end
#     constraint_redispatch_active_power_gen(pm, n::Int, i::Int)
#     constraint_redispatch_reactive_power_gen(pm, n::Int, i::Int)
# end
# constraint_redispatch_power_gen(pm::GenericPowerModel, i::Int) = constraint_redispatch_power_gen(pm::GenericPowerModel, pm.cnw, i::Int)
#
# function constraint_redispatch_active_power_gen(pm, n::Int, i::Int)
#     gen = PowerModels.ref(pm, n, :gen, i)
#     return constraint_redispatch_active_power_gen(pm, n, gen["index"], gen["pref"])
# end
# constraint_redispatch_active_power_gen(pm::GenericPowerModel, i::Int) = constraint_redispatch_active_power_gen(pm::GenericPowerModel, pm.cnw, i::Int)
#
# function constraint_redispatch_reactive_power_gen(pm, n::Int, i::Int)
#     gen = PowerModels.ref(pm, n, :gen, i)
#     return constraint_redispatch_reactive_power_gen(pm, n, gen["index"], gen["qref"])
# end
# constraint_redispatch_reactive_power_gen(pm::GenericPowerModel, i::Int) = constraint_redispatch_reactive_power_gen(pm::GenericPowerModel, pm.cnw, i::Int)
""
function constraint_second_stage_redispatch_power_gen(pm, nw::Int, i::Int, first_stage_network_id; cnd::Int = pm.ccnd)
    constraint_second_stage_redispatch_active_power_gen(pm, nw::Int, cnd::Int,  i::Int, first_stage_network_id)
    constraint_second_stage_redispatch_reactive_power_gen(pm, nw::Int, cnd::Int, i::Int, first_stage_network_id)
end

function constraint_second_stage_redispatch_active_power_gen(pm, nw::Int, cnd::Int, i::Int, first_stage_network_id)
    gen = PowerModels.ref(pm, nw, :gen, i)
    return constraint_second_stage_redispatch_active_power_gen(pm, nw, cnd, gen["index"], first_stage_network_id)
end

function constraint_second_stage_redispatch_reactive_power_gen(pm, nw::Int, cnd::Int, i::Int, first_stage_network_id)
    gen = PowerModels.ref(pm, nw, :gen, i)
    return constraint_second_stage_redispatch_reactive_power_gen(pm, nw, cnd, gen["index"], first_stage_network_id)
end

# function constraint_second_stage_redispatch_power_gen(pm, n::Int, i::Int, first_stage_network_id)
#     constraint_second_stage_redispatch_active_power_gen(pm, n::Int, i::Int, first_stage_network_id)
#     constraint_second_stage_redispatch_reactive_power_gen(pm, n::Int, i::Int, first_stage_network_id)
# end
# constraint_second_stage_redispatch_power_gen(pm::GenericPowerModel, i::Int, first_stage_network_id) = constraint_second_stage_redispatch_power_gen(pm::GenericPowerModel, pm.cnw, i::Int, first_stage_network_id)
#
# function constraint_second_stage_redispatch_active_power_gen(pm, n::Int, i::Int, first_stage_network_id)
#     gen = PowerModels.ref(pm, n, :gen, i)
#     return constraint_second_stage_redispatch_active_power_gen(pm, n, gen["index"], first_stage_network_id)
# end
# constraint_second_stage_redispatch_active_power_gen(pm::GenericPowerModel, i::Int, first_stage_network_id) = constraint_second_stage_redispatch_active_power_gen(pm::GenericPowerModel, pm.cnw, i::Int, first_stage_network_id)
#
# function constraint_second_stage_redispatch_reactive_power_gen(pm, n::Int, i::Int, first_stage_network_id)
#     gen = PowerModels.ref(pm, n, :gen, i)
#     return constraint_second_stage_redispatch_reactive_power_gen(pm, n, gen["index"], first_stage_network_id)
# end
# constraint_second_stage_redispatch_reactive_power_gen(pm::GenericPowerModel, i::Int, first_stage_network_id) = constraint_second_stage_redispatch_reactive_power_gen(pm::GenericPowerModel, pm.cnw, i::Int, first_stage_network_id)

""
function constraint_redispatch_power_load(pm, i::Int; nw::Int = pm.cnw, cnd::Int = pm.ccnd)
    constraint_redispatch_active_power_load(pm, nw::Int, cnd::Int, i::Int)
    constraint_redispatch_reactive_power_load(pm, nw::Int, cnd::Int, i::Int)
end

function constraint_redispatch_active_power_load(pm, nw::Int, cnd::Int, i::Int)
    load = PowerModels.ref(pm, nw, :load, i)
    return constraint_redispatch_active_power_load(pm, nw, cnd, load["index"], load["pref"])
end

function constraint_redispatch_reactive_power_load(pm, nw::Int, cnd::Int, i::Int)
    load = PowerModels.ref(pm, nw, :load, i)
    return constraint_redispatch_reactive_power_load(pm, nw, cnd, load["index"], load["qref"])
end
constraint_redispatch_reactive_power_load(pm::GenericPowerModel, i::Int) = constraint_redispatch_reactive_power_load(pm::GenericPowerModel, pm.cnw, i::Int)
""
function constraint_second_stage_redispatch_power_load(pm, nw::Int, i::Int, first_stage_network_id; cnd::Int = pm.ccnd)
    constraint_second_stage_redispatch_active_power_load(pm, nw::Int, cnd::Int, i::Int, first_stage_network_id)
    constraint_second_stage_redispatch_reactive_power_load(pm, nw::Int, cnd::Int, i::Int, first_stage_network_id)
    constraint_tan_phi_load(pm, nw::Int, cnd::Int, i::Int)
end

function constraint_second_stage_redispatch_active_power_load(pm, nw::Int, cnd::Int, i::Int, first_stage_network_id)
    load = PowerModels.ref(pm, nw, :load, i)
    return constraint_second_stage_redispatch_active_power_load(pm, nw, cnd, load["index"], first_stage_network_id)
end

function constraint_second_stage_redispatch_reactive_power_load(pm, nw::Int, cnd::Int, i::Int, first_stage_network_id)
    load = PowerModels.ref(pm, nw, :load, i)
    return constraint_second_stage_redispatch_reactive_power_load(pm, nw, cnd, load["index"], first_stage_network_id)
end

function constraint_tan_phi_load(pm, nw::Int, cnd::Int, i::Int)
    load_angle = PowerModels.ref(pm, nw, :load_angle, i)[1]
    return constraint_tan_phi_load(pm, nw, cnd, i, load_angle)
end

# function constraint_second_stage_redispatch_power_load(pm, n::Int, i::Int, first_stage_network_id)
#     constraint_second_stage_redispatch_active_power_load(pm, n::Int, i::Int, first_stage_network_id)
#     constraint_second_stage_redispatch_reactive_power_load(pm, n::Int, i::Int, first_stage_network_id)
#     constraint_tan_phi_load(pm, n::Int, i::Int)
# end
# constraint_second_stage_redispatch_power_load(pm::GenericPowerModel, i::Int, first_stage_network_id) = constraint_second_stage_redispatch_power_load(pm::GenericPowerModel, pm.cnw, i::Int, first_stage_network_id)
#
# function constraint_second_stage_redispatch_active_power_load(pm, n::Int, i::Int, first_stage_network_id)
#     load = PowerModels.ref(pm, n, :load, i)
#     return constraint_second_stage_redispatch_active_power_load(pm, n, load["index"], first_stage_network_id)
# end
# constraint_second_stage_redispatch_active_power_load(pm::GenericPowerModel, i::Int, first_stage_network_id) = constraint_second_stage_redispatch_active_power_load(pm::GenericPowerModel, pm.cnw, i::Int, first_stage_network_id)
#
# function constraint_second_stage_redispatch_reactive_power_load(pm, n::Int, i::Int, first_stage_network_id)
#     load = PowerModels.ref(pm, n, :load, i)
#     return constraint_second_stage_redispatch_reactive_power_load(pm, n, load["index"], first_stage_network_id)
# end
# constraint_second_stage_redispatch_reactive_power_load(pm::GenericPowerModel, i::Int, first_stage_network_id) = constraint_second_stage_redispatch_reactive_power_load(pm::GenericPowerModel, pm.cnw, i::Int, first_stage_network_id)
#
# function constraint_tan_phi_load(pm, n::Int, i::Int)
#     load_angle = PowerModels.ref(pm, n, :load_angle, i)[1]
#     return constraint_tan_phi_load(pm, n, i, load_angle)
# end
# constraint_tan_phi_load(pm::GenericPowerModel, i::Int) = constraint_tan_phi_load(pm::GenericPowerModel, pm.cnw, i::Int)

""
function constraint_fixed_load(pm, i::Int; nw::Int = pm.cnw, cnd::Int = pm.ccnd)
    constraint_fixed_active_load(pm, nw, cnd, i)
    constraint_fixed_reactive_load(pm, nw, cnd, i)
end

function constraint_fixed_active_load(pm, nw::Int, cnd::Int, i::Int)
    load = PowerModels.ref(pm, nw, :load, i)
    return constraint_fixed_active_load(pm, nw, cnd, load["index"], load["pref"])
end

function constraint_fixed_reactive_load(pm, nw::Int, cnd::Int, i::Int)
    load = PowerModels.ref(pm, nw, :load, i)
    return constraint_fixed_reactive_load(pm, nw, cnd, load["index"], load["qref"])
end

# function constraint_fixed_load(pm::GenericPowerModel, n::Int, i::Int)
#     constraint_fixed_active_load(pm::GenericPowerModel, n::Int, i::Int)
#     constraint_fixed_reactive_load(pm::GenericPowerModel, n::Int, i::Int)
# end
# constraint_fixed_load(pm::GenericPowerModel, i::Int) = constraint_fixed_load(pm::GenericPowerModel, pm.cnw, i::Int)

# function constraint_fixed_active_load(pm, n::Int, i::Int)
#     load = PowerModels.ref(pm, n, :load, i)
#     return constraint_fixed_active_load(pm, n, load["index"], load["pref"])
# end
# constraint_fixed_active_load(pm::GenericPowerModel, i::Int) = constraint_fixed_active_load(pm::GenericPowerModel, pm.cnw, i::Int)
#
# function constraint_fixed_reactive_load(pm, n::Int, i::Int)
#     load = PowerModels.ref(pm, n, :load, i)
#     return constraint_fixed_reactive_load(pm, n, load["index"], load["qref"])
# end
# constraint_fixed_reactive_load(pm::GenericPowerModel, i::Int) = constraint_fixed_reactive_load(pm::GenericPowerModel, pm.cnw, i::Int)

""
function constraint_gen_contingency(pm::GenericPowerModel, nw::Int, i::Int; cnd::Int = pm.ccnd)
    constraint_active_power_gen_contingency(pm::GenericPowerModel, nw::Int, cnd::Int, i::Int)
    constraint_reactive_power_gen_contingency(pm::GenericPowerModel, nw::Int, cnd::Int, i::Int)
end

# function constraint_gen_contingency(pm::GenericPowerModel, n::Int, i::Int)
#     constraint_active_power_gen_contingency(pm::GenericPowerModel, n::Int, i::Int)
#     constraint_reactive_power_gen_contingency(pm::GenericPowerModel, n::Int, i::Int)
# end
# constraint_gen_contingency(pm::GenericPowerModel, i::Int) = constraint_gen_contingency(pm::GenericPowerModel, pm.cnw, i::Int)

""
function constraint_branch_contingency(pm::GenericPowerModel, nw::Int, i::Int; cnd::Int = pm.ccnd)
    constraint_active_power_branch_contingency(pm::GenericPowerModel, nw::Int, cnd::Int, i::Int)
    constraint_reactive_power_branch_contingency(pm::GenericPowerModel, nw::Int, cnd::Int, i::Int)
end

function constraint_active_power_branch_contingency(pm::GenericPowerModel, nw::Int, cnd::Int, i::Int)
    branch = PowerModels.ref(pm, nw, :branch, i)
    f_bus = branch["f_bus"]
    t_bus = branch["t_bus"]
    f_idx = (i, f_bus, t_bus)
    t_idx = (i, t_bus, f_bus)

    return constraint_active_power_branch_contingency(pm, nw, cnd, branch["index"], f_idx, t_idx)
end

function constraint_reactive_power_branch_contingency(pm::GenericPowerModel, nw::Int, cnd::Int, i::Int)
    branch = PowerModels.ref(pm, nw, :branch, i)
    f_bus = branch["f_bus"]
    t_bus = branch["t_bus"]
    f_idx = (i, f_bus, t_bus)
    t_idx = (i, t_bus, f_bus)

    return constraint_reactive_power_branch_contingency(pm, nw, cnd,  branch["index"], f_idx, t_idx)
end

# function constraint_branch_contingency(pm::GenericPowerModel, n::Int, i::Int)
#     constraint_active_power_branch_contingency(pm::GenericPowerModel, n::Int, i::Int)
#     constraint_reactive_power_branch_contingency(pm::GenericPowerModel, n::Int, i::Int)
# end
# constraint_branch_contingency(pm::GenericPowerModel, i::Int) = constraint_branch_contingency(pm::GenericPowerModel, pm.cnw, i::Int)
#
# function constraint_active_power_branch_contingency(pm::GenericPowerModel, n::Int, i::Int)
#     branch = PowerModels.ref(pm, n, :branch, i)
#     f_bus = branch["f_bus"]
#     t_bus = branch["t_bus"]
#     f_idx = (i, f_bus, t_bus)
#     t_idx = (i, t_bus, f_bus)
#
#     return constraint_active_power_branch_contingency(pm, n, branch["index"], f_idx, t_idx)
# end
# constraint_active_power_branch_contingency(pm::GenericPowerModel, i::Int) = constraint_active_power_branch_contingency(pm::GenericPowerModel, pm.cnw, i::Int)
#
# function constraint_reactive_power_branch_contingency(pm::GenericPowerModel, n::Int, i::Int)
#     branch = PowerModels.ref(pm, n, :branch, i)
#     f_bus = branch["f_bus"]
#     t_bus = branch["t_bus"]
#     f_idx = (i, f_bus, t_bus)
#     t_idx = (i, t_bus, f_bus)
#
#     return constraint_reactive_power_branch_contingency(pm, n, branch["index"], f_idx, t_idx)
# end
# constraint_reactive_power_branch_contingency(pm::GenericPowerModel, i::Int) = constraint_reactive_power_branch_contingency(pm::GenericPowerModel, pm.cnw, i::Int)

max_issues_repo_name: frederikgeth/PowerModelsReliability

max_forks_repo_name: frederikgeth/PowerModelsReliability


text:
#################################### Branch Variables ##################################################
get_variable_binary(_, ::Type{<:PSY.DCBranch}, ::AbstractDCLineFormulation) = false

get_variable_multiplier(::FlowActivePowerVariable, ::Type{<:PSY.DCBranch}, _) = NaN

get_variable_multiplier(
    ::FlowActivePowerFromToVariable,
    ::Type{<:PSY.DCBranch},
    ::AbstractDCLineFormulation,
) = -1.0
get_variable_multiplier(
    ::FlowActivePowerToFromVariable,
    ::Type{<:PSY.DCBranch},
    ::AbstractDCLineFormulation,
) = 1.0

get_variable_lower_bound(::FlowActivePowerVariable, d::PSY.DCBranch, ::HVDCUnbounded) =
    nothing

get_variable_upper_bound(::FlowActivePowerVariable, d::PSY.DCBranch, ::HVDCUnbounded) =
    nothing

get_variable_lower_bound(
    ::FlowActivePowerVariable,
    d::PSY.DCBranch,
    ::AbstractDCLineFormulation,
) = max(PSY.get_active_power_limits_from(d).min, PSY.get_active_power_limits_to(d).min)

get_variable_upper_bound(
    ::FlowActivePowerVariable,
    d::PSY.DCBranch,
    ::AbstractDCLineFormulation,
) = min(PSY.get_active_power_limits_from(d).max, PSY.get_active_power_limits_to(d).max)

#! format: on

function get_default_time_series_names(
    ::Type{U},
    ::Type{V},
) where {U <: PSY.DCBranch, V <: AbstractDCLineFormulation}
    return Dict{Type{<:TimeSeriesParameter}, String}()
end

function get_default_attributes(
    ::Type{U},
    ::Type{V},
) where {U <: PSY.DCBranch, V <: AbstractDCLineFormulation}
    return Dict{String, Any}()
end

get_initial_conditions_device_model(
    ::OperationModel,
    ::DeviceModel{T, <:AbstractDCLineFormulation},
) where {T <: PSY.HVDCLine} = DeviceModel(T, HVDCDispatch)

#################################### Rate Limits Constraints ##################################################
function branch_rate_bounds!(
    container::OptimizationContainer,
    devices::IS.FlattenIteratorWrapper{B},
    ::DeviceModel{B, HVDCLossless},
    ::Type{<:PM.AbstractPowerModel},
) where {B <: PSY.HVDCLine}
    var = get_variable(container, FlowActivePowerVariable(), B)
    for d in devices
        name = PSY.get_name(d)
        for t in get_time_steps(container)
            _var = var[name, t]
            max_val = max(
                PSY.get_active_power_limits_to(d).max,
                PSY.get_active_power_limits_from(d).max,
            )
            min_val = min(
                PSY.get_active_power_limits_to(d).min,
                PSY.get_active_power_limits_from(d).min,
            )
            JuMP.set_upper_bound(_var, max_val)
            JuMP.set_lower_bound(_var, min_val)
        end
    end
    return
end

function branch_rate_bounds!(
    container::OptimizationContainer,
    devices::IS.FlattenIteratorWrapper{B},
    ::DeviceModel{B, <:AbstractDCLineFormulation},
    ::Type{<:PM.AbstractPowerModel},
) where {B <: PSY.HVDCLine}
    vars = [
        get_variable(container, FlowActivePowerVariable(), B),
        get_variable(container, HVDCTotalPowerDeliveredVariable(), B),
    ]
    for d in devices
        name = PSY.get_name(d)
        for t in get_time_steps(container)
            JuMP.set_upper_bound(vars[1][name, t], PSY.get_active_power_limits_from(d).max)
            JuMP.set_lower_bound(vars[1][name, t], PSY.get_active_power_limits_from(d).min)
            JuMP.set_upper_bound(vars[2][name, t], PSY.get_active_power_limits_to(d).max)
            JuMP.set_lower_bound(vars[2][name, t], PSY.get_reactive_power_limits_to(d).min)
        end
    end
    return
end

function add_constraints!(
    container::OptimizationContainer,
    cons_type::Type{FlowRateConstraint},
    devices::IS.FlattenIteratorWrapper{B},
    ::DeviceModel{B, HVDCLossless},
    ::Type{<:PM.AbstractDCPModel},
) where {B <: PSY.DCBranch}
    var = get_variable(container, FlowActivePowerVariable(), B)
    time_steps = get_time_steps(container)
    names = [PSY.get_name(d) for d in devices]
    constraint = add_constraints_container!(container, cons_type(), B, names, time_steps)
    for t in time_steps, d in devices
        min_rate = max(
            PSY.get_active_power_limits_from(d).min,
            PSY.get_active_power_limits_to(d).min,
        )
        max_rate = min(
            PSY.get_active_power_limits_from(d).max,
            PSY.get_active_power_limits_to(d).max,
        )
        constraint[PSY.get_name(d), t] = JuMP.@constraint(
            container.JuMPmodel,
            min_rate <= var[PSY.get_name(d), t] <= max_rate
        )
    end
    return
end

add_constraints!(
    ::OptimizationContainer,
    ::Type{<:Union{FlowRateConstraintFromTo, FlowRateConstraintToFrom, FlowRateConstraint}},
    ::IS.FlattenIteratorWrapper{<:PSY.DCBranch},
    ::DeviceModel{<:PSY.DCBranch, HVDCUnbounded},
    ::Type{<:PM.AbstractPowerModel},
) = nothing

function add_constraints!(
    container::OptimizationContainer,
    cons_type::Type{
        <:Union{FlowRateConstraintFromTo, FlowRateConstraintToFrom, FlowRateConstraint},
    },
    devices::IS.FlattenIteratorWrapper{B},
    ::DeviceModel{B, <:AbstractDCLineFormulation},
    ::Type{<:PM.AbstractPowerModel},
) where {B <: PSY.DCBranch}
    time_steps = get_time_steps(container)
    names = [PSY.get_name(d) for d in devices]

    var = get_variable(container, FlowActivePowerVariable(), B)
    constraint = add_constraints_container!(container, cons_type(), B, names, time_steps)
    for t in time_steps, d in devices
        min_rate = max(
            PSY.get_active_power_limits_from(d).min,
            PSY.get_active_power_limits_to(d).min,
        )
        max_rate = min(
            PSY.get_active_power_limits_from(d).max,
            PSY.get_active_power_limits_to(d).max,
        )
        constraint[PSY.get_name(d), t] = JuMP.@constraint(
            container.JuMPmodel,
            min_rate <= var[PSY.get_name(d), t] <= max_rate
        )
    end
    return
end

function add_constraints!(
    container::OptimizationContainer,
    cons_type::Type{HVDCPowerBalance},
    devices::IS.FlattenIteratorWrapper{B},
    ::DeviceModel{B, <:AbstractDCLineFormulation},
    ::Type{<:PM.AbstractPowerModel},
) where {B <: PSY.DCBranch}
    time_steps = get_time_steps(container)
    names = [PSY.get_name(d) for d in devices]

    delivered_power_var = get_variable(container, HVDCTotalPowerDeliveredVariable(), B)
    flow_var = get_variable(container, FlowActivePowerVariable(), B)
    constraint = add_constraints_container!(container, cons_type(), B, names, time_steps)
    for t in get_time_steps(container), d in devices
        constraint[PSY.get_name(d), t] = JuMP.@constraint(
            container.JuMPmodel,
            delivered_power_var[PSY.get_name(d), t] ==
            -PSY.get_loss(d).l1 * flow_var[PSY.get_name(d), t] - PSY.get_loss(d).l0,
        )
    end
    return
end


text:
function obv{T,N}(ohlcv::TimeArray{T,N}; price="Close", v="Volume")

    ret    = percentchange(ohlcv[price])
    vol    = zeros(length(ohlcv))
    vol[1] = ohlcv[v].values[1]

    for i=2:length(ohlcv)
      if ret.values[i-1] >= 0
        vol[i] += ohlcv[v].values[i]
      else
        vol[i] -= ohlcv[v].values[i]
      end
    end

    TimeArray(ohlcv.timestamp, cumsum(vol), ["obv"], ohlcv.meta)
end

function vwap{T,N}(ohlcv::TimeArray{T,N}, n::Int; price="Close", v="Volume")

    p   = ohlcv[price]
    q   = ohlcv[v]
    ∑PQ = moving(p.*q, sum, n)
    ∑Q  = moving(q, sum, n)
    val = ∑PQ ./ ∑Q

    TimeArray(val.timestamp, val.values, ["vwap"], ohlcv.meta)
end

vwap{T,N}(ohlcv::TimeArray{T,N}) = vwap(ohlcv, 10)

function advance_decline(x)
    #code here
end

function mcclellan_summation(x)
    #code here
end

function williams_ad(x)
    #code here
end


text:
using RecipesBase

function getxyz(pts)
    xs = get.(pts, 1, 0.0)
    ys = get.(pts, 2, 0.0)
    zs = get.(pts, 3, 0.0)
    if !isempty(pts) && length(pts[1]) == 3
        xs, ys, zs
    else
        xs, ys
    end
end

@recipe function plot(gc::GeodesicComplex,
                      res = nothing; only_landmarks = true, graph = true)
    # edges
    if graph
        @series begin
            label := "edges"
            edgepoints = Vector{Float64}[]
            for e in edges(landmark_graph(gc))
                s = points(gc, landmarks(gc, src(e)))
                d = points(gc, landmarks(gc, dst(e)))
                append!(edgepoints, (s, d, fill(NaN, length(s))))
            end
            getxyz(edgepoints)
        end
    end
    # landmarks
    @series begin
        markersize --> 1.0
        seriestype --> :scatter
        label := "landmarks"
        getxyz(points(gc, landmarks(gc)))
    end
    # others
    if !only_landmarks
        @series begin
            markersize --> 0.5
            seriestype --> :scatter
            label := "others"
            getxyz(points(gc, setdiff(1:n_points(gc), landmarks(gc))))
        end
    end

    if res ≢ nothing
        for (i, c) in enumerate(reverse(res))
            @series begin
                label := "$i, d=$(round(c.diameter, sigdigits=5)), p=$(round(c.perimeter, sigdigits=5))"
                linewidth := 5
                edgepoints = vcat(points(c), [first(points(c))])
                getxyz(edgepoints)
            end
        end
    end
end

max_stars_repo_name: mtsch/IntrinsicPersistence

max_issues_repo_name: mtsch/IntrinsicPersistence

max_forks_repo_name: mtsch/IntrinsicPersistence


text:
# set_param!(mt, :max_depth, 1)
# generate_MIO_model(mt, X, Y)
# set_optimizer(mt, SOLVER_SILENT)
# optimize!(mt)
# for i = 2:get_param(mt, :max_depth)
#     set_param!(mt, :max_depth, i)
#     generate_MIO_model(mt, X, Y)
#     set_optimizer(mt, SOLVER_SILENT)
#     optimize!(mt)
# end


text:
module AnalyzeKnownSLList

include("../src/pi.jl")
include("../src/evidence.jl")
include("../src/nlmodel.jl")
include("../src/keyoutputs.jl")
include("../src/essential.jl")
include("../src/results.jl")
include("../src/sl.jl")
include("../src/idMap.jl")
#include("../src/coexpress.jl")

function run(pifile, slfilename, lowerbound, upperbound, dbidfile, verbose)
    pinodes = Pi.readFile(pifile)
    slnodes = SL.getNodes(dbidfile)
    pinodesSet = Set(keys(pinodes))

#    coexpress = CoExpress.getForPiNodes(pinodesSet, dbidfile)
#    println(coexpress)
#    exit()

    essentialgenes = Essential.getGenes(collect(keys(pinodes)), dbidfile)
    nodetogene     = DbIdNameMapping.nodeToGene(dbidfile)

    slessential = Dict{String,Any}[]
    slpinodes = String[]
    slpinodesPairs = []
    for sl in slnodes
        for nodea in sl["GeneANodes"]
            for nodeb in sl["GeneBNodes"]
                if in(nodea, pinodesSet) && in(nodeb, pinodesSet) && pinodes[nodea].relation == "ROOT" && pinodes[nodeb].relation == "ROOT"
                    if in(nodeb, slpinodes) == false
                        push!(slpinodes, nodeb)
                    end
                    if in(nodea, slpinodes) == false
                        push!(slpinodes, nodea)
                    end
                    push!(slpinodesPairs, [nodea, nodeb])
                    for essentialgene in essentialgenes
                        if nodetogene[essentialgene] == nodetogene[nodea] || nodetogene[essentialgene] == nodetogene[nodeb]
                            continue
                        end

                        slcopy = copy(sl)
                        delete!(slcopy, "GeneANodes")
                        delete!(slcopy, "GeneBNodes")

                        slcopy["GeneANode"] = nodea
                        slcopy["GeneBNode"] = nodeb
                        slcopy["EssentialGene"] = essentialgene
                        push!(slessential, slcopy)
                    end
                end
            end
        end
    end
    allGenes = DbIdNameMapping.allGeneReferenceProduct(dbidfile)
    allGenesSet = Set(allGenes)
    for node in slpinodes
        (sampleresults, x, x_bar) = NLmodel.run(pinodes,
                                                Dict(node => 0),
                                                essentialgenes,
                                                lowerbound,
                                                upperbound,
                                                verbose)

        for (essentialnode, essentialvalue) in sampleresults
            for sl in slessential
                if sl["EssentialGene"] == essentialnode
                    if sl["GeneANode"] == node
                        sl["GeneANodeValue"] = essentialvalue
                    elseif sl["GeneBNode"] == node
                        sl["GeneBNodeValue"] = essentialvalue
                    end
                end
            end
        end
    end

    sloutfile = open(slfilename, "w")
    headercolumns = ["Count"]
    for column in keys(slessential[1])
        push!(headercolumns, column)
    end
    header = join(headercolumns, "\t")
    write(sloutfile, string(header, "\n"))
    flush(sloutfile)

    for slnodespair in slpinodesPairs
        (sampleresults, x, x_bar) = NLmodel.run(pinodes,
                                                Dict(slnodespair[1] => 0,
                                                     slnodespair[2] => 0),
                                                     essentialgenes,
                                                     lowerbound,
                                                     upperbound,
                                                     verbose)

         for (essentialnode, essentialvalue) in sampleresults
             for sl in slessential
                 if sl["EssentialGene"] == essentialnode && sl["GeneANode"] == slnodespair[1] && sl["GeneBNode"] == slnodespair[2]
                     sl["EssentialGeneValue"] = essentialvalue
                 end
             end
         end
    end

    sloutfile = open(slfilename, "w")
    headercolumns = ["Count"]
    for column in keys(slessential[1])
        push!(headercolumns, column)
    end
    header = join(headercolumns, "\t")
    write(sloutfile, string(header, "\n"))

    count = 0
    for sl in slessential
        count = count + 1
        columnvalues = String[]
        for column in headercolumns
            if column == "Count"
                push!(columnvalues, string(count))
            else
                push!(columnvalues, string(sl[column]))
            end
        end
        write(sloutfile, join(columnvalues, "\t"), "\n")
    end

    close(sloutfile)
end

end

max_stars_repo_name: OICR/mp-biopath

max_issues_repo_name: OICR/mp-biopath

max_forks_repo_name: OICR/mp-biopath


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder

name = "GEOS"
version = v"3.10.2"

# Collection of sources required to build GEOS
sources = [
    ArchiveSource("http://download.osgeo.org/geos/geos-$version.tar.bz2",
                  "50bbc599ac386b4c2b3962dcc411f0040a61f204aaef4eba7225ecdd0cf45715")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/geos-*/

CMAKE_FLAGS=()
CMAKE_FLAGS+=(-DCMAKE_INSTALL_PREFIX=${prefix})
CMAKE_FLAGS+=(-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN})
CMAKE_FLAGS+=(-DLLVM_HOST_TRIPLE=${MACHTYPE})
CMAKE_FLAGS+=(-DCMAKE_BUILD_TYPE=Release)
CMAKE_FLAGS+=(-S.) # source

# arm complains about duplicate symbols unless we disable inlining
if [[ ${target} == arm* ]]; then
    CMAKE_FLAGS+=(-DDISABLE_GEOS_INLINE=true)
fi

cmake ${CMAKE_FLAGS[@]}
make -j${nproc}
make install
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = expand_cxxstring_abis(supported_platforms(; experimental=true))

# The products that we will ensure are always built
products = [
    LibraryProduct("libgeos_c", :libgeos),
    LibraryProduct(["libgeos", "libgeos-$(version.major)-$(version.minor)"], :libgeos_cpp),
    ExecutableProduct("geosop", :geosop),
]

# Dependencies that must be installed before this package can be built
dependencies = []

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat="1.6", preferred_gcc_version=v"6")


text:
#################################################################
# This file defines an abstract type to represent spaces and abstract functions to specify the spaces
# AbstractSpace: the abstract super type for the state, action and observation spaces
#################################################################

abstract AbstractSpace

# returns an integer
@pomdp_func dimensions(s::AbstractSpace)
# returns bound of dim i
@pomdp_func lowerbound(s::AbstractSpace, i::Int)
# returns bound of dim i
@pomdp_func upperbound(s::AbstractSpace, i::Int)
# sample a space and return the sample
@pomdp_func rand(rng::AbstractRNG, d::AbstractSpace, state::Any)
# return an iterable object corresponding to the space
@pomdp_func iterator(s::AbstractSpace)

# return a space type
@pomdp_func states(pomdp::POMDP)
@pomdp_func states(pomdp::POMDP, state::State, sts::AbstractSpace=states(pomdp))
@pomdp_func actions(pomdp::POMDP)
@pomdp_func actions(pomdp::POMDP, state::State, acts::AbstractSpace=actions(pomdp))
@pomdp_func actions(pomdp::POMDP, belief::Belief, acts::AbstractSpace=actions(pomdp))
@pomdp_func observations(pomdp::POMDP)
@pomdp_func observations(pomdp::POMDP, state::State, obs::AbstractSpace=observations(pomdp))

max_stars_repo_name: sisl/ExprSearch

max_issues_repo_name: sisl/ExprSearch


text:
const CODEBLOCK_FOREGROUND = get(ENV, "PRESENTATION_JL_CODEBLOCK_FOREGROUND", 0x909090) |> UInt32
const CODEBLOCK_BACKGROUND = get(ENV, "PRESENTATION_JL_CODEBLOCK_BACKGROUND", 0xf0f0f0) |> UInt32
const PRESENTATION_JL_LEXERS = Dict(
                                    "julia" => JuliaLexer,
                                    # "python" => PythonLexer,
                                   )

draw_border(io, x, y, w, h) = draw_border(io, x, y, w, h, Crayon())

function draw_border(io, x, y, w, h, c)

    cmove(x, y)             ; print(io, c(repeat("━", w)))
    cmove(x, y + h)         ; print(io, c(repeat("━", w)))
    for i in 1:h
        cmove(x, y + i)     ; print(io, c("┃"))
        cmove(x + w, y + i) ; print(io, c("┃"))
    end
    cmove(x, y)             ; print(io, c("┏"))
    cmove(x + w, y)         ; print(io, c("┓"))
    cmove(x, y + h)         ; print(io, c("┗"))
    cmove(x + w, y + h)     ; print(io, c("┛"))

end

"""
Syntax Highlighter
"""
function Highlights.Format.render(io::IO, ::MIME"text/ansi", tokens::Highlights.Format.TokenIterator)
    for (str, id, style) in tokens
        fg = style.fg.active ? map(Int, (style.fg.r, style.fg.g, style.fg.b)) : :nothing
        bg = style.bg.active ? map(Int, (style.bg.r, style.bg.g, style.bg.b)) : :nothing
        crayon = Crayon(
            foreground = fg,
            background = bg,
            bold       = style.bold,
            italics    = style.italic,
            underline  = style.underline,
        )
        print(io, crayon, str, inv(crayon))
    end
end

## Render functions

render(e) = render(stdout, e)

render(io, e::Pandoc.RawBlock) = nothing

function render(io, e::Pandoc.Link)
    iob = IOBuffer()
    for se in e.content
        render(iob, se)
    end
    title = String(take!(iob))
    url = e.target.url
    # This seems to be an iTerm2 only feature
    print(io, "$ESC]8;;$url$ESC\\$title$ESC]8;;$ESC\\")
end

function render(io, e::Pandoc.Strikeout)
    c = Crayon(strikethrough = true)
    print(io, c)
    for ec in e.content
        render(io, ec)
    end
    print(io, inv(c))
end

function render(io, e::Pandoc.Emph)
    c = Crayon(italics = true)
    print(io, c)
    for ec in e.content
        render(io, ec)
    end
    print(io, inv(c))
end

function render(io, e::Pandoc.Strong)
    c = Crayon(bold = true)
    print(io, c)
    for ec in e.content
        render(io, ec)
    end
    print(io, inv(c))
end

function render(io, es::Vector{Pandoc.Block})
    x, y = getXY()
    cmove(x + 4, y)
    for e in es
        render(io, e)
    end
    cmove(x, getY())
end

function render(io, e::Pandoc.SoftBreak)
end

function render(io, e::Pandoc.Plain)
    x, y = getXY()
    w, h = canvassize()

    oldX, oldY = getXY()
    print(io, "▶ ")

    for se in e.content
        render(io, se)
        newX, newY = getXY()
        if newX > w * 7/8
            cmove(x, newY + 1)
            oldX, oldY = newX, newY
        elseif newY > oldY
            cmove(x, newY)
            oldX, oldY = newX, newY
        end
    end

    cmove(x, getY() + 2)
end

function render(io, e::Pandoc.OrderedList)
    x, y = getXY()
    for items in e.content
        render(io, items)
    end
end

function render(io, e::Pandoc.BulletList)
    x, y = getXY()
    cmove(x, getY() + 1)
    for items in e.content
        render(io, items)
    end
    cmove(x, getY() + 1)
end

function render(io, e::Pandoc.Image)
    w, h = canvassize()
    x, y = getXY()
    cmove(round(Int, w / 3), y + 2)
    data = read(abspath(joinpath(dirname(filename()), e.target.url)))
    TerminalExtensions.iTerm2.display_file(
                                           data;
                                           io=io,
                                           width="$(round(Int, w/3))",
                                           filename="image",
                                           inline=true,
                                           preserveAspectRatio=true
                                          )
    title = e.target.title
    cmove(round(Int, w / 2) - round(Int, length(title) / 2), getY() + 2)
    print(io, "$title")
end

render(io, e::Pandoc.Element) = error("Not implemented renderer for $e")

hex2rgb(c) = convert.(Int, ((c >> 16) % 0x100, (c >> 8) % 0x100, c % 0x100))

function render(io, e::Pandoc.CodeBlock)
    w = round(Int, getW() * 6 / 8)
    x, y = getXY()
    if length(e.attr.classes) > 0
        lexer = get(PRESENTATION_JL_LEXERS, e.attr.classes[1], AbstractLexer)
        if lexer == AbstractLexer
            content = e.content
        else
            iob = IOBuffer()
            highlight(iob, MIME("text/ansi"), e.content, lexer)
            content = String(take!(iob))
        end
    else
        content = e.content
    end
    c = Crayon(background = hex2rgb(CODEBLOCK_BACKGROUND))
    cmove(x, y)
    print(io, c(repeat(" ", w)))
    y += 1
    # draw background
    save_y = y
    split_content = split(content, '\n')
    for (i, code_line) in enumerate(split_content)
        cmove(x, y)
        print(io, c(repeat(" ", w)))
        print(io, Crayon(background = hex2rgb(CODEBLOCK_FOREGROUND))(" "))
        y += 1
    end
    cmove(x, y)
    print(io, c(repeat(" ", w)))
    print(io, Crayon(background = hex2rgb(CODEBLOCK_FOREGROUND))(" "))
    y += 1
    cmove(x+1, y)
    println(io, Crayon(foreground = hex2rgb(CODEBLOCK_FOREGROUND))(repeat("▀", w)))
    # write code blocks
    y = save_y
    for code_line in split_content
        cmove(x+2, y)
        println(io, c(code_line))
        y += 1
    end
end

render(io, e::Pandoc.Str) = print(io, e.content)
render(io, e::Pandoc.Space) = print(io, " ")
render(io, e::Pandoc.Code) = print(io, "`", Crayon(foreground=:red)("$(e.content)"), "`")

render(io, h::Pandoc.Header) = render(io, h, Val{h.level}())

function render(io, e::Pandoc.Header, level::Val{1})
    c = Crayon(bold = true)
    w, h = canvassize()
    x, y = round(Int, w / 2), round(Int, h / 2)
    iob = IOBuffer()
    for se in e.content
        render(iob, se)
    end
    t = String(take!(iob))
    lines = wrap(t)
    for line in lines
        cmove(x - round(Int, length(line) / 2), y)
        print(io, c(line))
        y += 1
    end
    m = maximum(length.(lines))
    draw_border(io, x - round(Int, m / 2) - 2, y - length(lines) - 1, m + 3, length(lines) + 1)
    cmove(round(Int, w / 8), getY() + 4)
end

function render(io, e::Pandoc.Header, level::Val{2})
    c = Crayon(bold = true)
    w, h = canvassize()
    x, y = round(Int, w / 2), round(Int, h / 8)
    iob = IOBuffer()
    for se in e.content
        render(iob, se)
    end
    t = String(take!(iob))
    lines = wrap(t)
    for line in lines
        cmove(x - round(Int, length(line) / 2), y)
        print(io, c(line))
        y += 1
    end
    m = maximum(length.(lines))
    draw_border(io, x - round(Int, m / 2) - 2, y - length(lines) - 1, m + 3, length(lines) + 1)
    cmove(round(Int, w / 8), getY() + 4)
end

function render(io, e::Pandoc.Para)
    w, h = canvassize()
    cmove(round(Int, w / 8), getY() + 2)
    oldX, oldY = getXY()
    for se in e.content
        render(io, se)
        newX, newY = getXY()
        if newX > w * 7/8
            cmove(round(Int, w / 8), newY + 1)
            oldX, oldY = newX, newY
        elseif newY > oldY
            cmove(round(Int, w / 8), newY)
            oldX, oldY = newX, newY
        end
    end
    cmove(round(Int, w / 8), getY() + 2)
end

function render(io, s::Slides)
    clear()
    width, height = canvassize()
    x, y = round(Int, width / 2), round(Int, height / 4)
    cmove(x, y)
    for e in current_slide(s)
        render(io, e)
    end
    cmove_bottom()
end

function render(io, md::Markdown.MD, filename)
    d = convert(Pandoc.Document, md)
    render(io, d, filename)
end

function render(io, d::Pandoc.Document, filename::AbstractString="")
    global SLIDES
    s = Slides(d, filename)
    SLIDES = s
    return render(io, s)
end

render(io, filename::AbstractString) = Pandoc.exists() ? render(io, PandocMarkdown, filename) : render(io, JuliaMarkdown, filename)

render(io, ::Type{T}, filename::AbstractString) where T = render(io, read(T, filename), filename)

Base.read(::Type{PandocMarkdown}, filename::AbstractString) = Pandoc.parse_file(filename)

Base.read(::Type{JuliaMarkdown}, filename::AbstractString) = Markdown.parse_file(filename)


text:
# plot a real-time spectrogram. This example is adapted from the GR example
# at http://gr-framework.org/examples/audio_ex.html

module SpectrumExample

using GR, PortAudio, SampledSignals

const N = 1024
const stream = PortAudioStream(1, 0, blocksize=N)
const buf = read(stream, N)
const fmin = 0Hz
const fmax = 10000Hz
const fs = Float32[float(f) for f in domain(fft(buf)[fmin..fmax])]

while true
    read!(stream, buf)
    plot(fs, abs(fft(buf)[fmin..fmax]), xlim=(fs[1],fs[end]), ylim=(0,100))
end

end


text:
#! What is the convention and or the most efficient way to store these multidim arrays: samples from column/row correspond to one distributions?
#! Here we choose row correspond to one distributions and number of row is the number of realization
#! It seems to be the convention
#TODO Only work for distributions with known fit_mle (cannot be product_distribution of mixture because of the typeof)
"""
Simply extend the `fit_mle` function to multivariate Product distributions.
"""
function fit_mle(g::Product, x::AbstractMatrix)
    S = size(x, 1) # row convention
    vec_g = g.v
    @argcheck S == length(vec_g)
    return product_distribution([fit_mle(typeof(vec_g[s]), y) for (s, y) in enumerate(eachrow(x))])
end

function fit_mle(g::Product, x::AbstractMatrix, γ::AbstractVector)
    S = size(x, 1) # row convention
    vec_g = g.v
    @argcheck S == length(vec_g)
    return product_distribution([fit_mle(typeof(vec_g[s]), y, γ) for (s, y) in enumerate(eachrow(x))])
end

"""
Now `fit_mle(Bernoulli(0.2), x)` is accepted in addition of `fit_mle(Bernoulli, x)` this allows compatibility with how `fit_mle(g::Product)` and `fit_mle(g::MixtureModel)` are written.
"""
function fit_mle(g::Distribution{Univariate,Discrete}, args...)
    fit_mle(typeof(g), args...)
end

function fit_mle(g::Distribution{Univariate,Continuous}, args...)
    fit_mle(typeof(g), args...)
end


text:
#' ---
#' title: Experiment Design
#' ---

#' **Originally Contributed by**: Arpit Bhatia, Chris Coey

#' This tutorial covers experiment design examples (D-optimal, A-optimal, and E-optimal)
#' from section 7.5 of the book Convex Optimization by Boyd and Vandenberghe[[1]](#c1)

#' ## Relaxed Experiment Design Problem

#' The basic experiment design problem is as follows.
#' Given the menu of possible choices for experiments, $v_{1}, \ldots, v_{p}$,
#' and the total number $m$ of experiments to be carried out, choose the numbers of each type of experiment,
#' $i . e ., m_{1}, \ldots, m_{p}$ to make the error covariance $E$ small (in some sense).
#' The variables $m_{1}, \ldots, m_{p}$ must, of course, be integers and sum to $m,$ the given total number of experiments.
#' This leads to the optimization problem

#' $$
#' \begin{array}{cl}{\operatorname{minimize}\left(\mathrm{w.r.t.} \mathbf{S}_{+}^{n}\right)} & {E=\left(\sum_{j=1}^{p} m_{j} v_{j} v_{j}^{T}\right)^{-1}} \\ {\text { subject to }} & {m_{i} \geq 0, \quad m_{1}+\cdots+m_{p}=m} \\ {} & {m_{i} \in \mathbf{Z}}\end{array}
#' $$

#' The basic experiment design problem can be a hard combinatorial problem when $m,$ the total number of experiments,
#' is comparable to $n$ , since in this case the $m_{i}$ are all small integers.
#' In the case when $m$ is large compared to $n$ , however, a good approximate solution can be found by ignoring,
#' or relaxing, the constraint that the $m_{i}$ are integers.
#' Let $\lambda_{i}=m_{i} / m,$ which is the fraction of the total number of experiments for which
#' $a_{j}=v_{i},$ or the relative frequency of experiment $i$.
#' We can express the error covariance in terms of $\lambda_{i}$ as

#' $$
#' E=\frac{1}{m}\left(\sum_{i=1}^{p} \lambda_{i} v_{i} v_{i}^{T}\right)^{-1}
#' $$

#' The vector $\lambda \in \mathbf{R}^{p}$ satisfies $\lambda \succeq 0,
#' \mathbf{1}^{T} \lambda=1,$ and also, each $\lambda_{i}$ is an integer multiple of $1 / m$.
#' By ignoring this last constraint, we arrive at the problem

#' $$
#' \begin{array}{ll}{\operatorname{minimize}\left(\mathrm{w.r.t.} \mathbf{S}_{+}^{n}\right)} & {E=(1 / m)\left(\sum_{i=1}^{p} \lambda_{i} v_{i} v_{i}^{T}\right)^{-1}} \\ {\text { subject to }} & {\lambda \succeq 0, \quad \mathbf{1}^{T} \lambda=1}\end{array}
#' $$

#' ## Types of Experiment Design Problems

#' Several scalarizations have been proposed for the experiment design problem,
#' which is a vector optimization problem over the positive semidefinite cone.

using JuMP
using SCS
using LinearAlgebra

q = 4 # dimension of estimate space
p = 8 # number of experimental vectors
nmax = 3 # upper bound on lambda
n = 12

V = randn(q, p)

eye = Matrix{Float64}(I, q, q);

#' ### A-optimal design

#' In A-optimal experiment design, we minimize tr $E$, the trace of the covariance matrix.
#' This objective is simply the mean of the norm of the error squared:

#' $$
#' \mathbf{E}\|e\|_{2}^{2}=\mathbf{E} \operatorname{tr}\left(e e^{T}\right)=\operatorname{tr} E
#' $$

#' The A-optimal experiment design problem in SDP form is

#' $$
#' \begin{array}{ll}{\operatorname{minimize}} & {\mathbf{1}^{T} u} \\ {\text { subject to }} & {\left[\begin{array}{cc}{\sum_{i=1}^{p} \lambda_{i} v_{i} v_{i}^{T}} & {e_{k}} \\ {e_{k}^{T}} & {u_{k}}\end{array}\right] \succeq 0, \quad k=1, \ldots, n} \\ {} & {\lambda \succeq 0, \quad \mathbf{1}^{T} \lambda=1}\end{array}
#' $$

aOpt = Model(with_optimizer(SCS.Optimizer, verbose = 0))
@variable(aOpt, np[1:p], lower_bound = 0, upper_bound = nmax)
@variable(aOpt, u[1:q], lower_bound = 0)

@constraint(aOpt, sum(np) <= n)
for i = 1:q
    @SDconstraint(aOpt, [V * diagm(0 => np ./ n) * V' eye[:, i]; eye[i, :]' u[i]] >= 0)
end

@objective(aOpt, Min, sum(u))

optimize!(aOpt)

@show objective_value(aOpt);
@show value.(np);

#' ### E-optimal design

#' In $E$ -optimal design, we minimize the norm of the error covariance matrix, i.e. the maximum eigenvalue of $E$.
#' Since the diameter (twice the longest semi-axis) of the confidence ellipsoid $\mathcal{E}$
#' is proportional to $\|E\|_{2}^{1 / 2}$,
#' minimizing $\|E\|_{2}$ can be interpreted geometrically as minimizing the diameter of the confidence ellipsoid.
#' E-optimal design can also be interpreted as minimizing the maximum variance of $q^{T} e$,
#' over all $q$ with $\|q\|_{2}=1$.
#' The E-optimal experiment design problem in SDP form is

#' $$
#' \begin{array}{cl}{\operatorname{maximize}} & {t} \\ {\text { subject to }} & {\sum_{i=1}^{p} \lambda_{i} v_{i} v_{i}^{T} \succeq t I} \\ {} & {\lambda \succeq 0, \quad \mathbf{1}^{T} \lambda=1}\end{array}
#' $$

eOpt = Model(with_optimizer(SCS.Optimizer, verbose = 0))
@variable(eOpt, np[1:p], lower_bound = 0, upper_bound = nmax)
@variable(eOpt, t)

@SDconstraint(eOpt, V * diagm(0 => np ./ n) * V' - (t .* eye) >= 0)
@constraint(eOpt, sum(np) <= n)

@objective(eOpt, Max, t)

optimize!(eOpt)

@show objective_value(eOpt);
@show value.(np);

#' ### D-optimal design
#' The most widely used scalarization is called $D$ -optimal design,
#' in which we minimize the determinant of the error covariance matrix $E$.
#' This corresponds to designing the experiment to minimize the volume of the resulting confidence ellipsoid
#' (for a fixed confidence level).
#' Ignoring the constant factor 1$/ m$ in $E$, and taking the logarithm of the objective,
#' we can pose this problem as convex optimization problem

#' $$
#' \begin{array}{ll}{\operatorname{minimize}} & {\log \operatorname{det}\left(\sum_{i=1}^{p} \lambda_{i} v_{i} v_{i}^{T}\right)^{-1}} \\ {\text { subject to }} & {\lambda \succeq 0, \quad \mathbf{1}^{T} \lambda=1}\end{array}
#' $$

dOpt = Model(with_optimizer(SCS.Optimizer, verbose = 0))
@variable(dOpt, np[1:p], lower_bound = 0, upper_bound = nmax)
@variable(dOpt, t)
@objective(dOpt, Max, t)
@constraint(dOpt, sum(np) <= n)
E = V * diagm(0 => np ./ n) * V'
@constraint(dOpt, [t, 1, (E[i, j] for i in 1:q for j in 1:i)...] in MOI.LogDetConeTriangle(q))

optimize!(dOpt)

@show objective_value(dOpt);
@show value.(np);

#' ### References
#'
#' 1. Boyd, S., & Vandenberghe, L. (2004). Convex Optimization. Cambridge: Cambridge University Press. doi:10.1017/CBO9780511804441


text:
dname = "/usr/share/dict/american-english"
DF = open(dname, "r")
tnym = tpad(DF)
close(DF)

println("The character to digit mapping is done according to")
println("these regular expressions (following uppercase conversion):")
for k in sort(collect(keys(tcode)), by=x->tcode[x])
    println("    ", tcode[k], " -> ", k)
end
println("Unmatched non-digit characters are mapped to 1")

println()
print("There are ", sum(map(x->length(x), values(tnym))))
println(" words in ", dname)
println("  which can be represented by the digit key mapping.")
print("They require ", length(keys(tnym)))
println(" digit combinations to represent them.")
print(sum(map(x->length(x)>1, values(tnym))))
println(" digit combinations represent Textonyms.")

println()
println("The degeneracies of telephone key encodings are:")
println("  Words Encoded   Number of codes")
dgen = zeros(maximum(map(x->length(x), values(tnym))))
for v in values(tnym)
    dgen[length(v)] += 1
end
for (i, d) in enumerate(dgen)
    println(@sprintf "%10d  %15d" i d)
end

println()
dgen = length(dgen) - 2
println("Codes mapping to ", dgen, " or more words:")
for (k, v) in tnym
    dgen <= length(v) || continue
    println(@sprintf "%7s (%2d) %s" k length(v) join(v, ", "))
end

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
device(x::LavaAbstraction) = Vk.device(handle(x))
instance(x::LavaAbstraction) = Vk.instance(handle(x))

Vk.bind_buffer_memory(buffer::Buffer, memory) = Vk.bind_buffer_memory(device(buffer), buffer, memory, offset(memory))
Vk.bind_image_memory(image::Image, memory) = Vk.bind_image_memory(device(image), image, memory, offset(memory))
Vk.cmd_bind_pipeline(cbuffer::VkCommandBuffer, pipeline::VkPipeline) = Vk.cmd_bind_pipeline(cbuffer, Vk.PipelineBindPoint(typeof(pipeline)), pipeline)
Vk.cmd_bind_vertex_buffers(cbuffer::VkCommandBuffer, buffers::AbstractVector{<:Buffer}) = Vk.cmd_bind_vertex_buffers(cbuffer, buffers, offset.(buffers))
Vk.cmd_bind_index_buffer(cbuffer::VkCommandBuffer, buffers::AbstractVector{<:Buffer}, T) = Vk.cmd_bind_index_buffer(cbuffer, buffer, offset(buffer), IndexType(T))

Vk.get_image_memory_requirements(image::Image) = Vk.get_image_memory_requirements(device(image), handle(image))
Vk.get_buffer_memory_requirements(buffer::Buffer) = Vk.get_buffer_memory_requirements(device(buffer), handle(buffer))

# TODO: wrap get_image/buffer_memory_requirements_2 for supported parameters (in pNext chain of the create info structure)
get_memory_requirements(image::Image) = Vk.get_image_memory_requirements(image)
get_memory_requirements(buffer::Buffer) = Vk.get_buffer_memory_requirements(buffer)

record(cbuffer::VkCommandBuffer, ::typeof(bind), pipeline::VkPipeline) = Vk.cmd_bind_pipeline(cbuffer, pipeline)
record(cbuffer::VkCommandBuffer, ::typeof(bind), buffers::AbstractVector{<:Buffer}, ::Type{<:Vertex}) = Vk.cmd_bind_vertex_buffers(cbuffer, pipeline, buffers)
record(cbuffer::VkCommandBuffer, ::typeof(bind), buffers::Buffer, ::Type{<:Index{T}}) where {T} = Vk.cmd_bind_index_buffer(cbuffer, pipeline, buffer, T)

Vk.IndexType(::Type{UInt8}) = Vk.INDEX_TYPE_UINT8_EXT
Vk.IndexType(::Type{UInt16}) = Vk.INDEX_TYPE_UINT16
Vk.IndexType(::Type{UInt32}) = Vk.INDEX_TYPE_UINT32
Vk.IndexType(::Type{Nothing}) = Vk.INDEX_TYPE_NONE_KHR

Vk.PipelineBindPoint(::Type{<:VkPipeline{<:Graphics}}) = Vk.PIPELINE_BIND_POINT_GRAPHICS
Vk.PipelineBindPoint(::Type{<:VkPipeline{<:Compute}}) = Vk.PIPELINE_BIND_POINT_COMPUTE
Vk.PipelineBindPoint(::Type{<:VkPipeline{<:RayTracing}}) = Vk.PIPELINE_BIND_POINT_RAY_TRACING_KHR

Base.reset(cbuffer::VkCommandBuffer; flags=0) = Vk.reset_command_buffer(cbuffer; flags)
Base.reset(pool::Pool{VkCommandBuffer}; flags=0) = Vk.reset_command_pool(device(pool), pool; flags)
Base.reset(pool::Pool{VkDescriptorSet}; flags=0) = Vk.reset_descriptor_pool(device(pool), pool; flags)
Base.reset(event::SynchronizationPrimitive{Any,Any}) = Vk.reset_event(device(event), fences)
Base.reset(fences::AbstractVector{<:SynchronizationPrimitive{CPU,GPU}}) = Vk.reset_fences(device(first(fences)), fences)

# # Flags

flag(::Type{Sparse{SparseBinding,VkBuffer}}) = Vk.BUFFER_CREATE_SPARSE_BINDING_BIT
flag(::Type{Sparse{SparseBinding,VkImage}}) = Vk.IMAGE_CREATE_SPARSE_BINDING_BIT

flag(::Type{Sparse{SparseResidency,VkBuffer}}) = Vk.BUFFER_CREATE_SPARSE_RESIDENCY_BIT
flag(::Type{Sparse{SparseResidency,VkImage}}) = Vk.IMAGE_CREATE_SPARSE_RESIDENCY_BIT


text:
function OPMParser()
    return OPMParser(())
end

function OPMParser(arg0::DataContext)
    return OPMParser((DataContext,), arg0)
end

function parse(obj::OPMParser, arg0::InputStream)
    return jcall(obj, "parse", OPMFile, (InputStream,), arg0)
end

function parse(obj::OPMParser, arg0::InputStream, arg1::JString)
    return jcall(obj, "parse", OPMFile, (InputStream, JString), arg0, arg1)
end

function parse(obj::OPMParser, arg0::JString)
    return jcall(obj, "parse", OPMFile, (JString,), arg0)
end

function with_conventions(obj::OPMParser, arg0::IERSConventions)
    return jcall(obj, "withConventions", OPMParser, (IERSConventions,), arg0)
end

function with_data_context(obj::OPMParser, arg0::DataContext)
    return jcall(obj, "withDataContext", OPMParser, (DataContext,), arg0)
end

function with_international_designator(obj::OPMParser, arg0::jint, arg1::jint, arg2::JString)
    return jcall(obj, "withInternationalDesignator", OPMParser, (jint, jint, JString), arg0, arg1, arg2)
end

function with_mission_reference_date(obj::OPMParser, arg0::AbsoluteDate)
    return jcall(obj, "withMissionReferenceDate", OPMParser, (AbsoluteDate,), arg0)
end

function with_mu(obj::OPMParser, arg0::jdouble)
    return jcall(obj, "withMu", OPMParser, (jdouble,), arg0)
end

function with_simple_eop(obj::OPMParser, arg0::jboolean)
    return jcall(obj, "withSimpleEOP", OPMParser, (jboolean,), arg0)
end


text:
using Base.Test
using Calc

# Setup. From package LispREPL that in turn came from the Julia base repo.

type FakeTerminal <: Base.Terminals.UnixTerminal
    in_stream::Base.IO
    out_stream::Base.IO
    err_stream::Base.IO
    hascolor::Bool
    raw::Bool
    FakeTerminal(stdin,stdout,stderr,hascolor=true) =
        new(stdin,stdout,stderr,hascolor,false)
end

Base.Terminals.hascolor(t::FakeTerminal) = t.hascolor
Base.Terminals.raw!(t::FakeTerminal, raw::Bool) = t.raw = raw
Base.Terminals.size(t::FakeTerminal) = (24, 80)

function fake_repl()
    # Use pipes so we can easily do blocking reads
    # In the future if we want we can add a test that the right object
    # gets displayed by intercepting the display
    stdin_read,stdin_write = (Base.PipeEndpoint(), Base.PipeEndpoint())
    stdout_read,stdout_write = (Base.PipeEndpoint(), Base.PipeEndpoint())
    stderr_read,stderr_write = (Base.PipeEndpoint(), Base.PipeEndpoint())
    Base.link_pipe(stdin_read,true,stdin_write,true)
    Base.link_pipe(stdout_read,true,stdout_write,true)
    Base.link_pipe(stderr_read,true,stderr_write,true)

    repl = Base.REPL.LineEditREPL(FakeTerminal(stdin_read, stdout_write, stderr_write))
    stdin_write, stdout_read, stderr_read, repl
end

# Writing ^C to the repl will cause sigint, so let's not die on that
ccall(:jl_exit_on_sigint, Void, (Cint,), 0)
stdin_write, stdout_read, stderr_read, repl = fake_repl()

repl.specialdisplay = Base.REPL.REPLDisplay(repl)
repl.history_file = false

repltask = @async Base.REPL.run_repl(repl)

sendrepl(cmd) = write(stdin_write,"inc || wait(b); r = $cmd; notify(c); r\r")

inc = false
b = Condition()
c = Condition()
sendrepl("\"Hello REPL\"")
inc=true
begin
    notify(b)
    wait(c)
end

Calc.initiate_calc_repl(repl)

# Tests.
function testentry(input, outputs...)
    write(stdin_write, input)
    println(input)
    for o in outputs
        readuntil(stdout_read, o)
    end
end

# General
testentry("=", "calc> ")
testentry("2\n3+", "1: 5")
testentry("4\t", "2: 4", "1: 5")
testentry("\t",  "2: 5", "1: 4")
testentry("\e[3~", "1: 5")  # delete key
testentry("U", "1: 4")
testentry("D", "1: 5")
testentry("U", "1: 4")
testentry("=", "calc= ")
testentry("2+_2\n", "1: 7", "calc> ")
# Arithmetic
testentry("4 3+",  "1: 7")
testentry("4n",    "1: -4")
testentry("4 3*",  "1: 12")
testentry("4 3/",  "1: 1.33333")
testentry("4&",    "1: 0.25")
testentry("4 3%",  "1: 1")
testentry("4nA",   "1: 4")
testentry("4fs",   "1: 1")
testentry("4nfs",  "1: -1")
testentry("4 3fn", "1: 3")
testentry("4 3fx", "1: 4")
testentry("4f[",   "1: 3")
testentry("4f]",   "1: 5")
# Algebraic
testentry("4Q",    "1: 2.0")
testentry("4IQ",   "1: 16")
testentry("2LIL",  "1: 2.0")
testentry("2LE",   "1: 2.0")
testentry("2HLIHL","1: 2.0")
testentry("8 2B",  "1: 3.0")
testentry("2 3^",  "1: 8")
testentry("8 3I^", "1: 2.0")
testentry("4 3fh", "1: 5.0")
# Trig
testentry("P",     "1: π = ")
testentry("mr",    "Using radians...")
testentry("PC",    "[rad|", "1: -1.0")
testentry("P2/S",  "1: 1.0")
testentry("P4/T",  "1: 1.0")
testentry("1ICC",  "1: 1.0")
testentry("1ISS",  "1: 1.0")
testentry("1ITT",  "1: 1.0")
testentry("md",    "Using degrees...")
testentry("180C",  "[deg|", "1: -1.0")
testentry("90S",   "1: 1.0")
testentry("45T",   "1: 1.0")
testentry("1IC",   "1: 0.0")
testentry("1IS",   "1: 90.0")
testentry("1IT",   "1: 45.0")
# Complex numbers
testentry("1 2X",    "1: 1+2im")
testentry("1 45Z",   "1: 0.707107+0.707107im")
testentry("1 2XIX",  "2: 1", "1: 2")
testentry("1 45ZIZ", "2: 1", "1: 45")
testentry("1 2XJ",   "1: 1-2im")
testentry("1 1XG",   "1: 45.0")
testentry("1 2Xfr",  "1: 1")
testentry("1 2Xfi",  "1: 2")
testentry("mp",      "Using polar coordinates...")
testentry("1 1X",    "1: 1.41421∠45.0°")
testentry("mp",      "Using rectangular coordinates...")
# Percentages
testentry("50\e%",    "1: 0.5")
testentry("0.5c%",    "1: 50.0")
testentry("100 70b%", "1: -30.0")
# Vectors
# testentry("Vp\e[3~", ".")  # delete the stack by packing and then the del key
testentry("1 2|3|",  "3]")  # [1,2,3]
testentry("Vu",      "3: 1", "2: 2", "1: 3")
testentry("Vp",      "3]")
# # Statistics
testentry("1 2|3|",  "3]")  # [1,2,3]
testentry("u#",    "1: 3")
testentry("Uu+",   "1: 6")
testentry("Uu*",   "1: 6")
testentry("UuX",   "1: 3")
testentry("UuN",   "1: 1")
testentry("UuM",   "1: 2.0")
testentry("UHuM",  "1: 2.0")
testentry("UuS",   "1: 1.0")
testentry("UHuS",  "1: 1.0")
# Storing - fails on v0.6 for some reason
# testentry("12 ss", "Variable name> ")  # Space is needed because this doesn't read the current value
# testentry("x\n",   "12")
# testentry("=x\n",  "1: 12")
# testentry("sS",    "Variable name> ")
# testentry("y\n",   "-element Array")

# User-defined keys
Calc.setkeys(Dict("fp" => Calc.calcfun((y, x) -> 1 / (1/y + 1/x), 2)))
testentry("3 1fp",  "1: 0.75")


text:
##############################################################################
#
# REFERENCES: "Statistical Distributions"
#
##############################################################################

immutable EmpiricalUnivariateDistribution <: ContinuousUnivariateDistribution
	values::Vector{Float64}
	cdf::Function
	entropy::Float64
	kurtosis::Float64
	mean::Float64
	median::Float64
	modes::Vector{Float64}
	skewness::Float64
	var::Float64
end

function EmpiricalUnivariateDistribution(x::Vector)
	EmpiricalUnivariateDistribution(sort(x),
	                                ecdf(x),
	                                NaN,
	                                NaN,
	                                mean(x),
	                                median(x),
	                                Float64[],
	                                NaN,
	                                var(x))
end

cdf(d::EmpiricalUnivariateDistribution, q::Real) = d.cdf(q)

entropy(d::EmpiricalUnivariateDistribution) = d.entropy

function insupport(d::EmpiricalUnivariateDistribution, x::Number)
    contains(d.values, x)
end

kurtosis(d::EmpiricalUnivariateDistribution) = d.kurtosis

mean(d::EmpiricalUnivariateDistribution) = d.mean

median(d::EmpiricalUnivariateDistribution) = d.median

modes(d::EmpiricalUnivariateDistribution) = Float64[]

function pdf(d::EmpiricalUnivariateDistribution, x::Real)
    ## TODO: Create lookup table for discrete case
    1.0 / length(d.values)
end

function quantile(d::EmpiricalUnivariateDistribution, p::Real)
    n = length(d.values)
    index = ifloor(p * n) + 1
    index > n ? d.values[n] : d.values[index]
end

function rand(d::EmpiricalUnivariateDistribution)
    d.values[rand(1:length(d.values))]
end

skewness(d::EmpiricalUnivariateDistribution) = NaN

var(d::EmpiricalUnivariateDistribution) = d.var

function fit_mle{T <: Real}(::Type{EmpiricalUnivariateDistribution},
	                    x::Vector{T})
	EmpiricalUnivariateDistribution(x)
end


text:
"""
Module with wrappers for performing linear interpolation..

Author: Eric Ford
"""
module LinearInterpolation

export make_interpolator_linear_flux, make_interpolator_linear_var

using Interpolations
using RvSpectMLBase

""" Return interpolator for fluxes in spectra. """

function make_interpolator_linear_flux(spectra::Union{AS,AC}) where { AS<:AbstractSpectra, AC<:AbstractChunkOfSpectrum}
    Interpolations.LinearInterpolation(spectra.λ, spectra.flux)
end
#; boost_λ::Real = 1
""" Return interpolator for variances in spectra. """
function make_interpolator_linear_var(spectra::Union{AS,AC}) where { AS<:AbstractSpectra, AC<:AbstractChunkOfSpectrum}
    Interpolations.LinearInterpolation(spectra.λ, spectra.var)
end

include("convenience.jl")
export interp_chunk_to_shifted_grid_linear, interp_chunk_to_shifted_grid_linear!
export interp_chunk_to_grid_linear, interp_chunk_to_grid_linear!

end  # module


text:
using Statistics;
using Random;

function distance(from::Vector{T}, to::Vector{V}) where {T,V}
    sum((from .- to) .^2) |> sqrt
end

function KMEANS(
    matrix::Vector{Vector{T}},
    k::Int;
    max::Int,
)::Vector{Vector{Vector{T}}} where {T}
    len = matrix |> length
    μ = shuffle(MersenneTwister(888888), 1:len)[1:k] .|> x -> matrix[x]
    C::Vector{Vector{Vector{T}}} = 1:k .|> _ -> []
    for _ ∈ 1:max
        for x ∈ matrix
            distances = μ .|> ϵ -> distance(x, ϵ)
            min = argmin(distances)
            C[min] = C[min] ∪ [x]
        end
        δ = C .|> x -> mean(x)
        μ == δ && break
        μ = δ
    end
    C
end

KMEANS(
    [
        [0, 2],
        [0, 0],
        [1.5, 0],
        [5, 0],
        [5, 2]
    ],
    2,
    max = 20,
) .|> println

max_stars_repo_name: lovebaihezi/lab

max_issues_repo_name: lovebaihezi/lab

max_forks_repo_name: lovebaihezi/lab


text:
if VERSION >= v"0.5.0-dev+7720"
    using Base.Test
else
    using BaseTestNext
    const Test = BaseTestNext
end
using JPLEphemeris
import Compat: ASCIIString

const AU = 0.149597870700000000e+09

const SPK_URL = Dict{Int, ASCIIString}(
    430 => "http://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de430.bsp",
    405 => "http://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/a_old_versions/de405.bsp",
)
const TEST_URL = Dict{Int, ASCIIString}(
    430 => "ftp://ssd.jpl.nasa.gov/pub/eph/planets/test-data/430/testpo.430",
    405 => "ftp://ssd.jpl.nasa.gov/pub/eph/planets/test-data/testpo.405",
)

path = abspath(joinpath(dirname(@__FILE__), "..", "deps"))

for denum in (430, 405)
    if !isdir(path)
        mkdir(path)
    end
    if !isfile("$path/de$denum.bsp")
        download(SPK_URL[denum], "$path/de$denum.bsp")
    end
    if !isfile("$path/testpo.$denum")
        download(TEST_URL[denum], "$path/testpo.$denum")
    end
end

include("basic.jl")
include("kernels.jl")