text:
# Reference geometry that is sufficiently complex to test relevant methods,
function setup_LineSegment2(::Type{T}) where {T}
    return LineSegment(Point{2,T}(0,0), Point{2,T}(1,1))
end

function setup_LineSegment3(::Type{T}) where {T}
    return LineSegment(Point{3,T}(0,0,0),
                       Point{3,T}(1,1,1))
end

function setup_QuadraticSegment2(::Type{T}) where {T}
    return QuadraticSegment(Point{2,T}(0,0),
                            Point{2,T}(1,0),
                            Point{2,T}(1//2, 1//2))
end

function setup_QuadraticSegment3(::Type{T}) where {T}
    return QuadraticSegment(Point{3,T}(0,0,0),
                            Point{3,T}(1,1,0),
                            Point{3,T}(1//2, 1//2, 1//2))
end

function setup_AABox2(::Type{T}) where {T}
    return AABox(Point{2,T}(0,0),
                 Point{2,T}(1,1))
end

function setup_AABox3(::Type{T}) where {T}
    return AABox(Point{3,T}(0,0,0),
                 Point{3,T}(1,1,1))
end

function setup_Triangle2(::Type{T}) where {T}
    return Triangle(Point{2,T}(0,0),
                    Point{2,T}(1,0),
                    Point{2,T}(0,1))
end

function setup_Triangle3(::Type{T}) where {T}
    return Triangle(Point{3,T}(0,0,0),
                    Point{3,T}(1,0,0),
                    Point{3,T}(0,1,1))
end

function setup_Quadrilateral2(::Type{T}) where {T}
    return Quadrilateral(Point{2,T}(0,0),
                         Point{2,T}(1,0),
                         Point{2,T}(1,1),
                         Point{2,T}(0,1))
end

function setup_Quadrilateral3(::Type{T}) where {T}
    return Quadrilateral(Point{3,T}(0,0,0),
                         Point{3,T}(1,0,1),
                         Point{3,T}(1,1,0),
                         Point{3,T}(0,1,1))
end

function setup_QuadraticTriangle2(::Type{T}) where {T}
    return QuadraticTriangle(Point{2,T}(0,0),
                             Point{2,T}(1,0),
                             Point{2,T}(0,1),
                             Point{2,T}(1//2, 1//20),
                             Point{2,T}(1//2, 1//2),
                             Point{2,T}(1//20, 1//2))
end

function setup_QuadraticTriangle3(::Type{T}) where {T}
    return QuadraticTriangle(Point{3,T}(0,0,0),
                             Point{3,T}(1,0,0),
                             Point{3,T}(0,1,0),
                             Point{3,T}(1//2,0,1//2),
                             Point{3,T}(1//2,1//2,0),
                             Point{3,T}(0,1//2,1//2))
end

function setup_QuadraticQuadrilateral2(::Type{T}) where {T}
    return QuadraticQuadrilateral(Point{2,T}(0,0),
                                  Point{2,T}(1,0),
                                  Point{2,T}(1,1),
                                  Point{2,T}(0,1),
                                  Point{2,T}(1//2, 0),
                                  Point{2,T}(9//10, 1//2),
                                  Point{2,T}(1//2, 1),
                                  Point{2,T}(1//10, 1//2))
end

function setup_QuadraticQuadrilateral3(::Type{T}) where {T}
    return QuadraticQuadrilateral(Point{3,T}(0,0,0),
                                  Point{3,T}(1,0,0),
                                  Point{3,T}(1,1,0),
                                  Point{3,T}(0,1,0),
                                  Point{3,T}(1//2, 0, 1//2),
                                  Point{3,T}(9//10, 1//2, 0),
                                  Point{3,T}(1//2, 1, 1//2),
                                  Point{3,T}(1//10, 1//2, 0))
end

function setup_Tetrahedron(::Type{T}) where {T}
    return Tetrahedron(Point{3,T}(0, 0, 0),
                       Point{3,T}(1, 0, 0),
                       Point{3,T}(0, 1, 0),
                       Point{3,T}(0, 0, 1))
end

function setup_Hexahedron(::Type{T}) where {T}
    return Hexahedron(Point{3,T}(0, 0, 0),
                      Point{3,T}(1, 0, 0),
                      Point{3,T}(0, 1, 0),
                      Point{3,T}(1, 1, 0),
                      Point{3,T}(0, 0, 1),
                      Point{3,T}(1, 0, 1),
                      Point{3,T}(0, 1, 1),
                      Point{3,T}(1, 1, 1))
end

function setup_QuadraticTetrahedron(::Type{T}) where {T}
    return QuadraticTetrahedron(Point{3,T}(0, 0, 0),
                                Point{3,T}(1, 0, 0),
                                Point{3,T}(0, 1, 0),
                                Point{3,T}(0, 0, 1),
                                Point{3,T}(1//2,    0,    0),
                                Point{3,T}(1//2, 1//2,    0),
                                Point{3,T}(0,    1//2,    0),
                                Point{3,T}(0,       0, 1//2),
                                Point{3,T}(1//2,    0, 1//2),
                                Point{3,T}(0,    1//2, 1//2))
end

function setup_QuadraticHexahedron(::Type{T}) where {T}
    return QuadraticHexahedron(Point{3,T}(0, 0, 0),
                               Point{3,T}(1, 0, 0),
                               Point{3,T}(0, 1, 0),
                               Point{3,T}(0, 0, 1),
                               Point{3,T}(1//2,    0,    0),
                               Point{3,T}(1//2, 1//2,    0),
                               Point{3,T}(0,    1//2,    0),
                               Point{3,T}(0,       0, 1//2),
                               Point{3,T}(1//2,    0, 1//2),
                               Point{3,T}(0,    1//2, 1//2),
                               Point{3,T}(0, 0, 0),
                               Point{3,T}(1, 0, 0),
                               Point{3,T}(0, 1, 0),
                               Point{3,T}(0, 0, 1),
                               Point{3,T}(1//2,    0,    0),
                               Point{3,T}(1//2, 1//2,    0),
                               Point{3,T}(0,    1//2,    0),
                               Point{3,T}(0,       0, 1//2),
                               Point{3,T}(1//2,    0, 1//2),
                               Point{3,T}(0,    1//2, 1//2))
end

max_stars_repo_name: khurrumsaleem/MOCNeutronTransport

max_issues_repo_name: khurrumsaleem/MOCNeutronTransport

max_forks_repo_name: khurrumsaleem/MOCNeutronTransport


text:
@testset "findindices" begin

    data = [0, 0, 0, 0, 1, 1, 1, 1]
    indices = findindices(data)
    @test isempty(indices)

    data = [0, 0, 0, 1, 0, 0, 0]
    indices = findindices(data)
    @test indices == [4]

    data = [0, 0, 1, 1, 1, 0, 0]
    indices = findindices(data)
    @test indices == [3]

    data = [0, 1, 2, 3, 2, 1, 0, 1, 2, 2, 2, 0, 3, 3, 6, 4, 0]
    indices = findindices(data)
    @test indices == [4, 9, 15]

    data = [Inf, -14.4, Inf, 14.0, 18.0, -Inf, 12.3]
    indices = findindices(data)
    @test indices == [3, 5]

    data = [1, NaN, 3, 2, NaN, 1]
    @test_logs (:warn,) findindices(data)

end

@testset "findprominences" begin

    data = [0, 0, 0, 0, 1, 1, 1, 1]
    indices = []
    prominences = findprominences(data, indices)
    @test isempty(prominences)

    data = [0, 1, 2, 3, 2, 1, 0, 1, 2, 2, 2, 0, 3, 3, 6, 4, 0]
    indices = [4, 9, 15]
    prominences = findprominences(data, indices)
    @test prominences == [3, 2, 6]

    data = [Inf, -14.4, Inf, 14.0, 18.0, -Inf, 12.3]
    indices = [3, 5]
    prominences = findprominences(data, indices)
    @test all(prominences .≈ [Inf, 4.0])

end

@testset "findwidthbounds" begin

    data = [0, 0, 0, 0, 1, 1, 1, 1]
    x = 1:length(data)
    indices = []
    prominences = []
    width_bounds = findwidthbounds(data, x, indices, prominences)
    @test isempty(width_bounds)
    width_bounds_2 = findwidthbounds(data, x, indices)
    @test isempty(width_bounds_2)

    data = [0, 1, 2, 3, 2, 1, 0, 1, 2, 2, 2, 0, 3, 3, 6, 4, 0]
    x = (1:length(data)) .+ 5
    indices = [4, 9, 15]
    prominences = [3, 2, 6]
    width_bounds = findwidthbounds(data, x, indices, prominences)
    @test all(width_bounds .≈ ([2.5 5.5; 8.0 11.5; 14.0 16.25] .+ 5))
    width_bounds_2 = findwidthbounds(data, x, indices)
    @test all(width_bounds_2 .≈ ([2.5 5.5; 8.0 11.5; 14.0 16.25] .+ 5))

    data = [0, -1, -2, -1, -2, -2, 1, 1, 2, 3, 4, 3, 2, 1]
    x = (1:length(data)) .- 2
    indices = [4, 11]
    prominences = [1, 3]
    width_bounds = findwidthbounds(data, x, indices, prominences)
    @test all(width_bounds .≈ ([3.5 4.5; 9.5 12.5] .- 2))
    width_bounds_2 = findwidthbounds(data, x, indices)
    @test all(isnan.(width_bounds_2[1, :]))
    @test all(width_bounds_2[2, :] .≈ ([9.0, 13.0] .- 2))

    data = [0, 1, 2, 3, 4, 3, 4, 5, 4, 3, 4, 3, 2, 1, 0]
    x = (1:length(data)) .+ 1.5
    indices = [5, 8, 11]
    prominences = [1, 5, 1]
    width_bounds = findwidthbounds(data, x, indices, prominences)
    @test all(width_bounds .≈ ([4.5 5.5; 3.5 12.5; 10.5 11.5] .+ 1.5))
    width_bounds_2 = findwidthbounds(data, x, indices)
    @test all(width_bounds_2 .≈ ([3.0 6.0; 6.0 10.0; 10.0 13.0] .+ 1.5))

    data = [3, 4, 3, 3, 3, 4, 4, 3]
    indices = [2, 6]
    x = [-1, NaN, 8, NaN, NaN, NaN, NaN, 31]
    width_bounds_2 = findwidthbounds(data, x, indices)
    @test all(width_bounds_2 .≈ [-1 8; 8 31])

end

@testset "findpeaks" begin

    data = [0, 1, 2, 3, 2, 1, 0, 1, 2, 2, 2, 0, 3, 3, 6, 4, 0]
    pr = findpeaks(data)
    @test pr.indices == [4, 9, 15]
    @test pr.peaks == [3, 2, 6]
    @test pr.locations == [4, 9, 15]
    @test pr.prominences == [3, 2, 6]
    @test all(pr.width_bounds .≈ [2.5 5.5; 8.0 11.5; 14.0 16.25])

    pr = findpeaks(data; npeaks = 2)
    @test pr.indices == [4, 9]

    @testset "sortstr, sortref" begin

        data = [0, 1, 2, 3, 2, 1, 0, 1, 2, 2, 2, 0, 3, 3, 6, 4, 0]
        pr = findpeaks(data; sortstr = "ascend")
        @test pr.indices == [9, 4, 15]

        pr = findpeaks(data; sortstr = "descend")
        @test pr.indices == [15, 4, 9]

        @test_logs (:warn, "sortstr is not specified, sortref will be ignored")
            findpeaks(data; sortref = "prominences")

        data = [0, 4, 2, 3, 0, 2, 0]
        pr = findpeaks(data; sortstr = "ascend", sortref = "prominence")
        @test pr.indices == [4, 6, 2]

        data = [0, 4, 2, 3, 0, 2, 0]
        pr = findpeaks(data; sortstr = "descend", sortref = "prominence")
        @test pr.indices == [2, 6, 4]

    end

    @testset "mindistance" begin

        data = [0, 1, 2, 3, 2, 1, 0, 1, 2, 2, 2, 0, 3, 3, 6, 4, 0]
        pr = findpeaks(data; mindistance = 8)
        @test pr.indices == [4, 15]

    end

    @testset "minprominence" begin

        data = [1, 1, 2, 3, 2, 4, 1, 1, 2, 3, 2, 3, 4, 5, 6, 4, 1]
        pr = findpeaks(data; minprominence = 3)
        @test pr.indices == [6, 15]

    end

    @testset "minheight" begin

        data = [1, 1, 2, 3, 2, 1, 1, 1, 2, 2, 2, 1, 3, 3, 6, 4, 1]
        pr = findpeaks(data; minheight = 3)
        @test pr.indices == [4, 15]

    end

    @testset "threshold" begin

        data = [0, 1, 2, 0, 2, 1, 0, 2, 0, 2, 2, 0, 4, 0]
        pr = findpeaks(data; threshold = 2)
        @test pr.indices == [8, 13]

    end

    @testset "widthreference" begin

        data = [0, 1, 2, 3, 4, 3, 4, 5, 4, 3, 4, 3, 2, 1, 0]
        pr = findpeaks(data, widthreference="halfheight")
        @test all(pr.width_bounds .≈ [3.0 6.0; 6.0 10.0; 10.0 13.0])
        pr = findpeaks(data, widthreference="halfprominence")
        @test all(pr.width_bounds .≈ [4.5 5.5; 3.5 12.5; 10.5 11.5])

    end

    @testset "minwidth" begin

        data = [0, 1, 0, 0, 2, 2, 2, 0, 1, 1, 0, 6, 0]
        pr = findpeaks(data; minwidth = 2)
        @test pr.indices == [5, 9]

    end

    @testset "maxwidth" begin

        data = [0, 1, 0, 0, 2, 2, 2, 0, 1, 1, 0, 6, 6, 0]
        pr = findpeaks(data; maxwidth = 2)
        @test pr.indices == [2, 9, 12]

    end

end

ext: jl

max_stars_repo_name: vkumpost/FindPeaks

max_issues_repo_name: vkumpost/FindPeaks

max_forks_repo_name: vkumpost/FindPeaks


text:
#=
Modia main module.

* Developers: Hilding Elmqvist (Mogram) and Martin Otter (DLR-SR)
* Copyright (c) 2016-2021: Hilding Elmqvist, Martin Otter
* License: MIT (expat)
=#

module Modia

const path = dirname(dirname(@__FILE__))   # Absolute path of package directory
const Version = "0.5.1-dev"
const Date = "2021-08-05"

#println(" \n\nWelcome to Modia - Dynamic MODeling and Simulation in julIA")
print(" \n\nWelcome to ")
print("Mod")
printstyled("ia", bold=true, color=:red)
print(" - ")
printstyled("Dynamic ", color=:light_black)
print("Mod")
printstyled("eling and Simulation with Jul", color=:light_black)
printstyled("ia", bold=true, color=:red)

println()
println("Version $Version ($Date)")

using Reexport

@reexport using ModiaLang
@reexport using ModiaLang.Unitful
@reexport using ModiaLang.DifferentialEquations
const modelsPath = joinpath(ModiaLang.path, "models")

include("Modia3D_Interface.jl")

end


text:
# ---
# title: 88. Merge Sorted Array
# id: problem88
# author: Tian Jun
# date: 2020-11-24
# difficulty: Easy
# categories: Array, Two Pointers
# link: <https://leetcode.com/problems/merge-sorted-array/description/>
# hidden: true
# ---
#
# Given two sorted integer arrays _nums1_ and _nums2_ , merge _nums2_ into
# _nums1_ as one sorted array.
#
# **Note:**
#
#   * The number of elements initialized in _nums1_ and _nums2_ are _m_ and _n_ respectively.
#   * You may assume that _nums1_ has enough space (size that is  **equal** to _m_ \+ _n_ ) to hold additional elements from _nums2_.
#
# **Example:**
#
#
#
#     Input:
#     nums1 = [1,2,3,0,0,0], m = 3
#     nums2 = [2,5,6],       n = 3
#
#     Output:  [1,2,2,3,5,6]
#
#
#
#
# **Constraints:**
#
#   * `-10^9 <= nums1[i], nums2[i] <= 10^9`
#   * `nums1.length == m + n`
#   * `nums2.length == n`
#
#
## @lc code=start
using LeetCode

function merge_sorted_array(
    nums1::AbstractVector{Int}, m::Int, nums2::AbstractVector{Int}, n::Int
)::Nothing
    i = m + n
    while m > 0 && n > 0
        if nums1[m] > nums2[n]
            nums1[i] = nums1[m]
            m -= 1
        else
            nums1[i] = nums2[n]
            n -= 1
        end
        i -= 1
    end

    while n > 0
        nums1[i] = nums2[n]
        n -= 1
        i -= 1
    end

    return nothing
end
## @lc code=end


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

"""
Tools for working with the Markdown file format. Mainly for documentation.
"""
module Markdown

import Base: show, ==, with_output_color, mapany
using Base64: stringmime

# Margin for printing in terminal.
const margin = 2

include("parse/config.jl")
include("parse/util.jl")
include("parse/parse.jl")

include("Common/Common.jl")
include("GitHub/GitHub.jl")
include("IPython/IPython.jl")
include("Julia/Julia.jl")

include("render/plain.jl")
include("render/html.jl")
include("render/latex.jl")
include("render/rst.jl")
include("render/terminal/render.jl")

export @md_str, @doc_str

parse(markdown::AbstractString; flavor = julia) = parse(IOBuffer(markdown), flavor = flavor)
parse_file(file::AbstractString; flavor = julia) = parse(read(file, String), flavor = flavor)

function mdexpr(s, flavor = :julia)
    md = parse(s, flavor = Symbol(flavor))
    esc(toexpr(md))
end

function docexpr(source::LineNumberNode, mod::Module, s, flavor = :julia)
    :($doc_str($(mdexpr(s, flavor)), $(QuoteNode(source)), $mod))
end

macro md_str(s, t...)
    mdexpr(s, t...)
end

function doc_str(md, source::LineNumberNode, mod::Module)
    md.meta[:path] = isa(source.file, Symbol) ? String(source.file) : ""
    md.meta[:module] = mod
    md
end
doc_str(md::AbstractString, source::LineNumberNode, mod::Module) = doc_str(parse(md), source, mod)

macro doc_str(s::AbstractString, t...)
    docexpr(__source__, __module__, s, t...)
end

import Base.Docs: catdoc

catdoc(md::MD...) = MD(md...)

end

max_stars_repo_name: TimoLarson/julia

max_issues_repo_name: TimoLarson/julia

max_forks_repo_name: TimoLarson/julia


text:
function EllipticalFieldOfView(arg0::Vector3D, arg1::Vector3D, arg2::jdouble, arg3::jdouble, arg4::jdouble)
    return EllipticalFieldOfView((Vector3D, Vector3D, jdouble, jdouble, jdouble), arg0, arg1, arg2, arg3, arg4)
end

function get_focus1(obj::EllipticalFieldOfView)
    return jcall(obj, "getFocus1", Vector3D, ())
end

function get_focus2(obj::EllipticalFieldOfView)
    return jcall(obj, "getFocus2", Vector3D, ())
end

function get_half_aperture_along_x(obj::EllipticalFieldOfView)
    return jcall(obj, "getHalfApertureAlongX", jdouble, ())
end

function get_half_aperture_along_y(obj::EllipticalFieldOfView)
    return jcall(obj, "getHalfApertureAlongY", jdouble, ())
end

function offset_from_boundary(obj::EllipticalFieldOfView, arg0::Vector3D, arg1::jdouble, arg2::VisibilityTrigger)
    return jcall(obj, "offsetFromBoundary", jdouble, (Vector3D, jdouble, VisibilityTrigger), arg0, arg1, arg2)
end

function project_to_boundary(obj::EllipticalFieldOfView, arg0::Vector3D)
    return jcall(obj, "projectToBoundary", Vector3D, (Vector3D,), arg0)
end


text:
module WebPlayer

using Colors, FixedPointNumbers, CSSUtil, WebIO, InteractNext

const set_play = js"""
function set_play(name, nvideos, fps, nframes, init, callback){
    var video;
    var button = document.getElementById("button");

    for(var i = 1; i <= nvideos; i++){
        video = document.getElementById(name + i);
        if(video.paused){
            video.play();
            if(!init){
                if(i == 1 && !init){
                    video.addEventListener('ended', callback);
                }
                var new_rate = (video.duration / nframes) / (1.0 / fps);
                video.playbackRate = new_rate;
            }
            button.textContent = " ⏸ ";

        }else{
            video.pause();
            button.textContent = " ▶ ";
        }
    }
    return video.currentTime / video.duration;
}
"""

const set_time = js"""
function set_time(name, nvideos, val, nframes){
    for(var i = 1; i <= nvideos; i++){
        var video = document.getElementById(name + i);
        var t = (val / nframes) * video.duration;
        video.currentTime = t;
    }
    return;
}
"""

function video_player(video, name, width, style = Dict())
    mktempdir() do dir
        _xdim, _ydim, nframes = size(video)
        xdim = _xdim % 2 == 0 ? _xdim : _xdim + 1
        ydim = _ydim % 2 == 0 ? _ydim : _ydim + 1
        frame = fill(RGB{N0f8}(1, 1, 1), ydim, xdim)
        path = joinpath(dir, "$name.mkv")
        io, process = open(`ffmpeg -loglevel quiet -f rawvideo -pixel_format rgb24 -r 24 -s:v $(ydim)x$(xdim) -i pipe:0 -vf vflip -y $path`, "w")
        for i = 1:nframes
            for x in 1:_xdim, y in 1:_ydim
                g = video[(_xdim + 1) - x, y, i]
                frame[y, x] = RGB{N0f8}(g, g, g)
            end
            write(io, frame)
        end
        flush(io)
        close(io)
        wait(process)
        mp4path = joinpath(dir, "$(name).mp4")
        run(`ffmpeg -loglevel quiet -i $(path) -c:v libx264 -preset slow -crf 22 -pix_fmt yuv420p -c:a libvo_aacenc -b:a 128k -y $(mp4path)`)
        dom"video"(
            dom"source"(attributes = Dict(
                :src => string("data:video/mp4;base64,", base64encode(read(mp4path))),
                :type => "video/mp4",
            )),
            id = name,
            attributes = merge(Dict(:width => "100%"), style)
        )
    end
end

package_dir() = joinpath(@__DIR__, "..")

function videobox(video, name, width)
    dom"div"(
        vbox(dom"div"(name), dom"div"(video, style = Dict(:width => "$width"))),
        style = Dict(:outline => "1px solid #555", :padding => "0.5em")
    )
end

"""
    playvideo(
        videos::Vector{Array{T, 3}}, names = ["video i" for i = 1:length(videos)];
        frames_per_second = 24, width = 500
    )

Plays multiple videos side by side - names are optional and fall back to `video i`.
You can change the playback speed by passing your favorite frame rate to `frames_per_second = rate`.
One can also modify the width with the keyword argument `width = 500`.
"""
function playvideo(
        videos::Vector{Array{T, 3}},
        names = ["video $i" for i = 1:length(videos)];
        frames_per_second = 24, width = 500
    ) where T <: AbstractFloat

    w = Widget()
    nvideos = length(videos)
    nframes = size(first(videos), 3)
    timestep = Observable(w, "timestep", 1)
    initialized = Observable(w, "initialized", false)
    unique_name = first(names)
    callback = @js function()
        @var button = document.getElementById("button")
        button.textContent = " ▶ "
        $timestep[] = 1
    end
    button = dom"button"(
        " ▶ ",
        id = "button",
        events = Dict(
            "click" => @js function ()
                @var tnorm = $(set_play)(
                    $unique_name, $nvideos, $frames_per_second,
                    $nframes, $initialized[], $callback
                )
                $initialized[] = false
                $timestep[] = Math.round($(nframes) * tnorm)
                return
            end),
    )
    s = dom"div"(
        InteractNext.slider(1:nframes, ob = timestep),
        style = Dict(:width => "400px", :padding => "0.5em")
    )

    onjs(timestep, @js function (val)
        $(set_time)($unique_name, $nvideos, val, $(nframes))
    end)
    video_players = w.(video_player.(videos, [string(unique_name, i) for i = 1:nvideos], width))
    vbox(hbox(w(button), s), hbox(videobox.(video_players, names, width)...))
end

function playvideo(
        videos::Array{T, 3}, names = nothing;
        kw_args...
    ) where T <: AbstractFloat
    error("You gave a single video to video player: $(typeof(videos)). To play a video use a vector of videos, e.g.: [video1, video2]")
end

export playvideo

end # module


text:
################################################################################
#
#   The unified (Wrapper) Module for all different sorts of lattices
#   and lattice based calculations.
#
#   Module structure mostly included in subfiles see below
#
################################################################################

# Start of module
module LatticePhysics

# uses Reexport.jl to reexport all exported functions from submodules
using Reexport

################################################################################
#
#   module LatticePhysics_Base
#
#   --> ABSTRACT TYPE DEFINITION
#           - AbstractSite{L,D}
#           - AbstractBond{L,N}
#           - AbstractUnitcell{S,B}
#           - AbstractLattice{S,B,U}
#
#   --> INTERFACING ABSTRACT TYPES
#           - AbstractSite{L,D}
#               - positions
#               - label
#           - AbstractBond{L,N}
#               - connecting identifiers
#               - label
#               - wrap
#           - AbstractUnitcell{S,B}
#               - Bravais lattice vectors
#               - sites
#               - bonds
#           - AbstractLattice{S,B,U}
#               - Unitcell
#               - Bravais lattice vectors
#               - sites
#               - bonds
#
#   --> NAIVE STRUCT DEFINITIONS
#           - Site{L,D}
#           - Bond{L,N}
#           - Unitcell{S,B}
#           - Lattice{S,B,U}
#
#   --> IMPLEMENTING JULIA.BASE FUNCTIONS
#           - show
#           - print
#
################################################################################

# include the relevant submodule
@reexport using LatPhysBase

################################################################################
#
#   module LatticePhysics_IO
#   -> LatticePhysics_Base
#   -> JLD2
#
#   --> IO FOR UNITCELLS / LATTICES
#           - save to xml ??
#           - JLD ??
#
################################################################################

################################################################################
#
#   module LatticePhysics_ConnectionRepresentation
#   -> LatticePhysics_Base
#   -> LinearAlgebra
#
#   --> FUNCTIONS FOR IDENTIFYING NEIGHBOURS
#
#   --> STATIC LOOKUP TABLES
#           - connectivity information
#           - lists of identifiers for every site
#           - list of booleans
#
#   --> INTERACTION MATRICES
#           - construction based on functions and dictonaries
#           - real space / momentum space?
#
################################################################################

################################################################################
#
#   module LatPhysUnitcellLibrary
#   -> LatticePhysics_Base
#   -> LinearAlgebra
#
#   --> PRE-IMPLEMENTED UNITCELLS 2D
#
#   --> PRE-IMPLEMENTED UNITCELLS 3D
#
################################################################################

# include the relevant submodule
@reexport using LatPhysUnitcellLibrary

################################################################################
#
#   module LatticePhysics_UnitcellConstruction
#   -> LatticePhysics_Base
#   -> LinearAlgebra
#
#   --> CONSTRUCTION OF UNITCELLS FROM SITES
#
#   --> CONSTRUCTION HELPER
#           - print the generating code for a Unitcell
#
################################################################################

################################################################################
#
#   module LatticePhysics_LatticeConstruction
#   -> LatticePhysics_Base
#   -> LinearAlgebra
#
#   --> NAIVE CONSTRUCTION OF LATTICES
#           - periodic pattern of unitcells
#           - semi-periodic pattern of unitcells
#           - open pattern of unitcells
#           - by bond distance to an origin site
#           - in a shape around an origin site
#
#   --> ADDING NNN TO LATTICE
#
#   --> LATTICE CONSTRUCTION ALGORITHM FROM SPIN SPIRALS PAPER
#
################################################################################

# include the relevant submodule
@reexport using LatPhysLatticeConstruction

################################################################################
#
#   module LatticePhysics_LatticeModification
#   -> LatticePhysics_Base
#   -> LinearAlgebra
#
#   --> MODIFICATION OF LATTICES COMPONENTS
#       - Adding / Removing Connections
#       - Adding / Removing sites
#
#   --> RELABELING BONDS / SITES
#       - relabeling bonds
#       - relabeling sites
#
#   --> SPATIAL MODIFICATIONS
#       - Scaling  in space
#       - Rotating in space
#       - Shifting in space
#       - Lattice vector optimization (relabeling unitcells)
#
################################################################################

# include the relevant submodule
@reexport using LatPhysLatticeModification

################################################################################
#
#   module LatticePhysics_Plaquettes
#   -> LatticePhysics_Base
#   -> LinearAlgebra
#
#   --> TYPE DEFINITION OF PLAQUETTE TYPE
#
#   --> PLAQUETTE OBTAINING FUNCTIONS
#           - get plaquettes of a site
#           - get plaquettes of a unitcell / lattice
#
#   --> PLAQUETTE INFORMATION FUNCTIONS
#           - obtain / print plaquette statistics
#
################################################################################

################################################################################
#
#   module LatPhysReciprocal
#   -> LatticePhysics_Base
#   -> LinearAlgebra
#
#   --> TYPE DEFINITIONS (Abstract / Concrete)
#           - Point
#           - Path
#           - BrillouinZone
#           - ReciprocalLattice ??
#
#   --> BUILDING FUNCTIONS FOR PATHS IN MOMENTUM SPACE
#           - modification of paths
#           - pre-implemented paths
#           - paths based on Unitcells
#
#   --> BRILLOUIN ZONES
#           - type definition
#           - pre-implemented BZs
#           - construction of default BZs (2D)
#           - construction of default BZs (3D)
#
################################################################################

# include the relevant submodule
@reexport using LatPhysReciprocal

################################################################################
#
#   module LatticePhysics_ReciprocalSpace_Plotting
#   -> LatticePhysics_Base
#   -> LatticePhysics_ReciprocalSpace
#   -> LinearAlgebra
#
#   --> PLOTTING OF PATHS
#           - 2D paths
#           - 3D paths
#
#   --> PLOTTING OF BRILLOUIN ZONES
#           - 2D Brillouin zones
#           - 3D Brillouin zones
#
################################################################################

################################################################################
#
#   module LatticePhysics_SVGBase
#
#   --> SVG STRINGS FOR FILES
#           - svg header
#           - svg footer
#
#   --> SVG STRINGS FOR GEOMETRIC OBJECTS
#           - ellipsoids
#           - rectangles
#           - paths
#           - text
#
################################################################################

################################################################################
#
#   module LatticePhysics_Plotting_SVG
#   -> LatticePhysics_Base
#   -> LatticePhysics_SVGBase
#   -> LinearAlgebra
#
#   --> PLOTTING OF LATTICES TO SVG FILES
#           - 2D lattices
#           - 3D lattices
#
################################################################################

################################################################################
#
#   module LatticePhysics_PlaquettePlotting_SVG
#   -> LatticePhysics_Base
#   -> LatticePhysics_Plaquettes
#   -> LatticePhysics_SVGBase
#   -> LatticePhysics_Plotting_SVG
#   -> LinearAlgebra
#
#   --> PLOTTING OF PLAQUETTES AND LATTICES TO SVG FILES
#           - 2D plaquettes and lattices
#
################################################################################

################################################################################
#
#   module LatticePhysics_Plotting_Blender
#   -> LatticePhysics_Base
#   -> LinearAlgebra
#
#   --> PLOTTING OF LATTICES TO TEXT FILES TO BE READ BY BLENDER
#           - 2D lattices
#           - 3D lattices
#
################################################################################

################################################################################
#
#   module LatticePhysics_Plotting_PyPlot
#   -> PyPlot
#   -> LatticePhysics_Base
#   -> LinearAlgebra
#
#   --> PLOTTING OF LATTICES WITH PYPLOT
#           - 2D lattices
#           - 3D lattices
#
################################################################################

################################################################################
#
#   module LatticePhysics_FreeFermion_Calculations
#   -> LatticePhysics_Base
#   -> LatticePhysics_ReciprocalSpace
#   -> LinearAlgebra
#
#   --> TYPE DEFINITIONS
#           - FermionBandstructure
#           - FermiSurface
#
#   --> IO OF TYPES
#
#   --> CALCULATION OF BANDSTRUCTURES AND EIGENVALUES
#           - in real space (pure eigenvalues)
#           - in momentum space (along cardinal directions)
#           - in momentum space (along reciprocal lattice directions)
#           - in momentum space (along path)
#
#   --> CALCULATION OF FERMI SURFACES
#           - calculation for 2D unitcells
#           - calculation for 3D unitcells
#
################################################################################

# include the relevant submodule
@reexport using LatPhysBandstructures

################################################################################
#
#   module LatticePhysics_FreeFermion_Plotting
#   -> PyPlot
#   -> LatticePhysics_Base
#   -> LatticePhysics_ReciprocalSpace
#   -> LatticePhysics_FreeFermion_Calculations
#   -> LinearAlgebra
#
#   --> PLOTTING OF BANDSTRUCTURES AND EIGENVALUES
#           - in real space (pure eigenvalues)
#           - in momentum space (along cardinal directions)
#           - in momentum space (along reciprocal lattice directions)
#           - in momentum space (along path)
#
#   --> PLOTTING OF FERMI SURFACES
#           - for 1D fermi surfaces in 2D
#           - for 2D fermi surfaces in 3D
#
################################################################################

################################################################################
#
#   module LatticePhysics_LuttingerTisza_Calculations
#   -> LatticePhysics_Base
#   -> LatticePhysics_ReciprocalSpace
#   -> LinearAlgebra
#
#   --> TYPE DEFINITIONS
#           - LTBandstructure
#           - LTGroundstateManifold
#
#   --> IO OF TYPES
#
#   --> SPIN INTERACTION MATRICES
#
#   --> CALCULATION OF LT CONSTRAINTS
#
#   --> CALCULATION OF LT BANDSTRUCTURES AND EIGENVALUES
#           - in real space (pure eigenvalues)
#           - in momentum space (along cardinal directions)
#           - in momentum space (along reciprocal lattice directions)
#           - in momentum space (along path)
#
#   --> CALCULATION OF LT GROUNDSTATE MANIFOLDS
#           - calculation for 2D unitcells
#           - calculation for 3D unitcells
#
################################################################################

# include the relevant submodule
#@reexport using LatPhysLuttingerTisza

################################################################################
#
#   module LatticePhysics_LuttingerTisza_Plotting
#   -> PyPlot
#   -> LatticePhysics_Base
#   -> LatticePhysics_ReciprocalSpace
#   -> LatticePhysics_LuttingerTisza_Calculations
#   -> LinearAlgebra
#
#   --> PLOTTING OF LT BANDSTRUCTURES AND EIGENVALUES
#           - in real space (pure eigenvalues)
#           - in momentum space (along cardinal directions)
#           - in momentum space (along reciprocal lattice directions)
#           - in momentum space (along path)
#
#   --> PLOTTING OF LT GROUNDSTATE MANIFOLDS
#           - plotting of manifolds in 2D
#           - plotting of manifolds in 3D
#
################################################################################

# End of module
end


text:
######################################################################
# Keyboard-related input abstraction
# -----
# Licensed under MIT License
using GLFW

export Key
struct Key <: GLFWWrapper{GLFW.Key}
    wrapped::GLFW.Key
end
Key(::Nothing) = Key(GLFW.KEY_UNKNOWN)
Key(special::Symbol) = resolve_key(Ident{special}())
function Key(digit::Integer; keypad::Bool = false)
    if digit ∉ 0:9
        throw(ArgumentError("number key must be single digit integers"))
    end
    I = Base.Enums.basetype(GLFW.Key)
    Key(GLFW.Key(Integer(keypad ? GLFW.KEY_KP_0 : GLFW.KEY_0) + I(digit)))
end
function Key(char::Char)
    if char ∈ 'a':'z' || char ∈ 'A':'Z'
        I = Base.Enums.basetype(GLFW.Key)
        return Key(GLFW.Key(Integer(GLFW.KEY_A) + convert(I, codepoint(lowercase(char)) - codepoint('a'))))
    end
    resolve_key(Ident{char}())
end

resolve_key(::Ident{K}) where K = throw(ArgumentError("unknown key \"$K\""))
resolve_key(::Ident{'\''}) = Key(GLFW.KEY_APOSTROPHE)
resolve_key(::Ident{','})  = Key(GLFW.KEY_COMMA)
resolve_key(::Ident{'-'})  = Key(GLFW.KEY_MINUS)
resolve_key(::Ident{'.'})  = Key(GLFW.KEY_PERIOD)
resolve_key(::Ident{'/'})  = Key(GLFW.KEY_SLASH)
resolve_key(::Ident{';'})  = Key(GLFW.KEY_SEMICOLON)
resolve_key(::Ident{'='})  = Key(GLFW.KEY_EQUAL)
resolve_key(::Ident{'['})  = Key(GLFW.KEY_LEFT_BRACKET)
resolve_key(::Ident{'\\'}) = Key(GLFW.KEY_BACKSLASH)
resolve_key(::Ident{']'})  = Key(GLFW.KEY_RIGHT_BRACKET)
resolve_key(::Ident{'`'})  = Key(GLFW.KEY_GRAVE_ACCENT)

macro addresolvekeys(blk::Expr)
    @assert blk.head === :block "must be a block expression enumerating the various keys/mappings"

    result = Expr(:block)
    for expr ∈ blk.args
        if expr isa LineNumberNode continue end

        key, mapping = if expr isa Expr
            @assert expr.head === :call && expr.args[1] === :(=>) && expr.args[2] isa Symbol && expr.args[3] isa Symbol "must be an arrow pair (a=>b) assignment"
            QuoteNode(expr.args[2]), Expr(:., :GLFW, QuoteNode(Symbol("KEY_$(uppercase(string(expr.args[3])))")))
        elseif expr isa Symbol
            QuoteNode(expr), Expr(:., :GLFW, QuoteNode(Symbol("KEY_$(uppercase(string(expr)))")))
        else
            throw(ArgumentError("invalid key mapping $expr"))
        end

        push!(result.args, :($(esc(:resolve_key))(::Ident{$key}) = Key($mapping)))
    end

    result
end

# This one needs to be added manually because 'end' is a keyword which breaks the macro
resolve_key(::Ident{:end}) = Key(GLFW.KEY_END)
@addresolvekeys begin
    space
    world1 => WORLD_1
    world2 => WORLD_2
    escape; esc => ESCAPE
    enter; tab; backspace; insert; delete
    right; left; down; up
    pageup => PAGE_UP
    pagedown => PAGE_DOWN
    home
    capslock   => CAPS_LOCK
    scrolllock => SCROLL_LOCK
    numlock    => NUM_LOCK
    print       => PRINT_SCREEN
    printscreen => PRINT_SCREEN
    pause
    f1; f2; f3; f4; f5; f6; f7; f8; f9; f10; f11; f12; f13; f14; f15; f16; f17; f18; f19; f20; f21; f22; f23; f24; f25
    decimal  => KP_DECIMAL
    divide   => KP_DIVIDE
    multiply => KP_MULTIPLY
    subtract => KP_SUBTRACT
    add      => KP_ADD
    keypad_enter => KP_ENTER
    keypad_equal => KP_EQUAL

    left_shift    => LEFT_SHIFT
    lshift        => LEFT_SHIFT
    left_control  => LEFT_CONTROL
    lcontrol      => LEFT_CONTROL
    lctrl         => LEFT_CONTROL
    left_alt      => LEFT_ALT
    lalt          => LEFT_ALT
    left_super    => LEFT_SUPER
    lsuper        => LEFT_SUPER
    right_shift   => RIGHT_SHIFT
    rshift        => RIGHT_SHIFT
    right_control => RIGHT_CONTROL
    rcontrol      => RIGHT_CONTROL
    rctrl         => RIGHT_CONTROL
    right_alt     => RIGHT_ALT
    ralt          => RIGHT_ALT
    right_super   => RIGHT_SUPER
    rsuper        => RIGHT_SUPER
    menu          => MENU
end

function register_key_callback(handler, wnd::Window)
    wrapper(::GLFW.Window, key::GLFW.Key, scancode::Integer, action::GLFW.Action, modifiers::Integer) = handler(wnd, Key(key), scancode, InputAction(action), ModifierKey(modifiers))
    GLFW.SetKeyCallback(wnd.handle, wrapper)
    wnd
end
function register_text_callback(handler, wnd::Window)
    wrapper(::GLFW.Window, char::Char) = handler(wnd, char)
    GLFW.SetCharCallback(wnd.handle, wrapper)
    wnd
end

export getkeyname
"""`getkeyname(named::Key, scancode::Integer)` attempts to retrieve a key's human readable name. If `named` is not `Key(nothing)`,
the name will be reminiscent of the named key. Otherwise, attempts to retrieve the key identified by `scancode`."""
getkeyname(named::Key, scancode::Integer) = GLFW.GetKeyName(named.wrapped, scancode)


text:
    language_codes = ("cn", "de", "el", "en", "es", "fr", "it", "pt", "ru")

    boolean( chance_of_getting_true=50)= rand(1:100) <= chance_of_getting_true

    null_boolean()=Dict( 0=> "none", 1=> true, -1=> false)[rand(-1:1)]

    #md5() = hexdigest("md5", "$(rand())")

    #sha1() = hexdigest("sha1", "$(rand())")

    #sha256() = hexdigest("sha256", "$(rand())")

    country_code()= executor(data["en"]["faker"]["address"]["country_code"])

    language_code() = language_codes[rand(1:length(language_codes))]

    locale()="$(language_code())_$(country_code())"

    #=uuid4()==#

    password( longitud=10, special_caracteres=true, digitos=true, upper_case=true, lower_case=true)=
       ( caracteres = [];
        for x=1:longitud
             special_caracteres==true && (push!(caracteres, "$(rand('!':'+'))"))
             digitos==true && (push!(caracteres, "$(rand(0:9))"))
             upper_case==true && (push!(caracteres, "$(rand('A':'Z'))"))
             lower_case==true && (push!(caracteres, "$(rand('a':'z'))"))
        end;

        for x=1:longitud
            ini = rand(1:length(caracteres))
            fin = rand(1:length(caracteres))
            intermedio = caracteres[ini]
            caracteres[ini] = caracteres[fin]
            caracteres[fin] = intermedio
        end;

       join(caracteres,""); )


text:
function solve()
    n = parse(Int, readline())
    a = [parse(Int, x) for x in split(readline())]

    dp = zeros(Int, n)
    dp[2] = max(a[1], a[2])
    oddsum = a[1]
    for i in 3:n
        if i % 2 == 0
            dp[i] = max(oddsum, dp[i-2] + a[i])
        else
            dp[i] = max(dp[i-1], dp[i-2] + a[i])
            oddsum += a[i]
        end
    end
    dp[n]
end

println(solve())

max_stars_repo_name: aishikawa/atcoder-julia

max_issues_repo_name: aishikawa/atcoder-julia

max_forks_repo_name: aishikawa/atcoder-julia


text:
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule gh_cli_jll
using Base
using Base: UUID
import JLLWrappers

JLLWrappers.@generate_main_file_header("gh_cli")
JLLWrappers.@generate_main_file("gh_cli", UUID("5d31d589-30fb-542f-b82d-10325e863e38"))
end  # module gh_cli_jll


text:
using Documenter, Ansillary

DocMeta.setdocmeta!(Ansillary, :DocTestSetup, :(using Ansillary))
DocMeta.setdocmeta!(
    Ansillary.Cursor,
    :DocTestSetup,
    :(using Ansillary; using Ansillary.Cursor),
)
DocMeta.setdocmeta!(
    Ansillary.Inputs,
    :DocTestSetup,
    :(using Ansillary; using Ansillary.Inputs),
)
DocMeta.setdocmeta!(
    Ansillary.Screen,
    :DocTestSetup,
    :(using Ansillary; using Ansillary.Screen),
)

makedocs(;
    modules = [Ansillary],
    format = Documenter.HTML(),
    pages = ["Home" => "index.md"],
    repo = "https://gitlab.com/seamsay/Ansillary.jl/blob/{commit}{path}#L{line}",
    sitename = "Ansillary.jl",
    authors = "Sean Marshallsay",
)


text:
using Latexify, Test

# Latexify.@generate_test latexify(:(x = [1, 2]), env=:bracket)
@test latexify(:(x = [1, 2]), env = :bracket) == replace(
raw"\[
x = \left[
\begin{array}{c}
1 \\
2 \\
\end{array}
\right]\]
", "\r\n"=>"\n")

# Latexify.@generate_test latexify([1, 2], env=:bracket)
@test latexify([1, 2], env = :bracket) == replace(
raw"\[
\left[
\begin{array}{c}
1 \\
2 \\
\end{array}
\right]\]
", "\r\n"=>"\n")


text:
#
# Groups
#

immutable Group{T}
    names::T
    offsets::Vector{RelOffset}
end

immutable LinkInfo
    version::UInt8
    flags::UInt8
    fractal_heap_address::RelOffset
    name_index_btree::RelOffset
end
define_packed(LinkInfo)

LinkInfo() = LinkInfo(0, 0, UNDEFINED_ADDRESS, UNDEFINED_ADDRESS)

@enum(CharacterSet,
      CSET_ASCII,
      CSET_UTF8)

const LM_CREATION_ORDER_PRESENT = UInt8(2^2)
const LM_LINK_TYPE_FIELD_PRESENT = UInt8(2^3)
const LM_LINK_NAME_CHARACTER_SET_FIELD_PRESENT = UInt8(2^4)

function read_link(io::IO)
    # Version
    version = read(io, UInt8)
    version == 1 || throw(UnsupportedVersionException())

    # Flags
    flags = read(io, UInt8)

    if (flags & LM_LINK_TYPE_FIELD_PRESENT) != 0
        read(io, UInt8) == 0 || throw(UnsupportedFeatureException())
    end

    if (flags & LM_CREATION_ORDER_PRESENT) != 0
        skip(io, 8)
    end

    # Link name character set
    cset = CSET_ASCII
    if (flags & LM_LINK_NAME_CHARACTER_SET_FIELD_PRESENT) != 0
        cset_byte = read(io, UInt8)
        cset = CharacterSet(cset_byte)
    end

    sz = read_size(io, flags)  # Size
    name = read(io, UInt8, sz) # Link name
    target = read(io, RelOffset)  # Link information

    (String(name), target)
end

sizeof_link(name::String) =
    3 + size_size(sizeof(name)) + sizeof(name) + sizeof(RelOffset)

function write_link(io::IO, name::String, target::RelOffset)
    # Version
    write(io, UInt8(1))

    # Flags
    flags = size_flag(sizeof(name))
    flags |= LM_LINK_NAME_CHARACTER_SET_FIELD_PRESENT
    write(io, flags::UInt8)

    # Link name character set
    write(io, UInt8(CSET_UTF8))

    # Length of link name
    write_size(io, sizeof(name))

    # Link name
    write(io, name)

    # Link target
    write(io, target::RelOffset)
end

const OH_ATTRIBUTE_CREATION_ORDER_TRACKED = 2^2
const OH_ATTRIBUTE_CREATION_ORDER_INDEXED = 2^3
const OH_ATTRIBUTE_PHASE_CHANGE_VALUES_STORED = 2^4
const OH_TIMES_STORED = 2^5

function payload_size(group::Group)
    # 2 extra headers for link info and group info
    nheaders = length(group.names) + 2
    sz = sizeof(LinkInfo) + 2 + nheaders * sizeof(HeaderMessage)
    for name in group.names
        sz += sizeof_link(name)
    end
    sz
end

function Base.read(io::IO, ::Type{Group})
    cio = begin_checksum(io)
    sz = read_obj_start(cio)
    pmax = position(cio) + sz

    # Messages
    names = String[]
    offsets = RelOffset[]
    while position(cio) < pmax
        msg = read(cio, HeaderMessage)
        endpos = position(cio) + msg.size
        if msg.msg_type == HM_LINK_INFO
            link_info = read(cio, LinkInfo)
            link_info.fractal_heap_address == UNDEFINED_ADDRESS || throw(UnsupportedFeatureException())
        elseif msg.msg_type == HM_GROUP_INFO
            # This message doesn't help us much, so we ignore it for now
        elseif msg.msg_type == HM_LINK_MESSAGE
            name, offset = read_link(cio)
            push!(names, name)
            push!(offsets, offset)
        elseif (msg.flags & 2^3) != 0
            throw(UnsupportedFeatureException())
        elseif msg.msg_type == HM_NIL
            break
        end
        seek(cio, endpos)
    end
    seek(cio, pmax)

    # Checksum
    end_checksum(cio) == read(io, UInt32) || throw(InvalidDataException())

    Group(names, offsets)
end

function Base.write(io::IO, group::Group)
    psz = payload_size(group)
    sz = sizeof(ObjectStart) + size_size(psz) + psz + 4

    cio = begin_checksum(io, sz - 4)

    # Object header
    write(cio, ObjectStart(size_flag(psz)))
    write_size(cio, psz)
    x = position(cio)

    # Link info message
    write(cio, HeaderMessage(HM_LINK_INFO, sizeof(LinkInfo), 0))
    write(cio, LinkInfo())

    # Group info message
    write(cio, HeaderMessage(HM_GROUP_INFO, 2, 0))
    write(cio, UInt16(0))

    # Datatypes
    for i = 1:length(group.names)
        write(cio, HeaderMessage(HM_LINK_MESSAGE, sizeof_link(group.names[i]), 0))
        write_link(io, group.names[i], group.offsets[i])
    end

    # Checksum
    write(io, end_checksum(cio))
end


text:
using Test
import CryptoGroups: ECGroup, Hash, specialize, value, ROPRG
import CryptoGroups

tobig(x) = parse(BigInt, bytes2hex(reverse(x)), base=16)
interpret(::Type{BigInt}, x::Vector{UInt8}) = tobig(reverse(x))

interpret(::Type{Vector{UInt8}}, x::Integer) = reverse(reinterpret(UInt8, [x]))

function interpret(::Type{T}, x::AbstractString) where T

    if mod(length(x), 2) == 1
        x = "0" * x
    end

    bytes = hex2bytes(x)

    return interpret(T, bytes)
end

function leaf(x::Vector{UInt8})

    N = UInt32(length(x))

    LEAF = UInt8(1)

    Nbin = interpret(Vector{UInt8}, N)
    bin = UInt8[LEAF, Nbin..., x...]

    return bin
end

leaf(x::String) = leaf(Vector{UInt8}(x))

### Let's make the setup complete. From repo I ahve a following public parameters:
nr = 100
rohash = Hash("sha256")
prghash = Hash("sha256")

ρ = hex2bytes("355806458d6cd42655a52be242705c8e824584ccdb6b1c016cad36c591413de4")

# Need to unmarchal this into numbers

# This one I need to validate in ShuffleProofs.jl
#group_spec = "com.verificatum.arithm.ECqPGroup(P-256)::00000000020100000020636f6d2e766572696669636174756d2e61726974686d2e4543715047726f75700100000005502d323536"

h_str = "((760858b410b6fd5b5329457488f93eefd76f74753fc018a88a04e0d1015ccced, 750609534db7741d4ffd1f721dfca0cb3a190fba73ad71652999b6846ff6cc6e),(1bb070702fd72beb7d1d019c46bd55db16b510fcaf56ad1cf5d8f2ab46e47703, 017b045263708a3a42b81c67f2aeb0750b90693d7f177f40bb0ab71aaca2a7c7),(cca2a9b54997b340951ff8a80caffd332fc2d18cdbf10b29863960ead8754297, 2536dab68d208a689845b597bfa1cfd06ae859d381babf4afefbc49893dc55de),(19c089238d119fb04034c61481f0032cb9746b569e4ce6fdf9f8bfb019b9c300, 2737321900c4be759486508e4bec21e1850792bbbc98bc0207b992079a46c4ea),(150beafe47a388cbf6b7b62af3de801cf5f39b6c2aa07df15a14870195325d66, 4f0d59a61036e071600050a896a7206bd660b675793ae0bfefcc594157821fa9),(58d18ce2c66aedd896031d6cd791eed6cbb4fe38c805971e465ea44ff436ad, 5e93996474cf43b5f2e02c077334d2ac16120385b67f193d26dd4748252aaeb2),(cb44deb0a87c8154c7f49a3d128c60bf32825e391d09a1c604a2a8d35b110e58, 33d3316d12f822e047f48520ee774d558d3edbbfa9f5d782023f4aa22683873d),(9d378038b627c4ad3e97726bdd7189fdca7b964d842bb5b0b9eafccd84baced7, 1fb99e6bb8bdc5518dd1c8a06a925a9999e72bf74664ee9c2df76959af9b95ef),(5e6c2170c6176600bedb2efd5ef02a72a7561142754f29217b4ebfcc39fe725b, 3c1ff9ce2ac3516928cb2486e7426851ef7fd50d492907494bb275b11081d41a),(b161c3cb307823857de3c032b7c8570a93ceda3f4d8d53837907b517cba92ac9, 27736dfef353719a3d4d7b7a004e62a9e39a32ddff6a525b80b8023bfac469dd),)"

a = split(replace(h_str, "("=>"", ")"=>"", " "=>""), ",")[1:end-1]
numbers = interpret.(BigInt, a)
𝐡 = collect(zip(numbers[1:2:end], numbers[2:2:end]))

d = [ρ..., leaf("generators")...]
roprg = ROPRG(d, rohash, prghash)
prg = roprg(UInt8[]) # d is a better argument than x

G = specialize(ECGroup, CryptoGroups.Curve_P_192)

𝐡′ = rand(prg, CryptoGroups.Curve_P_256, 10; nr)

@test 𝐡 == 𝐡′

max_stars_repo_name: PeaceFounder/DiffieHellmanGroups

max_issues_repo_name: PeaceFounder/DiffieHellmanGroups

max_forks_repo_name: PeaceFounder/DiffieHellmanGroups


text:
#### Paper_Experiment_Predictions ####
# Run on a file and compute accuracy on a nFold cross validation
# Compute also the brier score and the logscore

if !isdefined(:DataAccess); include("../test/DataExamples.jl"); end;
if !isdefined(:TestFunctions); include("../test/test_functions.jl");end;
using TestFunctions
using DataExamples

@test function()
####### Data and Training Parameters #######
### Setting the Dataset ###
#= Datasets available with get_Waveform and get_BreastCancer=#
(X_data,y_data,DatasetName) = get_BreastCancer()
(nSamples,nFeatures) = size(X_data);
nFold = 10; #Chose the number of folds
fold_separation = collect(1:nSamples÷nFold:nSamples+1) #Separate the data in nFold

### Setting results output ###
doTime = true #Compute time needed for training
doAccuracy = true #Compute Accuracy
doBrierScore = true #Compute BrierScore
doLogScore = false #Compute LogScore
doWrite = false #Write results in appropriate folder
ShowIntResults = false #Show intermediate time, and results for each fold

### Training Parameters and Hyperparameters###
MaxIter = 3000 #Maximum number of iterations for every algorithm
main_param = DefaultParameters(); main_param["nFeatures"] = nFeatures; main_param["nSamples"] = nSamples
main_param["ϵ"] = 1e-5 #Convergence criterium;
main_param["M"] = min.(100,floor(Int64,0.2*nSamples));main_param["Kernel"] = "rbf"
main_param["Θ"] = 5.0 #Hyperparameter of the kernel
main_param["BatchSize"] = 10; main_param["Verbose"] = false;
main_param["Window"] = floor(Int64,sqrt.(nSamples)/main_param["BatchSize"])
println("Smoothing window of $(main_param["Window"])")
#### Creating the Model ####
#BSVM Parameters (Stochastic is for the Stochastic version, Sparse is with induing points and ALR is adaptative learning rate)
SBSVMParam = BSVMParameters(NonLinear=true,Stochastic=true,Sparse=true,ALR=true,Autotuning=false,main_param=main_param)
Model = TestingModel("SBSVM",DatasetName,"Prediction","BSVM",SBSVMParam)

writing_order = Array{String,1}();                    if doTime; push!(writing_order,"time"); end;
if doAccuracy; push!(writing_order,"accuracy"); end;  if doBrierScore; push!(writing_order,"brierscore"); end;
if doLogScore; push!(writing_order,"logscore"); end;
#Initialize the results storage
if doTime;        Model.Results["time"]       = Array{Float64,1}();end; if doAccuracy;    Model.Results["accuracy"]   = Array{Float64,1}();end;
if doBrierScore;  Model.Results["brierscore"] = Array{Float64,1}();end; if doLogScore;    Model.Results["logscore"]   = Array{Float64,1}();end;

###### Training  Model ######
println("Running BSVM on $(Model.DatasetName) dataset : $nSamples points in $nFeatures dimensions")
for i in 1:nFold #Run over all folds of the data
  if ShowIntResults
    println("#### Fold number $i/$nFold ###")
  end
  #Separating Data
  X_test = X_data[fold_separation[i]:(fold_separation[i+1])-1,:]
  y_test = y_data[fold_separation[i]:(fold_separation[i+1])-1]
  X = X_data[vcat(collect(1:fold_separation[i]-1),collect(fold_separation[i+1]:nSamples)),:]
  y = y_data[vcat(collect(1:fold_separation[i]-1),collect(fold_separation[i+1]:nSamples))]
  #Add Data to the Model
  CreateModel(Model,X,y)
  #Train the Model
  time = TrainModel(Model,MaxIter)
  if ShowIntResults
    println("$(Model.MethodName) : Time  = $time")
  end
  if doTime; push!(Model.Results["time"],time); end;
  #Run the tests on the last fold of data
  RunTests(Model,X_test,y_test,accuracy=doAccuracy,brierscore=doBrierScore,logscore=doLogScore)
end

##### Process the results from the k-fold ####
ProcessResults(Model,writing_order) #Compute mean and std deviation
PrintResults(Model.Results["allresults"],Model.MethodName,writing_order) #Print the Results in the end
if doWrite
  top_fold = "data";
  if !isdir(top_fold); mkdir(top_fold); end;
  WriteResults(Model,top_fold) #Write the results in an adapted format into a folder
end

return true
end #end of testing


text:
@testset "UC With DC - PF" begin
    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range; parameters = false)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalUnitCommitment, PM.DCPlosslessForm, sys5b_uc, time_range; parameters = false);
    @test !(:params in keys(ps_model.JuMPmodel.ext))
    @test JuMP.num_variables(ps_model.JuMPmodel) == 480
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 504
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 96
end

@testset "UC With AC - PF" begin
    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range; parameters = false)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalUnitCommitment, PM.StandardACPForm, sys5b_uc, time_range; parameters = false);
    @test !(:params in keys(ps_model.JuMPmodel.ext))
    @test JuMP.num_variables(ps_model.JuMPmodel) == 600
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 624
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 96
end

@testset "Dispatch With DC - PF" begin
    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalDispatch, PM.DCPlosslessForm, sys5b_uc, time_range);
    @test JuMP.num_variables(ps_model.JuMPmodel) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0

    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range; parameters = false)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalDispatch, PM.DCPlosslessForm, sys5b_uc, time_range; parameters = false)
    @test !(:params in keys(ps_model.JuMPmodel.ext))
    @test JuMP.num_variables(ps_model.JuMPmodel) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0
    end

@testset "Dispatch With AC - PF" begin
    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalDispatch, PM.StandardACPForm, sys5b_uc, time_range);
    @test JuMP.num_variables(ps_model.JuMPmodel) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0

    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range; parameters = false)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalDispatch, PM.StandardACPForm, sys5b_uc, time_range; parameters = false)
    @test !(:params in keys(ps_model.JuMPmodel.ext))
    @test JuMP.num_variables(ps_model.JuMPmodel) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0
    end

@testset "Dispatch No-Minimum With DC - PF" begin
    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalDispatchNoMin, PM.DCPlosslessForm, sys5b_uc, time_range);
    @test JuMP.num_variables(ps_model.JuMPmodel) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0

    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range; parameters = false)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalDispatchNoMin, PM.DCPlosslessForm, sys5b_uc, time_range; parameters = false)
    @test !(:params in keys(ps_model.JuMPmodel.ext))
    @test JuMP.num_variables(ps_model.JuMPmodel) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0
end

@testset "Dispatch No-Minimum With AC - PF" begin
    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalDispatchNoMin, PM.StandardACPForm, sys5b_uc, time_range);
    @test JuMP.num_variables(ps_model.JuMPmodel) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0

    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range; parameters = false)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalDispatchNoMin, PM.StandardACPForm, sys5b_uc, time_range; parameters = false);
    @test !(:params in keys(ps_model.JuMPmodel.ext))
    @test JuMP.num_variables(ps_model.JuMPmodel) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0
end

@testset "Dispatch No-Minimum With DC - PF" begin
    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalDispatchNoMin, PM.DCPlosslessForm, sys5b_uc, time_range);
    @test JuMP.num_variables(ps_model.JuMPmodel) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0

    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range; parameters = false)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalDispatchNoMin, PM.DCPlosslessForm, sys5b_uc, time_range; parameters = false)
    @test !(:params in keys(ps_model.JuMPmodel.ext))
    @test JuMP.num_variables(ps_model.JuMPmodel) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0
end

@testset "Ramp Limited Dispatch With AC - PF" begin
    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalRampLimited, PM.StandardACPForm, sys5b_uc, time_range);
    @test JuMP.num_variables(ps_model.JuMPmodel) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 192
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0

    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range; parameters = false)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalRampLimited, PM.StandardACPForm, sys5b_uc, time_range; parameters = false)
    @test !(:params in keys(ps_model.JuMPmodel.ext))
    @test JuMP.num_variables(ps_model.JuMPmodel) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 240
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 192
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0
end

@testset "Ramp Limited Dispatch With DC - PF" begin
    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalRampLimited, PM.DCPlosslessForm, sys5b_uc, time_range);
    @test JuMP.num_variables(ps_model.JuMPmodel) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 192
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0

    ps_model = PSI._canonical_model_init(bus_numbers, nothing, PM.AbstractPowerFormulation, time_range; parameters = false)
    PSI.construct_device!(ps_model, PSY.ThermalGen, PSI.ThermalRampLimited, PM.DCPlosslessForm, sys5b_uc, time_range; parameters = false)
    @test !(:params in keys(ps_model.JuMPmodel.ext))
    @test JuMP.num_variables(ps_model.JuMPmodel) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.Interval{Float64}) == 120
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.LessThan{Float64}) == 192
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.GreaterThan{Float64}) == 0
    @test JuMP.num_constraints(ps_model.JuMPmodel,GenericAffExpr{Float64,VariableRef},MOI.EqualTo{Float64}) == 0
end


text:
const ascii_signs = [0b100_000_000 0b000_100_000 0b000_000_100;
                     0b010_000_000 0b000_010_000 0b000_000_010;
                     0b001_000_000 0b000_001_000 0b000_000_001]

const ascii_lookup = Dict{UInt16,Char}()
const ascii_decode = Array(Char, 512)
ascii_lookup[0b101_000_000] = '"'
ascii_lookup[0b111_111_111] = '@'
ascii_lookup[0b011_110_011] = '$'
ascii_lookup[0b010_000_000] = '\''
ascii_lookup[0b010_100_010] = '('
ascii_lookup[0b010_001_010] = ')'
ascii_lookup[0b000_010_000] = '*'
ascii_lookup[0b010_111_010] = '+'
ascii_lookup[0b000_010_010] = ','
ascii_lookup[0b000_100_100] = ','
ascii_lookup[0b000_001_001] = ','
ascii_lookup[0b000_111_000] = '-'
ascii_lookup[0b000_000_010] = '.'
ascii_lookup[0b000_000_100] = '.'
ascii_lookup[0b000_000_001] = '.'
ascii_lookup[0b001_010_100] = '/'
ascii_lookup[0b010_100_000] = '/'
ascii_lookup[0b001_010_110] = '/'
ascii_lookup[0b011_010_010] = '/'
ascii_lookup[0b001_010_010] = '/'
ascii_lookup[0b110_010_111] = '1'
ascii_lookup[0b111_010_100] = '7'
ascii_lookup[0b010_000_010] = ':'
ascii_lookup[0b111_000_111] = '='
ascii_lookup[0b010_111_101] = 'A'
ascii_lookup[0b011_100_011] = 'C'
ascii_lookup[0b110_101_110] = 'D'
ascii_lookup[0b111_110_100] = 'F'
ascii_lookup[0b011_101_011] = 'G'
ascii_lookup[0b101_111_101] = 'H'
ascii_lookup[0b111_010_111] = 'I'
ascii_lookup[0b011_001_111] = 'J'
ascii_lookup[0b101_110_101] = 'K'
ascii_lookup[0b100_100_111] = 'L'
ascii_lookup[0b111_111_101] = 'M'
ascii_lookup[0b101_101_101] = 'N'
ascii_lookup[0b111_101_111] = 'O'
ascii_lookup[0b111_111_100] = 'P'
ascii_lookup[0b111_010_010] = 'T'
ascii_lookup[0b101_101_111] = 'U'
ascii_lookup[0b101_101_010] = 'V'
ascii_lookup[0b101_111_111] = 'W'
ascii_lookup[0b101_010_101] = 'X'
ascii_lookup[0b101_010_010] = 'Y'
ascii_lookup[0b110_100_110] = '['
ascii_lookup[0b010_001_000] = '\\'
ascii_lookup[0b100_010_001] = '\\'
ascii_lookup[0b110_010_010] = '\\'
ascii_lookup[0b100_010_011] = '\\'
ascii_lookup[0b100_010_010] = '\\'
ascii_lookup[0b011_001_011] = ']'
ascii_lookup[0b010_101_000] = '^'
ascii_lookup[0b000_000_111] = '_'
ascii_lookup[0b100_000_000] = '`'
ascii_lookup[0b000_111_111] = 'a'
ascii_lookup[0b100_111_111] = 'b'
ascii_lookup[0b001_111_111] = 'd'
ascii_lookup[0b001_111_010] = 'f'
ascii_lookup[0b100_111_101] = 'h'
ascii_lookup[0b100_101_101] = 'k'
ascii_lookup[0b110_010_011] = 'l'
ascii_lookup[0b000_111_101] = 'n'
ascii_lookup[0b000_111_100] = 'r'
ascii_lookup[0b000_101_111] = 'u'
ascii_lookup[0b000_101_010] = 'v'
ascii_lookup[0b011_110_011] = '{'
ascii_lookup[0b010_010_010] = '|'
ascii_lookup[0b100_100_100] = '|'
ascii_lookup[0b001_001_001] = '|'
ascii_lookup[0b110_011_110] = '}'

ascii_decode[0b1] = ' '
for i in 1:511
    min_dist = typemax(Int)
    min_char = ' '
    for (k, v) in ascii_lookup
        cur_dist = count_ones(UInt16(i) $ k)
        if cur_dist < min_dist
            min_dist = cur_dist
            min_char = v
        end
    end
    min_char
    ascii_decode[i + 1] = min_char
end

"""
As the name suggests the `AsciiCanvas` only uses
ASCII characters to draw it's content. Naturally,
it doesn't look quite as nice as the Unicode-based
ones. However, in some situations it might yield
better results. Printing plots to a file is one
of those situations.

The AsciiCanvas is best utilized in combination
with `lineplot`.
For `scatterplot` we suggest to use the `DotCanvas`
instead.
"""
type AsciiCanvas <: LookupCanvas
    grid::Array{UInt16,2}
    colors::Array{UInt8,2}
    pixel_width::Int
    pixel_height::Int
    origin_x::Float64
    origin_y::Float64
    width::Float64
    height::Float64
end

@inline x_pixel_per_char(::Type{AsciiCanvas}) = 3
@inline y_pixel_per_char(::Type{AsciiCanvas}) = 3

@inline lookup_encode(c::AsciiCanvas) = ascii_signs
@inline lookup_decode(c::AsciiCanvas) = ascii_decode

function AsciiCanvas(args...; nargs...)
    CreateLookupCanvas(AsciiCanvas, args...; nargs...)
end


text:
@testset "Testing Utils" begin
    @testset "Testing Always" begin
        f = CachedArrays.Always(10)
        @test f() == 10
        @test f(1) == 10
        @test f(1, "hello") == 10
        @test f(; g = 5) == 10
        @test f(1; h = "hello") == 10

        @test CachedArrays.donothing() === nothing
        @test CachedArrays.alwaysfalse() == false
    end

    # @spinlock
    @testset "Testing @spinlock" begin
        a = Threads.SpinLock()
        b = Threads.SpinLock()
        c = Threads.SpinLock()

        # Test that locks are acquired.
        @test islocked(a) == false
        @test islocked(b) == false
        @test islocked(c) == false
        CachedArrays.@spinlock a b c begin
            @test islocked(a) == true
            @test islocked(b) == true
            @test islocked(c) == true
        end
        @test islocked(a) == false
        @test islocked(b) == false
        @test islocked(c) == false

        # Throw an error and make sure we recover
        try
            CachedArrays.@spinlock a b c begin
                @test islocked(a) == true
                @test islocked(b) == true
                @test islocked(c) == true
                throw(AssertionError())
            end
        catch e
            !isa(e, AssertionError) && rethrow(e)
        end
        @test islocked(a) == false
        @test islocked(b) == false
        @test islocked(c) == false

        # nofail versions
        CachedArrays.@spinlock_nofail a b c begin
            @test islocked(a) == true
            @test islocked(b) == true
            @test islocked(c) == true
        end
        @test islocked(a) == false
        @test islocked(b) == false
        @test islocked(c) == false

        try
            CachedArrays.@spinlock_nofail a b c begin
                @test islocked(a) == true
                @test islocked(b) == true
                @test islocked(c) == true
                throw(AssertionError())
            end
        catch e
            !isa(e, AssertionError) && rethrow(e)
        end
        @test islocked(a) == true
        @test islocked(b) == true
        @test islocked(c) == true

        unlock(a)
        unlock(b)
        unlock(c)
    end

    @testset "Testing @checknothing" begin
        # This is the "nothing" case
        x = 100
        v = CachedArrays.@checknothing CachedArrays.donothing() (x = 5)
        @test v === nothing
        @test x == 5

        # This is the "not nothing" case
        x = 100
        v = CachedArrays.@checknothing 10 (x = 5)
        @test v === 10
        @test x == 100
    end

    @testset "Testing findT" begin
        x = Int(1)
        y = Float32(10)
        findT = CachedArrays.findT
        @test findT(Int, (x, y)) == 1
        @test findT(Int, (y, x)) == 1
        @test findT(Float32, (x, y)) == 10
        @test findT(Float32, (y, x)) == 10
        @test findT(Float64, (y, x)) === nothing

        @test findT(Integer, 1) == 1
        @test findT(Integer, Float32(10)) === nothing
        @test findT(Integer, ("nothing", 1)) == 1
        @test findT(Int, Base.Broadcast.Broadcasted(+, (x, y))) == 1

        # Make sure this works on arrays
        x = [1,2,3]
        @test findT(Vector{Int}, x) == x
        @test findT(Vector{Int}, view(x, 1:2)) == x
    end

    @testset "Testing `atomic_ptr_xchg`" begin
        a = Ref(Ptr{Int}())
        @test Int(a[]) == 0

        CachedArrays.atomic_ptr_xchg!(Base.unsafe_convert(Ptr{Ptr{Int}}, a), Ptr{Int}(1))
        @test Int(a[]) == 1
    end
end


text:
#Reference:http://nbviewer.jupyter.org/gist/genkuroki/b46b0a094ee232302d41780defaffd6e

import PyPlot # Juliaでmatplotlib.pyplotを使うためのパッケージ
plt = PyPlot # as plt の代わり

using PyCall # JuliaからPythonの任意のライブラリを使うためのパッケージ
animation = pyimport("matplotlib.animation") # as animation の代わり

# このノートブックでは imagemagick でGIF動画を作成し,
# ノートブック内にbase64エンコードして読み込んで表示する.
function displayfile(mimetype, filename)
    open(filename) do f
        base64text = base64encode(f)
        display("text/html", """<img src="data:$mimetype;base64,$base64text">""")
    end
end

fig,ax=plt.subplots()
ax[:set_xlim](-4.5,10.5)
ax[:set_ylim](-4.5,4.5)

b=0.8
x=10.0
y=3.0
times=200
srand(12345) # np.random.seed(12345) の代わり. 上のセルと同じ結果になるように挿入した.

function update(data) # defをfunctionに置き換えて, コロンを消した.
    u1 = rand()
    u2 = rand()
    global x, y
    x_old=x
    x = sqrt(-2*log(u1))*cos(2*pi*u2) + b*y
    ax[:plot]([x_old, x], [y, y], lw=1)
    y_old = y
    y = sqrt(-2*log(u1))*sin(2*pi*u2) + b*x
    ax[:plot]([x, x], [y_old, y], lw=1)
    ax[:set_title]("$data")
end # end を追加した.
ani=animation[:FuncAnimation](fig,update,frames=times,interval=100)
ani[:save]("output.gif", writer="imagemagick") # GIFファイルに出力

plt.clf() # ←必ずしも必要ない. 単に余計な表示を消すためのコード

displayfile("image/gif", "output.gif")

max_stars_repo_name: terasakisatoshi/juliaExer

max_issues_repo_name: terasakisatoshi/juliaExer

max_forks_repo_name: terasakisatoshi/juliaExer


text:
using Ensemblearn
using Test

include("util.jl")

function test_create_forest(min_score=0.8::AbstractFloat)
    # Get iris data
    x, y = get_iris_data()
    n = size(y, 1)

    # Create a RandomForest
    rf = RandomForest(50, 5)

    # Fit RandomForest
    fit!(rf, x, y)

    # Get predictions over x
    p = predict(rf, x)

    # Obtain tuples of (pred, actual)
    p_y = collect(zip(p, y))

    # Score as rate of hits (accuracy)
    score = sum(map(t -> t[1] == t[2], p_y)) / Float64(n)

    # Assert a minimum score on predictions
    @test score >= min_score

end

@testset "RunTestRandomForest" begin
    # Normal case
    test_create_forest()
end


text:
# Simple LL comb simulation
T_FWHM = 1.0ps
T_T0 = T_FWHM/(2*log(1+sqrt(2)))
β₂ = -0.013ps^2/m
γnl = 0.000032W/m
α = 1.75e-5/m
coupling = 1.75e-5
P_in= 55.6e-3W
FSR = 0.0182THz
L = 0.0119m
detuning = 0.0012
comb_LL = ToyModel(;betacoeff=[0.0/m, 0.0ps/m, β₂],
                    nonlinearcoeff=γnl,
                    linearloss=α,
                    power_in=P_in,
                    pulsetime=0.0ps,
                    length=L,
                    FSR=FSR,
                    detuning=detuning,
                    coupling=coupling)
prob_LL = build_problem(comb_LL, DynamicLL(); time_window=10.0ps, tpoints=2^12)
sol_LL = solve(prob_LL)


text:
struct RevisedAffineForm{N,T<:AbstractFloat}
    c::T
    ϵ::SVector{N,T}
    Δ::T
end

function RevisedAffineForm(
    c::T, ϵ::SVector{N,S}, Δ::R
) where {T<:AbstractFloat,N,S<:AbstractFloat,R<:AbstractFloat}
    Q = promote_type(T, S, R)
    return RevisedAffineForm(convert(Q, c), convert(SVector{N,Q}, ϵ), convert(Q, Δ))
end

function RevisedAffineForm(
    c::Interval{T}, ϵ::SVector{N,Interval{T}}, Δ::T
) where {N,T<:AbstractFloat}
    Δ = Δ ⊕₊ radius(c)
    @inbounds for ϵᵢ in ϵ
        Δ = Δ ⊕₊ radius(ϵᵢ)
    end
    return RevisedAffineForm(mid(c), mid.(ϵ), Δ)
end

RevisedAffineForm(c, ϵ, Δ) = RevisedAffineForm(float(c), SVector(float(ϵ)...), float(Δ))

function RevisedAffineForm(x::T, n::Int) where {T<:Real}
    TS = float(T)
    return RevisedAffineForm(convert(TS, x), SVector{n,TS}(zeros(TS, n)), zero(TS))
end

function RevisedAffineForm(x::Interval{T}, n::Int) where {T<:AbstractFloat}
    c, r = midpoint_radius(x)
    return RevisedAffineForm(c, SVector{n,T}(zeros(T, n)), r)
end

function ±(x::RevisedAffineForm, Δ::Real)
    Δ < 0 && throw(ArgumentError("cumulated error must be non-negative"))
    return RevisedAffineForm(x.c, x.ϵ, x.Δ ⊕₊ float(Δ))
end

############
# PRINTING #
############

function _lower(n::Int)
    idx = ('₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉')
    s = ""
    ds = reverse!(digits(n))
    for d in ds
        s *= idx[d + 1]
    end
    return s
end

function Base.show(io::IO, x::RevisedAffineForm{N}) where {N}
    print(io, x.c)
    names = isempty(config[:names]) ? ['ϵ' * _lower(i) for i in 1:N] : config[:names]
    @inbounds for (e, n) in zip(x.ϵ, names)
        iszero(e) && continue
        print(io, e > 0 ? " + " : " - ")
        print(io, abs(e), n)
    end
    x.Δ > 0 && print(io, " ± ", x.Δ)
    return nothing
end

############
# EQUALITY #
############
function ==(x::RevisedAffineForm{N}, y::RevisedAffineForm{N}) where {N}
    return x.c == y.c && x.ϵ == y.ϵ && x.Δ == y.Δ
end


text:
const Min_Max = NamedTuple{(:min, :max),Tuple{Float64,Float64}}
const From_To_Float = NamedTuple{(:from, :to),Tuple{Float64,Float64}}
const FromTo_ToFrom_Float = NamedTuple{(:from_to, :to_from),Tuple{Float64,Float64}}

"From http://www.pserc.cornell.edu/matpower/MATPOWER-manual.pdf Table B-4"
@enum GeneratorCostModel begin
    PIECEWISE_LINEAR = 1
    POLYNOMIAL = 2
end

@enum AngleUnit begin
    DEGREES
    RADIANS
end

@enum BusType begin
    ISOLATED
    PQ
    PV
    REF
    SLACK
end

@enum LoadModel begin
    ConstantImpedance #Z
    ConstantCurrent   #I
    ConstantPower     #P
end

"From https://www.eia.gov/survey/form/eia_923/instructions.pdf"
@enum PrimeMovers begin
    BA #Energy Storage, Battery
    BT #Turbines Used in a Binary Cycle (including those used for geothermal applications)
    CA #Combined-Cycle – Steam Part
    CC #Combined-Cycle - Aggregated Plant *augmentation of EIA
    CE #Energy Storage, Compressed Air
    CP #Energy Storage, Concentrated Solar Power
    CS #Combined-Cycle Single-Shaft Combustion turbine and steam turbine share a single generator
    CT #Combined-Cycle Combustion Turbine Part
    ES #Energy Storage, Other (Specify on Schedule 9, Comments)
    FC #Fuel Cell
    FW #Energy Storage, Flywheel
    GT #Combustion (Gas) Turbine (including jet engine design)
    HA #Hydrokinetic, Axial Flow Turbine
    HB #Hydrokinetic, Wave Buoy
    HK #Hydrokinetic, Other
    HY #Hydraulic Turbine (including turbines associated with delivery of water by pipeline)
    IC #Internal Combustion (diesel, piston, reciprocating) Engine
    PS #Energy Storage, Reversible Hydraulic Turbine (Pumped Storage)
    OT #Other – Specify on SCHEDULE 9.
    ST #Steam Turbine (including nuclear, geothermal and solar steam; does not include combined-cycle turbine)
    PVe #Photovoltaic *renaming from EIA PV to PVe to avoid conflict with BusType::PV
    WT #Wind Turbine, Onshore
    WS #Wind Turbine, Offshore
end

"AER Aggregated Fuel Code From https://www.eia.gov/survey/form/eia_923/instructions.pdf"
@enum ThermalFuels begin
    COAL #COL    #Anthracite Coal and Bituminous Coal
    WASTE_COAL #WOC    #Waste/Other Coal (includes anthracite culm, gob, fine coal, lignite waste, waste coal)
    DISTILLATE_FUEL_OIL #DFO #Distillate Fuel Oil (Diesel, No. 1, No. 2, and No. 4
    WASTE_OIL #WOO    #Waste Oil Kerosene and JetFuel Butane, Propane,
    PETROLEUM_COKE #PC  #Petroleum Coke
    RESIDUAL_FUEL_OIL    #RFO #Residual Fuel Oil (No. 5, No. 6 Fuel Oils, and Bunker Oil)
    NATURAL_GAS #NG    #Natural Gas
    OTHER_GAS #OOG    #Other Gas and blast furnace gas
    NUCLEAR #NUC #Nuclear Fission (Uranium, Plutonium, Thorium)
    AG_BIPRODUCT #ORW    #Agricultural Crop Byproducts/Straw/Energy Crops
    MUNICIPAL_WASTE #MLG    #Municipal Solid Waste – Biogenic component
    WOOD_WASTE #WWW     #Wood Waste Liquids excluding Black Liquor (BLQ) (Includes red liquor, sludge wood, spent sulfite liquor, and other wood-based liquids)
    GEOTHERMAL #GEO     #Geothermal
    OTHER #OTH     #Other
end

PS_MAX_LOG = parse(Int, get(ENV, "PS_MAX_LOG", "50"))
DEFAULT_BASE_MVA = 100.0

const POWER_SYSTEM_STRUCT_DESCRIPTOR_FILE =
    joinpath(dirname(pathof(PowerSystems)), "descriptors", "power_system_structs.json")


text:
module AutoML

using XGBoost
using MLBase

include("preprocess/preprocess.jl")
include("feature_engineer/feature_engineer.jl")
include("model/model.jl")
include("evaluation/evaluation.jl")

end # module


text:
include("ismv.jl")
include("lbv.jl")
include("pdf.jl")
include("sharp.jl")


text:
######################################################################
# Macros UTs
# -----
# Licensed under MIT License
module TestMacros
using Test
using KirUtil
import ..Helpers: testmultiply

struct Resource1
    open::Mutable{Bool}
end
Resource1() = Resource1(Mutable(true))
Base.close(res::Resource1) = res.open[] = false

struct Resource2 end
Base.close(::Resource2) = throw("closed")

function foo(n::Integer)
    @once n > 512 throw("triggered once")
    nothing
end

@testset "KirUtil Macros" begin
    @testset "@await" begin
        let t0 = time()
            @test @await(sleep(0.2), 42) == 42
            @test isapprox(time()-t0, 0.2, atol=0.05)
        end
    end

    @testset "@curry" begin
        @test(@curry(42, truncate=true, testmultiply(2.1)) == 88)
    end

    @testset "@once" begin
        @test foo(512) === nothing
        @test_throws "triggered once" foo(513)
        @test foo(514) === nothing
    end

    @testset "@sym_str" begin
        @test sym"foobar" === :foobar
        @test sym"hello, world!" === Symbol("hello, world!")
    end

    @testset "@with" begin
        @test begin
            res = Resource1()
            @with res begin end
            !res.open[]
        end

        @test_throws "closed" @with Resource2() begin end
        @test_throws "closed" @with res = Resource2() begin end
    end
end
end # module TestMacros


text:
"""
FISTA

"""
mutable struct FISTA <: FOSAlgorithm
    α::Float64
    direct::Bool
    options
end
FISTA(α=1.0; direct=false, kwargs...) = FISTA(α, direct, kwargs)

struct FISTAData{T1,T2} <: FOSSolverData
    t::Base.RefValue{Float64}
    y::Array{Float64,1}
    xold::Array{Float64,1}
    tmp1::Array{Float64,1}
    S1::T1
    S2::T2
end

function init_algorithm!(alg::FISTA, model::AbstractFOSModel)
    S1, S2, n, status_generator = get_sets_and_status(alg, model)
    data = FISTAData(Ref(1.0), zeros(n), zeros(n), Array{Float64,1}(undef, n), S1, S2)
    return data, status_generator
end

function Base.step(alg::FISTA, data::FISTAData, x, i, status::AbstractStatus, longstep=nothing)
    α,y,xold,tmp1,S1,S2 = alg.α,data.y,data.xold,data.tmp1,data.S1,data.S2
    t = data.t #Reference
    if i == 1 #TODO this is ugly initializing hack
        y .= x
    end
    # Relaxed projection onto S1
    prox!(tmp1, S1, y)
    addprojeq(longstep, tmp1, y)
    tmp1 .= α.*tmp1 .+ (1-α).*y
    # Relaxed projection onto S2
    xold .= x
    prox!(x, S2, tmp1)
    checkstatus(status, x)
    addprojineq(longstep, x, tmp1)

    told = t.x
    t.x = (1+sqrt(1+4*t.x^2))/2
    y .= x .+ (told-1)./(t.x).*(x .- xold)
    return
end

function getsol(::FISTA, data::FISTAData, x)
    tmp1,S1,S2 = data.tmp1,data.S1,data.S2
    tmp2 = similar(x)
    prox!(tmp1, S1, x)
    prox!(tmp2, S2, tmp1)
    return tmp2
end

support_longstep(::FISTA) = true
projections_per_step(::FISTA) = (1,1)


text:
### A Pluto.jl notebook ###
# v0.18.0

using Markdown
using InteractiveUtils

# ╔═╡ 6b1ad54f-61e4-490d-9032-7a557e8dc82f
md"""
## CHEME 5440/7770: Structural Analysis of the Urea Cycle Network (PS2)
"""

# ╔═╡ 7057c8e4-9e94-4a28-a885-07f5c96ebe39
html"""

Student name, Student name, Student name ... Student name

Smith School of Chemical and Biomolecular Engineering, Cornell University, Ithaca NY 14850

"""

# ╔═╡ 87a183bc-3857-4189-8103-18c46ff3245d
md"""
#### Build the stoichiometric array
"""

# ╔═╡ 5338451e-3c4b-4030-bbbb-42eaf4209a89
begin

	# fill me in
	# ...

end

# ╔═╡ 6970dab5-16bd-4898-b88d-723cb1b3d89e
md"""
#### Convex analysis: extreme pathways
"""

# ╔═╡ 97b0763d-dcab-4afa-b660-52e18b3d523f
begin

	# fill me in
	# ...

end

# ╔═╡ b473b17e-3bf5-4b6c-af24-fe57b5a7e7e9
md"""
#### Metabolite connectivity array (MCA)
"""

# ╔═╡ 999ae1fd-5341-4f66-9db2-dec53fa0cd49

# ╔═╡ b7e5d1a6-57ed-4d09-a039-a4bd12386367
md"""
#### Reaction connectivity array (RCA)
"""

# ╔═╡ 4520fc6e-7305-487e-924d-af22406e6d45
begin

	# fill me in ...
end

# ╔═╡ 267865de-1b5c-4579-861b-c6c46beb4739
function ingredients(path::String)

	# this is from the Julia source code (evalfile in base/loading.jl)
	# but with the modification that it returns the module instead of the last object
	name = Symbol("lib")
	m = Module(name)
	Core.eval(m,
        Expr(:toplevel,
             :(eval(x) = $(Expr(:core, :eval))($name, x)),
             :(include(x) = $(Expr(:top, :include))($name, x)),
             :(include(mapexpr::Function, x) = $(Expr(:top, :include))(mapexpr, $name, x)),
             :(include($path))))
	m
end

# ╔═╡ 67f5db98-88d0-11ec-27ac-b57538a166f4
begin
	# import some packages -
	using PlutoUI
	using PrettyTables
	using LinearAlgebra

	# setup paths -
	const _PATH_TO_NOTEBOOK = pwd()
	const _PATH_TO_SRC = joinpath(_PATH_TO_NOTEBOOK,"src")

	# load the PS2 code lib -
	lib = ingredients(joinpath(_PATH_TO_SRC, "Include.jl"));

	# return -
	nothing
end

# ╔═╡ ab2bcfd5-3ba7-4388-8a3c-2cb95fba989a
html"""
"""

# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
PrettyTables = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d"

[compat]
PlutoUI = "~0.7.34"
PrettyTables = "~1.3.1"
"""

# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised

julia_version = "1.7.1"
manifest_format = "2.0"

[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"

[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"

[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"

[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"

[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.0"

[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"

[[deps.Crayons]]
git-tree-sha1 = "249fe38abf76d48563e2f4556bebd215aa317e15"
uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
version = "4.1.1"

[[deps.DataAPI]]
git-tree-sha1 = "cc70b17275652eb47bc9e5f81635981f13cea5c8"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.9.0"

[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"

[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"

[[deps.Downloads]]
deps = ["ArgTools", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"

[[deps.FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"

[[deps.Formatting]]
deps = ["Printf"]
git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8"
uuid = "59287772-0a20-5a39-b81b-1366585eb4c0"
version = "0.4.2"

[[deps.Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.4"

[[deps.HypertextLiteral]]
git-tree-sha1 = "2b078b5a615c6c0396c77810d92ee8c6f470d238"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.3"

[[deps.IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "f7be53659ab06ddc986428d3a9dcc95f6fa6705a"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.2"

[[deps.InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"

[[deps.IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"

[[deps.JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.2"

[[deps.LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"

[[deps.LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"

[[deps.LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"

[[deps.LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"

[[deps.Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"

[[deps.LinearAlgebra]]
deps = ["Libdl", "libblastrampoline_jll"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"

[[deps.Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"

[[deps.Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"

[[deps.MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"

[[deps.Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"

[[deps.MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"

[[deps.NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"

[[deps.OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"

[[deps.Parsers]]
deps = ["Dates"]
git-tree-sha1 = "0b5cfbb704034b5b4c1869e36634438a047df065"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.2.1"

[[deps.Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"

[[deps.PlutoUI]]
deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "Markdown", "Random", "Reexport", "UUIDs"]
git-tree-sha1 = "8979e9802b4ac3d58c503a20f2824ad67f9074dd"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.34"

[[deps.PrettyTables]]
deps = ["Crayons", "Formatting", "Markdown", "Reexport", "Tables"]
git-tree-sha1 = "dfb54c4e414caa595a1f2ed759b160f5a3ddcba5"
uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d"
version = "1.3.1"

[[deps.Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"

[[deps.REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"

[[deps.Random]]
deps = ["SHA", "Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"

[[deps.Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"

[[deps.SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"

[[deps.Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"

[[deps.Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"

[[deps.SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"

[[deps.Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"

[[deps.TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"

[[deps.TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"

[[deps.Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"]
git-tree-sha1 = "bb1064c9a84c52e277f1096cf41434b675cd368b"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.6.1"

[[deps.Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"

[[deps.Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"

[[deps.UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"

[[deps.Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"

[[deps.Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"

[[deps.libblastrampoline_jll]]
deps = ["Artifacts", "Libdl", "OpenBLAS_jll"]
uuid = "8e850b90-86db-534c-a0d3-1478176c7d93"

[[deps.nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"

[[deps.p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
"""

# ╔═╡ Cell order:
# ╟─6b1ad54f-61e4-490d-9032-7a557e8dc82f
# ╟─7057c8e4-9e94-4a28-a885-07f5c96ebe39
# ╟─87a183bc-3857-4189-8103-18c46ff3245d
# ╠═5338451e-3c4b-4030-bbbb-42eaf4209a89
# ╠═6970dab5-16bd-4898-b88d-723cb1b3d89e
# ╠═97b0763d-dcab-4afa-b660-52e18b3d523f
# ╟─b473b17e-3bf5-4b6c-af24-fe57b5a7e7e9
# ╠═999ae1fd-5341-4f66-9db2-dec53fa0cd49
# ╟─b7e5d1a6-57ed-4d09-a039-a4bd12386367
# ╠═4520fc6e-7305-487e-924d-af22406e6d45
# ╠═67f5db98-88d0-11ec-27ac-b57538a166f4
# ╠═267865de-1b5c-4579-861b-c6c46beb4739
# ╟─ab2bcfd5-3ba7-4388-8a3c-2cb95fba989a
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002


text:
"""
Return the edges of a square graph
"""
function square_edges()
    head = [1, 1, 2, 3]
    tail = [2, 3, 4, 4]
    n = max(maximum(tail), maximum(head))
    edges = collect(zip(head, tail))
    return edges, n
end

mean(x) = sum(x)/length(x)

max_stars_repo_name: EQt/graphidx

max_issues_repo_name: EQt/graphidx

max_forks_repo_name: EQt/graphidx


text:
function read_hypergraph_label_names(dataname::String)
    names = String[]
    open("data/$dataname/label-names-$dataname.txt") do f
        for line in eachline(f)
            push!(names, line)
        end
    end
    return names
end

function read_hypergraph_labels(dataname::String)
    labels = Int64[]
    open("data/$dataname/node-labels-$dataname.txt") do f
        for line in eachline(f)
            push!(labels, parse(Int64, line))
        end
    end
    return labels
end

function read_hypergraph_edges(dataname::String, maxsize::Int64=25, minsize::Int64=2)
    E = Dict{Integer, Dict}()
    open("data/$dataname/hyperedges-$dataname.txt") do f
        for line in eachline(f)
            edge = [parse(Int64, v) for v in split(line, ',')]
            sort!(edge)
            if minsize <= length(edge) <= maxsize
                sz = length(edge)
                if !haskey(E, sz)
                    E[sz] = Dict{}()
                end
                E[sz][edge] = 1
            end
        end
    end
    return E
end

function read_hypergraph_data(dataname::String, maxsize::Int64=25, minsize::Int64=2, return_labels=true)
    E = read_hypergraph_edges(dataname, maxsize, minsize)

    n = maximum([maximum(e) for k in keys(E) for e in keys(E[k])])
    D = zeros(Int64, n)
    for (sz, edges) in E
        for (e, _) in edges
            D[e] .+= 1
        end
    end

    maxedges = maximum(keys(E))
    for k in 1:maxedges
        if !haskey(E, k)
            E[k] = Dict{}()
        end
    end

    N = 1:n

    if return_labels
        labels = read_hypergraph_labels(dataname)
        return hypergraph(N, E, D), labels[N]
    end

    return hypergraph(N, E, D)
end
;

function hyperedges(dataname::String)
    nverts = Int64[]
    open("$(dataname)-nverts.txt") do f
        for line in eachline(f); push!(nverts, parse(Int64, line)); end
    end
    simps = Int64[]
    open("$(dataname)-simplices.txt") do f
        for line in eachline(f); push!(simps, parse(Int64, line)); end
    end
    edges = Set{Set{Int64}}()
    ind = 0
    for nvert in nverts
        edge = Set{Int64}(simps[(ind + 1):(ind + nvert)])
        push!(edges, edge)
        ind += nvert
    end
    open("hyperedges-$(dataname).txt", "w") do f
        for edge in edges
            vedge = collect(edge)
            sort!(vedge)
            s = join(vedge, ",")
            write(f, "$s\n")
        end
    end
end

function read_stats_data(kmax=0)
    path = "data/SCC2016-with-abs/SCC2016/Data/authorPaperBiadj.txt"
    A = DelimitedFiles.readdlm(path, '\t', Int, '\n');

    n = size(A)[1]
    N = 1:n
    E = Dict()
    if kmax == 0
        kmax = maximum(sum(A, dims = 1))
    end
    E = Dict(k => Dict() for k ∈ 2:kmax)

    for j ∈ 1:size(A)[2]
        k = sum(A[:,j])
        if k >= 2
            if k <= kmax
                authors = findall(x -> (x ≈ 1), A[:,j])
                sort!(authors)
                E[k][authors] = get(E[k], authors, 0) + 1
            end
        end
    end

    H = HypergraphModularity.hypergraph(N, E, zero(N))
    HypergraphModularity.computeDegrees!(H);
    return H
end

function readTemporalData(name; kmax = 20, tmin = 0, tmax = 2050)

    prefix = "data/$name/$name"

    nverts    = open(prefix * "-nverts.txt") do f
        parse.(Int64, collect(eachline(f)))
    end

    simplices = open(prefix * "-simplices.txt") do f
        parse.(Int64, collect(eachline(f)))
    end

    times     = open(prefix * "-times.txt") do f
        parse.(Int64, collect(eachline(f)))
    end

    j = 1
    edges = []

    for i ∈ 1:length(nverts)
        e = simplices[j:(j+nverts[i]-1)]
        push!(edges, (e, nverts[i], times[i]))
        j += nverts[i]
    end

    subset = [e for e in edges if (length(e[1]) >= 2) & (e[3] ∈ tmin:tmax)];

    nodes = unique(collect(Iterators.flatten([e[1] for e in subset])))
    nodemap = Dict(zip(nodes, 1:length(nodes)));

    function recode(e)
        return [[nodemap[i] for i in e[1]], e[2], e[3]]
    end

    subset = [recode(e) for e in subset];

    E = Dict(k => Dict() for k ∈ 2:kmax)

    for e in subset
        sort!(e[1])
        if e[2] ∈ keys(E)
            E[e[2]][e[1]] = get(E[e[2]], e[1], 0) + 1
        end
    end

    H = HypergraphModularity.hypergraph(1:length(nodes), E, [0])
    HypergraphModularity.computeDegrees!(H);

    return H
end

max_stars_repo_name: PhilChodrow/HypergraphModularity

max_issues_repo_name: PhilChodrow/HypergraphModularity

max_forks_repo_name: PhilChodrow/HypergraphModularity