text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

@doc raw"""
    ObjsFile(;
        channels=nothing,
        comments_count=nothing,
        created=nothing,
        date_delete=nothing,
        display_as_bot=nothing,
        editable=nothing,
        editor=nothing,
        external_id=nothing,
        external_type=nothing,
        external_url=nothing,
        filetype=nothing,
        groups=nothing,
        has_rich_preview=nothing,
        id=nothing,
        image_exif_rotation=nothing,
        ims=nothing,
        is_external=nothing,
        is_public=nothing,
        is_starred=nothing,
        is_tombstoned=nothing,
        last_editor=nothing,
        mimetype=nothing,
        mode=nothing,
        name=nothing,
        non_owner_editable=nothing,
        num_stars=nothing,
        original_h=nothing,
        original_w=nothing,
        permalink=nothing,
        permalink_public=nothing,
        pinned_info=nothing,
        pinned_to=nothing,
        pretty_type=nothing,
        preview=nothing,
        public_url_shared=nothing,
        reactions=nothing,
        shares=nothing,
        size=nothing,
        source_team=nothing,
        state=nothing,
        thumb_1024=nothing,
        thumb_1024_h=nothing,
        thumb_1024_w=nothing,
        thumb_160=nothing,
        thumb_360=nothing,
        thumb_360_h=nothing,
        thumb_360_w=nothing,
        thumb_480=nothing,
        thumb_480_h=nothing,
        thumb_480_w=nothing,
        thumb_64=nothing,
        thumb_720=nothing,
        thumb_720_h=nothing,
        thumb_720_w=nothing,
        thumb_80=nothing,
        thumb_800=nothing,
        thumb_800_h=nothing,
        thumb_800_w=nothing,
        thumb_960=nothing,
        thumb_960_h=nothing,
        thumb_960_w=nothing,
        thumb_tiny=nothing,
        timestamp=nothing,
        title=nothing,
        updated=nothing,
        url_private=nothing,
        url_private_download=nothing,
        user=nothing,
        user_team=nothing,
        username=nothing,
    )

    - channels::Vector{DefsChannelId}
    - comments_count::Int32
    - created::Int32
    - date_delete::Int32
    - display_as_bot::Bool
    - editable::Bool
    - editor::DefsUserId
    - external_id::String
    - external_type::String
    - external_url::String
    - filetype::String
    - groups::Vector{DefsGroupId}
    - has_rich_preview::Bool
    - id::DefsFileId
    - image_exif_rotation::Int32
    - ims::Vector{DefsDmId}
    - is_external::Bool
    - is_public::Bool
    - is_starred::Bool
    - is_tombstoned::Bool
    - last_editor::DefsUserId
    - mimetype::String
    - mode::String
    - name::String
    - non_owner_editable::Bool
    - num_stars::Int32
    - original_h::Int32
    - original_w::Int32
    - permalink::String
    - permalink_public::String
    - pinned_info::DefsPinnedInfo
    - pinned_to::Vector{DefsChannel}
    - pretty_type::String
    - preview::String
    - public_url_shared::Bool
    - reactions::Vector{ObjsReaction}
    - shares::ObjsFileShares
    - size::Int32
    - source_team::DefsTeam
    - state::String
    - thumb_1024::String
    - thumb_1024_h::Int32
    - thumb_1024_w::Int32
    - thumb_160::String
    - thumb_360::String
    - thumb_360_h::Int32
    - thumb_360_w::Int32
    - thumb_480::String
    - thumb_480_h::Int32
    - thumb_480_w::Int32
    - thumb_64::String
    - thumb_720::String
    - thumb_720_h::Int32
    - thumb_720_w::Int32
    - thumb_80::String
    - thumb_800::String
    - thumb_800_h::Int32
    - thumb_800_w::Int32
    - thumb_960::String
    - thumb_960_h::Int32
    - thumb_960_w::Int32
    - thumb_tiny::String
    - timestamp::Int32
    - title::String
    - updated::Int32
    - url_private::String
    - url_private_download::String
    - user::String
    - user_team::DefsTeam
    - username::String
"""
mutable struct ObjsFile <: SwaggerModel
    channels::Any # spec type: Union{ Nothing, Vector{DefsChannelId} } # spec name: channels
    comments_count::Any # spec type: Union{ Nothing, Int32 } # spec name: comments_count
    created::Any # spec type: Union{ Nothing, Int32 } # spec name: created
    date_delete::Any # spec type: Union{ Nothing, Int32 } # spec name: date_delete
    display_as_bot::Any # spec type: Union{ Nothing, Bool } # spec name: display_as_bot
    editable::Any # spec type: Union{ Nothing, Bool } # spec name: editable
    editor::Any # spec type: Union{ Nothing, DefsUserId } # spec name: editor
    external_id::Any # spec type: Union{ Nothing, String } # spec name: external_id
    external_type::Any # spec type: Union{ Nothing, String } # spec name: external_type
    external_url::Any # spec type: Union{ Nothing, String } # spec name: external_url
    filetype::Any # spec type: Union{ Nothing, String } # spec name: filetype
    groups::Any # spec type: Union{ Nothing, Vector{DefsGroupId} } # spec name: groups
    has_rich_preview::Any # spec type: Union{ Nothing, Bool } # spec name: has_rich_preview
    id::Any # spec type: Union{ Nothing, DefsFileId } # spec name: id
    image_exif_rotation::Any # spec type: Union{ Nothing, Int32 } # spec name: image_exif_rotation
    ims::Any # spec type: Union{ Nothing, Vector{DefsDmId} } # spec name: ims
    is_external::Any # spec type: Union{ Nothing, Bool } # spec name: is_external
    is_public::Any # spec type: Union{ Nothing, Bool } # spec name: is_public
    is_starred::Any # spec type: Union{ Nothing, Bool } # spec name: is_starred
    is_tombstoned::Any # spec type: Union{ Nothing, Bool } # spec name: is_tombstoned
    last_editor::Any # spec type: Union{ Nothing, DefsUserId } # spec name: last_editor
    mimetype::Any # spec type: Union{ Nothing, String } # spec name: mimetype
    mode::Any # spec type: Union{ Nothing, String } # spec name: mode
    name::Any # spec type: Union{ Nothing, String } # spec name: name
    non_owner_editable::Any # spec type: Union{ Nothing, Bool } # spec name: non_owner_editable
    num_stars::Any # spec type: Union{ Nothing, Int32 } # spec name: num_stars
    original_h::Any # spec type: Union{ Nothing, Int32 } # spec name: original_h
    original_w::Any # spec type: Union{ Nothing, Int32 } # spec name: original_w
    permalink::Any # spec type: Union{ Nothing, String } # spec name: permalink
    permalink_public::Any # spec type: Union{ Nothing, String } # spec name: permalink_public
    pinned_info::Any # spec type: Union{ Nothing, DefsPinnedInfo } # spec name: pinned_info
    pinned_to::Any # spec type: Union{ Nothing, Vector{DefsChannel} } # spec name: pinned_to
    pretty_type::Any # spec type: Union{ Nothing, String } # spec name: pretty_type
    preview::Any # spec type: Union{ Nothing, String } # spec name: preview
    public_url_shared::Any # spec type: Union{ Nothing, Bool } # spec name: public_url_shared
    reactions::Any # spec type: Union{ Nothing, Vector{ObjsReaction} } # spec name: reactions
    shares::Any # spec type: Union{ Nothing, ObjsFileShares } # spec name: shares
    size::Any # spec type: Union{ Nothing, Int32 } # spec name: size
    source_team::Any # spec type: Union{ Nothing, DefsTeam } # spec name: source_team
    state::Any # spec type: Union{ Nothing, String } # spec name: state
    thumb_1024::Any # spec type: Union{ Nothing, String } # spec name: thumb_1024
    thumb_1024_h::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_1024_h
    thumb_1024_w::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_1024_w
    thumb_160::Any # spec type: Union{ Nothing, String } # spec name: thumb_160
    thumb_360::Any # spec type: Union{ Nothing, String } # spec name: thumb_360
    thumb_360_h::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_360_h
    thumb_360_w::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_360_w
    thumb_480::Any # spec type: Union{ Nothing, String } # spec name: thumb_480
    thumb_480_h::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_480_h
    thumb_480_w::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_480_w
    thumb_64::Any # spec type: Union{ Nothing, String } # spec name: thumb_64
    thumb_720::Any # spec type: Union{ Nothing, String } # spec name: thumb_720
    thumb_720_h::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_720_h
    thumb_720_w::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_720_w
    thumb_80::Any # spec type: Union{ Nothing, String } # spec name: thumb_80
    thumb_800::Any # spec type: Union{ Nothing, String } # spec name: thumb_800
    thumb_800_h::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_800_h
    thumb_800_w::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_800_w
    thumb_960::Any # spec type: Union{ Nothing, String } # spec name: thumb_960
    thumb_960_h::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_960_h
    thumb_960_w::Any # spec type: Union{ Nothing, Int32 } # spec name: thumb_960_w
    thumb_tiny::Any # spec type: Union{ Nothing, String } # spec name: thumb_tiny
    timestamp::Any # spec type: Union{ Nothing, Int32 } # spec name: timestamp
    title::Any # spec type: Union{ Nothing, String } # spec name: title
    updated::Any # spec type: Union{ Nothing, Int32 } # spec name: updated
    url_private::Any # spec type: Union{ Nothing, String } # spec name: url_private
    url_private_download::Any # spec type: Union{ Nothing, String } # spec name: url_private_download
    user::Any # spec type: Union{ Nothing, String } # spec name: user
    user_team::Any # spec type: Union{ Nothing, DefsTeam } # spec name: user_team
    username::Any # spec type: Union{ Nothing, String } # spec name: username

    function ObjsFile(;channels=nothing, comments_count=nothing, created=nothing, date_delete=nothing, display_as_bot=nothing, editable=nothing, editor=nothing, external_id=nothing, external_type=nothing, external_url=nothing, filetype=nothing, groups=nothing, has_rich_preview=nothing, id=nothing, image_exif_rotation=nothing, ims=nothing, is_external=nothing, is_public=nothing, is_starred=nothing, is_tombstoned=nothing, last_editor=nothing, mimetype=nothing, mode=nothing, name=nothing, non_owner_editable=nothing, num_stars=nothing, original_h=nothing, original_w=nothing, permalink=nothing, permalink_public=nothing, pinned_info=nothing, pinned_to=nothing, pretty_type=nothing, preview=nothing, public_url_shared=nothing, reactions=nothing, shares=nothing, size=nothing, source_team=nothing, state=nothing, thumb_1024=nothing, thumb_1024_h=nothing, thumb_1024_w=nothing, thumb_160=nothing, thumb_360=nothing, thumb_360_h=nothing, thumb_360_w=nothing, thumb_480=nothing, thumb_480_h=nothing, thumb_480_w=nothing, thumb_64=nothing, thumb_720=nothing, thumb_720_h=nothing, thumb_720_w=nothing, thumb_80=nothing, thumb_800=nothing, thumb_800_h=nothing, thumb_800_w=nothing, thumb_960=nothing, thumb_960_h=nothing, thumb_960_w=nothing, thumb_tiny=nothing, timestamp=nothing, title=nothing, updated=nothing, url_private=nothing, url_private_download=nothing, user=nothing, user_team=nothing, username=nothing)
        o = new()
        validate_property(ObjsFile, Symbol("channels"), channels)
        setfield!(o, Symbol("channels"), channels)
        validate_property(ObjsFile, Symbol("comments_count"), comments_count)
        setfield!(o, Symbol("comments_count"), comments_count)
        validate_property(ObjsFile, Symbol("created"), created)
        setfield!(o, Symbol("created"), created)
        validate_property(ObjsFile, Symbol("date_delete"), date_delete)
        setfield!(o, Symbol("date_delete"), date_delete)
        validate_property(ObjsFile, Symbol("display_as_bot"), display_as_bot)
        setfield!(o, Symbol("display_as_bot"), display_as_bot)
        validate_property(ObjsFile, Symbol("editable"), editable)
        setfield!(o, Symbol("editable"), editable)
        validate_property(ObjsFile, Symbol("editor"), editor)
        setfield!(o, Symbol("editor"), editor)
        validate_property(ObjsFile, Symbol("external_id"), external_id)
        setfield!(o, Symbol("external_id"), external_id)
        validate_property(ObjsFile, Symbol("external_type"), external_type)
        setfield!(o, Symbol("external_type"), external_type)
        validate_property(ObjsFile, Symbol("external_url"), external_url)
        setfield!(o, Symbol("external_url"), external_url)
        validate_property(ObjsFile, Symbol("filetype"), filetype)
        setfield!(o, Symbol("filetype"), filetype)
        validate_property(ObjsFile, Symbol("groups"), groups)
        setfield!(o, Symbol("groups"), groups)
        validate_property(ObjsFile, Symbol("has_rich_preview"), has_rich_preview)
        setfield!(o, Symbol("has_rich_preview"), has_rich_preview)
        validate_property(ObjsFile, Symbol("id"), id)
        setfield!(o, Symbol("id"), id)
        validate_property(ObjsFile, Symbol("image_exif_rotation"), image_exif_rotation)
        setfield!(o, Symbol("image_exif_rotation"), image_exif_rotation)
        validate_property(ObjsFile, Symbol("ims"), ims)
        setfield!(o, Symbol("ims"), ims)
        validate_property(ObjsFile, Symbol("is_external"), is_external)
        setfield!(o, Symbol("is_external"), is_external)
        validate_property(ObjsFile, Symbol("is_public"), is_public)
        setfield!(o, Symbol("is_public"), is_public)
        validate_property(ObjsFile, Symbol("is_starred"), is_starred)
        setfield!(o, Symbol("is_starred"), is_starred)
        validate_property(ObjsFile, Symbol("is_tombstoned"), is_tombstoned)
        setfield!(o, Symbol("is_tombstoned"), is_tombstoned)
        validate_property(ObjsFile, Symbol("last_editor"), last_editor)
        setfield!(o, Symbol("last_editor"), last_editor)
        validate_property(ObjsFile, Symbol("mimetype"), mimetype)
        setfield!(o, Symbol("mimetype"), mimetype)
        validate_property(ObjsFile, Symbol("mode"), mode)
        setfield!(o, Symbol("mode"), mode)
        validate_property(ObjsFile, Symbol("name"), name)
        setfield!(o, Symbol("name"), name)
        validate_property(ObjsFile, Symbol("non_owner_editable"), non_owner_editable)
        setfield!(o, Symbol("non_owner_editable"), non_owner_editable)
        validate_property(ObjsFile, Symbol("num_stars"), num_stars)
        setfield!(o, Symbol("num_stars"), num_stars)
        validate_property(ObjsFile, Symbol("original_h"), original_h)
        setfield!(o, Symbol("original_h"), original_h)
        validate_property(ObjsFile, Symbol("original_w"), original_w)
        setfield!(o, Symbol("original_w"), original_w)
        validate_property(ObjsFile, Symbol("permalink"), permalink)
        setfield!(o, Symbol("permalink"), permalink)
        validate_property(ObjsFile, Symbol("permalink_public"), permalink_public)
        setfield!(o, Symbol("permalink_public"), permalink_public)
        validate_property(ObjsFile, Symbol("pinned_info"), pinned_info)
        setfield!(o, Symbol("pinned_info"), pinned_info)
        validate_property(ObjsFile, Symbol("pinned_to"), pinned_to)
        setfield!(o, Symbol("pinned_to"), pinned_to)
        validate_property(ObjsFile, Symbol("pretty_type"), pretty_type)
        setfield!(o, Symbol("pretty_type"), pretty_type)
        validate_property(ObjsFile, Symbol("preview"), preview)
        setfield!(o, Symbol("preview"), preview)
        validate_property(ObjsFile, Symbol("public_url_shared"), public_url_shared)
        setfield!(o, Symbol("public_url_shared"), public_url_shared)
        validate_property(ObjsFile, Symbol("reactions"), reactions)
        setfield!(o, Symbol("reactions"), reactions)
        validate_property(ObjsFile, Symbol("shares"), shares)
        setfield!(o, Symbol("shares"), shares)
        validate_property(ObjsFile, Symbol("size"), size)
        setfield!(o, Symbol("size"), size)
        validate_property(ObjsFile, Symbol("source_team"), source_team)
        setfield!(o, Symbol("source_team"), source_team)
        validate_property(ObjsFile, Symbol("state"), state)
        setfield!(o, Symbol("state"), state)
        validate_property(ObjsFile, Symbol("thumb_1024"), thumb_1024)
        setfield!(o, Symbol("thumb_1024"), thumb_1024)
        validate_property(ObjsFile, Symbol("thumb_1024_h"), thumb_1024_h)
        setfield!(o, Symbol("thumb_1024_h"), thumb_1024_h)
        validate_property(ObjsFile, Symbol("thumb_1024_w"), thumb_1024_w)
        setfield!(o, Symbol("thumb_1024_w"), thumb_1024_w)
        validate_property(ObjsFile, Symbol("thumb_160"), thumb_160)
        setfield!(o, Symbol("thumb_160"), thumb_160)
        validate_property(ObjsFile, Symbol("thumb_360"), thumb_360)
        setfield!(o, Symbol("thumb_360"), thumb_360)
        validate_property(ObjsFile, Symbol("thumb_360_h"), thumb_360_h)
        setfield!(o, Symbol("thumb_360_h"), thumb_360_h)
        validate_property(ObjsFile, Symbol("thumb_360_w"), thumb_360_w)
        setfield!(o, Symbol("thumb_360_w"), thumb_360_w)
        validate_property(ObjsFile, Symbol("thumb_480"), thumb_480)
        setfield!(o, Symbol("thumb_480"), thumb_480)
        validate_property(ObjsFile, Symbol("thumb_480_h"), thumb_480_h)
        setfield!(o, Symbol("thumb_480_h"), thumb_480_h)
        validate_property(ObjsFile, Symbol("thumb_480_w"), thumb_480_w)
        setfield!(o, Symbol("thumb_480_w"), thumb_480_w)
        validate_property(ObjsFile, Symbol("thumb_64"), thumb_64)
        setfield!(o, Symbol("thumb_64"), thumb_64)
        validate_property(ObjsFile, Symbol("thumb_720"), thumb_720)
        setfield!(o, Symbol("thumb_720"), thumb_720)
        validate_property(ObjsFile, Symbol("thumb_720_h"), thumb_720_h)
        setfield!(o, Symbol("thumb_720_h"), thumb_720_h)
        validate_property(ObjsFile, Symbol("thumb_720_w"), thumb_720_w)
        setfield!(o, Symbol("thumb_720_w"), thumb_720_w)
        validate_property(ObjsFile, Symbol("thumb_80"), thumb_80)
        setfield!(o, Symbol("thumb_80"), thumb_80)
        validate_property(ObjsFile, Symbol("thumb_800"), thumb_800)
        setfield!(o, Symbol("thumb_800"), thumb_800)
        validate_property(ObjsFile, Symbol("thumb_800_h"), thumb_800_h)
        setfield!(o, Symbol("thumb_800_h"), thumb_800_h)
        validate_property(ObjsFile, Symbol("thumb_800_w"), thumb_800_w)
        setfield!(o, Symbol("thumb_800_w"), thumb_800_w)
        validate_property(ObjsFile, Symbol("thumb_960"), thumb_960)
        setfield!(o, Symbol("thumb_960"), thumb_960)
        validate_property(ObjsFile, Symbol("thumb_960_h"), thumb_960_h)
        setfield!(o, Symbol("thumb_960_h"), thumb_960_h)
        validate_property(ObjsFile, Symbol("thumb_960_w"), thumb_960_w)
        setfield!(o, Symbol("thumb_960_w"), thumb_960_w)
        validate_property(ObjsFile, Symbol("thumb_tiny"), thumb_tiny)
        setfield!(o, Symbol("thumb_tiny"), thumb_tiny)
        validate_property(ObjsFile, Symbol("timestamp"), timestamp)
        setfield!(o, Symbol("timestamp"), timestamp)
        validate_property(ObjsFile, Symbol("title"), title)
        setfield!(o, Symbol("title"), title)
        validate_property(ObjsFile, Symbol("updated"), updated)
        setfield!(o, Symbol("updated"), updated)
        validate_property(ObjsFile, Symbol("url_private"), url_private)
        setfield!(o, Symbol("url_private"), url_private)
        validate_property(ObjsFile, Symbol("url_private_download"), url_private_download)
        setfield!(o, Symbol("url_private_download"), url_private_download)
        validate_property(ObjsFile, Symbol("user"), user)
        setfield!(o, Symbol("user"), user)
        validate_property(ObjsFile, Symbol("user_team"), user_team)
        setfield!(o, Symbol("user_team"), user_team)
        validate_property(ObjsFile, Symbol("username"), username)
        setfield!(o, Symbol("username"), username)
        o
    end
