text:
module GLUT

import GetC.@getCFun

include("../deps/deps.jl")
@osx? (libglut = "/System/Library/Frameworks/GLUT.framework/GLUT") : nothing

@getCFun libglut glutInit glutInit(pargc::Ptr{Int32}, argv::Ptr{Ptr{Uint8}})::Void
glutInit() = glutInit(convert(Ptr{Int32},pointer([1])), ["a"])
export glutInit

@getCFun libglut glutInitWindowPosition glutInitWindowPosition(x::Int32, y::Int32)::Void
export glutInitWindowPosition
@getCFun libglut glutInitWindowSize glutInitWindowSize(width::Int32, height::Int32)::Void
export glutInitWindowSize
@getCFun libglut glutInitDisplayMode glutInitDisplayMode(displayMode::Uint32)::Void
export glutInitDisplayMode
@getCFun libglut glutInitDisplayString glutInitDisplayString(displayMode::Ptr{Uint8})::Void
export glutInitDisplayString

@getCFun libglut glutMainLoop glutMainLoop()::Void
export glutMainLoop

@getCFun libglut glutCreateWindow glutCreateWindow(title::Ptr{Uint8})::Int32
export glutCreateWindow
@getCFun libglut glutCreateSubWindow glutCreateSubWindow(window::Int32, x::Int32, y::Int32, width::Int32, height::Int32)::Int32
export glutCreateSubWindow
@getCFun libglut glutDestroyWindow glutDestroyWindow(window::Int32)::Void
export glutDestroyWindow
@getCFun libglut glutSetWindow glutSetWindow(window::Int32)::Void
export glutSetWindow
@getCFun libglut glutGetWindow glutGetWindow()::Int32
export glutGetWindow
@getCFun libglut glutSetWindowTitle glutSetWindowTitle(title::Ptr{Uint8})::Void
export glutSetWindowTitle
@getCFun libglut glutSetIconTitle glutSetIconTitle(title::Ptr{Uint8})::Void
export glutSetIconTitle
@getCFun libglut glutReshapeWindow glutReshapeWindow(width::Int32, height::Int32)::Void
export glutReshapeWindow
@getCFun libglut glutPositionWindow glutPositionWindow(x::Int32, y::Int32)::Void
export glutPositionWindow
@getCFun libglut glutShowWindow glutShowWindow()::Void
export glutShowWindow
@getCFun libglut glutHideWindow glutHideWindow()::Void
export glutHideWindow
@getCFun libglut glutIconifyWindow glutIconifyWindow()::Void
export glutIconifyWindow
@getCFun libglut glutPushWindow glutPushWindow()::Void
export glutPushWindow
@getCFun libglut glutPopWindow glutPopWindow()::Void
export glutPopWindow
@getCFun libglut glutFullScreen glutFullScreen()::Void
export glutFullScreen

@getCFun libglut glutPostWindowRedisplay glutPostWindowRedisplay(window::Int32)::Void
export glutPostWindowRedisplay
@getCFun libglut glutPostRedisplay glutPostRedisplay()::Void
export glutPostRedisplay
@getCFun libglut glutSwapBuffers glutSwapBuffers()::Void
export glutSwapBuffers

@getCFun libglut glutTimerFunc glutTimerFunc(time::Uint32, callback::Ptr{Void}, value::Int32)::Void
export glutTimerFunc
@getCFun libglut glutIdleFunc glutIdleFunc(callback::Ptr{Void})::Void
export glutIdleFunc

@getCFun libglut glutKeyboardFunc glutKeyboardFunc(callback::Ptr{Void})::Void
export glutKeyboardFunc
@getCFun libglut glutKeyboardUpFunc glutKeyboardUpFunc(callback::Ptr{Void})::Void
export glutKeyboardUpFunc
@getCFun libglut glutSpecialFunc glutSpecialFunc(callback::Ptr{Void})::Void
export glutSpecialFunc
@getCFun libglut glutSpecialUpFunc glutSpecialUpFunc(callback::Ptr{Void})::Void
export glutSpecialUpFunc
@getCFun libglut glutSetKeyRepeat glutSetKeyRepeat(repeatMode::Cint)::Cint
export glutSetKeyRepeat

@getCFun libglut glutReshapeFunc glutReshapeFunc(callback::Ptr{Void})::Void
export glutReshapeFunc
@getCFun libglut glutVisibilityFunc glutVisibilityFunc(callback::Ptr{Void})::Void
export glutVisibilityFunc
@getCFun libglut glutDisplayFunc glutDisplayFunc(callback::Ptr{Void})::Void
export glutDisplayFunc
@getCFun libglut glutMouseFunc glutMouseFunc(callback::Ptr{Void})::Void
export glutMouseFunc
@getCFun libglut glutMotionFunc glutMotionFunc(callback::Ptr{Void})::Void
export glutMotionFunc
@getCFun libglut glutPassiveMotionFunc glutPassiveMotionFunc(callback::Ptr{Void})::Void
export glutPassiveMotionFunc
@getCFun libglut glutEntryFunc glutEntryFunc(callback::Ptr{Void})::Void
export glutEntryFunc
@getCFun libGlut glutCloseFunc glutCloseFunc(callback::Ptr{Void})::Void
export glutCloseFunc

@getCFun libglut glutGetProcAddress glutGetProcAddress(name::Ptr{Uint8})::Ptr{Void}
export glutGetProcAddress
@getCFun libglut glutGet glutGet(state::Uint16)::Cint
export glutGet

const  FREEGLUT                        = 1
const  GLUT_API_VERSION                = 4
const  FREEGLUT_VERSION_2_0            = 1
const  GLUT_XLIB_IMPLEMENTATION        = 13

const  GLUT_KEY_F1                     = 0x0001
const  GLUT_KEY_F2                     = 0x0002
const  GLUT_KEY_F3                     = 0x0003
const  GLUT_KEY_F4                     = 0x0004
const  GLUT_KEY_F5                     = 0x0005
const  GLUT_KEY_F6                     = 0x0006
const  GLUT_KEY_F7                     = 0x0007
const  GLUT_KEY_F8                     = 0x0008
const  GLUT_KEY_F9                     = 0x0009
const  GLUT_KEY_F10                    = 0x000A
const  GLUT_KEY_F11                    = 0x000B
const  GLUT_KEY_F12                    = 0x000C
const  GLUT_KEY_LEFT                   = 0x0064
const  GLUT_KEY_UP                     = 0x0065
const  GLUT_KEY_RIGHT                  = 0x0066
const  GLUT_KEY_DOWN                   = 0x0067
const  GLUT_KEY_PAGE_UP                = 0x0068
const  GLUT_KEY_PAGE_DOWN              = 0x0069
const  GLUT_KEY_HOME                   = 0x006A
const  GLUT_KEY_END                    = 0x006B
const  GLUT_KEY_INSERT                 = 0x006C

const  GLUT_LEFT_BUTTON                = 0x0000
const  GLUT_MIDDLE_BUTTON              = 0x0001
const  GLUT_RIGHT_BUTTON               = 0x0002
const  GLUT_DOWN                       = 0x0000
const  GLUT_UP                         = 0x0001
const  GLUT_LEFT                       = 0x0000
const  GLUT_ENTERED                    = 0x0001

const  GLUT_RGB                        = 0x0000
const  GLUT_RGBA                       = 0x0000
const  GLUT_INDEX                      = 0x0001
const  GLUT_SINGLE                     = 0x0000
const  GLUT_DOUBLE                     = 0x0002
const  GLUT_ACCUM                      = 0x0004
const  GLUT_ALPHA                      = 0x0008
const  GLUT_DEPTH                      = 0x0010
const  GLUT_STENCIL                    = 0x0020
const  GLUT_MULTISAMPLE                = 0x0080
const  GLUT_STEREO                     = 0x0100
const  GLUT_LUMINANCE                  = 0x0200

const  GLUT_MENU_NOT_IN_USE            = 0x0000
const  GLUT_MENU_IN_USE                = 0x0001
const  GLUT_NOT_VISIBLE                = 0x0000
const  GLUT_VISIBLE                    = 0x0001
const  GLUT_HIDDEN                     = 0x0000
const  GLUT_FULLY_RETAINED             = 0x0001
const  GLUT_PARTIALLY_RETAINED         = 0x0002
const  GLUT_FULLY_COVERED              = 0x0003

const  GLUT_WINDOW_X                   = 0x0064
const  GLUT_WINDOW_Y                   = 0x0065
const  GLUT_WINDOW_WIDTH               = 0x0066
const  GLUT_WINDOW_HEIGHT              = 0x0067
const  GLUT_WINDOW_BUFFER_SIZE         = 0x0068
const  GLUT_WINDOW_STENCIL_SIZE        = 0x0069
const  GLUT_WINDOW_DEPTH_SIZE          = 0x006A
const  GLUT_WINDOW_RED_SIZE            = 0x006B
const  GLUT_WINDOW_GREEN_SIZE          = 0x006C
const  GLUT_WINDOW_BLUE_SIZE           = 0x006D
const  GLUT_WINDOW_ALPHA_SIZE          = 0x006E
const  GLUT_WINDOW_ACCUM_RED_SIZE      = 0x006F
const  GLUT_WINDOW_ACCUM_GREEN_SIZE    = 0x0070
const  GLUT_WINDOW_ACCUM_BLUE_SIZE     = 0x0071
const  GLUT_WINDOW_ACCUM_ALPHA_SIZE    = 0x0072
const  GLUT_WINDOW_DOUBLEBUFFER        = 0x0073
const  GLUT_WINDOW_RGBA                = 0x0074
const  GLUT_WINDOW_PARENT              = 0x0075
const  GLUT_WINDOW_NUM_CHILDREN        = 0x0076
const  GLUT_WINDOW_COLORMAP_SIZE       = 0x0077
const  GLUT_WINDOW_NUM_SAMPLES         = 0x0078
const  GLUT_WINDOW_STEREO              = 0x0079
const  GLUT_WINDOW_CURSOR              = 0x007A

const  GLUT_SCREEN_WIDTH               = 0x00C8
const  GLUT_SCREEN_HEIGHT              = 0x00C9
const  GLUT_SCREEN_WIDTH_MM            = 0x00CA
const  GLUT_SCREEN_HEIGHT_MM           = 0x00CB
const  GLUT_MENU_NUM_ITEMS             = 0x012C
const  GLUT_DISPLAY_MODE_POSSIBLE      = 0x0190
const  GLUT_INIT_WINDOW_X              = 0x01F4
const  GLUT_INIT_WINDOW_Y              = 0x01F5
const  GLUT_INIT_WINDOW_WIDTH          = 0x01F6
const  GLUT_INIT_WINDOW_HEIGHT         = 0x01F7
const  GLUT_INIT_DISPLAY_MODE          = 0x01F8
const  GLUT_ELAPSED_TIME               = 0x02BC
const  GLUT_WINDOW_FORMAT_ID           = 0x007B

const  GLUT_HAS_KEYBOARD               = 0x0258
const  GLUT_HAS_MOUSE                  = 0x0259
const  GLUT_HAS_SPACEBALL              = 0x025A
const  GLUT_HAS_DIAL_AND_BUTTON_BOX    = 0x025B
const  GLUT_HAS_TABLET                 = 0x025C
const  GLUT_NUM_MOUSE_BUTTONS          = 0x025D
const  GLUT_NUM_SPACEBALL_BUTTONS      = 0x025E
const  GLUT_NUM_BUTTON_BOX_BUTTONS     = 0x025F
const  GLUT_NUM_DIALS                  = 0x0260
const  GLUT_NUM_TABLET_BUTTONS         = 0x0261
const  GLUT_DEVICE_IGNORE_KEY_REPEAT   = 0x0262
const  GLUT_DEVICE_KEY_REPEAT          = 0x0263
const  GLUT_HAS_JOYSTICK               = 0x0264
const  GLUT_OWNS_JOYSTICK              = 0x0265
const  GLUT_JOYSTICK_BUTTONS           = 0x0266
const  GLUT_JOYSTICK_AXES              = 0x0267
const  GLUT_JOYSTICK_POLL_RATE         = 0x0268