end # type ObjsFile

const _property_map_ObjsFile = Dict{Symbol,Symbol}(Symbol("channels")=>Symbol("channels"), Symbol("comments_count")=>Symbol("comments_count"), Symbol("created")=>Symbol("created"), Symbol("date_delete")=>Symbol("date_delete"), Symbol("display_as_bot")=>Symbol("display_as_bot"), Symbol("editable")=>Symbol("editable"), Symbol("editor")=>Symbol("editor"), Symbol("external_id")=>Symbol("external_id"), Symbol("external_type")=>Symbol("external_type"), Symbol("external_url")=>Symbol("external_url"), Symbol("filetype")=>Symbol("filetype"), Symbol("groups")=>Symbol("groups"), Symbol("has_rich_preview")=>Symbol("has_rich_preview"), Symbol("id")=>Symbol("id"), Symbol("image_exif_rotation")=>Symbol("image_exif_rotation"), Symbol("ims")=>Symbol("ims"), Symbol("is_external")=>Symbol("is_external"), Symbol("is_public")=>Symbol("is_public"), Symbol("is_starred")=>Symbol("is_starred"), Symbol("is_tombstoned")=>Symbol("is_tombstoned"), Symbol("last_editor")=>Symbol("last_editor"), Symbol("mimetype")=>Symbol("mimetype"), Symbol("mode")=>Symbol("mode"), Symbol("name")=>Symbol("name"), Symbol("non_owner_editable")=>Symbol("non_owner_editable"), Symbol("num_stars")=>Symbol("num_stars"), Symbol("original_h")=>Symbol("original_h"), Symbol("original_w")=>Symbol("original_w"), Symbol("permalink")=>Symbol("permalink"), Symbol("permalink_public")=>Symbol("permalink_public"), Symbol("pinned_info")=>Symbol("pinned_info"), Symbol("pinned_to")=>Symbol("pinned_to"), Symbol("pretty_type")=>Symbol("pretty_type"), Symbol("preview")=>Symbol("preview"), Symbol("public_url_shared")=>Symbol("public_url_shared"), Symbol("reactions")=>Symbol("reactions"), Symbol("shares")=>Symbol("shares"), Symbol("size")=>Symbol("size"), Symbol("source_team")=>Symbol("source_team"), Symbol("state")=>Symbol("state"), Symbol("thumb_1024")=>Symbol("thumb_1024"), Symbol("thumb_1024_h")=>Symbol("thumb_1024_h"), Symbol("thumb_1024_w")=>Symbol("thumb_1024_w"), Symbol("thumb_160")=>Symbol("thumb_160"), Symbol("thumb_360")=>Symbol("thumb_360"), Symbol("thumb_360_h")=>Symbol("thumb_360_h"), Symbol("thumb_360_w")=>Symbol("thumb_360_w"), Symbol("thumb_480")=>Symbol("thumb_480"), Symbol("thumb_480_h")=>Symbol("thumb_480_h"), Symbol("thumb_480_w")=>Symbol("thumb_480_w"), Symbol("thumb_64")=>Symbol("thumb_64"), Symbol("thumb_720")=>Symbol("thumb_720"), Symbol("thumb_720_h")=>Symbol("thumb_720_h"), Symbol("thumb_720_w")=>Symbol("thumb_720_w"), Symbol("thumb_80")=>Symbol("thumb_80"), Symbol("thumb_800")=>Symbol("thumb_800"), Symbol("thumb_800_h")=>Symbol("thumb_800_h"), Symbol("thumb_800_w")=>Symbol("thumb_800_w"), Symbol("thumb_960")=>Symbol("thumb_960"), Symbol("thumb_960_h")=>Symbol("thumb_960_h"), Symbol("thumb_960_w")=>Symbol("thumb_960_w"), Symbol("thumb_tiny")=>Symbol("thumb_tiny"), Symbol("timestamp")=>Symbol("timestamp"), Symbol("title")=>Symbol("title"), Symbol("updated")=>Symbol("updated"), Symbol("url_private")=>Symbol("url_private"), Symbol("url_private_download")=>Symbol("url_private_download"), Symbol("user")=>Symbol("user"), Symbol("user_team")=>Symbol("user_team"), Symbol("username")=>Symbol("username"))
const _property_types_ObjsFile = Dict{Symbol,String}(Symbol("channels")=>"Vector{DefsChannelId}", Symbol("comments_count")=>"Int32", Symbol("created")=>"Int32", Symbol("date_delete")=>"Int32", Symbol("display_as_bot")=>"Bool", Symbol("editable")=>"Bool", Symbol("editor")=>"DefsUserId", Symbol("external_id")=>"String", Symbol("external_type")=>"String", Symbol("external_url")=>"String", Symbol("filetype")=>"String", Symbol("groups")=>"Vector{DefsGroupId}", Symbol("has_rich_preview")=>"Bool", Symbol("id")=>"DefsFileId", Symbol("image_exif_rotation")=>"Int32", Symbol("ims")=>"Vector{DefsDmId}", Symbol("is_external")=>"Bool", Symbol("is_public")=>"Bool", Symbol("is_starred")=>"Bool", Symbol("is_tombstoned")=>"Bool", Symbol("last_editor")=>"DefsUserId", Symbol("mimetype")=>"String", Symbol("mode")=>"String", Symbol("name")=>"String", Symbol("non_owner_editable")=>"Bool", Symbol("num_stars")=>"Int32", Symbol("original_h")=>"Int32", Symbol("original_w")=>"Int32", Symbol("permalink")=>"String", Symbol("permalink_public")=>"String", Symbol("pinned_info")=>"DefsPinnedInfo", Symbol("pinned_to")=>"Vector{DefsChannel}", Symbol("pretty_type")=>"String", Symbol("preview")=>"String", Symbol("public_url_shared")=>"Bool", Symbol("reactions")=>"Vector{ObjsReaction}", Symbol("shares")=>"ObjsFileShares", Symbol("size")=>"Int32", Symbol("source_team")=>"DefsTeam", Symbol("state")=>"String", Symbol("thumb_1024")=>"String", Symbol("thumb_1024_h")=>"Int32", Symbol("thumb_1024_w")=>"Int32", Symbol("thumb_160")=>"String", Symbol("thumb_360")=>"String", Symbol("thumb_360_h")=>"Int32", Symbol("thumb_360_w")=>"Int32", Symbol("thumb_480")=>"String", Symbol("thumb_480_h")=>"Int32", Symbol("thumb_480_w")=>"Int32", Symbol("thumb_64")=>"String", Symbol("thumb_720")=>"String", Symbol("thumb_720_h")=>"Int32", Symbol("thumb_720_w")=>"Int32", Symbol("thumb_80")=>"String", Symbol("thumb_800")=>"String", Symbol("thumb_800_h")=>"Int32", Symbol("thumb_800_w")=>"Int32", Symbol("thumb_960")=>"String", Symbol("thumb_960_h")=>"Int32", Symbol("thumb_960_w")=>"Int32", Symbol("thumb_tiny")=>"String", Symbol("timestamp")=>"Int32", Symbol("title")=>"String", Symbol("updated")=>"Int32", Symbol("url_private")=>"String", Symbol("url_private_download")=>"String", Symbol("user")=>"String", Symbol("user_team")=>"DefsTeam", Symbol("username")=>"String")
Base.propertynames(::Type{ ObjsFile }) = collect(keys(_property_map_ObjsFile))
Swagger.property_type(::Type{ ObjsFile }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_ObjsFile[name]))}
Swagger.field_name(::Type{ ObjsFile }, property_name::Symbol) =  _property_map_ObjsFile[property_name]

function check_required(o::ObjsFile)
    true
end

function validate_property(::Type{ ObjsFile }, name::Symbol, val)
end


text: Base.convert(::Type{Vec{N, T1}}, v::Vec{N, Bool}) where {N, T1<:SIMD.FloatingTypes} = convert(Vec{N, T1}, reinterpret(Vec{N, UInt8}, v))

ext: jl


text:
## ExoplanetsSysSim/examples/hsu_etal_2018/invdet_calc.jl
## (c) 2018 Danley C. Hsu
# Script for producing Q1-Q16 FGK planet candidate occurrence rate estimates
#    using both the inverse detection efficiency and the simple
#    Bayesian methods

using ExoplanetsSysSim
include(joinpath(dirname(pathof(ExoplanetsSysSim)),"..","examples","poisson_tests", "christiansen_func.jl"))

global sim_param_closure = setup_sim_param_christiansen()
sim_param_closure = set_test_param(sim_param_closure)
add_param_fixed(sim_param_closure,"koi_catalog","q1_q16_koi_cand.csv")

df_star = setup_star_table_christiansen(sim_param_closure)
println("# Finished reading in stellar data")
df_koi,usable_koi = read_koi_catalog(sim_param_closure)
println("# Finished reading in KOI data")
cat_obs = setup_actual_planet_candidate_catalog(df_star, df_koi, usable_koi, sim_param_closure)

@time inv_det_simp_bayes(cat_obs, sim_param_closure)


text:
########################################################################
#################### Summary Tables ####################################
########################################################################

count(x) = sum(map(y->1, x))
p10(x) = quantile(x |> collect, .1)
p25(x) = quantile(x |> collect, .25)
p50(x) = quantile(x |> collect, .50)
p75(x) = quantile(x |> collect, .75)
p90(x) = quantile(x |> collect, .9)

function default_stats(detail::Bool)
    if !detail
        return ("Obs"         => count ∘ skipmissing,
                "Mean"        => mean ∘ skipmissing,
                "Std. Dev."   => std ∘ skipmissing,
                "Min"         => minimum ∘ skipmissing,
                "Max"         => maximum ∘ skipmissing)
    else
        return ("Obs"         => count ∘ skipmissing,
                "Mean"        => mean ∘ skipmissing,
                "Std. Dev."   => std ∘ skipmissing,
                "Min"         => minimum ∘ skipmissing,
                "p10"         => p10 ∘ skipmissing,
                "p25"         => p25 ∘ skipmissing,
                "p50"         => p50 ∘ skipmissing,
                "p75"         => p75 ∘ skipmissing,
                "p90"         => p90 ∘ skipmissing,
                "Max"         => maximum ∘ skipmissing)
    end
end

NumericCol = AbstractVector{T} where {T1<:Real, T2<:Real,
                                      T<:Union{T1, Union{T2, Missing}}}

tuplefy(x) = tuple(x)
tuplefy(x::Tuple) = x

function promotearray(x::AbstractArray{S, N}) where {S,N}
    types = typeof.(x) |> unique
    T     = promote_type(types...)
    return Array{T,N}
end

function summarize(df::AbstractDataFrame, fields=names(df);
                   detail=false, stats=default_stats(detail), kwargs...)

    cols = TableCol[]
    for pair in tuplefy(stats)
        col = TableCol(pair.first)
        for header in fields
            if promotearray(df[header]) <: NumericCol
                col[header] = pair.second(df[header])
            else
                col[header] = ""
            end
        end
        push!(cols, col)
    end

    return hcat(cols...)
end

function summarize(df::AbstractDataFrame, field::Symbol; kwargs...)
    summarize(df, vcat(field); kwargs...)
end

function summarize_by(df, byname::Symbol,
                      fields=setdiff(names(df), vcat(byname));
                      kwargs...)
    tabs = []
    gd = groupby(df, byname)
    for sub in gd
        tab = summarize(sub, fields; kwargs...)
        vals= unique(sub[byname])
        length(vals) == 1 || throw(error("Groupby isn't working"))
        idx = vals[1]
        push!(tabs, idx=>tab)
    end

    return append_table(tabs...)
end

########################################################################
#################### Cross Tabulations #################################
########################################################################

function tabulate(df::AbstractDataFrame, field)

    # Count the number of observations by `field`
    tab = by(df, field) do d
        return DataFrame(N=count(d[field]))
    end

    # Construct a Frequency Column
    sort!(tab, field)
    vals  = tab[field] .|> Symbol
    freq  = tab[:N]
    pct   = freq/sum(freq)*100
    cum   = cumsum(pct)

    # Construct Table
    col1 = append_table(TableCol("Freq.",    vals, freq),
                        TableCol("Freq.", "Total"=>sum(freq)))
    col2 = append_table(TableCol("Percent",  vals, pct ),
                        TableCol("Percent", "Total"=>sum(pct)))
    col3 = TableCol("Cum.",     vals, cum )
    col = hcat(col1, col2, col3)
end


text:
module TestPackage2
export hello2, domath2

@static if Sys.iswindows()
  hello2(who::String) = "Hello, $who"

else
  domath2(x::Number) = x + 5

end

end


text:
"""
Prototype for IPs based on "Machine-Learning", to be imported by
modules that either define basis sets or regression methods
"""
module MLIPs

using JuLIP:       AbstractCalculator, AbstractAtoms, JVec, AtomicNumber, JMat

import JuLIP:      energy, forces, virial, site_energy, site_energy_d,
                   alloc_temp, alloc_temp_d, evaluate, evaluate_d,
                   evaluate!, evaluate_d!, evaluate_ed,
                   read_dict, write_dict, fltype, rfltype

import JuLIP.Potentials: site_virial

import Base:       ==

export IPSuperBasis, IPCollection, combine

abstract type AbstractBasis <: AbstractCalculator end

"""
`abstract type IPBasis` : A type derived from `IPBasis` defines
not an IP as such but a collection of IPs that can be understood as
a basis set. E.g., a 2B-potential could be obtained from
polynomials,
```
   ϕ(r) = ∑_k c_k exp(-k r)
```
then the `B::IPBasis` might specify the basis functions {r -> exp(-kr)} as
a collection of `PairPotential`s.

Then, `energy(at, B)` does not return a single energy but a vector
of energies.

## Developer Notes

* `length(basis::IPBasis)` must return the number of basis functions
"""
abstract type IPBasis <: AbstractBasis end

"""
`alloc_B(B, x)`

if `B::IPBasis` and `x` is some argument, then allocate storage to evaluate
the basis when evaluated with argument `x`.
"""
alloc_B(basis, args...) = zeros(fltype(basis), length(basis))

"""
`alloc_dB(B, x)`

if `B::IPBasis` and `x` is some argument, then allocate storage to evaluate
the derivative of the basis when evaluated with argument `x`.
"""
alloc_dB(basis, x::AbstractVector, args...) = alloc_dB(basis, length(x))
alloc_dB(basis, x::Union{Number, JVec}, args...) = alloc_dB(basis)
alloc_dB(basis) = zeros(JVec{fltype(basis)}, length(basis))
alloc_dB(basis, N::Integer) = zeros(JVec{fltype(basis)}, (length(basis), N))

evaluate(B::IPBasis, x, args...) =
   evaluate!(alloc_B(B, x), alloc_temp(B, x), B, x, args...)

function evaluate_ed(B::IPBasis, x, args...)
   b = alloc_B(B, x)
   db = alloc_dB(B, x)
   tmp = alloc_temp_d(B, x)
   evaluate_d!(b, db, tmp, B, x, args...)
   return b, db
end

evaluate_d(B::IPBasis, x, args...) = evaluate_ed(B::IPBasis, x, args...)[2]

# ========== wrap one more more calculators into a basis =================

# the main difference with IPSuperBasis is that an IPCollection is
# a basis of individual calculators, whereas an IPSuperBasis combines
# two or more `IPBasis` sets.

struct IPCollection{T} <: IPBasis
   coll::Vector{T}
end

IPCollection(args...) = IPCollection([args...])
Base.length(coll::IPCollection) = length(coll.coll)
combine(basis::IPCollection, coeffs::AbstractVector{<:Number}) =
      SumIP([ c * b for (c, b) in zip(coeffs, basis.coll) ])

energy(coll::IPCollection, at::AbstractAtoms) =
         [ energy(B, at) for B in coll.coll ]
forces(coll::IPCollection, at::AbstractAtoms) =
         [ forces(B, at) for B in coll.coll ]
virial(coll::IPCollection, at::AbstractAtoms) =
         [ virial(B, at) for B in coll.coll ]
site_energy(coll::IPCollection, at::AbstractAtoms, i0::Integer) =
         [ site_energy(V, at, i0) for V in coll.coll ]
site_energy_d(coll::IPCollection, at::AbstractAtoms, i0::Integer) =
         [ site_energy_d(V, at, i0) for V in coll.coll ]

write_dict(coll::IPCollection) = Dict(
            "__id__" => "JuLIP_IPCollection",
            "coll" => Dict.(coll.coll) )
IPCollection(D::Dict) = IPCollection( read_dict.( D["coll"] ) )
read_dict(::Val{:JuLIP_IPCollection}, D::Dict) = IPCollection(D)
==(B1::IPCollection, B2::IPCollection) = all(B1.coll .== B2.coll)

# ========== IPSuperBasis : combine multiple sub-basis =================

"""
`struct IPSuperBasis:` a collection of IP basis sets, re-interpreted
as a large basis
"""
struct IPSuperBasis{TB <: IPBasis} <: IPBasis
   BB::Vector{TB}
end

_convert_basis_(b::IPBasis) = b
_convert_basis_(b::AbstractCalculator) = IPCollection(b)
_convert_basis_(b::AbstractVector) = IPCollection(b)

IPSuperBasis(args...) = IPSuperBasis([_convert_basis_(b) for b in args])

Base.length(super::IPSuperBasis) = sum(length.(super.BB))

function combine(basis::IPSuperBasis, coeffs::AbstractVector{<:Number})
   i0 = 0
   components = []
   for B in basis.BB
      lenB = length(B)
      push!(components, combine(B, coeffs[i0+1:i0+lenB]))
      i0 += lenB
   end
   return SumIP(components)
end