const  GLUT_OVERLAY_POSSIBLE           = 0x0320
const  GLUT_LAYER_IN_USE               = 0x0321
const  GLUT_HAS_OVERLAY                = 0x0322
const  GLUT_TRANSPARENT_INDEX          = 0x0323
const  GLUT_NORMAL_DAMAGED             = 0x0324
const  GLUT_OVERLAY_DAMAGED            = 0x0325

const  GLUT_VIDEO_RESIZE_POSSIBLE      = 0x0384
const  GLUT_VIDEO_RESIZE_IN_USE        = 0x0385
const  GLUT_VIDEO_RESIZE_X_DELTA       = 0x0386
const  GLUT_VIDEO_RESIZE_Y_DELTA       = 0x0387
const  GLUT_VIDEO_RESIZE_WIDTH_DELTA   = 0x0388
const  GLUT_VIDEO_RESIZE_HEIGHT_DELTA  = 0x0389
const  GLUT_VIDEO_RESIZE_X             = 0x038A
const  GLUT_VIDEO_RESIZE_Y             = 0x038B
const  GLUT_VIDEO_RESIZE_WIDTH         = 0x038C
const  GLUT_VIDEO_RESIZE_HEIGHT        = 0x038D

const  GLUT_NORMAL                     = 0x0000
const  GLUT_OVERLAY                    = 0x0001

const  GLUT_ACTIVE_SHIFT               = 0x0001
const  GLUT_ACTIVE_CTRL                = 0x0002
const  GLUT_ACTIVE_ALT                 = 0x0004

const  GLUT_CURSOR_RIGHT_ARROW         = 0x0000
const  GLUT_CURSOR_LEFT_ARROW          = 0x0001
const  GLUT_CURSOR_INFO                = 0x0002
const  GLUT_CURSOR_DESTROY             = 0x0003
const  GLUT_CURSOR_HELP                = 0x0004
const  GLUT_CURSOR_CYCLE               = 0x0005
const  GLUT_CURSOR_SPRAY               = 0x0006
const  GLUT_CURSOR_WAIT                = 0x0007
const  GLUT_CURSOR_TEXT                = 0x0008
const  GLUT_CURSOR_CROSSHAIR           = 0x0009
const  GLUT_CURSOR_UP_DOWN             = 0x000A
const  GLUT_CURSOR_LEFT_RIGHT          = 0x000B
const  GLUT_CURSOR_TOP_SIDE            = 0x000C
const  GLUT_CURSOR_BOTTOM_SIDE         = 0x000D
const  GLUT_CURSOR_LEFT_SIDE           = 0x000E
const  GLUT_CURSOR_RIGHT_SIDE          = 0x000F
const  GLUT_CURSOR_TOP_LEFT_CORNER     = 0x0010
const  GLUT_CURSOR_TOP_RIGHT_CORNER    = 0x0011
const  GLUT_CURSOR_BOTTOM_RIGHT_CORNER = 0x0012
const  GLUT_CURSOR_BOTTOM_LEFT_CORNER  = 0x0013
const  GLUT_CURSOR_INHERIT             = 0x0064
const  GLUT_CURSOR_NONE                = 0x0065
const  GLUT_CURSOR_FULL_CROSSHAIR      = 0x0066

const  GLUT_RED                        = 0x0000
const  GLUT_GREEN                      = 0x0001
const  GLUT_BLUE                       = 0x0002

const  GLUT_KEY_REPEAT_OFF             = 0x0000
const  GLUT_KEY_REPEAT_ON              = 0x0001
const  GLUT_KEY_REPEAT_DEFAULT         = 0x0002

const  GLUT_JOYSTICK_BUTTON_A          = 0x0001
const  GLUT_JOYSTICK_BUTTON_B          = 0x0002
const  GLUT_JOYSTICK_BUTTON_C          = 0x0004
const  GLUT_JOYSTICK_BUTTON_D          = 0x0008

const  GLUT_GAME_MODE_ACTIVE           = 0x0000
const  GLUT_GAME_MODE_POSSIBLE         = 0x0001
const  GLUT_GAME_MODE_WIDTH            = 0x0002
const  GLUT_GAME_MODE_HEIGHT           = 0x0003
const  GLUT_GAME_MODE_PIXEL_DEPTH      = 0x0004
const  GLUT_GAME_MODE_REFRESH_RATE     = 0x0005
const  GLUT_GAME_MODE_DISPLAY_CHANGED  = 0x0006

export  FREEGLUT
export  GLUT_API_VERSION
export  FREEGLUT_VERSION_2_0
export  GLUT_XLIB_IMPLEMENTATION

export  GLUT_KEY_F1
export  GLUT_KEY_F2
export  GLUT_KEY_F3
export  GLUT_KEY_F4
export  GLUT_KEY_F5
export  GLUT_KEY_F6
export  GLUT_KEY_F7
export  GLUT_KEY_F8
export  GLUT_KEY_F9
export  GLUT_KEY_F10
export  GLUT_KEY_F11
export  GLUT_KEY_F12
export  GLUT_KEY_LEFT
export  GLUT_KEY_UP
export  GLUT_KEY_RIGHT
export  GLUT_KEY_DOWN
export  GLUT_KEY_PAGE_UP
export  GLUT_KEY_PAGE_DOWN
export  GLUT_KEY_HOME
export  GLUT_KEY_END
export  GLUT_KEY_INSERT

export  GLUT_LEFT_BUTTON
export  GLUT_MIDDLE_BUTTON
export  GLUT_RIGHT_BUTTON
export  GLUT_DOWN
export  GLUT_UP
export  GLUT_LEFT
export  GLUT_ENTERED

export  GLUT_RGB
export  GLUT_RGBA
export  GLUT_INDEX
export  GLUT_SINGLE
export  GLUT_DOUBLE
export  GLUT_ACCUM
export  GLUT_ALPHA
export  GLUT_DEPTH
export  GLUT_STENCIL
export  GLUT_MULTISAMPLE
export  GLUT_STEREO
export  GLUT_LUMINANCE

export  GLUT_MENU_NOT_IN_USE
export  GLUT_MENU_IN_USE
export  GLUT_NOT_VISIBLE
export  GLUT_VISIBLE
export  GLUT_HIDDEN
export  GLUT_FULLY_RETAINED
export  GLUT_PARTIALLY_RETAINED
export  GLUT_FULLY_COVERED

export  GLUT_WINDOW_X
export  GLUT_WINDOW_Y
export  GLUT_WINDOW_WIDTH
export  GLUT_WINDOW_HEIGHT
export  GLUT_WINDOW_BUFFER_SIZE
export  GLUT_WINDOW_STENCIL_SIZE
export  GLUT_WINDOW_DEPTH_SIZE
export  GLUT_WINDOW_RED_SIZE
export  GLUT_WINDOW_GREEN_SIZE
export  GLUT_WINDOW_BLUE_SIZE
export  GLUT_WINDOW_ALPHA_SIZE
export  GLUT_WINDOW_ACCUM_RED_SIZE
export  GLUT_WINDOW_ACCUM_GREEN_SIZE
export  GLUT_WINDOW_ACCUM_BLUE_SIZE
export  GLUT_WINDOW_ACCUM_ALPHA_SIZE
export  GLUT_WINDOW_DOUBLEBUFFER
export  GLUT_WINDOW_RGBA
export  GLUT_WINDOW_PARENT
export  GLUT_WINDOW_NUM_CHILDREN
export  GLUT_WINDOW_COLORMAP_SIZE
export  GLUT_WINDOW_NUM_SAMPLES
export  GLUT_WINDOW_STEREO
export  GLUT_WINDOW_CURSOR

export  GLUT_SCREEN_WIDTH
export  GLUT_SCREEN_HEIGHT
export  GLUT_SCREEN_WIDTH_MM
export  GLUT_SCREEN_HEIGHT_MM
export  GLUT_MENU_NUM_ITEMS
export  GLUT_DISPLAY_MODE_POSSIBLE
export  GLUT_INIT_WINDOW_X
export  GLUT_INIT_WINDOW_Y
export  GLUT_INIT_WINDOW_WIDTH
export  GLUT_INIT_WINDOW_HEIGHT
export  GLUT_INIT_DISPLAY_MODE
export  GLUT_ELAPSED_TIME
export  GLUT_WINDOW_FORMAT_ID

export  GLUT_HAS_KEYBOARD
export  GLUT_HAS_MOUSE
export  GLUT_HAS_SPACEBALL
export  GLUT_HAS_DIAL_AND_BUTTON_BOX
export  GLUT_HAS_TABLET
export  GLUT_NUM_MOUSE_BUTTONS
export  GLUT_NUM_SPACEBALL_BUTTONS
export  GLUT_NUM_BUTTON_BOX_BUTTONS
export  GLUT_NUM_DIALS
export  GLUT_NUM_TABLET_BUTTONS
export  GLUT_DEVICE_IGNORE_KEY_REPEAT
export  GLUT_DEVICE_KEY_REPEAT
export  GLUT_HAS_JOYSTICK
export  GLUT_OWNS_JOYSTICK
export  GLUT_JOYSTICK_BUTTONS
export  GLUT_JOYSTICK_AXES
export  GLUT_JOYSTICK_POLL_RATE

export  GLUT_OVERLAY_POSSIBLE
export  GLUT_LAYER_IN_USE
export  GLUT_HAS_OVERLAY
export  GLUT_TRANSPARENT_INDEX
export  GLUT_NORMAL_DAMAGED
export  GLUT_OVERLAY_DAMAGED

export  GLUT_VIDEO_RESIZE_POSSIBLE
export  GLUT_VIDEO_RESIZE_IN_USE
export  GLUT_VIDEO_RESIZE_X_DELTA
export  GLUT_VIDEO_RESIZE_Y_DELTA
export  GLUT_VIDEO_RESIZE_WIDTH_DELTA
export  GLUT_VIDEO_RESIZE_HEIGHT_DELTA
export  GLUT_VIDEO_RESIZE_X
export  GLUT_VIDEO_RESIZE_Y
export  GLUT_VIDEO_RESIZE_WIDTH
export  GLUT_VIDEO_RESIZE_HEIGHT

export  GLUT_NORMAL
export  GLUT_OVERLAY

export  GLUT_ACTIVE_SHIFT
export  GLUT_ACTIVE_CTRL
export  GLUT_ACTIVE_ALT

export  GLUT_CURSOR_RIGHT_ARROW
export  GLUT_CURSOR_LEFT_ARROW
export  GLUT_CURSOR_INFO
export  GLUT_CURSOR_DESTROY
export  GLUT_CURSOR_HELP
export  GLUT_CURSOR_CYCLE
export  GLUT_CURSOR_SPRAY
export  GLUT_CURSOR_WAIT
export  GLUT_CURSOR_TEXT
export  GLUT_CURSOR_CROSSHAIR
export  GLUT_CURSOR_UP_DOWN
export  GLUT_CURSOR_LEFT_RIGHT
export  GLUT_CURSOR_TOP_SIDE
export  GLUT_CURSOR_BOTTOM_SIDE
export  GLUT_CURSOR_LEFT_SIDE
export  GLUT_CURSOR_RIGHT_SIDE
export  GLUT_CURSOR_TOP_LEFT_CORNER
export  GLUT_CURSOR_TOP_RIGHT_CORNER
export  GLUT_CURSOR_BOTTOM_RIGHT_CORNER
export  GLUT_CURSOR_BOTTOM_LEFT_CORNER
export  GLUT_CURSOR_INHERIT
export  GLUT_CURSOR_NONE
export  GLUT_CURSOR_FULL_CROSSHAIR

export  GLUT_RED
export  GLUT_GREEN
export  GLUT_BLUE