energy(superB::IPSuperBasis, at::AbstractAtoms) =
         vcat([ energy(B, at) for B in superB.BB ]...)
forces(superB::IPSuperBasis, at::AbstractAtoms) =
         vcat([ forces(B, at) for B in superB.BB ]...)
virial(superB::IPSuperBasis, at::AbstractAtoms) =
         vcat([ virial(B, at) for B in superB.BB ]...)
site_energy(superB::IPSuperBasis, at::AbstractAtoms, i0::Integer) =
         vcat([ site_energy(B, at, i0) for B in superB.BB ]...)
site_energy_d(superB::IPSuperBasis, at::AbstractAtoms, i0::Integer) =
         vcat([ site_energy_d(B, at, i0) for B in superB.BB ]...)

write_dict(superB::IPSuperBasis) = Dict(
      "__id__" => "JuLIP_IPSuperBasis",
      "components" => write_dict.(superB.BB) )
IPSuperBasis(D::Dict) = IPSuperBasis( read_dict.( D["components"] ) )
read_dict(::Val{:JuLIP_IPSuperBasis}, D::Dict) = IPSuperBasis(D)
==(B1::IPSuperBasis, B2::IPSuperBasis) = all(B1.BB .== B2.BB)

# ========== SumIP =================
# a sum of several IPs.

struct SumIP{T} <: AbstractCalculator
   components::Vector{T}
end

SumIP(args...) = SumIP([args...])

==(V1::SumIP, V2::SumIP) = all(V1.components .== V2.components)

energy(sumip::SumIP, at::AbstractAtoms; kwargs...) =
         sum(energy(calc, at; kwargs...) for calc in sumip.components)
forces(sumip::SumIP, at::AbstractAtoms; kwargs...) =
         sum(forces(calc, at; kwargs...) for calc in sumip.components)
virial(sumip::SumIP, at::AbstractAtoms; kwargs...) =
         sum(virial(calc, at; kwargs...) for calc in sumip.components)
site_energy(sumip::SumIP, at::AbstractAtoms, i0::Integer) =
         sum(site_energy(V, at, i0) for V in sumip.components)
site_energy_d(sumip::SumIP, at::AbstractAtoms, i0::Integer) =
         sum(site_energy_d(V, at, i0) for V in sumip.components)

write_dict(sumip::SumIP) = Dict(
      "__id__" => "JuLIP_SumIP",
      "components" => write_dict.(sumip.components) )
SumIP(D::Dict) = SumIP( read_dict.( D["components"] ) )
read_dict(::Val{:JuLIP_SumIP}, D::Dict) = SumIP(D)

SumIP(V::AbstractCalculator, sumip::SumIP) =
   SumIP( [ [V]; sumip.components ]  )
SumIP(sumip::SumIP, V::AbstractCalculator) =
   SumIP( [ sumip.components; [V] ]  )
SumIP(sum1::SumIP, sum2::SumIP) =
   SumIP( [ sum1.components; sum2.components ]  )

# -------------------------------------------------------------
#       JuLIP Calculator functionality for IPBasis
# -------------------------------------------------------------

using NeighbourLists: maxneigs
using JuLIP: sites, neighbourlist, cutoff, JVec
using JuLIP.Potentials: neigsz!

function energy(shipB::IPBasis, at::AbstractAtoms{T}) where {T}
   E = zeros(fltype(shipB), length(shipB))
   B = alloc_B(shipB)
   nlist = neighbourlist(at, cutoff(shipB); storelist=false)
   maxnR = maxneigs(nlist)
   tmp = alloc_temp(shipB, maxnR)
   tmpRZ = (R = zeros(JVec{T}, maxnR), Z = zeros(AtomicNumber, maxnR))
   for i = 1:length(at)
      j, R, Z = neigsz!(tmpRZ, nlist, at, i)
      fill!(B, 0)
      evaluate!(B, tmp, shipB, R, Z, at.Z[i])
      E[:] .+= B[:]
   end
   return E
end

function forces(shipB::IPBasis, at::AbstractAtoms{T}) where {T}
   # precompute the neighbourlist to count the number of neighbours
   nlist = neighbourlist(at, cutoff(shipB); storelist=false)
   maxR = maxneigs(nlist)
   # allocate space accordingly
   F = zeros(JVec{T}, length(at), length(shipB))
   B = alloc_B(shipB, maxR)
   dB = alloc_dB(shipB, maxR)
   tmp = alloc_temp_d(shipB, maxR)
   tmpRZ = (R = zeros(JVec{T}, maxR), Z = zeros(AtomicNumber, maxR))
   return forces_inner!(shipB, at, nlist, F, B, dB, tmp, tmpRZ)
end

# this is a little hack to remove a type instability. It probably makes no
# difference in practise...
function forces_inner!(shipB::IPBasis, at::AbstractAtoms{T},
                       nlist, F, B, dB, tmp, tmpRZ) where {T}
   # assemble site gradients and write into F
   for i = 1:length(at)
      j, R, Z = neigsz!(tmpRZ, nlist, at, i)
      fill!(dB, zero(JVec{T}))
      fill!(B, 0)
      evaluate_d!(B, dB, tmp, shipB, R, Z, at.Z[i])
      for a = 1:length(R)
         F[j[a], :] .-= dB[:, a]
         F[i, :] .+= dB[:, a]
      end
   end
   return [ F[:, iB] for iB = 1:length(shipB) ]
end

function virial(shipB::IPBasis, at::AbstractAtoms{T}) where {T}
   # precompute the neighbourlist to count the number of neighbours
   nlist = neighbourlist(at, cutoff(shipB); storelist=false)
   maxR = maxneigs(nlist)
   # allocate space accordingly
   V = zeros(JMat{T}, length(shipB))
   B = alloc_B(shipB, maxR)
   dB = alloc_dB(shipB, maxR)
   tmp = alloc_temp_d(shipB, maxR)
   tmpRZ = (R = zeros(JVec{T}, maxR), Z = zeros(AtomicNumber, maxR))
   # assemble site gradients and write into F
   for i = 1:length(at)
      j, R, Z = neigsz!(tmpRZ, nlist, at, i)
      fill!(dB, zero(JVec{T}))
      fill!(B, 0)
      evaluate_d!(B, dB, tmp, shipB, R, Z, at.Z[i])
      for iB = 1:length(shipB)
         V[iB] += site_virial(dB[iB, :], R)
      end
   end
   return V
end

function _get_neigs(at::AbstractAtoms{T}, i0::Integer, rcut) where {T}
   nlist = neighbourlist(at, rcut)
   maxR = maxneigs(nlist)
   tmpRZ = (R = zeros(JVec{T}, maxR), Z = zeros(AtomicNumber, maxR))
   j, R, Z = neigsz!(tmpRZ, nlist, at, i0)
   return j, R, Z
end

function site_energy(basis::IPBasis, at::AbstractAtoms, i0::Integer)
   j, Rs, Zs = _get_neigs(at, i0, cutoff(basis))
   return evaluate(basis, Rs, Zs, at.Z[i0])
end

function site_energy_d(basis::IPBasis, at::AbstractAtoms{T}, i0::Integer) where {T}
   Ineigs, Rs, Zs = _get_neigs(at, i0, cutoff(basis))
   dEs = [ zeros(JVec{T}, length(at)) for _ = 1:length(basis) ]
   dB = alloc_dB(basis, length(Rs))
   tmp = alloc_temp_d(basis, length(Rs))
   evaluate_d!(dB, tmp, basis, Rs, Zs, at.Z[i0])
   @assert dB isa Matrix{JVec{T}}
   @assert size(dB) == (length(Rs), length(basis))
   for iB = 1:length(basis), n = 1:length(Ineigs)
      dEs[iB][Ineigs[n]] += dB[n, iB]
      dEs[iB][i0] -= dB[n, iB]
   end
   return dEs
end

end


text:
using Test: @test, @testset, @test_throws
import Pasteee
import HTTP

const appkey = ENV["PASTEEE_APPKEY"]

@testset "Pasteee" begin
    id = Pasteee.paste(appkey, "Batido de mamey"; expiration="3600")
    paste = Pasteee.get(appkey, id)
    @test paste["sections"][1]["contents"] == "Batido de mamey"

    Pasteee.delete(appkey, id)
    @test_throws HTTP.ExceptionRequest.StatusError Pasteee.get(appkey, id)

    pastes = Pasteee.pastes(appkey; perpage=12, page=2)
    @test pastes["current_page"] == 2
    @test pastes["per_page"] == 12
end


text:
"""
#abstract type MaybeContinuousDynamics end struct
HasContinuousDynamics end struct HasNoContinuousDynamics end
MaybeContinuousDynamics(::Type{<:Any}) = NoContinuousDynamics
MaybeContinuousDynamics(::Type{<:EThruster}) = ContinuousDynamics
# MaybeContinuousDynamics(::Type{<:TunableISA}) = NoContinuousDynamics

#this is the first method that should be overridden by any System that
#declares having continuous dynamics. function f_cont!(s::System{C},
args...) where {C<:SystemDescriptor} f_cont!(s, MaybeContinuousDynamics(C),
args...) end function f_cont!(::S, ::ContinuousDynamics, args...) where
{S<:System} println("Warning: S declared itself as having
ContinuousDynamics but does not implement f_cont!") end f_cont!(::System,
::NoContinuousDynamics, args...) = nothing #its OK #this assumes that when some
type calls f_cont! with variable arguments, but the #second one is NOT of type
MaybeContinuousDynamics, the compiler will dispatch #to the first method first.
this method should have been overridden

#we could do the same with MaybeDiscreteDynamics

#what purpose does it serve? it avoids an unwanted and inadverted dispatch to
#the fallback f_cont! or f_disc due to wrong interface in its own
#implementation. obviously, the component is assumed to have actually
#implemented f_cont! and f_disc! and declared itself as having Continous or
#DiscreteDynamics. a component that neither declares ContinuousDynamics nor
#defines f_cont! will receive no warning

#we could go another step and do the same with init_x0, which will also dispatch
#on MaybeContinuousDynamics, and init_d0, on MaybeDiscreteDynamics. then
#MaybeInput, MaybeOutput for init_u0 and init_d0

#however, all this does is force systems with continuous dyanmics to define the
#a MaybeContinuousDynamics method in addition to f_cont!. on exchange, systems
without continuous dynamics are not forced to implement f_cont!. not much to be
gained

"""


text:
__precompile__()

module CausalTrees
import Statistics
import PyPlot
import Plots

include("tree.jl")
include("loss.jl")
include("utils.jl")
include("clearning.jl")
include("plearning.jl")
include("plot.jl")

export causal_tree
export causal_forest
export predict
export mse_tau
export decision_tree
export random_forest
export plot

end # module


text:
"""
Handles WebSockets communication logic.
"""
module WebChannels

using HTTP, JSON, Distributed
using Genie.Loggers

const ClientId =                          UInt64
const ChannelId =                         String
const ChannelClient =                     Dict{Symbol, Union{HTTP.WebSockets.WebSocket,Vector{ChannelId}}}
const ChannelClientsCollection =          Dict{ClientId,ChannelClient} # { id(ws) => { :client => ws, :channels => ["foo", "bar", "baz"] } }
const ChannelSubscriptionsCollection =    Dict{ChannelId,Vector{ClientId}}  # { "foo" => ["4", "12"] }
const MessagePayload =                    Union{Nothing,Dict}

mutable struct ChannelMessage
  channel::ChannelId
  client::ClientId
  message::String
  payload::MessagePayload
end

const CLIENTS       = ChannelClientsCollection()
const SUBSCRIPTIONS = ChannelSubscriptionsCollection()

"""
    subscribe(ws::WebSockets.WebSocket, channel::ChannelId) :: Nothing

Subscribes a web socket client `ws` to `channel`.
"""
function subscribe(ws::HTTP.WebSockets.WebSocket, channel::ChannelId) :: Nothing
  if haskey(CLIENTS, id(ws))
    ! in(channel, CLIENTS[id(ws)][:channels]) && push!(CLIENTS[id(ws)][:channels], channel)
  else
    CLIENTS[id(ws)] = Dict(
                          :client => ws,
                          :channels => ChannelId[channel]
                          )
  end

  push_subscription(id(ws), channel)

  nothing
end

function id(ws::HTTP.WebSockets.WebSocket)
  hash(ws)
end

"""
    unsubscribe(ws::WebSockets.WebSocket, channel::ChannelId) :: Nothing

Unsubscribes a web socket client `ws` from `channel`.
"""
function unsubscribe(ws::HTTP.WebSockets.WebSocket, channel::ChannelId) :: Nothing
  if haskey(CLIENTS, id(ws))
    delete!(CLIENTS[id(ws)][:channels], channel)
  end

  pop_subscription(id(ws), channel)

  nothing
end

"""
    unsubscribe_client(ws::WebSockets.WebSocket) :: Nothing

Unsubscribes a web socket client `ws` from all the channels.
"""
function unsubscribe_client(client::ClientId) :: Nothing
  unsubscribe_client(CLIENTS[client][:client])
end
function unsubscribe_client(ws::HTTP.WebSockets.WebSocket) :: Nothing
  if haskey(CLIENTS, id(ws))
    for channel_id in CLIENTS[id(ws)][:channels]
      pop_subscription(id(ws), channel_id)
    end

    delete!(CLIENTS, id(ws))
  end

  nothing
end

"""
    push_subscription(client::ClientId, channel::ChannelId) :: Nothing

Adds a new subscription for `client` to `channel`.
"""
function push_subscription(client::ClientId, channel::ChannelId) :: Nothing
  if haskey(SUBSCRIPTIONS, channel)
    ! in(client, SUBSCRIPTIONS[channel]) && push!(SUBSCRIPTIONS[channel], client)
  else
    SUBSCRIPTIONS[channel] = ClientId[client]
  end

  nothing
end

"""
    pop_subscription(client::ClientId, channel::ChannelId) :: Nothing

Removes the subscription of `client` to `channel`.
"""
function pop_subscription(client::ClientId, channel::ChannelId) :: Nothing
  if haskey(SUBSCRIPTIONS, channel)
    filter!(SUBSCRIPTIONS[channel]) do (client_id)
      client_id != client
    end
    isempty(SUBSCRIPTIONS[channel]) && delete!(SUBSCRIPTIONS, channel)
  end

  nothing
end

"""
    pop_subscription(client::ClientId) :: Nothing

Removes all subscriptions of `client`.
"""
function pop_subscription(channel::ChannelId) :: Nothing
  if haskey(SUBSCRIPTIONS, channel)
    delete!(SUBSCRIPTIONS, channel)
  end

  nothing
end

"""
    broadcast(channels::Union{ChannelId,Vector{ChannelId}}, msg::String) :: Nothing
    broadcast{U,T}(channels::Vector{ChannelId}, msg::String, payload::Dict{U,T}) :: Nothing

Pushes `msg` (and `payload`) to all the clients subscribed to the channels in `channels`.
"""
function broadcast(channels::Union{ChannelId,Vector{ChannelId}}, msg::String) :: Nothing
  isa(channels, Array) || (channels = ChannelId[channels])

  @distributed for channel in channels
    for client in SUBSCRIPTIONS[channel]
      ws_write_message(client, msg)
    end
  end

  nothing
end
function broadcast(channels::Union{ChannelId,Vector{ChannelId}}, msg::String, payload::Dict{U,T})::Nothing where {U,T}
  isa(channels, Array) || (channels = ChannelId[channels])

  @distributed for channel in channels
    in(channel, keys(SUBSCRIPTIONS)) || continue

    for client in SUBSCRIPTIONS[channel]
      try
        ws_write_message(client, ChannelMessage(channel, client, msg, payload) |> JSON.json)
      catch ex
        log(string(ex), :err)
        log("$(@__FILE__):$(@__LINE__)")

        rethrow(ex)
      end
    end
  end

  nothing
end

"""
    broadcast(msg::String) :: Nothing
    broadcast{U,T}(msg::String, payload::Dict{U,T}) :: Nothing

Pushes `msg` (and `payload`) to all the clients subscribed to all the channels.
"""
function broadcast(msg::String) :: Nothing
  broadcast(collect(keys(SUBSCRIPTIONS)), msg)
end
function broadcast(msg::String, payload::Dict{U,T})::Nothing where {U,T}
  broadcast(collect(keys(SUBSCRIPTIONS)), msg, payload)
end

"""
  message(channel::ChannelId, msg::String) :: Nothing
  message{U,T}(channel::ChannelId, msg::String, payload::Dict{U,T}) :: Nothing

Pushes `msg` (and `payload`) to `channel`.
"""
function message(channel::ChannelId, msg::String) :: Nothing
  broadcast(ChannelId[channel], msg)
end
function message(channel::ChannelId, msg::String, payload::Dict{U,T})::Nothing where {U,T}
  broadcast(ChannelId[channel], msg, payload)
end

"""
    ws_write_message(client::ClientId, msg::String) :: Nothing

Writes `msg` to web socket for `client`.
"""
function ws_write_message(client::ClientId, msg::String) :: Nothing
  write(CLIENTS[client][:client], msg)

  nothing
end

"""
    message(client::ChannelClient, msg::String) :: Nothing

Send message `msg` to `client`.
"""
function message(client::ChannelClient, msg::String) :: Nothing
  write(client[:client], msg)

  nothing
end

end


text:
mutable struct HardSphereSimulation{
    N, T,
    F<:HardSphereFluid{N,T},
    H<:AbstractEventHandler,
    L<:AbstractFlowDynamics,
    C<:AbstractCollisionDynamics
	}

    fluid::F
    event_handler::H
    flow_dynamics::L
    collision_dynamics::C
	current_time::T
end

HardSphereSimulation(fluid::HardSphereFluid{N,T}, event_handler, flow_dynamics, collision_dynamics) where {N,T}=
	HardSphereSimulation(fluid, event_handler, flow_dynamics, collision_dynamics, zero(T))

overlap(b1::MovableBall, b2::MovableBall) =
    normsq(b1.x - b2.x) < (b1.r + b2.r)^2

overlap(b::MovableBall, balls::Vector{MovableBall{N,T}}) where {N,T} =
    any(overlap.(Ref(b), balls))

"""
Generate initial condition for balls.

Uses random sequential deposition:
place a disc at a time and check that it doesn't overlap with any previously placed disc.

Generates allowed ball positions and uniform velocities.
"""
function initial_condition!(balls::Vector{MovableBall{N,T}}, table;
		lower=table.lower, upper=table.upper) where {N,T}

	## TODO: Check that initial condition is OK with respect to planes

    U = Uniform.(lower .+ balls[1].r, upper .- balls[1].r)
    balls[1].x = rand.(U)

    for i = 2:length(balls)
        U = Uniform.(lower .+ balls[i].r, upper .- balls[i].r)
        balls[i].x = rand.(U)

        count = 0

        while overlap(balls[i], balls[1:i-1])
            balls[i].x = rand.(U)
            count += 1

            count > 10^5 && error("Unable to place disc $i")
        end
    end

    # generate velocities with sum(v_i^2) = 1:f
    for i = 1:length(balls)
        balls[i].v = @SVector randn(N)
    end

    sumsq = sum(normsq(balls[i].v) for i = 1:length(balls))

    for i = 1:length(balls)
        balls[i].v /= sqrt(sumsq)
    end
end

initial_condition!(fluid::HardSphereFluid; kw...) = initial_condition!(fluid.balls, fluid.box;
	kw...)

"Carry out collision assuming already at moment of collision"
function collide!(fluid::HardSphereFluid, event_handler, collision_dynamics)

	@unpack balls, box = fluid
	@unpack partner1, partner2, collision_type = event_handler

	if collision_type == :wall_collision
		collide!(balls[partner1], box.walls[partner2], collision_dynamics)

	elseif collision_type == :disc_collision
		collide!(balls[partner1], balls[partner2], collision_dynamics)

	else
		error("No collision")
	end

end

"""
	evolve!(fluid::HardSphereFluid, num_collisions::Integer)

Discrete-time evolution: Evolve fluid for `num_collisions` collisions.
Both sphere--sphere and sphere--wall collisions are counted as collisions.

Returns post-collision states, times at which collisions occur, and collision types.
"""
function evolve!(simulation::HardSphereSimulation{N,T}, num_collisions::Integer) where {N,T}

	@unpack fluid, flow_dynamics, collision_dynamics, event_handler = simulation

    # positions = [ [ball.x for ball in balls] ]
	# velocities = [ [ball.v for ball in balls] ]
	states = [deepcopy(fluid.balls)]
	times = [0.0]
	collision_types = [:none]

    for i in 1:num_collisions

		flow!(fluid.balls, (event_handler.next_collision_time - simulation.current_time), flow_dynamics)
		simulation.current_time = event_handler.next_collision_time

		push!(collision_types, event_handler.collision_type)

		collide!(fluid, event_handler, collision_dynamics)
		find_collision!(event_handler, fluid, flow_dynamics)

		push!(states, deepcopy(fluid.balls))
        push!(times, simulation.current_time)

    end

    return states, times, collision_types

end

"""
	flow!(fluid::HardSphereFluid, t)

Update hard sphere fluid by flowing for a time `t`, taking
account of possible collisions during that time.
"""

function flow!(simulation::HardSphereSimulation, t)

	@unpack fluid, flow_dynamics, collision_dynamics, event_handler = simulation
	# @unpack balls, table = fluid

	time_to_next_collision = event_handler.next_collision_time - simulation.current_time

	while t > time_to_next_collision
		t -= time_to_next_collision

		flow!(fluid.balls, time_to_next_collision, flow_dynamics)
		simulation.current_time += time_to_next_collision

		collide!(fluid, event_handler, collision_dynamics)
		find_collision!(event_handler, fluid, flow_dynamics)

		time_to_next_collision = event_handler.next_collision_time - simulation.current_time

	end

	flow!(fluid.balls, t, flow_dynamics)
	simulation.current_time += t

end

"""
	evolve!(fluid::HardSphereFluid, times)

Time evolution, calculating positions and velocities at given times.
"""
function evolve!(simulation::HardSphereSimulation{N,T}, times) where {N,T}

	@unpack fluid, flow_dynamics, collision_dynamics, event_handler = simulation

	states = [deepcopy(fluid.balls)]
	ts = [0.0]

	current_t = 0.0

	for t in times
		flow!(simulation, t - current_t)
        push!(states, deepcopy(fluid.balls))
		push!(ts, t)

		current_t = t
    end

    return states, ts
end

"""
	evolve!(fluid::HardSphereFluid, δt, final_time)

Calculate positions and velocities at times up to `final_time`,
spaced by `δt`.

"""
evolve!(simulation::HardSphereSimulation, δt, final_time) = evolve!(simulation, δt:δt:final_time)

#=
# states, times, collision_types = evolve!(simulation, 100);

using StaticArrays

table = HardSphereDynamics.RectangularBox(SA[-0.5, -0.5, -10.0],
					SA[+0.5, +0.5, +10.0])

fluid = HardSphereFluid{3,Float64}(table, 100, 0.05)
initial_condition!(fluid)
# flow_type = FreeFlow()
flow_type = ExternalFieldFlow(SA[0.0, 0.0, -1.0])

function run_simulation(N, r)

	table = HardSphereDynamics.RectangularBox(SA[-0.5, -0.5, -1.0],
					SA[+0.5, +0.5, +100.0])

	fluid = HardSphereFluid{3,Float64}(table, N, r)

	initial_condition!(fluid, lower=table.lower, upper=-table.lower)
	collision_type = ElasticCollision()

	flow_type = ExternalFieldFlow(SA[0.0, 0.0, -10.0])
	event_handler = AllToAll(fluid, flow_type)

	simulation =  HardSphereSimulation(
		fluid, event_handler, flow_type, collision_type);

	states, times = evolve!(simulation, 0.01, 100);

	visualize_3d(states, sleep_step=0.005, lower=table.lower, upper=-table.lower)
end

using Makie
visualize_3d(states, sleep_step=0.001, lower=table.lower, upper=table.upper)
=#

max_stars_repo_name: dpsanders/HardSphereDynamics

max_forks_repo_name: dpsanders/HardSphereDynamics


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct EncryptionConfig <: SwaggerModel
    type::Any # spec type: Union{ Nothing, String } # spec name: type
    keyVaultMetaInfo::Any # spec type: Union{ Nothing, KeyVaultMetaInfo } # spec name: keyVaultMetaInfo

    function EncryptionConfig(;type=nothing, keyVaultMetaInfo=nothing)
        o = new()
        validate_property(EncryptionConfig, Symbol("type"), type)
        setfield!(o, Symbol("type"), type)
        validate_property(EncryptionConfig, Symbol("keyVaultMetaInfo"), keyVaultMetaInfo)
        setfield!(o, Symbol("keyVaultMetaInfo"), keyVaultMetaInfo)
        o
    end
end # type EncryptionConfig

const _property_map_EncryptionConfig = Dict{Symbol,Symbol}(Symbol("type")=>Symbol("type"), Symbol("keyVaultMetaInfo")=>Symbol("keyVaultMetaInfo"))
const _property_types_EncryptionConfig = Dict{Symbol,String}(Symbol("type")=>"String", Symbol("keyVaultMetaInfo")=>"KeyVaultMetaInfo")
Base.propertynames(::Type{ EncryptionConfig }) = collect(keys(_property_map_EncryptionConfig))
Swagger.property_type(::Type{ EncryptionConfig }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_EncryptionConfig[name]))}
Swagger.field_name(::Type{ EncryptionConfig }, property_name::Symbol) =  _property_map_EncryptionConfig[property_name]

const _allowed_EncryptionConfig_type = ["UserManaged", "ServiceManaged"]