export  GLUT_KEY_REPEAT_OFF
export  GLUT_KEY_REPEAT_ON
export  GLUT_KEY_REPEAT_DEFAULT

export  GLUT_JOYSTICK_BUTTON_A
export  GLUT_JOYSTICK_BUTTON_B
export  GLUT_JOYSTICK_BUTTON_C
export  GLUT_JOYSTICK_BUTTON_D

export  GLUT_GAME_MODE_ACTIVE
export  GLUT_GAME_MODE_POSSIBLE
export  GLUT_GAME_MODE_WIDTH
export  GLUT_GAME_MODE_HEIGHT
export  GLUT_GAME_MODE_PIXEL_DEPTH
export  GLUT_GAME_MODE_REFRESH_RATE
export  GLUT_GAME_MODE_DISPLAY_CHANGED

end


text: # Coupling a spatial diffusion model with the SIR model

ext: jl


text:
#!/usr/bin/env julia

using HTTP, JSON3, Scratch, TimeZones, Dates, Tar, Gzip_jll

# Get list of Pkg servers
pkg_servers = JSON3.read(String(HTTP.get("https://pkg.julialang.org/meta/siblings").body))
#storage_servers = JSON3.read(String(HTTP.get("https://pkg.julialang.org/meta/parents").body))
storage_servers = ["https://us-east.storage.juliahub.com", "https://kr.storage.juliahub.com"]

function update_git_repo(repo_url::AbstractString, repo_path::AbstractString; branch::AbstractString = "master")
    mkpath(repo_path)
    st = stat(joinpath(repo_path,"HEAD"))
    if !isfile(st)
        run(`git clone --mirror $(repo_url) $(repo_path)`)
    end

    # Return the latest fetched treehash
    run(`git -C $(repo_path) fetch --all`)
    return readchomp(`git -C $(repo_path) rev-parse "$(branch)^{tree}"`)
end

# Clone/update General registry
gen_uuid = Base.UUID("23338594-aafe-5451-b93e-139f81909106")
reg_dir = get_scratch!(Base.UUID("eac38ba3-4627-46d4-b1a1-bcb86ba22f8b"), "Registry-General")
latest_treehash = update_git_repo("https://github.com/JuliaRegistries/General", reg_dir)

function commit_for_tree(repo_path, tree)
    p = open(`git -C $(repo_path) log --pretty='%H %T'`; read=true)
    for line in eachline(p.out)
        commit_hash, commit_tree = split(line)[1:2]
        if commit_tree == tree
            return commit_hash
        end
    end
    return nothing
end
function commit_time(repo_path, commit)
    time_str = readchomp(`git -C $(repo_path) show --quiet --pretty='%cI' $(commit)`)
    ZonedDateTime(time_str, "yyyy-mm-ddTHH:MM:SSzzzzz")
end

hash_map = Dict()
function get_general_time(treehash)
    if haskey(hash_map, treehash)
        return hash_map[treehash]
    end

    commit = commit_for_tree(reg_dir, treehash)
    if commit === nothing
        # If we couldn't find this commit, it's probably because the Registry contains an empty directory or something.
        # This causes us to generate a different hash than git would.  We get the git-compatible hash by downloading the
        # registry then using `Tar` to generate a yskip hash:
        local skip_treehash
        mktempdir() do dir
            @info("Commit for treehash $(treehash) could not be found, determining skip treehash...")
            tarball = joinpath(dir, treehash)
            tarball = HTTP.download("https://pkg.julialang.org/registry/$(gen_uuid)/$(treehash)", tarball)
            gzip() do gzip
                p = open(pipeline(`cat $(tarball)`, `gzip -d`), read=true)
                skip_treehash = Tar.tree_hash(p.out; skip_empty=true)
                close(p.in)
                @info("skip_treehash: $(skip_treehash)")
            end
            Base.Filesystem.prepare_for_deletion(dir)
        end

        commit = commit_for_tree(reg_dir, skip_treehash)
        if commit === nothing
            error("Unable to find commit for General hash $(treehash)/$(skip_treehash)")
        end
    end

    hash_map[treehash] = commit_time(reg_dir, commit)
    return hash_map[treehash]
end

latest_time = get_general_time(latest_treehash)
function get_server_registry_lag(server, flavor)
    local registries
    try
        registries = split(String(HTTP.get("$(server)/registries.$(flavor)"; readtimeout=5).body), "\n")
    catch e
        if isa(e, InterruptException)
            rethrow(e)
        end
        @warn("Unable to fetch `/registries.$(flavor)` from $(server)")
        return Inf
    end
    treehash = basename(first(filter(r -> startswith(r, "/registry/$(gen_uuid)/"), registries)))
    time = get_general_time(treehash)
    lag = canonicalize(latest_time - time)

    # I don't like seeing "empty period" so I manually change it to "0 seconds"
    if isempty(lag.periods)
        return Second(0)
    end
    return lag
end

function async_server_responses(servers; flavors=("eager", "conservative"))
    c = Channel(length(servers))
    # One `async` to get all requests running and return immediately
    @async begin
        # One `sync` so that we can `close()` once everything else is done
        @sync begin
            for server in servers
                # Another `async` so that each server is processed in parallel
                @async begin
                    flavor_lags = Dict{String,Any}()
                    @sync begin
                        for flavor in flavors
                            # Yet another `@async` so that each request to a single server
                            # is done in parallel as well.
                            @async flavor_lags[flavor] = get_server_registry_lag(server, flavor)
                        end
                    end
                    # Once this particular server is done processing, `put!()` its results
                    put!(c, (server, flavor_lags))
                end
            end
        end
        # After the overall `sync`, close to signify we're done
        close(c)
    end
    return c
end

function print_servers(c::Channel)
    while isopen(c) || isready(c)
        try
            server, flavor_lags = take!(c)
            @info(server, (Symbol(string(k, "_lag")) => v for (k, v) in flavor_lags)...)
        catch e
            if isa(e, InvalidStateException) && e.state == :closed
                continue
            end
            rethrow(e)
        end
    end
end

# Get the current registry hashes for each server:
@info("Storage Servers:")
print_servers(async_server_responses(storage_servers))

@info("Pkg Servers:")
print_servers(async_server_responses(pkg_servers))

max_stars_repo_name: StefanKarpinski/PkgServer

max_issues_repo_name: StefanKarpinski/PkgServer

max_forks_repo_name: StefanKarpinski/PkgServer


text:
using Polynomials: Poly

struct Banana{T}
    ex   ::Vector{T}
    Δe   ::Vector{T}
    dΔe  ::Vector{T}
    e    ::Vector{T}
    de   ::Vector{T}
    etot ::Vector{T}
    exfromede::Poly
end

function Banana(filename::Union{String, IO})
    rows = Vector{Float32}[]
    poly = nothing
    for line in readlines(filename)
        tokens = split(line, r",?\s+")
        if length(tokens) != 6
            if length(tokens) > 1 && startswith(tokens[1], "chi")
                a0 = tokens[5][1:end-3]
                a1 = tokens[8]
                a2 = tokens[11][1:end-8]
                (a0, a1, a2) = parse.(Float32, [a0, a1, a2])
                poly = Poly{Float32}([a0*1e3, a1, a2/1e3])
            end
            continue
        end
        try
          push!(rows, parse.(Float32, tokens))
        catch ArgumentError
            continue
        end
    end
    rows = hcat(rows...)
    Banana{Float32}([rows[i, :] for i in 1:6]..., poly)
end

function smash(banana::Banana)

end

max_stars_repo_name: Caronthir/JSort

max_issues_repo_name: Caronthir/JSort

max_forks_repo_name: Caronthir/JSort


text:
__precompile__()
module ModelParameters

using KeywordDispatch

include("Units.jl")

using ModelParameters.Units

export regconv, toSI, fromSI, get_toSI_converter, get_fromSI_converter

export AbstractParameter, ParameterBase
export Parameter, ParameterOptions, ParameterContainer, PerturbedParameter
export ParameterBroadcaster
export id, name, description, transformer, value, transform, units
export setid!, setname!, setdescription!, settransformer!, setvalue!
export traverse, transform
export perturbation, setperturbation!, perturb!
export selection, setselection!
export broadcastsize, setbroadcastsize!
export parameter

parameter = KeywordDispatchFunction()

"""
Abstract Parameter: all parameters must have it as a parent
"""
abstract AbstractParameter

"""
Base type for all parameters: provides shared fields:
	- `id` (`Symbol`) identification of the parameter
	- `name` (`AbstractString`) printable name
	- `decription` (`AbstractString`) detailed description of the parameter
	- `transformer` (`Function`) parameter value transformer to get target
		value/object
"""
type ParameterBase
    id :: Symbol
    name :: AbstractString
    description :: AbstractString
    transformer
	function ParameterBase(; id = :id, name = string(id),
							description = "", transformer = identity,
							more...)
		new(id, name, description, transformer)
	end
end

"""
Returns the name of the parameter

This function is required to implement a new parameter
"""
name(p :: ParameterBase) = p.name

"""
Sets the new name of the parameter

This function is required to implement a new parameter
"""
setname!(p :: ParameterBase, newname) = p.name = newname

"""
Returns the identification of the parameter (symbol)

This function is required to implement a new parameter
"""
id(p :: ParameterBase) = p.id

"""
Sets the new id to a parameter

This function is required to implement a new parameter
"""
setid!(p :: ParameterBase, newid) = p.id = newid

"""
Returns an extended description of the parameter

This function is required to implement a new parameter
"""
description(p :: ParameterBase) = p.description

"""
Sets the new description to a parameter

This function is required to implement a new parameter
"""
setdescription!(p :: ParameterBase, newdesc) = p.description = newdesc

"""
Returns the transformer of the value associated with the parameter

This function is required to implement a new parameter
"""
transformer(p :: ParameterBase) = p.transformer

"""
Sets new tranformer to a parameter

This function is required to implement a new parameter
"""
settransformer!(p :: ParameterBase, f) = p.transformer = f

"""
Returns actual useful value out of parameter.

It usually combines `value` and `transformer` to construct actual value

This function is required to implement a new parameter
"""
transform(p :: AbstractParameter) = transformer(p)(value(p))

"""
Creates an implementation of basic generic functions of parameters:

`name`, `setname!`, `id`, `setid!`, `description`, `setdescription!`,
`transformer` and `setransformer!`

by passing the call to the corresponding function of the `field` of
the parameter.

For example,

	@parambasics(NewKindParameter, basic)

Will result for `name` to become:

	name(p :: NewKindParameter) = name(p.basic)
"""
macro parambasics(param, field)
	quote
		global name(p :: $param) = name(p.$field)
		global setname!(p :: $param, newname) = setname!(p.$field, newname)
		global id(p :: $param) = id(p.$field)
		global setid!(p :: $param, newid) = setid!(p.$field, newid)
		global description(p :: $param) = description(p.$field)
		global setdescription!(p :: $param, d) = setdescription!(p.$field, d)
		global transformer(p :: $param) = transformer(p.$field)
		global settransformer!(p :: $param, f) = settransformer!(p.$field, f)
	end
end

"""
Single Parameter
"""
type Parameter <: AbstractParameter
    base :: ParameterBase
    value :: Any
    units :: AbstractString
    function Parameter(; value = 0, units = "-", kwargs...)
        new(ParameterBase(;kwargs...), value, units)
    end
end

@parambasics(Parameter, base)

"""
Returns the "value" associated with a parameter.

This function is required to implement a new parameter
"""
value(p :: Parameter) = p.value

"""
Sets a new value with the parameter

This function is required to implement a new parameter
"""
setvalue!(p :: Parameter, newvalue) = p.value = newvalue

"""
Returns units of measure of the parameter

This function is NOT required to implement a new parameter.

The single value parameter should implement it
"""
units( p :: Parameter) = p.units

"""
Sets new units of measure of the parameter

This function is NOT required to implement a new parameter.

The single value parameter should implement it
"""
setunits!(p :: Parameter, newunits) = p.units = newunits

"""
Applies function `f` to parameter. Convention used: f(x) must return Bool.
If f(x) is true: keep applying it to subparameters of `p` if `p` is some
kind of container parameter of other parameters.
"""
traverse(p :: Parameter, f) = f(p)

"""
Container of other parameters
"""
type ParameterContainer <: AbstractParameter
    base :: ParameterBase
    children :: Vector{AbstractParameter}
    function ParameterContainer(;
			children = [],
			transformer = (; kw...) -> kw,
			kwargs...)
		updatedargs = [(:transformer, transformer), kwargs...]
		base = ParameterBase(; updatedargs...)
        new(base, children)
    end
end

@parambasics(ParameterContainer, base)

value(p :: ParameterContainer) =
	Dict{Symbol, Any}(map(c -> (id(c), value(c)), p.children))

function Base.get(p :: ParameterContainer, key)
	for child in p.children
		if id(child) === key
			return child
		end
	end
	throw(KeyError(key))
end

function Base.get(p :: ParameterContainer, key, default)
	for child in p.children
		if id(child) === key
			return child
		end
	end
	return default
end

function Base.getindex(p :: ParameterContainer, key)
	return get(p, key)
end

function Base.setindex!(p :: ParameterContainer, val, key)
	c = p.children
	cnew = map(child -> id(child)=== key? val : child, c)
	p.children = cnew
end

function setvalue!(p :: ParameterContainer, newvalue)
	for (k,v) in newvalue
		setvalue!(get(p, k), v)
	end
end

"""
Transform for container is slightly different: the transformer is assumed to
take keyword arguments
"""
function transform(p :: ParameterContainer)
	args = (map(c -> (id(c), transform(c)), p.children))
	transformer(p)(;args...)
end

function traverse(p :: ParameterContainer, f)
	if f(p)
		for child in p.children
			traverse(child, f)
		end
	end
end

"""
Selection between alternative options
"""
type ParameterOptions <: AbstractParameter
    base :: ParameterContainer
    selection :: Symbol
    function ParameterOptions(; transformer = identity, selection = 1, kwargs...)
        new(ParameterContainer(;[(:transformer, transformer), kwargs...]...), selection)
    end
end

@parambasics(ParameterOptions, base)

selection(p :: ParameterOptions) = p.selection

function setselection!(p :: ParameterOptions, s)
	let g = gensym()
		if !(get(p.base, s, g) === g)
			p.selection = s
		else
			throw(KeyError(s))
		end
	end
end

value(p :: ParameterOptions) = value(p.base)[p.selection]

function setvalue!(p :: ParameterOptions, newvalue)
	vals = value(p.base)
	vals[p.selection] = newvalue
	setvalue!(p.base, vals)
end

function transform(p :: ParameterOptions)
	selected = get(p.base, p.selection)
	transformer(p)(transform(selected))
end

function traverse(p :: ParameterOptions, f)
	if f(p)
		tranverse(p.base, f)
	end
end

type PerturbedParameter <: AbstractParameter
	parameter :: Parameter
	perturbation :: Float64
	function PerturbedParameter(p :: Parameter, v :: Float64)
		new(p, v)
	end
	function PerturbedParameter(; perturbation = 0.0, kwargs...)
		new(Parameter(; kwargs...), perturbation)
	end
end

@parambasics(PerturbedParameter, parameter)

value(p :: PerturbedParameter) = value(p.parameter)
setvalue!(p :: PerturbedParameter, newval) = setvalue!(p.parameter, newval)

"""
Returns perturbation of the parameter. If parameter does not have a
perturbation usefully associated with it, returns 0.0
"""
perturbation(p :: AbstractParameter) = 0.0
perturbation(p :: PerturbedParameter) = p.perturbation
setperturbation!(p :: PerturbedParameter, val) = p.perturbation = val

function perturb!(p :: PerturbedParameter, val :: Float64)
	setperturbation!(p, val)
	return p
end

function perturb!(p :: Parameter, val :: Float64)
	return PerturbedParameter(p, val)
end

function perturb!{T <: Any}(p :: ParameterContainer, val :: Dict{Symbol, T})
	notfound = gensym()
	for (k,v) in val
		if !(get(p, k, notfound) === notfound)
			p[k] = perturb!(p[k], v)
		else
			warn("Parameter $k not found in $p")
		end
	end
	return p
end

function perturb!{T <: Any}(p :: ParameterOptions, val :: Dict{Symbol, T})
	p.base = perturb!(p.base, val)
	return p
end

function transform(p :: PerturbedParameter)
	transform(p.parameter) * (1.0 + (2.0 * rand() - 1.0) * p.perturbation)
end

function traverse(p :: PerturbedParameter, f)
	if f(p)
		traverse(p.parameter, f)
	end
end

type ParameterBroadcaster <: AbstractParameter
	base :: ParameterContainer
	size :: Parameter
	function ParameterBroadcaster(;
			size = 1,
			size_name = "Number of items",
			size_id = :broadcastsize,
			size_desc = "Number of items to be instantiated",
			kwargs...)
		p = parameter(name = size_name,
			id = size_id,
			value = size,
			description = size_desc)
		new(ParameterContainer(;kwargs...), p)
	end
end

@parambasics(ParameterBroadcaster, base)

function transform(p :: ParameterBroadcaster)
	n = broadcastsize(p)
	map(i -> transform(p.base), 1:n)
end

function value(p :: ParameterBroadcaster)
	d = value(p.base)
	d[id(p.size)] = value(p.size)
	return d
end

function setvalue!(p :: ParameterBroadcaster, v)
	newsize = pop!(v, id(p.size), value(p.size))
	setvalue!(p.size, newsize)
	setvalue!(p.base, v)
end

Base.get(p :: ParameterBroadcaster, key) =
	key === id(p.size)? p.size : get(p.base, key)

Base.get(p :: ParameterBroadcaster, key, default) =
	key === id(p.size)? p.size : get(p.base, key, default)

function Base.getindex(p :: ParameterBroadcaster, key)
	if key === id(p.size)
		p.size
	else
		p.base[key]
	end
end

function Base.setindex!(p :: ParameterBroadcaster, val, key)
	if key === id(p.size)
		p.size = val
	else
		p.base[key] = val
	end
end

function perturb!{T <: Any}(p :: ParameterBroadcaster, val :: Dict{Symbol, T})
	p.base = perturb!(p.base, val)
	return p
end

broadcastsize(p :: ParameterBroadcaster) = value(p.size)

setbroadcastsize!(p :: ParameterBroadcaster, n) =
	setvalue!(p.size, n)

@defkwspec parameter [:value] (args) begin
	Parameter(; args...)
end

macroexpand(:(@defkwspec parameter [:value] (args) begin
	Parameter(; args...)
end))

@defkwspec parameter [:children] (args) begin
	ParameterContainer(; args...)
end

@defkwspec parameter [:children :selection] (args) begin
	ParameterOptions(; args...)
end

@defkwspec parameter [:value :perturbation] (args) begin
	PerturbedParameter(; args...)
end

@defkwspec parameter [:children :size] (args) begin
	ParameterBroadcaster(; args...)
end

# include("YAMLParameters.jl")

# p1 = Parameter(id = :mass, value = 1.0, units = "g")

# p1 = PerturbedParameter(id = :mass, value = 1.0, units = "g", perturbation = 0.1)
#
# p1
#
# transform(p1)

# p2 = Parameter(id = :speed, value = 36.0, units = "km/h")
#
#
# pc = ParameterContainer(id = :momentum, children = [p1, p2])
#
# p3 = Parameter(id = :temperature, value = 20.0, units = "°C")
#
# po = ParameterOptions(id = :physics, options = [pc, p3])
# po.selection = 2
#
# transform(po)

# file = "/home/alexey/.julia/v0.4/Parameters/test/base.yaml"
# x = load_yaml_config(file)
# y = load_yaml_config(file, Dict(:example => vec -> Dict(vec), :k => x -> x * 1e7))
# transform(y)

# parameter(
# 	id = :container,
# 	name = "Container",
# 	children = [
# 		parameter(id = :a, value = 1.0),
# 		parameter(id = :b, value = 2.0, units = "cm"),
# 		parameter(id = :options, options =[
# 			parameter(id = :option1, value = 1.0),
# 			parameter(id = :option2, value = 2.0)])])

end # module


text:
### ndft functions ###

"""
    ndft!(plan::NFFTPlan{D}, g::AbstractArray{Tg,D}, f::AbstractArray{T,D})

Compute NDFT of input array `f`
and store result in pre-allocated output array `g`.
Both arrays must have the same size compatible with the NFFT `plan`.

"""
function ndft!(plan::NFFTPlan{D}, g::AbstractArray{Tg,D}, f::AbstractArray{T,D}) where {D,T,Tg}

    plan.N == size(f) ||
        throw(DimensionMismatch("Data f is not consistent with NFFTPlan"))
    plan.N == size(g) ||
        throw(DimensionMismatch("Output g is inconsistent with NFFTPlan"))

    g .= zero(Tg)

    for l=1:prod(plan.N)
        idx = CartesianIndices(plan.N)[l]

        for k=1:plan.M
            arg = zero(T)
            for d=1:D
                arg += plan.x[d,k] * ( idx[d] - 1 - plan.N[d] / 2 )
            end
            g[k] += f[l] * cis(-2*pi*arg)
        end
    end

    return g
end

"""
    ndft(plan::NFFTPlan{D}, f::AbstractArray{T,D})
    ndft(x, f::AbstractArray, rest...; kwargs...)

Non pre-allocated versions of NDFT; see `ndft!`.
"""
ndft(plan::NFFTPlan{D}, f::AbstractArray{T,D}) where {D,T} =
    ndft!(plan, similar(f), f)

ndft(x, f::AbstractArray, rest...; kwargs...) =
    ndft(NFFTPlan(x, size(f), rest...; kwargs...), f)

"""
    ndft_adjoint!(plan::NFFTPlan{D}, g::AbstractArray{Tg,D}, fHat::AbstractVector)

Compute adjoint NDFT of input vector `fHat`
and store result in pre-allocated output array `g`.
The input arrays must have sizes compatible with the NFFT `plan`.
"""
function ndft_adjoint!(plan::NFFTPlan{D}, g::AbstractArray{Tg,D}, fHat::AbstractVector{T}) where {D,T,Tg}

    plan.M == length(fHat) ||
        throw(DimensionMismatch("Data f inconsistent with NFFTPlan"))
    plan.N == size(g) ||
        throw(DimensionMismatch("Output g inconsistent with NFFTPlan"))

    g .= zero(Tg)

    for l=1:prod(plan.N)
        idx = CartesianIndices(plan.N)[l]

        for k=1:plan.M
            arg = zero(T)
            for d=1:D
                arg += plan.x[d,k] * ( idx[d] - 1 - plan.N[d] / 2 )
            end
            g[l] += fHat[k] * cis(2*pi*arg)
        end
    end

    return g
end

"""
    ndft_adjoint(plan::NFFTPlan, fHat::AbstractVector)
    ndft_adjoint(x, N, fHat::AbstractVector, rest...; kwargs...)

Non pre-allocated versions of NDFT adjoint; see `ndft_adjoint!`.
"""
ndft_adjoint(plan::NFFTPlan, fHat::AbstractVector) =
    ndft_adjoint!(plan, similar(fHat, plan.N), fHat)

ndft_adjoint(x, N, fHat::AbstractVector, rest...; kwargs...) =
    ndft_adjoint(NFFTPlan(x, N, rest...; kwargs...), fHat)


text:
# This file contains mostly random utilities
# TODO: make the matrix aggrigator only take the output array