function check_required(o::EncryptionConfig)
    true
end

function validate_property(::Type{ EncryptionConfig }, name::Symbol, val)
    if name === Symbol("type")
        Swagger.validate_param(name, "EncryptionConfig", :enum, val, _allowed_EncryptionConfig_type)
    end
end


text:
#
# # OnlinePLS: Thomas Breloff (Cointegrated Technologies)
#
#
# # implements an online partial least squares (OPLS) algorithm... modeled on Zeng et al (2014) [1]:
# #		"Incremental partial least squares analysis of big streaming data"
#
#
#
# # Goal: We're looking for a linear combination of the X-components which produces high covariance with y.
# # 			We then fit the reduced-dimension regression y = Zβ + e, where Z = XW has k columns of uncorrelated series.
#
# # Reason:  If X has high multicolinearity between components, there will likely be overfitting
# #					 problems for the model y = Xβ + e
#
#
# # Method:
# # There are 3 phases... model update, weight matrix extraction, and finally least squares fitting.
#
#
# # Model update:
#
# # We are trying to maximize Cov(y, Xw) for some dx1 vector of weights w...
# #	this will approximate the loadings for the first latent vector.
# # Taking the derivative of a Lagrange function gives us the solution w = Xᵀy / ‖Xᵀy‖
# # Our online model updates the estimate of v := Xᵀy, and also tracks the decomposition of X using OnlinePCA
# # in order to estimate the covariance matrix C := XᵀX/n, to reduce cpu/memory usage
#
# # Note: we replace the update of v as in [1] with a smoothed version, which is correct for the exponential case,
# # and approximately correct for the equal weighted case.
# # proof summary for exponential weighting correctness:
# #		vₜ = ∑ᵗ [λ(1-λ)ᵗ⁻ⁱyᵢXᵢ]
# #			 = λyₜXₜ + ∑ᵗ⁻¹ [λ(1-λ)ᵗ⁻¹⁻ⁱyᵢXᵢ]
# #			 = λyₜXₜ + (1-λ)vₜ₋₁
#
# # Weight matrix building:
#
# # When the state is requested: "PLS projection directions are computed from a Gram-Schmidt orthonormalization
# # of the Krylov sequence" [1]
# # This gives us the weighting matrix W:
# #		V := [v, Cv\{v}, C²v\{v,Cv}, ... Cᴷ⁻¹v\{v,Cv,...,Cᴷ⁻²v}]
# #		W := [V₁/‖V₁‖, ..., Vₖ/‖Vₖ‖]
#
# # where "f/{g,h...} refers to the components of f that are orthogonal to the space spanned by {g,h,...}" [1]
#
#
# # Regression:
#
# # Now that we have our weight matrix W, we can project X into a reduced dimensional space,
# #	and should get more robust regression results.
# #		Z = XW
# #		y = Zβ + e
#
#
# # Summary:
# # 	update v estimate
# #		update OnlinePCA estimate (V) of first l pca vectors
# #   build W matrix, and project Z = XW
# #		regress y = Zβ + e
# #		state = (v, V, W, β)
#
#
# #-------------------------------------------------------# Type and Constructors
#
# type OnlinePLS{W<:Weighting} <: OnlineStat
# 	d::Int  			# num dependent vars
# 	l::Int 				# num latent vars in OnlinePCA
# 	k::Int 				# num latent vars in PLS
# 	n::Int
# 	weighting::W
#
# 	ymean::Mean{W}
# 	xmeans::Means{W}
#
# 	v1::VecF				# (d x 1) vector -- estimate of first column of V
# 	W::MatF 				# (d x k) matrix (see fls comment below)
# 	pca::OnlinePCA{W}  # tracks pca decomposition of X
# 	fls::OnlineFLS  # flexible least squares to solve for β: y = (XW)β + e
# end
#
# name(o::OnlinePLS) = "OPLS"
#
#
# function OnlinePLS(d::Integer, l::Integer, k::Integer, δ::Real, wgt::Weighting = default(Weighting))
# 	OnlinePLS(d, l, k, 0, wgt, Mean(wgt), Means(d, wgt), zeros(d), zeros(d, k), OnlinePCA(d, l, wgt), OnlineFLS(k, δ, wgt))
# end
#
# function OnlinePLS(x::AVecF, y::Real, l::Integer, k::Integer, δ::Real, wgt::Weighting = default(Weighting))
# 	d = length(x)
# 	o = OnlinePLS(d, l, k, δ, wgt)
# 	update!(o, x, y)
# 	o
# end
#
# function OnlinePLS(X::AMatF, y::AVecF, l::Integer, k::Integer, δ::Real, wgt::Weighting = default(Weighting))
# 	d = size(X,2)
# 	o = OnlinePLS(d, l, k, δ, wgt)
# 	update!(o, X, y)
# 	o
# end
#
# #-----------------------------------------------------------------------# state
#
# # note: pca and fls refer to the states of the respective objects
# statenames(o::OnlinePLS) = [:v1, :pca, :W, :fls, :nobs]
# state(o::OnlinePLS) = Any[copy(o.v1), state(o.pca), copy(o.W), state(o.fls), nobs(o)]
#
#
# #---------------------------------------------------------------------# update!
#
#
# # # NOTE: assumes X mat is (T x p), where T is the number of observations
# # # TODO: optimize
# # function update!(o::OnlinePLS, X::AMatF, y::AVecF)
# # 	@assert length(y) == size(X,1)
# # 	@inbounds for i in 1:length(y)
# # 		update!(o, row(X,i), y[i])
# # 	end
# # end
#
# function update!(o::OnlinePLS, x::AVecF, y::Real)
#
# 	# center x and y
# 	y = center!(o.ymean, y)
# 	x = center!(o.xmeans, x)
#
# 	# update v1 and pca
# 	# @LOG y x y*x
# 	smooth!(o.v1, y * x, weight(o))
# 	# @LOG o.v1
# 	update!(o.pca, x)
#
# 	# recompute W
# 	V = VecF[]
# 	vi = copy(o.v1)
# 	w = copy(o.v1)
#
# 	# do the gram-schmidt process
# 	@inbounds for i in 1:o.k
# 		if i > 1
# 			# multiply Cw
# 			nextw = zeros(o.d)
# 			for j in 1:o.l
# 				pcaUj = row(o.pca.U, j)  # dx1 vector
# 				pcaVj = row(o.pca.V, j)	 # dx1 vector -- normalized -- eigenvector
# 				nextw += pcaUj * dot(pcaVj, w) / o.n  # TODO:  I don't like this n here... doesn't make sense with exponential weighting... how to change??
# 			end
# 		end
#
# 		# compute vi and add to V
# 		vi = copy(w)
# 		for j in 1:i-1
# 			vi -= vi .* V[j] .* V[j]
# 		end
# 		push!(V, vi)
#
# 		# add normalized vi to W
# 		col!(o.W, i, vi / if0then1(norm(vi)))
# 	end
#
# 	# update fls regression
# 	update!(o.fls, y, o.W' * x)
# 	# @LOG o.fls
#
# 	o.n += 1
# 	return
#
# end
#
#
# function Base.empty!(o::OnlinePLS)
# 	o.n = 0
# 	empty!(o.ymean)
# 	empty!(o.xmeans)
# 	o.v1 = zeros(o.d)
# 	o.W = zeros(o.d, o.k)
# 	empty!(o.pca)
# 	empty!(o.fls)
# 	nothing
# end
#
# function Base.merge!(o1::OnlinePLS, o2::OnlinePLS)
# 	error("Merging undefined for PLS")
# end
#
#
# function StatsBase.coef(o::OnlinePLS)
# 	error("not implemented")
# end
#
# function StatsBase.coeftable(o::OnlinePLS)
# 	error("not implemented")
# end
#
# function StatsBase.confint(o::OnlinePLS, level::Real = 0.95)
# 	error("not implemented")
# end
#
# # predicts yₜ for a given xₜ
# function StatsBase.predict(o::OnlinePLS, x::AVecF)
# 	# center x
# 	# multiply Wx to get a (kx1) vector of latent vars
# 	# y = predict(fls,Wx)
# 	# uncenter y
# 	x = center(o.xmeans, x)
# 	y = predict(o.fls, o.W' * x)
# 	uncenter(o.ymean, y)
# end
#
# # NOTE: uses most recent estimate of βₜ to predict the whole matrix
# function StatsBase.predict(o::OnlinePLS, X::AMatF)
# 	n = size(X,1)
# 	pred = zeros(n)
# 	for i in 1:n
# 		pred[i] = predict(o, row(X,i))
# 	end
# 	pred
# end
#
#


text: println("Hello from julia!")


text:
###
# Helpers for libarchive callbacks

"""
    ssize_t archive_read_callback(struct archive*,
                                  void *client_data, const void **buffer)

Returns pointer and size of next block of data from archive.
"""
macro to_read_callback(f, T)
    :(@cfunction($f, Cssize_t, (Ptr{Cvoid}, Ref{$(esc(T))}, Ptr{Ptr{Cvoid}})))
end

"""
    int64_t archive_skip_callback(struct archive*,
                                  void *client_data, int64_t request)

Skips at most request bytes from archive and returns the skipped amount.
This may skip fewer bytes than requested; it may even skip zero bytes.
If you do skip fewer bytes than requested, libarchive will invoke your
read callback and discard data as necessary to make up the full skip.
"""
macro to_skip_callback(f, T)
    :(@cfunction($f, Int64, (Ptr{Cvoid}, Ref{$(esc(T))}, Int64)))
end

"""
    int64_t archive_seek_callback(struct archive*,
                                  void *client_data, int64_t offset, int whence)

Seeks to specified location in the file and returns the position.
Whence values are SEEK_SET, SEEK_CUR, SEEK_END from stdio.h.
Return ARCHIVE_FATAL if the seek fails for any reason.
"""
macro to_seek_callback(f, T)
    :(@cfunction($f, Int64, (Ptr{Cvoid}, Ref{$(esc(T))}, Int64, Cint)))
end

"""
    ssize_t archive_write_callback(struct archive*,
                                   void *client_data,
                                   const void *buffer, size_t length);

Returns size actually written, zero on EOF, -1 on error.
"""
macro to_write_callback(f, T)
    :(@cfunction($f, Cssize_t, (Ptr{Cvoid}, Ref{$(esc(T))}, Ptr{Cvoid}, Csize_t)))
end

"""
    int archive_open_callback(struct archive*, void *client_data)
"""
macro to_open_callback(f, T)
    :(@cfunction($f, Cint, (Ptr{Cvoid}, Ref{$(esc(T))})))
end

"""
    int archive_close_callback(struct archive*, void *client_data)
"""
macro to_close_callback(f, T)
    :(@cfunction($f, Cint, (Ptr{Cvoid}, Ref{$(esc(T))})))
end


text:
"""
random vector on unit sphere, should be uniformly distributed?
"""
function rand_sphere(T = Float64)
   R = randn(SVector{3, T})
   return R / norm(R)
end

"""
random rotation matrix;
WARN: never checked what the distribution is
"""
rand_rot() = (K = (@SMatrix rand(3,3)) .- 0.5; exp(K - K'))

"""
random reflection, represented as 1, -1 Integer
"""
rand_refl() = rand([-1,1])

"""
random isometry i.e. element of O(3)
"""
rand_O3() = rand_refl() * rand_rot()

# the following two functions are a little hack to make sure
# that the basis spec is read in the same symbol-order as it is written
# (since dicts don't have a specified ordering...)

function _write_dict_1pspec(spec::Vector{NamedTuple{SYMS, NTuple{NSYM, Int}}}) where {SYMS, NSYM}
   inds = Vector{Int}[]
   for b in spec
      vals = [getproperty(b, sym) for sym in SYMS]
      push!(inds, vals)
   end
   return Dict("SYMS" => [ string.(SYMS)... ], "inds" => inds)
end

function _read_dict_1pspec(D::Dict)
   NTPROTO = namedtuple(D["SYMS"]...)
   return [ NTPROTO(binds) for binds in D["inds"] ]
end

#
# This is a useful utility function used e.g. in scal1pbasis.jl
#

"""
returns an `SVector{N}` of the form `x * e_I` where `e_I` is the Ith canonical basis vector.
"""
@generated function __e(::SVector{N}, ::Val{I}, x::T) where {N, I, T}
   code = "SA["
   for i = 1:N
      if i == I
         code *= "x,"
      else
         code *= "0,"
      end
   end
   code *= "]"
   quote
      $( Meta.parse(code) )
   end
end

__e(xx::SVector{N, T}, valI::Val{I}) where {N, T, I} = __e(xx, valI, one(T))

__e(::Number, ::Any, x) = x


text:
using HTTP, JSON, JuMP
include("REopt.jl")
include("GHPGHX.jl")

using .REopt
using .GHPGHX

function job(req::HTTP.Request)
    d = JSON.parse(String(req.body))
    timeout = pop!(d, "timeout_seconds")
    tol = pop!(d, "tolerance")
    m = xpress_model(timeout, tol)
    @info "Starting REopt with timeout of $(timeout) seconds..."
	error_response = Dict()
	results = Dict()
	try
    	results = reopt(m, d)
	catch e
		@error "Something went wrong in the Julia code!" exception=(e, catch_backtrace())
		error_response["error"] = sprint(showerror, e)
	end
	finalize(backend(m))
	GC.gc()
	if isempty(error_response)
    	@info "REopt model solved with status $(results["status"])."
    	return HTTP.Response(200, JSON.json(results))
	else
		@info "An error occured in the Julia code."
		return HTTP.Response(500, JSON.json(error_response))
	end
end

function ghpghx(req::HTTP.Request)
    inputs_dict = JSON.parse(String(req.body))
    @info "Starting GHPGHX" #with timeout of $(timeout) seconds..."
    results, inputs_params = GHPGHX.ghp_model(inputs_dict)
    # Create a dictionary of the results data needed for REopt
    ghpghx_results = GHPGHX.get_ghpghx_results_for_reopt(results, inputs_params)
    @info "GHPGHX model solved" #with status $(results["status"])."
    return HTTP.Response(200, JSON.json(ghpghx_results))
end

function health(req::HTTP.Request)
    return HTTP.Response(200, JSON.json(Dict("Julia-api"=>"healthy!")))
end

# define REST endpoints to dispatch to "service" functions
const ROUTER = HTTP.Router()

HTTP.@register(ROUTER, "POST", "/job", job)
HTTP.@register(ROUTER, "POST", "/ghpghx", ghpghx)
HTTP.@register(ROUTER, "GET", "/health", health)
HTTP.serve(ROUTER, "0.0.0.0", 8081, reuseaddr=true)


text:
# https://datatofish.com/install-julia/
# https://julialang.org/downloads/
# https://www.geeksforgeeks.org/hello-world-in-julia/
# https://docs.julialang.org/en/v1/manual/getting-started/
# https://juliabyexample.helpmanual.io/

print("Hello World!")

#println("Hello World!") # Prints to a new line

max_stars_repo_path: Julia/Hello World/Hello World.jl

max_issues_repo_path: Julia/Hello World/Hello World.jl

max_forks_repo_path: Julia/Hello World/Hello World.jl


text:
module SigmaDC

using Mea.Periodize

function dfdw(beta_::Float64, ww::Float64)

    #if abs(beta_*ww) > 20.0
    #    return 0.0
    #end

    return (-beta_*exp(beta_*ww)/(1.0 + exp(beta_*ww))^2.0   )
end

function calc_sigmadc(modelvec::Periodize.ModelVector, beta_::Float64)

  cutoff = 20.0
  cutoffidx=0
  for (ii, ww) in enumerate(modelvec.wvec_)
    if abs(ww*beta_) < cutoff
      cutoffidx = ii
      #println("ii = ", ii)
      break
    end
  end

  #println("cutoffidx = ", cutoffidx)

  modelvec.wvec_ = modelvec.wvec_[cutoffidx:end-cutoffidx]
  modelvec.sEvec_c_ = modelvec.sEvec_c_[cutoffidx:end-cutoffidx,:,:]

  dos2 = Periodize.calcdos2(modelvec, maxevals=100000)

  integrand = zeros(Float64, size(dos2)[1])
  for ii in 1:size(dos2)[1]
      integrand[ii] = dfdw(beta_, dos2[ii, 1])*dos2[ii, 2]
  end

  sigmadc = 0.0

      for ii in 1:size(dos2)[1]-1
                              # y                                 x
          sigmadc += 0.5 * (integrand[ii] + integrand[ii+1]) * (dos2[ii+1, 1] - dos2[ii, 1])
      end
  sigmadc*= -2.0/(2.0*pi)
  println(sigmadc)
  return sigmadc
end

end


text:
module AuthenticationsController

using Genie, Genie.Renderer, Genie.Router, Genie.Sessions, Genie.Helpers
using SearchLight, SearchLight.QueryBuilder
using GenieAuthentication

function show_login()
  html!(:authentications, :show_login, context = @__MODULE__)
end

function login()
  query = (from(User) + where("username = ?", @params(:username)) + where("password = ?", @params(:password))) |> prepare
  try
    user = SearchLight.find_one!!(query...)
    GenieAuthentication.authenticate(user.id, Sessions.session(@params))

    return "Authentication successful"
  catch ex
    flash("Authentication failed")
    redirect_to(:show_login)
  end
end

function logout()
  GenieAuthentication.deauthenticate(Sessions.session(@params))
end

end

max_stars_repo_name: tetsugps/julia

max_issues_repo_name: tetsugps/julia

max_forks_repo_name: tetsugps/julia


text:
# Testing of simple and reference expressions on scalar context

import Devectorize
import Devectorize.@devec
import Devectorize.@inspect_devec
import Devectorize.dump_devec

using Base.Test

#data

a = [1., 2., 3., 4., 5., 6., 7., 8.]
b = [3., 4., 5., 6., 8., 7., 6., 5.]
c = [9., 8., 7., 6., 4., 2., 3., 1.]
cv = 12.0
cv_a = [12., 12., 12., 12., 12., 12., 12., 12.]

abc = [a b c]

at = a'
bt = b'
ct = c'
abct = [at, bt, ct]

type X
    x
end

ax = X(a)

###########################################################
#
#   trivial/simple assignments
#
###########################################################

@devec r = a
@test r === a

@devec r = ax.x
@test r === ax.x

r = X(0)
@devec r.x = a
@test r.x === a

r = X(0)
@devec r.x = ax.x
@test r.x === ax.x

r = similar(a)
r0 = r
#dump_devec(:(r[:] = b))
@devec r[:] = b
@test r === r0
@test isequal(r, b)

###########################################################
#
#   scalar or scalar references
#
###########################################################

@devec r[:] = 12.
@test isequal(r, cv_a)

@devec r[:] = cv
@test isequal(r, cv_a)

r = similar(a)
@devec r[:] = a[3]
@test isequal(r, fill(a[3], size(a)))

i = 2
@devec r[:] = a[i]
@test isequal(r, fill(a[i], size(a)))

@devec r[:] = abc[1,3]
@test isequal(r, fill(c[1], size(a)))

i = 2
@devec r[:] = abc[i,3]
@test isequal(r, fill(c[i], size(a)))

@devec r[:] = abc[2,i]
@test isequal(r, fill(b[2], size(a)))

j = 1
@devec r[:] = abc[i,j]
@test isequal(r, fill(a[i], size(a)))

###########################################################
#
#   1D references
#
###########################################################

# 1D ref on RHS

@devec r = a[:]
@test isequal(r, a)

@devec r = a[1:]
@test isequal(r, a)

@devec r = a[1:5]
@test isequal(r, a[1:5])

v = 4
@devec r = a[1:v]
@test isequal(r, a[1:v])

@devec r = a[3:]
@test isequal(r, a[3:])

@devec r = a[3:6]
@test isequal(r, a[3:6])

v = 7
@devec r = a[3:v]
@test isequal(r, a[3:v])

u = 2
@devec r = a[u:]
@test isequal(r, a[u:])

@devec r = a[u:6]
@test isequal(r, a[u:6])

v = 7
@devec r = a[u:v]
@test isequal(r, a[u:v])

# 1D ref on LHS

r = zeros(size(a))
@devec r[:] = b[:]
rr = zeros(size(a))
rr[:] = b[:]
@test isequal(r, rr)

r = zeros(size(a))
@devec r[3:6] = cv
rr = zeros(size(a))
rr[3:6] = cv
@test isequal(r, rr)

r = zeros(size(a))
@devec r[3:6] = b[2:5]
rr = zeros(size(a))
rr[3:6] = b[2:5]
@test isequal(r, rr)

u = 1

r = zeros(size(a))
@devec r[1:] = b[u:]
rr = zeros(size(a))
rr[1:] = b[u:]
@test isequal(r, rr)

r = zeros(size(a))
@devec r[u:] = b[:]
rr = zeros(size(a))
rr[u:] = b[:]
@test isequal(r, rr)

u = 2

r = zeros(size(a))
@devec r[2:] = b[u:]
rr = zeros(size(a))
rr[2:] = b[u:]
@test isequal(r, rr)

r = zeros(size(a))
@devec r[u:] = b[2:]
rr = zeros(size(a))
rr[u:] = b[2:]
@test isequal(r, rr)

u, v = 4, 7

r = zeros(size(a))
@devec r[3:6] = b[u:v]
rr = zeros(size(a))
rr[3:6] = b[u:v]
@test isequal(r, rr)

r = zeros(size(a))
@devec r[u:v] = b[2:5]
rr = zeros(size(a))
rr[u:v] = b[2:5]
@test isequal(r, rr)

###########################################################
#
#   column references
#
###########################################################

# col-ref on RHS

j = 2

@devec r = abc[:,1]
@test isequal(r, a)

@devec r = abc[1:,1]
@test isequal(r, a)

@devec r = abc[1:5,1]
@test isequal(r, a[1:5])

@devec r = abc[:,j]
@test isequal(r, b)

@devec r = abc[1:,j]
@test isequal(r, b)

@devec r = abc[1:5,j]
@test isequal(r, b[1:5])

v = 4
@devec r = abc[1:v,1]
@test isequal(r, a[1:v])

@devec r = abc[3:,1]
@test isequal(r, a[3:])

@devec r = abc[3:6,1]
@test isequal(r, a[3:6])

@devec r = abc[1:v,j]
@test isequal(r, b[1:v])

@devec r = abc[3:,j]
@test isequal(r, b[3:])

@devec r = abc[3:6,j]
@test isequal(r, b[3:6])

v = 7
@devec r = abc[3:v,1]
@test isequal(r, a[3:v])

@devec r = abc[3:v,j]
@test isequal(r, b[3:v])

u = 2
@devec r = abc[u:,1]
@test isequal(r, a[u:])

@devec r = abc[u:6,1]
@test isequal(r, a[u:6])

@devec r = abc[u:,j]
@test isequal(r, b[u:])

@devec r = abc[u:6,j]
@test isequal(r, b[u:6])

v = 7
@devec r = abc[u:v,1]
@test isequal(r, a[u:v])

@devec r = abc[u:v,j]
@test isequal(r, b[u:v])

# col-ref on LHS

r = zeros(size(abc))
@devec r[:,1] = b[:]
rr = zeros(size(abc))
rr[:,1] = b[:]
@test isequal(r, rr)

r = zeros(size(abc))
@devec r[3:6,1] = cv
rr = zeros(size(abc))
rr[3:6,1] = cv
@test isequal(r, rr)

r = zeros(size(abc))
@devec r[3:6,1] = b[2:5]
rr = zeros(size(abc))
rr[3:6,1] = b[2:5]
@test isequal(r, rr)

u = 1

r = zeros(size(abc))
@devec r[1:,1] = b[u:]
rr = zeros(size(abc))
rr[1:,1] = b[u:]
@test isequal(r, rr)

r = zeros(size(abc))
@devec r[u:,1] = b[:]
rr = zeros(size(abc))
rr[u:,1] = b[:]
@test isequal(r, rr)

j = 3
u = 2

r = zeros(size(abc))
@devec r[2:,j] = b[u:]
rr = zeros(size(abc))
rr[2:,j] = b[u:]
@test isequal(r, rr)

r = zeros(size(abc))
@devec r[u:,j] = b[2:]
rr = zeros(size(abc))
rr[u:,j] = b[2:]
@test isequal(r, rr)

u, v = 4, 7

r = zeros(size(abc))
@devec r[3:6,j] = b[u:v]
rr = zeros(size(abc))
rr[3:6,j] = b[u:v]
@test isequal(r, rr)

r = zeros(size(abc))
@devec r[u:v,j] = b[2:5]
rr = zeros(size(abc))
rr[u:v,j] = b[2:5]
@test isequal(r, rr)

###########################################################
#
#   row references
#
###########################################################

# row-ref on RHS

i = 2

@devec r = abct[1,:]
@test isequal(r, at)

@devec r = abct[1,1:]
@test isequal(r, abct[1,1:])

@devec r = abct[1,1:5]
@test isequal(r, abct[1,1:5])

@devec r = abct[i,:]
@test isequal(r, abct[i,:])

@devec r = abct[i,1:]
@test isequal(r, abct[i,1:])

@devec r = abct[i,1:5]
@test isequal(r, abct[i,1:5])

v = 4
@devec r = abct[1,1:v]
@test isequal(r, abct[1,1:v])

@devec r = abct[1,3:]
@test isequal(r, abct[1,3:])

@devec r = abct[1,3:6]
@test isequal(r, abct[1,3:6])

@devec r = abct[i,1:v]
@test isequal(r, abct[i,1:v])

@devec r = abct[i,3:]
@test isequal(r, abct[i,3:])

@devec r = abct[i,3:6]
@test isequal(r, abct[i,3:6])

v = 7
@devec r = abct[1,3:v]
@test isequal(r, abct[1,3:v])

@devec r = abct[i,3:v]
@test isequal(r, abct[i,3:v])

u = 2
@devec r = abct[1,u:]
@test isequal(r, abct[1,u:])

@devec r = abct[1,u:6]
@test isequal(r, abct[1,u:6])

@devec r = abct[i,u:]
@test isequal(r, abct[i,u:])

@devec r = abct[i,u:6]
@test isequal(r, abct[i,u:6])

v = 7
@devec r = abct[1,u:v]
@test isequal(r, abct[1,u:v])

@devec r = abct[i,u:v]
@test isequal(r, abct[i,u:v])

# row-ref on LHS

r = zeros(size(abct))
@devec r[1,:] = bt[:]
rr = zeros(size(abct))
rr[1,:] = bt[:]
@test isequal(r, rr)

r = zeros(size(abct))
@devec r[1,3:6] = cv
rr = zeros(size(abct))
rr[1,3:6] = cv
@test isequal(r, rr)

r = zeros(size(abct))
@devec r[1,3:6] = bt[2:5]
rr = zeros(size(abct))
rr[1,3:6] = bt[2:5]
@test isequal(r, rr)

u = 1

r = zeros(size(abct))
@devec r[1,1:] = bt[u:]
rr = zeros(size(abct))
rr[1,1:] = bt[u:]
@test isequal(r, rr)

r = zeros(size(abct))
@devec r[1,u:] = bt[:]
rr = zeros(size(abct))
rr[1,u:] = bt[:]
@test isequal(r, rr)

i = 2
u = 2

r = zeros(size(abct))
@devec r[i,2:] = bt[u:]
rr = zeros(size(abct))
rr[i,2:] = bt[u:]
@test isequal(r, rr)

r = zeros(size(abct))
@devec r[i,u:] = bt[2:]
rr = zeros(size(abct))
rr[i,u:] = bt[2:]
@test isequal(r, rr)

u, v = 4, 7

r = zeros(size(abct))
@devec r[i,3:6] = bt[u:v]
rr = zeros(size(abct))
rr[i,3:6] = bt[u:v]
@test isequal(r, rr)

r = zeros(size(abct))
@devec r[i,u:v] = bt[2:5]
rr = zeros(size(abct))
rr[i,u:v] = bt[2:5]
@test isequal(r, rr)

###########################################################
#
#   2D references
#
###########################################################

B = reshape(linspace(1., 64., 64), 8, 8)

# 2D ref on RHS

u = 3
v = 7

@devec r = B[:,:]
@test isequal(r, B[:,:])

@devec r = B[:,2:]
@test isequal(r, B[:,2:])

@devec r = B[:,2:5]
@test isequal(r, B[:,2:5])

@devec r = B[u:,:]
@test isequal(r, B[u:,:])

@devec r = B[u:,2:]
@test isequal(r, B[u:,2:])

@devec r = B[u:,2:5]
@test isequal(r, B[u:,2:5])

@devec r = B[u:v,:]
@test isequal(r, B[u:v,:])

@devec r = B[u:v,2:]
@test isequal(r, B[u:v,2:])

@devec r = B[u:v,2:5]
@test isequal(r, B[u:v,2:5])

@devec r = B[2:,:]
@test isequal(r, B[2:,:])

@devec r = B[2:5,:]
@test isequal(r, B[2:5,:])

@devec r = B[:,u:]
@test isequal(r, B[:,u:])

@devec r = B[2:,u:]
@test isequal(r, B[2:,u:])

@devec r = B[2:5,u:]
@test isequal(r, B[2:5,u:])

@devec r = B[:,u:v]
@test isequal(r, B[:,u:v])

@devec r = B[2:,u:v]
@test isequal(r, B[2:,u:v])

@devec r = B[2:5,u:v]
@test isequal(r, B[2:5,u:v])

# 2D ref on LHS

r = zeros(size(B))
rr = zeros(size(B))
@devec r[:,:] = B[:,:]
rr[:,:] = B[:,:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[:,2:] = B[:,2:]
rr[:,2:] = B[:,2:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[:,2:5] = B[:,2:5]
rr[:,2:5] = B[:,2:5]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[u:,:] = B[u:,:]
rr[u:,:] = B[u:,:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[u:,2:] = B[u:,2:]
rr[u:,2:] = B[u:,2:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[u:,2:5] = B[u:,2:5]
rr[u:,2:5] = B[u:,2:5]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[u:v,:] = B[u:v,:]
rr[u:v,:] = B[u:v,:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[u:v,2:] = B[u:v,2:]
rr[u:v,2:] = B[u:v,2:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[u:v,2:5] = B[u:v,2:5]
rr[u:v,2:5] = B[u:v,2:5]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[2:,:] = B[2:,:]
rr[2:,:] = B[2:,:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[2:5,:] = B[2:5,:]
rr[2:5,:] = B[2:5,:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[:,u:] = B[:,u:]
rr[:,u:] = B[:,u:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[2:,u:] = B[2:,u:]
rr[2:,u:] = B[2:,u:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[2:5,u:] = B[2:5,u:]
rr[2:5,u:] = B[2:5,u:]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[:,u:v] = B[:,u:v]
rr[:,u:v] = B[:,u:v]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[2:,u:v] = B[2:,u:v]
rr[2:,u:v] = B[2:,u:v]
@test isequal(r, rr)

r = zeros(size(B))
rr = zeros(size(B))
@devec r[2:5,u:v] = B[2:5,u:v]
rr[2:5,u:v] = B[2:5,u:v]
@test isequal(r, rr)

###########################################################
#
#   Interactions of different kinds
#
#   LHS: Ref1D, RefCol, RelRow, Ref2D
#   RHS: Var, Scalar, Ref1D, RefCol, RefRow, Ref2D
#
###########################################################

# LHS is Ref1D

r = zeros(size(a))
@devec r[:] = a
@test isequal(r, a)

r = zeros(size(a))
@devec r[:] = cv
@test isequal(r, fill(cv, size(a)))

r = zeros(size(a))
@devec r[:] = a[:]
@test isequal(r, a)

r = zeros(size(a))
@devec r[:] = abc[:,2]
@test isequal(r, b)

r = zeros(size(a))
@devec r[:] = abct[2,:]
@test isequal(r, b)

# LHS is sub-range of Ref1D

m = 10

r = zeros(m)
rr = zeros(m)
@devec r[2:9] = a
rr[2:9] = a
@test isequal(r, rr)

r = zeros(m)
rr = zeros(m)
@devec r[2:9] = cv
rr[2:9] = cv
@test isequal(r, rr)

r = zeros(m)
rr = zeros(m)
@devec r[2:9] = a[:]
rr[2:9] = a[:]
@test isequal(r, rr)

r = zeros(m)
rr = zeros(m)
@devec r[2:9] = abc[:,2]
rr[2:9] = abc[:,2]
@test isequal(r, rr)

r = zeros(m)
rr = zeros(m)
@devec r[2:9] = abct[2,:]
rr[2:9] = abct[2,:]
@test isequal(r, rr)

# LHS is RefCol

r = zeros(size(abc))
rr = zeros(size(abc))
@devec r[:,2] = a
rr[:,2] = a
@test isequal(r, rr)

r = zeros(size(abc))
rr = zeros(size(abc))
@devec r[:,2] = cv
rr[:,2] = cv
@test isequal(r, rr)

r = zeros(size(abc))
rr = zeros(size(abc))
@devec r[:,2] = a[:]
rr[:,2] = a[:]
@test isequal(r, rr)

r = zeros(size(abc))
rr = zeros(size(abc))
@devec r[:,2] = abc[:,2]
rr[:,2] = abc[:,2]
@test isequal(r, rr)

r = zeros(size(abc))
rr = zeros(size(abc))
@devec r[:,2] = abct[2,:]
rr[:,2] = abct[2,:]
@test isequal(r, rr)

# LHS is RefRow

r = zeros(size(abct))
rr = zeros(size(abct))
@devec r[2,:] = a
rr[2,:] = a
@test isequal(r, rr)

r = zeros(size(abct))
rr = zeros(size(abct))
@devec r[2,:] = cv
rr[2,:] = cv
@test isequal(r, rr)

r = zeros(size(abct))
rr = zeros(size(abct))
@devec r[2,:] = a[:]
rr[2,:] = a[:]
@test isequal(r, rr)

r = zeros(size(abct))
rr = zeros(size(abct))
@devec r[2,:] = abc[:,2]
rr[2,:] = abc[:,2]
@test isequal(r, rr)

r = zeros(size(abct))
rr = zeros(size(abct))
@devec r[2,:] = abct[2,:]
rr[2,:] = abct[2,:]
@test isequal(r, rr)

# LHS is Ref2D

r = zeros(size(abc))
@devec r[:,:] = abc
@test isequal(r, abc)

r = zeros(size(abc))
@devec r[:,:] = cv
@test isequal(r, fill(cv, size(abc)))

r = zeros(size(abc))
@devec r[:,:] = abc[:,:]
@test isequal(r, abc)

# LHS is a subrange of Ref2D

m = 12
n = 5

r = zeros(m, n)
rr = zeros(m, n)
@devec r[3:10, 2:4] = abc
rr[3:10, 2:4] = abc
@test isequal(r, rr)

r = zeros(m, n)
rr = zeros(m, n)
@devec r[3:10, 2:4] = cv
rr[3:10, 2:4] = cv
@test isequal(r, rr)

r = zeros(m, n)
rr = zeros(m, n)
@devec r[3:10, 2:4] = abc[:,:]
rr[3:10, 2:4] = abc[:,:]
@test isequal(r, rr)

# using qualified names

ax = X(a)
@devec r = ax.x[:]
@test isequal(r, a)

r = X(0)
@devec r.x = abc[:,:]
@test isequal(r.x, abc)

r = X(0)
abcx = X(abc)
@devec r.x = abcx.x[:,2]
@test isequal(r.x, b)


text:
"""
    Constraints Data
"""
struct ConstraintsData
    c
    cx
    cu
end

function constraints_data(model::Model, p::Vector, T::Int;
	n = [model.n for t = 1:T],
	m = [model.m for t = 1:T-1])

    c = [zeros(p[t]) for t = 1:T]
    cx = [zeros(p[t], n[t]) for t = 1:T]
    cu = [zeros(p[t], m[t]) for t = 1:T-1]
    ConstraintsData(c, cx, cu)
end

struct StageConstraint
    p::Int
    info::Dict
end

ConstraintSet = Vector{StageConstraint}

struct StageConstraints <: Constraints
    con::ConstraintSet
    data::ConstraintsData
    T::Int
end

c!(a, cons::StageConstraints, x, u, t) = nothing

function constraints!(cons::StageConstraints, x, u)
    T = cons.T

    for t = 1:T-1
        c!(cons.data.c[t], cons, x[t], u[t], t)
    end

    c!(cons.data.c[T], cons, x[T], nothing, T)
end

function constraint_violation(cons::StageConstraints; norm_type = Inf)
    T = cons.T
    c_max = 0.0

    for t = 1:T
        c_viol = copy(cons.data.c[t])

        # find inequality constraints
        if haskey(cons.con[t].info, :inequality)
            for i in cons.con[t].info[:inequality]
                c_viol[i] = max.(0.0, cons.data.c[t][i])
            end
        end

        c_max = max(c_max, norm(c_viol, norm_type))
    end

    return c_max
end

function constraint_violation(cons::StageConstraints, x, u; norm_type = Inf)
    constraints!(cons, x, u)
    constraint_violation(cons, norm_type = norm_type)
end


text:
# This file was generated, do not modify it. # hide
MLJ.restrict(X::AbstractNode, f::AbstractNode, i) =
    node((XX, ff) -> restrict(XX, ff, i), X, f);
MLJ.corestrict(X::AbstractNode, f::AbstractNode, i) =
    node((XX, ff) -> corestrict(XX, ff, i), X, f);


text:
abstract type CVGSurface end

struct Triangle <: CVGSurface
    triangleID :: Int64
    x :: Float64
    y :: Float64
    z :: Float64
end
Triangle() = Triangle(1,1.0,1.0,1.0)

struct TrBoundry <:CVGSurface
    triangleID1 :: Int64
    triangleID2 :: Int64
    triangleID3 :: Int64
    boundryID ::Int64
end
TrBoundry() = TrBoundry(1,1,1,1)

struct Surface <: CVGSurface
    n_max_vertex :: Int64
    n_vertices :: Int64
    n_triangles :: Int64
    triangles :: Array{Triangle,1}
    surfaces :: Array{TrBoundry,1}
end

max_stars_repo_name: powerzf/CVGSurfaceFile

max_issues_repo_name: powerzf/CVGSurfaceFile

max_forks_repo_name: powerzf/CVGSurfaceFile