@doc """
    Scattered = wrap(layers::stParallel{K, M}, results::Array{T,N}, X) where {K, N, M, T<:Number}

given a stParallel and an array as produced by the thin ST, wrap the
results in the easier to process Scattered type. note that the data is zero
when produced this way.

TODO: the 2nd layer still has a weird size, since both indices are stuck together (see the cwt example)
"""
function rollSt(layers::stParallel{K,1}, results::AbstractArray{T,N}, X;
    percentage = 0.9, outputSubsample = (-1, -1), full = false) where {K,N,T<:Number}
    if full
        wrapped = ScatteredFull(layers, X, outputSubsample = outputSubsample)
    else
        wrapped = ScatteredOut(layers, X, outputSubsample = outputSubsample)
    end
    n, q, dataSizes, outputSizes, resultingSize = calculateSizes(layers,
        outputSubsample,
        size(X),
        percentage = percentage)
    @info "" n' q' dataSizes' outputSizes' resultingSize'
    outerAxes = axes(X)[2:end]
    addedLayers = getListOfScaleDims(layers, n)
    for i = 1:depth(layers)+1
        concatStart = sum([resultingSize[m] * prod(outputSizes[m][2:end-ndims(X)+1]) for m = 1:i-1]) + 1
        for js in indexOverScales(addedLayers, i)
            j = linearFromTuple(js, addedLayers[i])
            accessed = results[concatStart.+j*resultingSize[i].+(0:(resultingSize[i]-1)),
                outerAxes...]
            thingToWrite = reshape(accessed,
                (resultingSize[i],
                    size(X)[2:end]...,))
            if js == 1
                wrapped.output[i][:, outerAxes...] = thingToWrite
            else
                wrapped.output[i][:, js..., outerAxes...] = thingToWrite
            end
        end
    end
    return wrapped
end

@doc """
    MatrixAggrigator(pardir::String; keep=[],named="output")

    gathers all sheared matrices in a file with the name grouped(keep) and makes a single matrix out of them, with each row being a single sheared transform. Keep determines which depth to keep, with an empty matrix meaning keep all layers. named is the name of the variable in the file, while it is saved to "grouped(keep)"
"""
function MatrixAggrigator(pardir::String; keep = [], named = "output")
    vectorLength = 0
    # First determine the size of a single entry
    for (root, dir, files) in walkdir(pardir)
        @debug "folder $root"
        for name in files
            if name[end-3:end] == ".jld"
                results = load("$root/$name", named)
                if keep == []
                    vectorLength = [prod(size(results))]
                else
                    vectorLength = [prod(size(x)) for x in results.output[keep]]
                end
                break
            end
        end
    end
    # quick walkthrough to determine the number of examples
    NumFiles = 0
    for (root, dir, files) in walkdir(pardir)
        for name in files
            if name[end-3:end] == ".jld"
                NumFiles += 1
            end
        end
    end
    @debug "vectorLength = $vectorLength"
    grouped = zeros(NumFiles, sum(vectorLength))
    if keep == []
        keep = 1:size(vectorLength, 1)
    end
    i = 1
    # Acutally load the data into the matrix
    for (root, dir, files) in walkdir(pardir)
        for name in files
            if name[end-3:end] == ".jld" && name[1:4] == "data"
                results = load("$root/$name", named)
                grouped[i, :] = reshape(results, (1, vectorLength[1]))
                i += 1
            end
        end
    end
    save("$(pardir)/grouped$(keep).jld", "grouped", grouped)
    return grouped
end

function reshapeFlattened(mat::Array{Float64}, sheared::S) where {S<:Scattered}
    return reshape(mat, size(sheared.output[end]))
end

@doc """
    transformFolder(sourceFolder::String, destFolder::String, layers::stParallel; separate::Bool=false, loadThis::Function=defaultLoadFunction, nonlinear::Function=abs, subsam::Function=bspline, stType::String="full", thin::Bool=true, postSubsample::Tuple{Int,Int}=(-1,-1), overwrite::Bool=false)

Given the (relative) name of a folder and a layered transform, it will load and transform the entire folder, and save the output into a similarly structured set of folders in destFolder. If separate is true, it will also save a file containing just the Scattered coefficients from all inputs.

The data is loaded via a user supplied function loadThis. This should have the signature `(data,hasContents) = loadThis(filename::String)`. `filename` is a (relative) path to the file, while `data` should be arranged so that the  last dimension is to be transformed. `hasContents` is a boolean that indicates if there is actually any data in the file.
If overwrite is false, then skip files that already exist. If overwrite is true, for right now, it uses whatever is already there as the last entries
"""
function transformFolder(sourceFolder::String, destFolder::String, layers::stParallel; separate::Bool = false, loadThis::Function = defaultLoadFunction, nonlinear::Function = abs, subsam::Function = bspline, stType::String = "full", thin::Bool = true, postSubsample::Tuple{Int,Int} = (-1, -1), overwrite::Bool = false)
    for (root, dirs, files) in walkdir(sourceFolder)
        for dir in dirs
            mkpath(joinpath(destFolder, dir))
        end
        @debug "" root
        for file in files
            # data is expected as *column* vectors
            @debug "starting file $(joinpath(root, file))"
            savefile = joinpath(destFolder, relpath(root, sourceFolder), "$(file).h5")
            savefileSize = stat(savefile).size
            if overwrite || savefileSize < 10
                (fullMatrix, hasContents) = loadThis(joinpath(root, file))
                if hasContents
                    # breaking up the data into managable chunks
                    nEx = size(fullMatrix, 1)
                    # if the save file already has meaningful content, load this content
                    if savefileSize > 10
                        prevWork = h5read(savefile, "result/result")
                    end
                    # if the savefile doesn't have content, or if there should be more examples than what the save file has, calculate the new coefficients
                    if savefileSize < 10 || (nEx > 2 && size(prevWork, 1) <= 2)
                        innerAxes = axes(fullMatrix)[2:end]
                        usefulSlice = 1:min(2, nEx)
                        if thin
                            tmpResult = thinSt(fullMatrix[usefulSlice, innerAxes...], layers, nonlinear = nonlinear, subsam = subsam, stType = stType, outputSubsample = postSubsample)
                        else
                            tmpResult = st(fullMatrix[usefulSlice, innerAxes...], layers, nonlinear = nonlinear, subsam = subsam, stType = stType)
                        end
                        # if the data is too big, we'll need extra room to store the results
                        result = zeros(nEx, size(tmpResult)[2:end]...)
                        innerResultAxes = axes(tmpResult)[2:end]
                        result[usefulSlice, innerResultAxes...] = tmpResult
                        if nEx > 2
                            if savefileSize > 10
                                usefulSlice = (2*ceil(Int, nEx / 2)-1):nEx
                                result[usefulSlice, innerResultAxes...] = prevWork
                            end
                            maxValue = (savefileSize > 10 && nEx > 2) ? ceil(Int, nEx / 2) - 1 : ceil(Int, nEx / 2)
                            for i = 2:maxValue
                                usefulSlice = (2*i-1):min(nEx, 2 * i)
                                if thin
                                    tmpResult = thinSt(fullMatrix[usefulSlice, innerAxes...], layers, nonlinear = nonlinear, subsam = subsam, stType = stType, outputSubsample = postSubsample)
                                else
                                    tmpResult = st(fullMatrix[usefulSlice, innerAxes...], layers, nonlinear = nonlinear, subsam = subsam, stType = stType)
                                end
                                result[usefulSlice, innerResultAxes...] = tmpResult
                            end
                            # repair a problem in the previous run
                        end
                        @info "saving to $(savefile)"
                        if savefileSize < 10 && isfile(savefile)
                            rm(savefile)
                        end
                        h5write(savefile, "result/result", result)
                    end
                end
            end
        end
    end
    @info "saving settings to $(joinpath(destFolder, "settings.h5"))"
    save(joinpath(destFolder, "settings.jld"), "layers", layers)
    return
end

function defaultLoadFunction(filename)
    return (h5read(filename, "data"), true)
end

function loadSyntheticMatFile(datafile::String)
    hasContents = (datafile[end-3:end] == ".mat")
    if hasContents
        wef = matread(datafile)
        return (wef["resp"]', hasContents)
    else
        return ([0.0 0.0; 0.0 0.0], hasContents)
    end
end

function loadhdf5(datafile::String)
    hasContents = (datafile[end-3:end] == ".mat")
    if hasContents
        wef = matread(datafile)
        return (wef["resp"]', hasContents)
    else
        return ([0.0 0.0; 0.0 0.0], hasContents)
    end
end
rollSt(results::AbstractArray{T,N}, layers::stParallel{K,1}, X;
    percentage = 0.9, outputSubsample = (-1, -1), full = false) where {K,N,T<:Number} = rollSt(layers, results, X;
    percentage = percentage, outputSubsample = outputSubsample, full = full)


text:
function CRC.rrule(::typeof(logpdf), d::Exponential, x)
    v = logpdf(d, x)
    function pullback(y)
        g = @thunk(gradlogpdf(d, x))
        dθ = @thunk(
            if x < 0
                zero(x)
            else
                -inv(d.θ) + x * inv(d.θ^2)
            end
        )
        return (NO_FIELDS, g, dθ)
    end
    return (v, pullback)
end

function CRC.rrule(::typeof(logpdf), d::Normal, x)
    v = logpdf(d, x)
    function pullback(y)
        μ = mean(d)
        σ = std(d)
        g = @thunk(gradlogpdf(d, x))
        dμ = @thunk((x - μ) / σ^2)
        dσ = @thunk(-inv(σ) + abs2(x - μ) * σ^(-3))
        return (NO_FIELDS, g, dμ, dσ)
    end
    return (v, pullback)
end

function CRC.rrule(::typeof(logpdf), d::Arcsine, x)
    v = logpdf(d, x)
    function pullback(y)
        T = promote_type(typeof(x), partype(d))
        (a, b) = support(d)
        g = @thunk(gradlogpdf(d, x))
        da = if x > b || x < a
                zero(T)
            else
                inv(2 * (x - a))
            end

        db = if x > b || x < a
                zero(T)
            else
                -inv(2 * (b - x))
            end
        return (NO_FIELDS, g, da, db)
    end
    return (v, pullback)
end

function CRC.rrule(::typeof(logpdf), d::Beta, x)
    v = logpdf(d, x)
    function pullback(y)
        T = promote_type(typeof(x), partype(d))
        (α, β) = params(d)
        g = @thunk(gradlogpdf(d, x))
        dα = if !(0 ≤ x ≤ 1)
                zero(T)
            else
                log(x) - digamma(α) + digamma(α + β)
            end
        dβ = if !(0 ≤ x ≤ 1)
                zero(T)
            else
                log(1 - x) - digamma(β) + digamma(α + β)
            end
        return (NO_FIELDS, g, dα, dβ)
    end
    return (v, pullback)
end


text:
#This script calculates the harmonic correction for a 2-level system.
using LinearAlgebra
using Plots; pyplot()
#using Statistics
using NPZ
using LaTeXStrings

include("MagnusExpansion.jl")
include("2ls.jl")
include("HarmonicCorrection2ls.jl")

σ = pauli_matrices()
#array with different gate times tf
tf0, tf1 = 0.1, 30.0
nt = 200
tf_array = collect(tf0: (tf1-tf0)/(nt-1): tf1)
nt = length(tf_array)

hDelta1(x) = 1.0
h1(x) = 1.0-cos(2.0*pi*x)
h2(x) = sin(2.0*pi*x)
h3(x) = 1.0-cos(4.0*pi*x)
env_Delta = (hDelta1,)
env_pulse1 = (h1,)
env_pulse2 = (h1,)

ncoeffs = length(env_Delta) + length(env_pulse1) + length(env_pulse2)
coeffs_array = zeros(ncoeffs, nt)
F1, F2 = zeros(nt), zeros(nt)
for j = 1: nt
	tf = tf_array[j]
	println(tf)
	# Ideal evolution
	U_ideal = U(tf, σ; ideal_dynamics=true)
	# Nonideal evolution
	U_nideal = U(tf, σ; ideal_dynamics=false)
	# Fidelity
	F1[j] = fidelity(U_nideal, U_ideal, 2)
	# Harmonic correction
	M = correction_matrix(tf, env_Delta, env_pulse1, env_pulse2)
	order = 2
	coeffs = get_coeffs(M, order, tf, env_Delta, env_pulse1, env_pulse2)
	coeffs_array[:,j] .= vcat(coeffs[1], coeffs[2])
	# Corrected evolution
	U_nideal2 = U(tf, σ, coeffs, env_Delta, env_pulse1, env_pulse2)
	# Fidelity
	F2[j] = fidelity(U_nideal2, U_ideal, 2)
end

y = 1 .- hcat(F1, F2)
plot(tf_array, y,
	 linewidth = 2,
	 labels = ["No correction" "2nd order\nMagnus"])
plot!(yaxis = :log,
	  tickfont = font(12, "Serif"),
	  xlabel = "Gate time "*L"\omega_\mathrm{q} t_\mathrm{f}",
	  ylabel = "Fidelity error "*L"\varepsilon",
	  guidefont = font(14, "Serif"),
	  legendfont = font(12, "Serif"),
	  background_color_legend = false,
	  margin = 5Plots.mm)

savefig("fig2a.pdf")

y = abs.(transpose(coeffs_array))
plot(tf_array, y,
	 linewidth = 2,
	 labels = [L"|\Delta|" L"|c_{x, 1}|" L"|c_{y, 1}|"])
plot!(yaxis = :log,
	  tickfont = font(12, "Serif"),
	  xlabel = "Gate time "*L"\omega_\mathrm{q} t_\mathrm{f}",
	  ylabel = "Coeff. "*L"\times \omega_\mathrm{q}^{-1}",
	  guidefont = font(14, "Serif"),
	  legendfont = font(12, "Serif"),
	  background_color_legend = false,
	  margin = 5Plots.mm)
savefig("fig2b.pdf")

output = zeros(nt, ncoeffs)
output[:, 1] = tf_array
output[:, 2] = F1
output[:, 3] = F2
npzwrite("fidelity.npy", output)
output = zeros(nt, ncoeffs + 1)
output[:, 1] = tf_array
output[:, 2: end] = transpose(coeffs_array)
npzwrite("correction_coef.npy", output)

max_stars_repo_name: thalesfr/MagnusCorrection

max_issues_repo_name: thalesfr/MagnusCorrection

max_forks_repo_name: thalesfr/MagnusCorrection


text:
using CairoMakie, VegaLite, Colors, LaTeXStrings, MakieTeX
using MBSinBLG

# DATA PATHS
pathfig2 = "MBSinBLG/data/fig2"

pathfig3 = "MBSinBLG/data/fig3"

pathfig4a = "MBSinBLG/data/fig4/panela"
pathfig4b = "MBSinBLG/data/fig4/panelb"
pathfig4c = "MBSinBLG/data/fig4/panela"
pathfig4d = "MBSinBLG/data/fig4/panelb"

pathfig5a = "MBSinBLG/data/fig5/panela"
pathfig5b = "MBSinBLG/data/fig5/panelb"
pathfig5c = "MBSinBLG/data/fig5/panelc"
pathfig5d = "MBSinBLG/data/fig5/paneld"

pathfig6a1 = "MBSinBLG/data/fig6/panela_red"
pathfig6a2 = "MBSinBLG/data/fig6/panela_blue"
pathfig6b  = "MBSinBLG/data/fig6/panelb"
pathfig6c1 = "MBSinBLG/data/fig6/panelc_red"
pathfig6c2 = "MBSinBLG/data/fig6/panelc_blue"
pathfig6d  = "MBSinBLG/data/fig6/paneld"
pathfig6e  = "MBSinBLG/data/fig6/panele"
pathfig6f  = "MBSinBLG/data/fig6/panelf"

pathfig7 = "MBSinBLG/data/fig7"

# fig2
fig2plot(pathfig2)

# fig3
fig3plot(pathfig3)

# fig4
figab = fig4plot(pathfig4a, pathfig4b) #fig a and b
figc = ldosonlattice(pathfig4c, "reds", W = 2700)
figd = ldosonlattice(pathfig4d, "reds", W = 2700)

# fig5
fig5plot(pathfig5a, pathfig5b, pathfig5c, pathfig5d)

# fig6
figa1 = ldosonlattice(pathfig6a1, "reds", angle = 2)
figa2 = ldosonlattice(pathfig6a2, "blues", angle = 2)
figb  = ldosonlattice(pathfig6b, "reds", angle = 2)
figc1 = ldosonlattice(pathfig6c1, "reds", angle = 2)
figc2 = ldosonlattice(pathfig6c2, "blues", angle = 2)
figd  = ldosonlattice(pathfig6d, "reds", angle = 2)
figef = fig6plot(pathfig6e, pathfig6f)

# fig7
fig7plot(pathfig7)

max_stars_repo_name: fernandopenaranda/MBSinBLG

max_issues_repo_name: fernandopenaranda/MBSinBLG

max_forks_repo_name: fernandopenaranda/MBSinBLG


text:
include("DeterministicMetadata.jl")
include("ProbabilisticMetadata.jl")
include("ScenariosMetadata.jl")
include("SingleTimeSeriesMetadata.jl")

export get_count
export get_horizon
export get_initial_timestamp
export get_interval
export get_length
export get_name
export get_percentiles
export get_resolution
export get_scaling_factor_multiplier
export get_scenario_count
export get_time_series_type
export get_time_series_uuid
export set_count!
export set_horizon!
export set_initial_timestamp!
export set_interval!
export set_length!
export set_name!
export set_percentiles!
export set_resolution!
export set_scaling_factor_multiplier!
export set_scenario_count!
export set_time_series_type!
export set_time_series_uuid!


text:
using SIIPExamples

using PowerSystems
using PowerSimulations
const PSI = PowerSimulations
using D3TypeTrees

using Dates
using DataFrames
using TimeSeries

using Cbc #solver

rts_dir = SIIPExamples.download("https://github.com/GridMod/RTS-GMLC")
rts_src_dir = joinpath(rts_dir, "RTS_Data", "SourceData")
rts_siip_dir = joinpath(rts_dir, "RTS_Data", "FormattedData", "SIIP");

rawsys = PowerSystems.PowerSystemTableData(
    rts_src_dir,
    100.0,
    joinpath(rts_siip_dir, "user_descriptors.yaml"),
    timeseries_metadata_file = joinpath(rts_siip_dir, "timeseries_pointers.json"),
    generator_mapping_file = joinpath(rts_siip_dir, "generator_mapping.yaml"),
);
sys = System(rawsys; time_series_resolution = Dates.Hour(1));

MultiDay = collect(
    DateTime("2020-01-01T00:00:00"):Hour(1):(DateTime("2020-01-01T00:00:00") + Hour(8783)),
);

for gen in get_components(ThermalGen, sys)
    varcost = get_operation_cost(gen)
    market_bid_cost = MarketBidCost(;
        variable = nothing,
        no_load = get_fixed(varcost),
        start_up = (hot = get_start_up(varcost), warm = 0.0, cold = 0.0),
        shut_down = get_shut_down(varcost),
        ancillary_services = Vector{Service}(),
    )
    set_operation_cost!(gen, market_bid_cost)

    data = TimeArray(MultiDay, repeat([get_cost(get_variable(varcost))], 8784))
    _time_series = SingleTimeSeries("variable_cost", data)
    set_variable_cost!(sys, gen, _time_series)
end

horizon = 24;
interval = Dates.Hour(24);
transform_single_time_series!(sys, horizon, interval)

uc_template = template_unit_commitment(network = CopperPlatePowerModel)

uc_template.devices[:Generators] =
    DeviceModel(ThermalStandard, ThermalMultiStartUnitCommitment)

solver = optimizer_with_attributes(Cbc.Optimizer, "logLevel" => 1, "ratioGap" => 0.5)

problem = OperationsProblem(
    EconomicDispatchProblem,
    uc_template,
    sys,
    horizon = 4,
    optimizer = solver,
    balance_slack_variables = true,
)

solve!(problem)

# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl


text:
# functions for convenience of use

## diagonal view

function diagview{T}(a::DenseArray{T,2})
    m, n = size(a)
    s1, s2 = strides(a)
    len = min(m, n)
    StridedView(parent(a), offset(a), (len,), ContRank{0}, (s1 + s2,))
end

## row vector view

function rowvec_view{T}(a::DenseArray{T,2}, i::Integer)
    m, n = size(a)
    s1, s2 = strides(a)
    StridedView(parent(a), offset(a) + (i-1) * s1, (n,), ContRank{0}, (s2,))
end

## flatten_view

flatten_view(a::ContiguousArray) =
    ContiguousView(parent(a), offset(a), (length(a),))

## reshape_view

function reshape_view{N}(a::ContiguousArray, shp::NTuple{N,Int})
    prod(shp) == length(a) || throw(DimensionMismatch("Inconsistent array size."))
    ContiguousView(parent(a), offset(a), shp)
end

## ellipview

@compat ellipview{T}(a::DenseArray{T,2}, i::Union{Integer, UnitRange}) = view(a, :, i)
@compat ellipview{T}(a::DenseArray{T,3}, i::Union{Integer, UnitRange}) = view(a, :, :, i)
@compat ellipview{T}(a::DenseArray{T,4}, i::Union{Integer, UnitRange}) = view(a, :, :, :, i)
@compat ellipview{T}(a::DenseArray{T,5}, i::Union{Integer, UnitRange}) = view(a, :, :, :, :, i)
@compat ellipview{T,N}(a::DenseArray{T,N}, i::Union{Integer, UnitRange}) = view(a, ntuple(i->Colon(),N-1)..., i)


text:
using DiffEqSensitivity, Test

@test DiffEqSensitivity.hasbranching(1, 2) do x, y
   (x < 0 ? -x : x) + exp(y)
end

@test !DiffEqSensitivity.hasbranching(1, 2) do x, y
   ifelse(x < 0, -x, x) + exp(y)
end


text:
module Targe2Showroom

__precompile__(false)

using Targe2
using Printf
using DelimitedFiles
import Statistics: mean
using WriteVTK

function _makepyloadscript(file)
    pyfile = "loadscript.py"
    open(pyfile, "w") do fid
        println(fid, """
from paraview.simple import *
paraview.simple._DisableFirstRenderCameraReset()

# create a new 'XML Unstructured Grid Reader'
triangulation = XMLUnstructuredGridReader(FileName=['$(file).vtu'])

# find source
plotData1 = FindSource('PlotData1')

# get active view
renderView1 = GetActiveViewOrCreate('RenderView')
# uncomment following to set a specific view size
# renderView1.ViewSize = [400, 400]

# show data in view
triangulationDisplay = Show(triangulation, renderView1)

# trace defaults for the display properties.
triangulationDisplay.Representation = 'Surface'
triangulationDisplay.ColorArrayName = [None, '']
triangulationDisplay.OSPRayScaleFunction = 'PiecewiseFunction'
triangulationDisplay.SelectOrientationVectors = 'None'
triangulationDisplay.ScaleFactor = 20.0
triangulationDisplay.SelectScaleArray = 'None'
triangulationDisplay.GlyphType = 'Arrow'
triangulationDisplay.GlyphTableIndexArray = 'None'
triangulationDisplay.GaussianRadius = 1.0
triangulationDisplay.SetScaleArray = [None, '']
triangulationDisplay.ScaleTransferFunction = 'PiecewiseFunction'
triangulationDisplay.OpacityArray = [None, '']
triangulationDisplay.OpacityTransferFunction = 'PiecewiseFunction'
triangulationDisplay.DataAxesGrid = 'GridAxesRepresentation'
triangulationDisplay.SelectionCellLabelFontFile = ''
triangulationDisplay.SelectionPointLabelFontFile = ''
triangulationDisplay.PolarAxes = 'PolarAxesRepresentation'
triangulationDisplay.ScalarOpacityUnitDistance = 16.62540800220111

# init the 'GridAxesRepresentation' selected for 'DataAxesGrid'
triangulationDisplay.DataAxesGrid.XTitleFontFile = ''
triangulationDisplay.DataAxesGrid.YTitleFontFile = ''
triangulationDisplay.DataAxesGrid.ZTitleFontFile = ''
triangulationDisplay.DataAxesGrid.XLabelFontFile = ''
triangulationDisplay.DataAxesGrid.YLabelFontFile = ''
triangulationDisplay.DataAxesGrid.ZLabelFontFile = ''

# init the 'PolarAxesRepresentation' selected for 'PolarAxes'
triangulationDisplay.PolarAxes.PolarAxisTitleFontFile = ''
triangulationDisplay.PolarAxes.PolarAxisLabelFontFile = ''
triangulationDisplay.PolarAxes.LastRadialAxisTextFontFile = ''
triangulationDisplay.PolarAxes.SecondaryRadialAxesTextFontFile = ''

# reset view to fit data
renderView1.ResetCamera()

# update the view to ensure updated data information
renderView1.Update()

# change representation type
triangulationDisplay.SetRepresentationType('Surface With Edges')

# set scalar coloring
ColorBy(triangulationDisplay, ('CELLS', 'Regions'))

# Properties modified on triangulationDisplay
triangulationDisplay.EdgeColor = [1.0, 1.0, 0.4980392156862745]

# rescale color and/or opacity maps used to include current data range
triangulationDisplay.RescaleTransferFunctionToDataRange(True, False)

# show color bar/color legend
triangulationDisplay.SetScalarBarVisibility(renderView1, True)

# get color transfer function/color map for 'Regions'
regionsLUT = GetColorTransferFunction('Regions')

# Properties modified on xMLUnstructuredGridReader1Display.DataAxesGrid
triangulationDisplay.DataAxesGrid.GridAxesVisibility = 1

# show color bar/color legend
triangulationDisplay.SetScalarBarVisibility(renderView1, False)

# reset view to fit data
renderView1.ResetCamera()

# save screenshot
SaveScreenshot('$(file).png', renderView1, ImageResolution=[618, 603])
""")
    end
    return pyfile
end

function writevtk(filename, mesh)
    cells = MeshCell[]
    cdata = fill(0.0, size(mesh.triconn, 1))
    celltype = (size(mesh.triconn, 2) == 3) ? VTKCellTypes.VTK_TRIANGLE : VTKCellTypes.VTK_QUADRATIC_TRIANGLE
    for i = 1:size(mesh.triconn, 1)
        push!(cells, MeshCell(celltype, vec(view(mesh.triconn, i, :))))
    end
    for i = 1:length(mesh.trigroups)
        for j = 1:length(mesh.trigroups[i])
            t = mesh.trigroups[i][j]
            cdata[t] = i
        end
    end
    vtk = vtk_grid(filename, transpose(mesh.xy), cells)
    vtk_cell_data(vtk, cdata, "Regions")
    vtk_save(vtk)
    return true
end

function showmesh(filename, mesh)
    writevtk(filename, mesh)
    pyfile = _makepyloadscript(filename)
    @async run(`"paraview.exe" --script=$(pyfile)`)
    return
end

"""
    demo(filename, commands)

Generate a mesh Targe2 and show it with Paraview.
"""
function demo(filename, commands; show = false, kwargs...)
    mesh = triangulate(commands, kwargs...)
    show && showmesh(filename, mesh)
    return mesh
end

end


text:
"""
    mean(::AbstractSecondOrderTensor{3})
    mean(::AbstractSymmetricSecondOrderTensor{3})

Compute the mean value of diagonal entries of a square tensor.

# Examples
```jldoctest
julia> x = rand(Mat{3,3})
3×3 Tensor{Tuple{3, 3}, Float64, 2, 9}:
 0.590845  0.460085  0.200586
 0.766797  0.794026  0.298614
 0.566237  0.854147  0.246837

julia> mean(x)
0.5439025118691712
```
"""
@inline mean(x::AbstractSquareTensor{3}) = tr(x) / 3

"""
    vol(::AbstractSecondOrderTensor{3})
    vol(::AbstractSymmetricSecondOrderTensor{3})

Compute the volumetric part of a square tensor.
Supported only for tensors in 3D.

# Examples
```jldoctest
julia> x = rand(Mat{3,3})
3×3 Tensor{Tuple{3, 3}, Float64, 2, 9}:
 0.590845  0.460085  0.200586
 0.766797  0.794026  0.298614
 0.566237  0.854147  0.246837

julia> vol(x)
3×3 Tensor{Tuple{3, 3}, Float64, 2, 9}:
 0.543903  0.0       0.0
 0.0       0.543903  0.0
 0.0       0.0       0.543903

julia> vol(x) + dev(x) ≈ x
true
```
"""
@inline function vol(x::AbstractSquareTensor{3})
    v = mean(x)
    z = zero(v)
    typeof(x)((i,j) -> ifelse(i == j, v, z))
end

"""
    vol(::AbstractVec{3})

Compute the volumetric part of a vector (assuming principal values of stresses and strains).
Supported only for tensors in 3D.

# Examples
```jldoctest
julia> x = rand(Vec{3})
3-element Vec{3, Float64}:
 0.5908446386657102
 0.7667970365022592
 0.5662374165061859

julia> vol(x)
3-element Vec{3, Float64}:
 0.6412930305580518
 0.6412930305580518
 0.6412930305580518

julia> vol(x) + dev(x) ≈ x
true
```
"""
@inline vol(x::AbstractVec{3}) = mean(x) * ones(x)

"""
    vol(::Type{FourthOrderTensor{3}})
    vol(::Type{SymmetricFourthOrderTensor{3}})

Construct volumetric fourth order identity tensor.
Supported only for tensors in 3D.

# Examples
```jldoctest
julia> x = rand(Mat{3,3});

julia> I = one(FourthOrderTensor{3});

julia> I_vol = vol(FourthOrderTensor{3});

julia> I_vol ⊡ x ≈ I ⊡ vol(x)
true

julia> vol(FourthOrderTensor{3}) + dev(FourthOrderTensor{3}) ≈ one(FourthOrderTensor{3})
true
```
"""
@inline vol(x::Type{TT}) where {TT <: Tensor} = _vol(basetype(TT))
@inline function _vol(x::Type{Tensor{NTuple{4, 3}, T}}) where {T}
    δ = one(SecondOrderTensor{3, T})
    δ ⊗ δ / T(3)
end
@inline function _vol(x::Type{Tensor{NTuple{2, @Symmetry{3,3}}, T}}) where {T}
    δ = one(SymmetricSecondOrderTensor{3, T})
    δ ⊗ δ / T(3)
end
@inline _vol(x::Type{Tensor{NTuple{4, 3}}}) = _vol(Tensor{NTuple{4, 3}, Float64})
@inline _vol(x::Type{Tensor{NTuple{2, @Symmetry{3,3}}}}) = _vol(Tensor{NTuple{2, @Symmetry{3,3}}, Float64})

"""
    dev(::AbstractSecondOrderTensor{3})
    dev(::AbstractSymmetricSecondOrderTensor{3})

Compute the deviatoric part of a square tensor.
Supported only for tensors in 3D.

# Examples
```jldoctest
julia> x = rand(Mat{3,3})
3×3 Tensor{Tuple{3, 3}, Float64, 2, 9}:
 0.590845  0.460085  0.200586
 0.766797  0.794026  0.298614
 0.566237  0.854147  0.246837

julia> dev(x)
3×3 Tensor{Tuple{3, 3}, Float64, 2, 9}:
 0.0469421  0.460085   0.200586
 0.766797   0.250123   0.298614
 0.566237   0.854147  -0.297065

julia> tr(dev(x))
0.0
```
"""
@inline dev(x::AbstractSquareTensor{3}) = x - vol(x)

"""
    dev(::AbstractVec{3})

Compute the deviatoric part of a vector (assuming principal values of stresses and strains).
Supported only for tensors in 3D.

# Examples
```jldoctest
julia> x = rand(Vec{3})
3-element Vec{3, Float64}:
 0.5908446386657102
 0.7667970365022592
 0.5662374165061859

julia> dev(x)
ERROR: StackOverflowError:
Stacktrace:
 [1] vol(x::Vec{3, Float64}) (repeats 79984 times)
   @ Tensorial ~/Documents/Source code/Julia/Tensorial/src/continuum_mechanics.jl:68

julia> vol(x) + dev(x) ≈ x
ERROR: StackOverflowError:
Stacktrace:
 [1] vol(x::Vec{3, Float64}) (repeats 79984 times)
   @ Tensorial ~/Documents/Source code/Julia/Tensorial/src/continuum_mechanics.jl:68
```
"""
@inline dev(x::AbstractVec{3}) = x - vol(x)

"""
    dev(::Type{FourthOrderTensor{3}})
    dev(::Type{SymmetricFourthOrderTensor{3}})

Construct deviatoric fourth order identity tensor.
Supported only for tensors in 3D.

# Examples
```jldoctest
julia> x = rand(Mat{3,3});

julia> I = one(FourthOrderTensor{3});

julia> I_dev = dev(FourthOrderTensor{3});

julia> I_dev ⊡ x ≈ I ⊡ dev(x)
true

julia> vol(FourthOrderTensor{3}) + dev(FourthOrderTensor{3}) ≈ one(FourthOrderTensor{3})
true
```
"""
@inline dev(x::Type{TT}) where {TT <: Tensor} = one(x) - vol(x)

"""
    stress_invariants(::AbstractSecondOrderTensor{3})
    stress_invariants(::AbstractSymmetricSecondOrderTensor{3})

Return `NamedTuple` storing stress invariants.

```math
\\begin{aligned}
I_1(\\bm{\\sigma}) &= \\mathrm{tr}(\\bm{\\sigma}) \\\\
I_2(\\bm{\\sigma}) &= \\frac{1}{2} (\\mathrm{tr}(\\bm{\\sigma})^2 - \\mathrm{tr}(\\bm{\\sigma}^2)) \\\\
I_3(\\bm{\\sigma}) &= \\det(\\bm{\\sigma})
\\end{aligned}
```

# Examples
```jldoctest
julia> σ = rand(SymmetricSecondOrderTensor{3})
3×3 SymmetricSecondOrderTensor{3, Float64, 6}:
 0.590845  0.766797  0.566237
 0.766797  0.460085  0.794026
 0.566237  0.794026  0.854147

julia> I₁, I₂, I₃ = stress_invariants(σ)
(I1 = 1.9050765715072775, I2 = -0.3695921176777066, I3 = -0.10054272199258936)
```

"""
@inline function stress_invariants(σ::AbstractSquareTensor{3})
    trσ = tr(σ)
    I1 = trσ
    I2 = (trσ^2 - tr(σ^2)) / 2
    I3 = det(σ)
    (; I1, I2, I3)
end

"""
    deviatoric_stress_invariants(::AbstractSecondOrderTensor{3})
    deviatoric_stress_invariants(::AbstractSymmetricSecondOrderTensor{3})

Return `NamedTuple` storing deviatoric stress invariants.

```math
\\begin{aligned}
J_1(\\bm{\\sigma}) &= \\mathrm{tr}(\\mathrm{dev}(\\bm{\\sigma})) = 0 \\\\
J_2(\\bm{\\sigma}) &= -\\frac{1}{2} \\mathrm{tr}(\\mathrm{dev}(\\bm{\\sigma})^2) \\\\
J_3(\\bm{\\sigma}) &= \\frac{1}{3} \\mathrm{tr}(\\mathrm{dev}(\\bm{\\sigma})^3)
\\end{aligned}
```

# Examples
```jldoctest
julia> σ = rand(SymmetricSecondOrderTensor{3})
3×3 SymmetricSecondOrderTensor{3, Float64, 6}:
 0.590845  0.766797  0.566237
 0.766797  0.460085  0.794026
 0.566237  0.794026  0.854147

julia> J₁, J₂, J₃ = deviatoric_stress_invariants(σ)
(J1 = 0.0, J2 = 1.5793643654463476, J3 = 0.6463152097154271)
```
"""
@inline function deviatoric_stress_invariants(σ::AbstractSquareTensor{3})
    I1, I2, I3 = stress_invariants(σ)
    s = dev(σ)
    J1 = zero(eltype(σ))
    J2 = I1^2/3 - I2             # tr(s^2) / 2
    J3 = 2I1^3/27 - I1*I2/3 + I3 # tr(s^3) / 3
    (; J1, J2, J3)
end


text:
module AVCodecs
  include(joinpath(dirname(@__FILE__),"..","..","..","init.jl"))
  w(f) = joinpath(avcodec_dir, f)

  using AVUtil

  include(w("LIBAVCODEC.jl"))

  AVPacket() = AVPacket([T<:Ptr ? C_NULL : zero(T) for T in AVPacket.types]...)

end

max_stars_repo_name: asafasban/AAVideoIO

max_issues_repo_name: asafasban/AAVideoIO

max_forks_repo_name: asafasban/AAVideoIO


text:
using HttpServer

http = HttpHandler(Base.PipeServer()) do req::Request, res::Response
    Response("Hello Unix World!")
end
http.events["listen"] = (socket_file) -> println("Listening file $socket_file...")

server = Server(http)
run(server, socket="/tmp/julia.socket")


text:
__precompile__()

"""
The Conda module provides access to the [conda](http://conda.pydata.org/) packages
manager. Its main purpose is to be used as a BinDeps provider, to install binary
dependencies of other Julia packages.

The main functions in Conda are:

- `Conda.add(package)`: install a package;
- `Conda.rm(package)`: remove (uninstall) a package;
- `Conda.update()`: update all installed packages to the latest version;
- `Conda.list()`: list all installed packages.
- `Conda.add_channel(channel)`: add a channel to the list of channels;
- `Conda.channels()`: get the current list of channels;
- `Conda.rm_channel(channel)`: remove a channel from the list of channels;

To use Conda as a binary provider for BinDeps, the `Conda.Manager` type is proposed. A
small example looks like this:

```julia
# Declare dependency
using BinDeps
@BinDeps.setup
netcdf = library_dependency("netcdf", aliases = ["libnetcdf","libnetcdf4"])

using Conda
#  Use alternative conda channel.
Conda.add_channel("my_channel")
provides(Conda.Manager, "libnetcdf", netcdf)
```
"""
module Conda
using Compat
import Compat.String
using JSON

const deps_file = joinpath(dirname(@__FILE__), "..", "deps", "deps.jl")

if isfile(deps_file)
    # Includes definition for ROOTENV
    include(deps_file)
else
    error("Conda is not properly configured.  Run Pkg.build(\"Conda\") before importing the Conda module.")
end

const Environment = Union{AbstractString,Symbol}

"Prefix for installation of the environment"
function prefix(name::Symbol)
    sname = string(name)
    if isempty(sname)
        throw(ArgumentError("Environment name should be non empty."))
    end
    return joinpath(ROOTENV, "envs", sname)
end

function prefix(path::AbstractString)
    if !isdir(path)
        throw(ArgumentError("Path to conda environment is not valid."))
    end
    return path
end

const PREFIX = prefix(ROOTENV)

"Prefix for the executable files installed with the packages"
function bin_dir(env::Environment)
    return is_windows() ? joinpath(prefix(env), "Library", "bin") : joinpath(prefix(env), "bin")
end
const BINDIR = bin_dir(ROOTENV)

"Prefix for the shared libraries installed with the packages"
function lib_dir(env::Environment)
    return is_windows() ? joinpath(prefix(env), "Library", "bin") : joinpath(prefix(env), "lib")
end
const LIBDIR = lib_dir(ROOTENV)

"Prefix for the python scripts. On UNIX, this is the same than Conda.BINDIR"
function script_dir(env::Environment)
    return is_windows() ? joinpath(prefix(env), "Scripts") : bin_dir(env)
end
const SCRIPTDIR = script_dir(ROOTENV)

"Prefix where the `python` command lives"
function python_dir(env::Environment)
    return is_windows() ? prefix(env) : bin_dir(env)
end
const PYTHONDIR = python_dir(ROOTENV)

function conda_bin(env::Environment)
    if is_windows()
        p = script_dir(env)
        conda_bat = joinpath(p, "conda.bat")
        return isfile(conda_bat) ? conda_bat : joinpath(p, "conda.exe")
    else
        return joinpath(script_dir(env), "conda")
    end
end
const conda = conda_bin(ROOTENV)

"Path to the condarc file"
conda_rc(env::Environment) = joinpath(prefix(env), "condarc-julia.yml")
const CONDARC = conda_rc(ROOTENV)

"""
Use a cleaned up environment for the command `cmd`.

Any environment variable starting by CONDA or PYTHON will interact with the run.
"""
function _set_conda_env(cmd, env::Environment=ROOTENV)
    env_var = copy(ENV)
    to_remove = Compat.UTF8String[]
    for var in keys(env_var)
        if startswith(var, "CONDA") || startswith(var, "PYTHON")
            push!(to_remove, var)
        end
    end
    for var in to_remove
        pop!(env_var, var)
    end
    env_var["CONDARC"] = conda_rc(env)
    env_var["CONDA_PREFIX"] = env_var["CONDA_DEFAULT_ENV"] = prefix(env)
    setenv(cmd, env_var)
end

"Run conda command with environment variables set."
function runconda(args::Cmd, env::Environment=ROOTENV)
    _install_conda(env)
    run(_set_conda_env(`$(conda_bin(env)) $args`, env))
end

"Run conda command with environment variables set and return the json output as a julia object"
function parseconda(args::Cmd, env::Environment=ROOTENV)
    _install_conda(env)
    JSON.parse(readstring(_set_conda_env(`$(conda_bin(env)) $args --json`, env)))
end

"Get the miniconda installer URL."
function _installer_url()
    res = "https://repo.continuum.io/miniconda/Miniconda2-latest-"
    if is_apple()
        res *= "MacOSX"
    elseif is_linux()
        res *= "Linux"
    elseif is_windows()
        res *= "Windows"
    else
        error("Unsuported OS.")
    end
    res *= Sys.WORD_SIZE == 64 ? "-x86_64" : "-x86"
    res *= is_windows() ? ".exe" : ".sh"
    return res
end

is_windows() && include("outlook.jl")

"Install miniconda if it hasn't been installed yet; _install_conda(true) installs Conda even if it has already been installed."
function _install_conda(env::Environment, force::Bool=false)
    if force || !isfile(Conda.conda)
        if is_windows() && is_outlook_running()
            error("""\n
            Outlook is running, and running the Miniconda installer will crash it.
            Please quit Outlook and then restart the installation.

            For more information, see:
                https://github.com/Luthaf/Conda.jl/issues/15
                https://github.com/conda/conda/issues/1084
            """)
        end
        info("Downloading miniconda installer ...")
        if is_unix()
            installer = joinpath(PREFIX, "installer.sh")
        end
        if is_windows()
            installer = joinpath(PREFIX, "installer.exe")
        end
        download(_installer_url(), installer)

        info("Installing miniconda ...")
        if is_unix()
            chmod(installer, 33261)  # 33261 corresponds to 755 mode of the 'chmod' program
            run(`$installer -b -f -p $PREFIX`)
        end
        if is_windows()
            if VERSION >= v"0.5.0-dev+8873" # Julia PR #13780
                run(Cmd(`$installer /S /AddToPath=0 /RegisterPython=0 /D=$PREFIX`, windows_verbatim=true))
            else
                # Workaround a bug in command-line argument parsing, see
                # https://github.com/Luthaf/Conda.jl/issues/17
                if match(r" {2,}", "") != nothing
                    error("The installer will fail when the path=\"$PREFIX\" contains two consecutive spaces")
                end
                run(`$installer /S /AddToPath=0 /RegisterPython=0 $(split("/D=$PREFIX"))`)
            end
        end
        Conda.add_channel("defaults")
        # Update conda because conda 4.0 is needed and miniconda download installs only 3.9
        runconda(`update -y conda`)
    end
    if !isdir(prefix(env))
        # conda doesn't allow totally empty environments. using zlib as the default package
        runconda(`create -y -p $(prefix(env)) zlib`)
    end
end

"Install a new package."
function add(pkg::AbstractString, env::Environment=ROOTENV)
    runconda(`install -y $pkg`, env)
end

"Uninstall a package."
function rm(pkg::AbstractString, env::Environment=ROOTENV)
    runconda(`remove -y $pkg`, env)
end

"Update all installed packages."
function update(env::Environment=ROOTENV)
    runconda(`update -y --all`, env)
end

"List all installed packages as an dict of tuples with (version_number, fullname)."
function  _installed_packages_dict(env::Environment=ROOTENV)
    _install_conda(env)
    package_dict = Dict{Compat.UTF8String, Tuple{VersionNumber, Compat.UTF8String}}()
    for line in eachline(_set_conda_env(`$(conda_bin(env)) list`, env))
        line = chomp(line)
        if !startswith(line, "#")
            name, version, build_string = split(line)
            # As julia do not accepts xx.yy.zz.rr version number the last part is removed.
            # see issue https://github.com/JuliaLang/julia/issues/7282 a maximum of three levels is inserted
            version_number = join(split(version,".")[1:min(3,end)],".")
            try
                package_dict[name] = (convert(VersionNumber, version_number), line)
            catch
                package_dict[name] = (v"9999.9999.9999", line)
                warn("Failed parsing string: \"$(version_number)\" to a version number. Please open an issue!")
            end
        end
    end
    return package_dict
end

"List all installed packages as an array."
_installed_packages(env::Environment=ROOTENV) = keys(_installed_packages_dict(env))

"List all installed packages to standard output."
function list(env::Environment=ROOTENV)
    runconda(`list`, env)
end

"Get the exact version of a package."
function version(name::AbstractString, env::Environment=ROOTENV)
    packages = parseconda(`list`, env)
    for package in packages
        if startswith(package, name) || ismatch(Regex("::$name"), package)
            return package
        end
    end
    error("Could not find the $name package")
end

"Search packages for a string"
function search(package::AbstractString, env::Environment=ROOTENV)
    return collect(keys(parseconda(`search $package`, env)))
end

"Search a specific version of a package"
function search(package::AbstractString, ver::AbstractString, env::Environment=ROOTENV)
    ret=parseconda(`search $package`, env)
    out = Compat.UTF8String[]
    for k in keys(ret)
      for i in 1:length(ret[k])
        ret[k][i]["version"]==ver && push!(out,k)
      end
    end
    out
end

"Check if a given package exists."
function exists(package::AbstractString, env::Environment=ROOTENV)
    if contains(package,"==")
      pkg,ver=split(package,"==")  # Remove version if provided
      return pkg in search(pkg,ver,env)
    else
      if package in search(package,env)
        # Found exactly this package
        return true
      else
        return false
      end
    end
end

"Get the list of channels used to search packages"
function channels(env::Environment=ROOTENV)
    ret=parseconda(`config --get channels`, env)
    if haskey(ret["get"], "channels")
        return collect(Compat.UTF8String, ret["get"]["channels"])
    else
        return Compat.UTF8String[]
    end
end

"Add a channel to the list of channels"
function add_channel(channel::AbstractString, env::Environment=ROOTENV)
    runconda(`config --add channels $channel --force`, env)
end

"Remove a channel from the list of channels"
function rm_channel(channel::AbstractString, env::Environment=ROOTENV)
    runconda(`config --remove channels $channel --force`, env)
end

include("bindeps_conda.jl")

end