text:
# syntax: proto2
using Compat
using ProtoBuf
import ProtoBuf.meta
import ..hadoop

struct __enum_ContainerStateProto <: ProtoEnum
    C_NEW::Int32
    C_RUNNING::Int32
    C_COMPLETE::Int32
    __enum_ContainerStateProto() = new(1,2,3)
end #struct __enum_ContainerStateProto
const ContainerStateProto = __enum_ContainerStateProto()

struct __enum_YarnApplicationStateProto <: ProtoEnum
    NEW::Int32
    NEW_SAVING::Int32
    SUBMITTED::Int32
    ACCEPTED::Int32
    RUNNING::Int32
    FINISHED::Int32
    FAILED::Int32
    KILLED::Int32
    __enum_YarnApplicationStateProto() = new(1,2,3,4,5,6,7,8)
end #struct __enum_YarnApplicationStateProto
const YarnApplicationStateProto = __enum_YarnApplicationStateProto()

struct __enum_YarnApplicationAttemptStateProto <: ProtoEnum
    APP_ATTEMPT_NEW::Int32
    APP_ATTEMPT_SUBMITTED::Int32
    APP_ATTEMPT_SCHEDULED::Int32
    APP_ATTEMPT_ALLOCATED_SAVING::Int32
    APP_ATTEMPT_ALLOCATED::Int32
    APP_ATTEMPT_LAUNCHED::Int32
    APP_ATTEMPT_FAILED::Int32
    APP_ATTEMPT_RUNNING::Int32
    APP_ATTEMPT_FINISHING::Int32
    APP_ATTEMPT_FINISHED::Int32
    APP_ATTEMPT_KILLED::Int32
    __enum_YarnApplicationAttemptStateProto() = new(1,2,3,4,5,6,7,8,9,10,11)
end #struct __enum_YarnApplicationAttemptStateProto
const YarnApplicationAttemptStateProto = __enum_YarnApplicationAttemptStateProto()

struct __enum_FinalApplicationStatusProto <: ProtoEnum
    APP_UNDEFINED::Int32
    APP_SUCCEEDED::Int32
    APP_FAILED::Int32
    APP_KILLED::Int32
    __enum_FinalApplicationStatusProto() = new(0,1,2,3)
end #struct __enum_FinalApplicationStatusProto
const FinalApplicationStatusProto = __enum_FinalApplicationStatusProto()

struct __enum_LocalResourceVisibilityProto <: ProtoEnum
    PUBLIC::Int32
    PRIVATE::Int32
    APPLICATION::Int32
    __enum_LocalResourceVisibilityProto() = new(1,2,3)
end #struct __enum_LocalResourceVisibilityProto
const LocalResourceVisibilityProto = __enum_LocalResourceVisibilityProto()

struct __enum_LocalResourceTypeProto <: ProtoEnum
    ARCHIVE::Int32
    FILE::Int32
    PATTERN::Int32
    __enum_LocalResourceTypeProto() = new(1,2,3)
end #struct __enum_LocalResourceTypeProto
const LocalResourceTypeProto = __enum_LocalResourceTypeProto()

struct __enum_NodeStateProto <: ProtoEnum
    NS_NEW::Int32
    NS_RUNNING::Int32
    NS_UNHEALTHY::Int32
    NS_DECOMMISSIONED::Int32
    NS_LOST::Int32
    NS_REBOOTED::Int32
    __enum_NodeStateProto() = new(1,2,3,4,5,6)
end #struct __enum_NodeStateProto
const NodeStateProto = __enum_NodeStateProto()

struct __enum_AMCommandProto <: ProtoEnum
    AM_RESYNC::Int32
    AM_SHUTDOWN::Int32
    __enum_AMCommandProto() = new(1,2)
end #struct __enum_AMCommandProto
const AMCommandProto = __enum_AMCommandProto()

struct __enum_ApplicationAccessTypeProto <: ProtoEnum
    APPACCESS_VIEW_APP::Int32
    APPACCESS_MODIFY_APP::Int32
    __enum_ApplicationAccessTypeProto() = new(1,2)
end #struct __enum_ApplicationAccessTypeProto
const ApplicationAccessTypeProto = __enum_ApplicationAccessTypeProto()

struct __enum_QueueStateProto <: ProtoEnum
    Q_STOPPED::Int32
    Q_RUNNING::Int32
    __enum_QueueStateProto() = new(1,2)
end #struct __enum_QueueStateProto
const QueueStateProto = __enum_QueueStateProto()

struct __enum_QueueACLProto <: ProtoEnum
    QACL_SUBMIT_APPLICATIONS::Int32
    QACL_ADMINISTER_QUEUE::Int32
    __enum_QueueACLProto() = new(1,2)
end #struct __enum_QueueACLProto
const QueueACLProto = __enum_QueueACLProto()

struct __enum_ReservationRequestInterpreterProto <: ProtoEnum
    R_ANY::Int32
    R_ALL::Int32
    R_ORDER::Int32
    R_ORDER_NO_GAP::Int32
    __enum_ReservationRequestInterpreterProto() = new(0,1,2,3)
end #struct __enum_ReservationRequestInterpreterProto
const ReservationRequestInterpreterProto = __enum_ReservationRequestInterpreterProto()

struct __enum_ContainerExitStatusProto <: ProtoEnum
    SUCCESS::Int32
    INVALID::Int32
    ABORTED::Int32
    DISKS_FAILED::Int32
    __enum_ContainerExitStatusProto() = new(0,-1000,-100,-101)
end #struct __enum_ContainerExitStatusProto
const ContainerExitStatusProto = __enum_ContainerExitStatusProto()

mutable struct SerializedExceptionProto <: ProtoType
    message::AbstractString
    trace::AbstractString
    class_name::AbstractString
    cause::SerializedExceptionProto
    SerializedExceptionProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct SerializedExceptionProto

mutable struct ApplicationIdProto <: ProtoType
    id::Int32
    cluster_timestamp::Int64
    ApplicationIdProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ApplicationIdProto

mutable struct ApplicationAttemptIdProto <: ProtoType
    application_id::ApplicationIdProto
    attemptId::Int32
    ApplicationAttemptIdProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ApplicationAttemptIdProto

mutable struct ContainerIdProto <: ProtoType
    app_id::ApplicationIdProto
    app_attempt_id::ApplicationAttemptIdProto
    id::Int64
    ContainerIdProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ContainerIdProto

mutable struct ResourceProto <: ProtoType
    memory::Int32
    virtual_cores::Int32
    ResourceProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ResourceProto

mutable struct ResourceOptionProto <: ProtoType
    resource::ResourceProto
    over_commit_timeout::Int32
    ResourceOptionProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ResourceOptionProto

mutable struct PriorityProto <: ProtoType
    priority::Int32
    PriorityProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct PriorityProto

mutable struct URLProto <: ProtoType
    scheme::AbstractString
    host::AbstractString
    port::Int32
    file::AbstractString
    userInfo::AbstractString
    URLProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct URLProto

mutable struct LocalResourceProto <: ProtoType
    resource::URLProto
    size::Int64
    timestamp::Int64
    _type::Int32
    visibility::Int32
    pattern::AbstractString
    should_be_uploaded_to_shared_cache::Bool
    LocalResourceProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct LocalResourceProto

mutable struct ApplicationResourceUsageReportProto <: ProtoType
    num_used_containers::Int32
    num_reserved_containers::Int32
    used_resources::ResourceProto
    reserved_resources::ResourceProto
    needed_resources::ResourceProto
    memory_seconds::Int64
    vcore_seconds::Int64
    ApplicationResourceUsageReportProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ApplicationResourceUsageReportProto

mutable struct ApplicationReportProto <: ProtoType
    applicationId::ApplicationIdProto
    user::AbstractString
    queue::AbstractString
    name::AbstractString
    host::AbstractString
    rpc_port::Int32
    client_to_am_token::hadoop.common.TokenProto
    yarn_application_state::Int32
    trackingUrl::AbstractString
    diagnostics::AbstractString
    startTime::Int64
    finishTime::Int64
    final_application_status::Int32
    app_resource_Usage::ApplicationResourceUsageReportProto
    originalTrackingUrl::AbstractString
    currentApplicationAttemptId::ApplicationAttemptIdProto
    progress::Float32
    applicationType::AbstractString
    am_rm_token::hadoop.common.TokenProto
    applicationTags::Base.Vector{AbstractString}
    ApplicationReportProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ApplicationReportProto
const __val_ApplicationReportProto = Dict(:diagnostics => "N/A")
meta(t::Type{ApplicationReportProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, __val_ApplicationReportProto, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct ApplicationAttemptReportProto <: ProtoType
    application_attempt_id::ApplicationAttemptIdProto
    host::AbstractString
    rpc_port::Int32
    tracking_url::AbstractString
    diagnostics::AbstractString
    yarn_application_attempt_state::Int32
    am_container_id::ContainerIdProto
    original_tracking_url::AbstractString
    ApplicationAttemptReportProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ApplicationAttemptReportProto
const __val_ApplicationAttemptReportProto = Dict(:diagnostics => "N/A")
meta(t::Type{ApplicationAttemptReportProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, __val_ApplicationAttemptReportProto, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct NodeIdProto <: ProtoType
    host::AbstractString
    port::Int32
    NodeIdProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct NodeIdProto

mutable struct NodeResourceMapProto <: ProtoType
    node_id::NodeIdProto
    resource_option::ResourceOptionProto
    NodeResourceMapProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct NodeResourceMapProto

mutable struct ContainerReportProto <: ProtoType
    container_id::ContainerIdProto
    resource::ResourceProto
    node_id::NodeIdProto
    priority::PriorityProto
    creation_time::Int64
    finish_time::Int64
    diagnostics_info::AbstractString
    log_url::AbstractString
    container_exit_status::Int32
    container_state::Int32
    node_http_address::AbstractString
    ContainerReportProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ContainerReportProto
const __val_ContainerReportProto = Dict(:diagnostics_info => "N/A")
meta(t::Type{ContainerReportProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, __val_ContainerReportProto, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct ContainerProto <: ProtoType
    id::ContainerIdProto
    nodeId::NodeIdProto
    node_http_address::AbstractString
    resource::ResourceProto
    priority::PriorityProto
    container_token::hadoop.common.TokenProto
    ContainerProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ContainerProto

mutable struct NodeReportProto <: ProtoType
    nodeId::NodeIdProto
    httpAddress::AbstractString
    rackName::AbstractString
    used::ResourceProto
    capability::ResourceProto
    numContainers::Int32
    node_state::Int32
    health_report::AbstractString
    last_health_report_time::Int64
    node_labels::Base.Vector{AbstractString}
    NodeReportProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct NodeReportProto

mutable struct NodeIdToLabelsProto <: ProtoType
    nodeId::NodeIdProto
    nodeLabels::Base.Vector{AbstractString}
    NodeIdToLabelsProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct NodeIdToLabelsProto

mutable struct LabelsToNodeIdsProto <: ProtoType
    nodeLabels::AbstractString
    nodeId::Base.Vector{NodeIdProto}
    LabelsToNodeIdsProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct LabelsToNodeIdsProto

mutable struct ResourceRequestProto <: ProtoType
    priority::PriorityProto
    resource_name::AbstractString
    capability::ResourceProto
    num_containers::Int32
    relax_locality::Bool
    node_label_expression::AbstractString
    ResourceRequestProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ResourceRequestProto
const __val_ResourceRequestProto = Dict(:relax_locality => true)
meta(t::Type{ResourceRequestProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, __val_ResourceRequestProto, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct PreemptionContainerProto <: ProtoType
    id::ContainerIdProto
    PreemptionContainerProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct PreemptionContainerProto

mutable struct StrictPreemptionContractProto <: ProtoType
    container::Base.Vector{PreemptionContainerProto}
    StrictPreemptionContractProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct StrictPreemptionContractProto

mutable struct PreemptionResourceRequestProto <: ProtoType
    resource::ResourceRequestProto
    PreemptionResourceRequestProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct PreemptionResourceRequestProto

mutable struct PreemptionContractProto <: ProtoType
    resource::Base.Vector{PreemptionResourceRequestProto}
    container::Base.Vector{PreemptionContainerProto}
    PreemptionContractProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct PreemptionContractProto

mutable struct PreemptionMessageProto <: ProtoType
    strictContract::StrictPreemptionContractProto
    contract::PreemptionContractProto
    PreemptionMessageProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct PreemptionMessageProto

mutable struct ResourceBlacklistRequestProto <: ProtoType
    blacklist_additions::Base.Vector{AbstractString}
    blacklist_removals::Base.Vector{AbstractString}
    ResourceBlacklistRequestProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ResourceBlacklistRequestProto

mutable struct LogAggregationContextProto <: ProtoType
    include_pattern::AbstractString
    exclude_pattern::AbstractString
    rolled_logs_include_pattern::AbstractString
    rolled_logs_exclude_pattern::AbstractString
    LogAggregationContextProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct LogAggregationContextProto
const __val_LogAggregationContextProto = Dict(:include_pattern => ".*", :rolled_logs_exclude_pattern => ".*")
meta(t::Type{LogAggregationContextProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, __val_LogAggregationContextProto, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct ApplicationACLMapProto <: ProtoType
    accessType::Int32
    acl::AbstractString
    ApplicationACLMapProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ApplicationACLMapProto
const __val_ApplicationACLMapProto = Dict(:acl => " ")
meta(t::Type{ApplicationACLMapProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, __val_ApplicationACLMapProto, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct YarnClusterMetricsProto <: ProtoType
    num_node_managers::Int32
    YarnClusterMetricsProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct YarnClusterMetricsProto

mutable struct QueueInfoProto <: ProtoType
    queueName::AbstractString
    capacity::Float32
    maximumCapacity::Float32
    currentCapacity::Float32
    state::Int32
    childQueues::Base.Vector{QueueInfoProto}
    applications::Base.Vector{ApplicationReportProto}
    accessibleNodeLabels::Base.Vector{AbstractString}
    defaultNodeLabelExpression::AbstractString
    QueueInfoProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct QueueInfoProto

mutable struct QueueUserACLInfoProto <: ProtoType
    queueName::AbstractString
    userAcls::Base.Vector{Int32}
    QueueUserACLInfoProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct QueueUserACLInfoProto

mutable struct ReservationIdProto <: ProtoType
    id::Int64
    cluster_timestamp::Int64
    ReservationIdProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ReservationIdProto

mutable struct ReservationRequestProto <: ProtoType
    capability::ResourceProto
    num_containers::Int32
    concurrency::Int32
    duration::Int64
    ReservationRequestProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ReservationRequestProto
const __val_ReservationRequestProto = Dict(:num_containers => 1, :concurrency => 1, :duration => -1)
meta(t::Type{ReservationRequestProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, __val_ReservationRequestProto, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct ReservationRequestsProto <: ProtoType
    reservation_resources::Base.Vector{ReservationRequestProto}
    interpreter::Int32
    ReservationRequestsProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ReservationRequestsProto
const __val_ReservationRequestsProto = Dict(:interpreter => ReservationRequestInterpreterProto.R_ALL)
meta(t::Type{ReservationRequestsProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, __val_ReservationRequestsProto, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct ReservationDefinitionProto <: ProtoType
    reservation_requests::ReservationRequestsProto
    arrival::Int64
    deadline::Int64
    reservation_name::AbstractString
    ReservationDefinitionProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ReservationDefinitionProto

mutable struct ContainerStatusProto <: ProtoType
    container_id::ContainerIdProto
    state::Int32
    diagnostics::AbstractString
    exit_status::Int32
    ContainerStatusProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ContainerStatusProto
const __val_ContainerStatusProto = Dict(:diagnostics => "N/A", :exit_status => -1000)
meta(t::Type{ContainerStatusProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, __val_ContainerStatusProto, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

mutable struct ContainerResourceIncreaseRequestProto <: ProtoType
    container_id::ContainerIdProto
    capability::ResourceProto
    ContainerResourceIncreaseRequestProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ContainerResourceIncreaseRequestProto

mutable struct ContainerResourceIncreaseProto <: ProtoType
    container_id::ContainerIdProto
    capability::ResourceProto
    container_token::hadoop.common.TokenProto
    ContainerResourceIncreaseProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ContainerResourceIncreaseProto

mutable struct ContainerResourceDecreaseProto <: ProtoType
    container_id::ContainerIdProto
    capability::ResourceProto
    ContainerResourceDecreaseProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ContainerResourceDecreaseProto

mutable struct StringLocalResourceMapProto <: ProtoType
    key::AbstractString
    value::LocalResourceProto
    StringLocalResourceMapProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct StringLocalResourceMapProto

mutable struct StringStringMapProto <: ProtoType
    key::AbstractString
    value::AbstractString
    StringStringMapProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct StringStringMapProto

mutable struct StringBytesMapProto <: ProtoType
    key::AbstractString
    value::Array{UInt8,1}
    StringBytesMapProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct StringBytesMapProto

mutable struct ContainerLaunchContextProto <: ProtoType
    localResources::Base.Vector{StringLocalResourceMapProto}
    tokens::Array{UInt8,1}
    service_data::Base.Vector{StringBytesMapProto}
    environment::Base.Vector{StringStringMapProto}
    command::Base.Vector{AbstractString}
    application_ACLs::Base.Vector{ApplicationACLMapProto}
    ContainerLaunchContextProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ContainerLaunchContextProto

mutable struct ApplicationSubmissionContextProto <: ProtoType
    application_id::ApplicationIdProto
    application_name::AbstractString
    queue::AbstractString
    priority::PriorityProto
    am_container_spec::ContainerLaunchContextProto
    cancel_tokens_when_complete::Bool
    unmanaged_am::Bool
    maxAppAttempts::Int32
    resource::ResourceProto
    applicationType::AbstractString
    keep_containers_across_application_attempts::Bool
    applicationTags::Base.Vector{AbstractString}
    attempt_failures_validity_interval::Int64
    log_aggregation_context::LogAggregationContextProto
    reservation_id::ReservationIdProto
    node_label_expression::AbstractString
    am_container_resource_request::ResourceRequestProto
    ApplicationSubmissionContextProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct ApplicationSubmissionContextProto
const __val_ApplicationSubmissionContextProto = Dict(:application_name => "N/A", :queue => "default", :cancel_tokens_when_complete => true, :unmanaged_am => false, :maxAppAttempts => 0, :applicationType => "YARN", :keep_containers_across_application_attempts => false, :attempt_failures_validity_interval => -1)
meta(t::Type{ApplicationSubmissionContextProto}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, __val_ApplicationSubmissionContextProto, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES, ProtoBuf.DEF_FIELD_TYPES)

export ContainerStateProto, YarnApplicationStateProto, YarnApplicationAttemptStateProto, FinalApplicationStatusProto, LocalResourceVisibilityProto, LocalResourceTypeProto, NodeStateProto, AMCommandProto, ApplicationAccessTypeProto, QueueStateProto, QueueACLProto, ReservationRequestInterpreterProto, ContainerExitStatusProto, SerializedExceptionProto, ApplicationIdProto, ApplicationAttemptIdProto, ContainerIdProto, ResourceProto, ResourceOptionProto, NodeResourceMapProto, PriorityProto, ContainerProto, ContainerReportProto, URLProto, LocalResourceProto, ApplicationResourceUsageReportProto, ApplicationReportProto, ApplicationAttemptReportProto, NodeIdProto, NodeReportProto, NodeIdToLabelsProto, LabelsToNodeIdsProto, ResourceRequestProto, PreemptionMessageProto, StrictPreemptionContractProto, PreemptionContractProto, PreemptionContainerProto, PreemptionResourceRequestProto, ResourceBlacklistRequestProto, ApplicationSubmissionContextProto, LogAggregationContextProto, ApplicationACLMapProto, YarnClusterMetricsProto, QueueInfoProto, QueueUserACLInfoProto, ReservationIdProto, ReservationRequestProto, ReservationRequestsProto, ReservationDefinitionProto, ContainerLaunchContextProto, ContainerStatusProto, ContainerResourceIncreaseRequestProto, ContainerResourceIncreaseProto, ContainerResourceDecreaseProto, StringLocalResourceMapProto, StringStringMapProto, StringBytesMapProto


text:
function logika(a,b)
    return a+b > a*b, a ^ b > b ^ a
end

ext: jl


text:
mergeclasses(args...) = join(args, ' ')

function getclass(T::WidgetTheme, arg, typ...)
    length(typ) > 0 && last(typ) == "label" && return ""
    if arg == :input
        typ==() && return "input"
        typ[1] in ["checkbox", "radio"] && return "is-checkradio"
        typ[1]=="toggle" && return "switch"
        typ==("range",) && return "slider"
        typ==("range", "fullwidth") && return "slider is-fullwidth"

        if typ[1]=="file"
            typ[2:end]==() && return "file"
            typ[2:end]==("span",) && return "file-cta"
            typ[2:end]==("span", "icon") && return "file-icon"
            typ[2:end]==("span","label") && return "file-label"
            typ[2:end]==("icon",) && return "fas fa-upload"
            typ[2:end]==("label",) && return "file-label"
            typ[2:end]==("name",) && return "file-name"
        end
        return "input"
    elseif arg == :dropdown
        return typ == (true,) ? "select is-multiple" : "select"
    elseif arg == :button
        typ==("primary",) && return "is-primary"
        typ==("active",) && return "is-primary is-selected"
        typ==("fullwidth",) && return "is-fullwidth"
        return "button"
    elseif arg==:tab
        typ==("active",) && return "is-active"
        return "not-active"
    elseif arg == :textarea
        return "textarea"
    elseif arg==:wdglabel
        return "interact"
    elseif arg==:div
        return "field"
    elseif arg==:togglebuttons
        return "field is-grouped has-addons is-oneline is-centered"
    elseif arg==:tabs
        return "tabs"
    elseif arg==:radiobuttons
        return "field"
    elseif arg==:ijulia
        return "interactbulma"
    else
        return ""
    end
end


text:
abstract type Shape end

abstract type AbstractRectangle <: Shape end

struct Rectangle <: AbstractRectangle
    corner_upper_left  :: Tuple{Float64, Float64}
    corner_lower_right :: Tuple{Float64, Float64}
end

struct GrayRectangle <: AbstractRectangle
    corner_upper_left  :: Tuple{Float64, Float64}
    corner_lower_right :: Tuple{Float64, Float64}
    gray_value         :: Float64
end

abstract type AbstractCircle end

struct Circle <: AbstractCircle
    center  :: Tuple{Float64, Float64}
    radius  :: Float64
end

struct GrayCircle <: AbstractCircle
    center     :: Tuple{Float64, Float64}
    radius     :: Float64
    gray_value :: Float64
end

# vim:syn=julia:cc=79:fdm=marker:sw=4:ts=4:


text:
Random.seed!(123)
n, m = 100, 10
V = randn(n, m)
orthogonal!(V)
@test V'*V ≈ I


text:
using JuliaKara
@World "./intro.world"

world.drawing_delay = 0.03

function line(kara,length::Int)
    for i in 1:length
        putLeaf(kara)
        i == length || move(kara)
    end
end

function turnAround(kara)
    turnLeft(kara)
    turnLeft(kara)
end

function move(kara,steps::Int)
    for i in 1:steps
        move(kara)
    end
end

function diagonal(kara,length::Int,direction::Symbol=:up)
    if direction == :up
        rot = [
            turnLeft,
            turnRight
        ]
    elseif direction == :down
        rot = [
            turnRight,
            turnLeft
        ]
    end
    for i in 1:length
        putLeaf(kara)
        i==length || begin
            rot[1](kara)
            move(kara)
            rot[2](kara)
            move(kara)
        end
    end
end

function K(kara)
    line(kara,5)
    turnAround(kara)
    move(kara,2)
    turnLeft(kara)
    move(kara)
    diagonal(kara,3)
    turnRight(kara)
    move(kara,3)
    turnRight(kara)
    move(kara)
    turnAround(kara)
    diagonal(kara,2,:down)
end

function around_A(kara)
    turnLeft(kara)
    move(kara,4)
    turnRight(kara)
    move(kara,4)
    turnRight(kara)
    move(kara)
    turnLeft(kara)
    move(kara,2)
    turnLeft(kara)
    move(kara)
    turnLeft(kara)
    move(kara,3)
    turnAround(kara)
    move(kara,2)
end

function R(kara)
    turnRight(kara)
    line(kara,5)
    turnLeft(kara)
    move(kara,3)
    turnAround(kara)
    diagonal(kara,3,:down)
    turnAround(kara)
    move(kara)
    putLeaf(kara)
    move(kara)
    turnLeft(kara)
    move(kara)
    putLeaf(kara)
    move(kara)
    turnLeft(kara)
    move(kara)
    putLeaf(kara)
    move(kara)
    putLeaf(kara)
end

function A(kara)
    turnRight(kara)
    move(kara)
    line(kara,4)
    turnLeft(kara)
    move(kara)
    turnLeft(kara)
    move(kara,2)
    putLeaf(kara)
    move(kara,2)
    putLeaf(kara)
    turnRight(kara)
    move(kara)
    turnRight(kara)
    move(kara)
    line(kara,4)
end
store!(world)
reset!(world)

K(kara)
move(kara)
around_A(kara)
R(kara)
turnAround(kara)
move(kara,4)
A(kara)
turnLeft(kara)
move(kara)


text:
using Test
using CLIMA.TurbulenceConvection.StateVecs
SV = StateVecs

@testset "DomainSubSet, unit tests" begin

  @test SV.get_param(SV.GridMean{1}) == 1
  @test SV.get_param(SV.Environment{1}) == 1
  @test SV.get_param(SV.Updraft{5}) == 5

  @test SV.gridmean(DomainSubSet(gm=true)) == true
  @test SV.environment(DomainSubSet(gm=true)) == false
  @test SV.updraft(DomainSubSet(gm=true)) == false

  @test SV.gridmean(DomainSubSet(en=true)) == false
  @test SV.environment(DomainSubSet(en=true)) == true
  @test SV.updraft(DomainSubSet(en=true)) == false

  @test SV.gridmean(DomainSubSet(ud=true)) == false
  @test SV.environment(DomainSubSet(ud=true)) == false
  @test SV.updraft(DomainSubSet(ud=true)) == true

  dd = DomainDecomp(gm=1, en=1, ud=4)
  @test SV.get_param(dd, DomainSubSet(gm=true)) == (1,0,0)
  @test SV.get_param(dd, DomainSubSet(en=true)) == (0,1,0)
  @test SV.get_param(dd, DomainSubSet(ud=true)) == (0,0,4)

  @test SV.gridmean(dd, DomainSubSet(gm=true)) == 1
  @test SV.environment(dd, DomainSubSet(en=true)) == 1
  @test SV.updraft(dd, DomainSubSet(ud=true)) == 4

  @test SV.gridmean(dd, DomainSubSet(en=true)) == 0
  @test SV.environment(dd, DomainSubSet(gm=true)) == 0
  @test SV.updraft(dd, DomainSubSet(gm=true)) == 0

  @test SV.sum(dd, DomainSubSet(gm=true)) == 1
  @test SV.sum(dd, DomainSubSet(en=true)) == 1
  @test SV.sum(dd, DomainSubSet(ud=true)) == 4
end

@testset "DomainSubSet, single domain" begin
  dd,dss = DomainDecomp(gm=1),DomainSubSet(gm=true)
  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)
  @test gm==1
  @test en==0
  @test ud==(0,)
  @test idx_ss==idx

  dd,dss = DomainDecomp(en=1),DomainSubSet(en=true)
  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)
  @test en==1
  @test gm==0
  @test ud==(0,)
  @test idx_ss==idx

  dd,dss = DomainDecomp(ud=1),DomainSubSet(ud=true)
  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)
  @test en==0
  @test gm==0
  @test ud==(1,)
  @test idx_ss==idx

  dd,dss = DomainDecomp(ud=2),DomainSubSet(ud=true)
  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)
  @test en==0
  @test gm==0
  @test ud==(1,2)
  @test idx_ss==idx
end

@testset "DomainSubSet, two domains" begin
  dd,dss = DomainDecomp(gm=1,en=1),DomainSubSet(gm=true,en=true)
  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)
  @test gm==2
  @test en==1
  @test ud==(0,)
  @test idx_ss==idx

  dd,dss = DomainDecomp(gm=1,ud=3),DomainSubSet(gm=true,ud=true)
  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)
  @test gm==4
  @test en==0
  @test ud==(1,2,3)
  @test idx_ss==idx

  dd,dss = DomainDecomp(en=1,ud=3),DomainSubSet(en=true,ud=true)
  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)
  @test gm==0
  @test en==4
  @test ud==(1,2,3)
  @test idx_ss==idx

  dd,dss = DomainDecomp(gm=1,ud=1),DomainSubSet(gm=true,ud=true)
  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)
  @test gm==2
  @test en==0
  @test ud==(1,)
  @test idx_ss==idx

  dd,dss = DomainDecomp(en=1,ud=1),DomainSubSet(en=true,ud=true)
  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)
  @test gm==0
  @test en==2
  @test ud==(1,)
  @test idx_ss==idx
end

@testset "DomainIdx, all domains" begin
  dd, dss = DomainDecomp(gm=1,en=1,ud=4), DomainSubSet(gm=true,en=true,ud=true)
  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)
  @test gm == 6
  @test en == 5
  @test ud == (1,2,3,4)
  @test idx_ss==idx
end

@testset "DomainIdx, utilizing DomainSubSet" begin
  dd = DomainDecomp(gm=1,en=1,ud=4)
  idx = DomainIdx(dd)

  gm, en, ud, sd, al = allcombinations(idx)
  @test gm == 6
  @test en == 5
  @test ud == (1,2,3,4)

  dss = DomainSubSet(gm=true)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)

  gm, en, ud, sd, al = allcombinations(idx_ss)
  @test gm == 1
  @test en == 0
  @test ud == (0,)

  dss = DomainSubSet(en=true)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)

  gm, en, ud, sd, al = allcombinations(idx_ss)
  @test gm == 0
  @test en == 1
  @test ud == (0,)

  dss = DomainSubSet(ud=true)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)

  gm, en, ud, sd, al = allcombinations(idx_ss)
  @test gm == 0
  @test en == 0
  @test ud == (1,2,3,4)
end

@testset "Test DomainSubSet indexing, multiple domains" begin
  dd, dss = DomainDecomp(gm=1,en=1,ud=4), DomainSubSet(gm=true)

  idx = DomainIdx(dd)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  gm, en, ud, sd, al = allcombinations(idx)

  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  @test SV.updraft(idx_ss) == (0,)
  @test SV.environment(idx_ss) == 0
  @test SV.gridmean(idx_ss) == 1

  dss = DomainSubSet(en=true)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  @test SV.updraft(idx_ss) == (0,)
  @test SV.environment(idx_ss) == 1
  @test SV.gridmean(idx_ss) == 0

  dss = DomainSubSet(ud=true)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  @test SV.updraft(idx_ss) == (1,2,3,4)
  @test SV.environment(idx_ss) == 0
  @test SV.gridmean(idx_ss) == 0

  dss = DomainSubSet(gm=true,en=true)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  @test SV.updraft(idx_ss) == (0,)
  @test SV.environment(idx_ss) == 1
  @test SV.gridmean(idx_ss) == 2

  dss = DomainSubSet(gm=true,ud=true)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  @test SV.updraft(idx_ss) == (1,2,3,4)
  @test SV.environment(idx_ss) == 0
  @test SV.gridmean(idx_ss) == 5

  dss = DomainSubSet(en=true,ud=true)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  @test SV.updraft(idx_ss) == (1,2,3,4)
  @test SV.environment(idx_ss) == 5
  @test SV.gridmean(idx_ss) == 0

  dss = DomainSubSet(gm=true,en=true,ud=true)
  idx_ss = DomainIdx(dd, dss)
  a_map = SV.get_sv_a_map(idx, idx_ss)
  @test SV.updraft(idx_ss) == (1,2,3,4)
  @test SV.environment(idx_ss) == 5
  @test SV.gridmean(idx_ss) == 6
end

@testset "Test global indexing, many updrafts" begin

  vars = ((:ρ_0,   DomainSubSet(gm=true)),
          (:a,     DomainSubSet(gm=true,en=true,ud=true)),
          (:tke,   DomainSubSet(en=true,ud=true)),
          (:K_h,   DomainSubSet(ud=true)),
          )

  D = Dict([x => y for (x,y) in vars])

  dd = DomainDecomp(gm=1,en=1,ud=4)
  idx = DomainIdx(dd)
  @test SV.get_param(dd) == (1,1,4)
  @test SV.has_gridmean(idx) == true
  @test SV.has_environment(idx) == true
  @test SV.has_updraft(idx) == true

  sd = subdomains(idx)
  al = alldomains(idx)
  gm, en, ud = eachdomain(idx)
  gm, en, ud, sd, al = allcombinations(idx)

  @test sum(dd) == 6

  sd_unmapped = SV.get_sd_unmapped(vars, idx, dd)
  sd_mapped = SV.get_sd_mapped(vars, idx, dd)

  @test sd_unmapped[:a] == Int[6, 5, 1, 2, 3, 4]
  @test sd_unmapped[:tke] == Int[5, 1, 2, 3, 4]
  @test sd_unmapped[:K_h] == Int[1, 2, 3, 4]
  @test sd_unmapped[:ρ_0] == Int[6]

  @test sd_mapped[:a] == Int[6, 5, 1, 2, 3, 4]
  @test sd_mapped[:tke] == Int[0, 5, 1, 2, 3, 4]
  @test sd_mapped[:K_h] == Int[0, 0, 1, 2, 3, 4]
  @test sd_mapped[:ρ_0] == Int[1, 0, 0, 0, 0]

  vm, dss_per_var, var_names = SV.get_var_mapper(vars, dd)

  idx_ss_per_var = Dict([name => DomainIdx(dd, dss_per_var[name]) for name in var_names]...)
  a_map = Dict([name => SV.get_sv_a_map(idx, idx_ss_per_var[name]) for name in var_names]...)
  gm, en, ud, sd, al = allcombinations(idx)

  @test SV.var_string(vm, idx, idx_ss_per_var[:a], :a, gm) == "a_gm"
  @test SV.var_string(vm, idx, idx_ss_per_var[:a], :a, en) == "a_en"
  @test SV.var_string(vm, idx, idx_ss_per_var[:a], :a, ud[1]) == "a_ud_1"
  @test SV.var_string(vm, idx, idx_ss_per_var[:a], :a, ud[2]) == "a_ud_2"
  @test SV.var_string(vm, idx, idx_ss_per_var[:a], :a, ud[3]) == "a_ud_3"
  @test SV.var_string(vm, idx, idx_ss_per_var[:a], :a, ud[4]) == "a_ud_4"
  @test SV.var_suffix(vm, idx, idx_ss_per_var[:a], :a, gm) == "_gm"
  @test SV.var_suffix(vm, idx, idx_ss_per_var[:a], :a, en) == "_en"
  @test SV.var_suffix(vm, idx, idx_ss_per_var[:a], :a, ud[1]) == "_ud_1"
  @test SV.var_suffix(vm, idx, idx_ss_per_var[:a], :a, ud[2]) == "_ud_2"
  @test SV.var_suffix(vm, idx, idx_ss_per_var[:a], :a, ud[3]) == "_ud_3"
  @test SV.var_suffix(vm, idx, idx_ss_per_var[:a], :a, ud[4]) == "_ud_4"
  @test_throws BoundsError SV.var_suffix(vm, idx, idx_ss_per_var[:a], :a, 1000)

  @test SV.get_i_var(a_map[:ρ_0], gm) == 1
  @test SV.get_i_var(a_map[:a]  , ud[1]) == 1
  @test SV.get_i_var(a_map[:a]  , ud[2]) == 2
  @test SV.get_i_var(a_map[:a]  , ud[3]) == 3
  @test SV.get_i_var(a_map[:a]  , ud[4]) == 4
  @test SV.get_i_var(a_map[:a]  , en) == 5
  @test SV.get_i_var(a_map[:a]  , gm) == 6

  @test SV.get_i_state_vec(vm, a_map[:ρ_0], :ρ_0, gm) == 1
  @test SV.get_i_state_vec(vm, a_map[:a]  , :a, ud[1]) == 2
  @test SV.get_i_state_vec(vm, a_map[:a]  , :a, ud[2]) == 3
  @test SV.get_i_state_vec(vm, a_map[:a]  , :a, ud[3]) == 4
  @test SV.get_i_state_vec(vm, a_map[:a]  , :a, ud[4]) == 5
  @test SV.get_i_state_vec(vm, a_map[:a]  , :a, en)    == 6
  @test SV.get_i_state_vec(vm, a_map[:a]  , :a, gm)    == 7

  @test SV.get_i_state_vec(vm, a_map[:tke], :tke, ud[1]) == 8
  @test SV.get_i_state_vec(vm, a_map[:tke], :tke, ud[2]) == 9
  @test SV.get_i_state_vec(vm, a_map[:tke], :tke, ud[3]) == 10
  @test SV.get_i_state_vec(vm, a_map[:tke], :tke, ud[4]) == 11
  @test SV.get_i_state_vec(vm, a_map[:tke], :tke, en)    == 12

  @test SV.get_i_state_vec(vm, a_map[:K_h], :K_h, ud[1]) == 13
  @test SV.get_i_state_vec(vm, a_map[:K_h], :K_h, ud[2]) == 14
  @test SV.get_i_state_vec(vm, a_map[:K_h], :K_h, ud[3]) == 15
  @test SV.get_i_state_vec(vm, a_map[:K_h], :K_h, ud[4]) == 16

end

max_stars_repo_name: akshaysridhar/CLIMA

max_issues_repo_name: akshaysridhar/CLIMA

max_forks_repo_name: akshaysridhar/CLIMA


text:
using POMDPs
using ContinuousPOMDPTreeSearchExperiments
using POMDPToolbox
using BasicPOMCP
using POMCPOW
using ParticleFilters
using CPUTime
using DataFrames
using ARDESPOT
using Distributions
using DiscreteValueIteration
using VDPTag2
using QMDP

pomdp = VDPTagPOMDP(mdp=VDPTagMDP(barriers=CardinalBarriers(0.2, 2.8)))

@show max_time = 1.0
@show max_depth = 10
@show RO = RandomSolver

function gen_sims(x::Vector{Float64}, n, k, seed)
    c = x[1]
    @assert c >= 0.0
    k_act = x[2]
    @assert k_act >= 1.0
    inv_alpha_act = x[3]
    @assert inv_alpha_act >= 0.1
    k_obs = x[4]
    @assert k_obs >= 1.0
    inv_alpha_obs = x[5]
    @assert inv_alpha_obs >= 0.1

    sims = []

    for i in 1:n
        rng = MersenneTwister(0)

        # ro = ToNextMLSolver(rng)
        ro = RandomSolver(rng)::RO
        solver = POMCPOWSolver(tree_queries=10_000_000,
                               criterion=MaxUCB(c),
                               final_criterion=MaxTries(),
                               max_depth=max_depth,
                               max_time=max_time,
                               k_action=k_act,
                               alpha_action=1/inv_alpha_act,
                               k_observation=k_obs,
                               alpha_observation=1/inv_alpha_obs,
                               estimate_value=FORollout(ro),
                               next_action=RootToNextMLFirst(rng),
                               check_repeat_obs=false,
                               check_repeat_act=false,
                               default_action=ReportWhenUsed(TagAction(false, 0.0)),
                               rng=rng
                              )

        planner = solve(solver, pomdp)
        filter = ObsAdaptiveParticleFilter(deepcopy(pomdp),
                                           LowVarianceResampler(10_000),
                                           0.05,
                                           MersenneTwister(i+10000*k))

        srand(planner, i+40000*k)
        sim = Sim(deepcopy(pomdp),
                  planner,
                  filter,
                  rng=MersenneTwister(i+50_000*k),
                  max_steps=50,
                  metadata=Dict(:i=>i, :k=>k)
                 )
        push!(sims, sim)
    end

    return sims
end

start_mean = [100.0, 25.0, 20.0, 6.0, 100.0]
start_cov = diagm([100.0^2, 20.0^2, 20.0^2, 5.0^2, 50.0^2])
d = MvNormal(start_mean, start_cov)
K = 150 # 60 # number of parameter samples
n = 20  # 100 # number of evaluation simulations
m = 30  # 15 # number of elite samples
max_iters = 100

for i in 1:max_iters
    sims = []
    params = Vector{Vector{Float64}}(K)
    print("creating $K simulation sets")
    for k in 1:K
        p = rand(d)
        p[1] = max(0.0, p[1])
        p[2] = max(1.0, p[2])
        p[3] = max(1.0, p[3])
        p[4] = max(1.0, p[4])
        p[5] = max(1.0, p[5])
        params[k] = p
        k_sims = gen_sims(p, n, k, i)
        print(".")
        append!(sims, k_sims)
    end
    println()
    results = run_parallel(sims)
    # results = run(sims)
    combined = by(results, :k) do df
        DataFrame(mean_reward=mean(df[:reward]))
    end
    @show mean(combined[:mean_reward])
    order = sortperm(combined[:mean_reward])
    elite = params[combined[:k][order[K-m:end]]]
    elite_matrix = Matrix{Float64}(length(start_mean), m)
    for k in 1:m
        elite_matrix[:,k] = elite[k]
    end
    try
        d = fit(typeof(d), elite_matrix)
    catch ex
        if ex isa Base.LinAlg.PosDefException
            println("pos def exception")
            d = fit(typeof(d), elite_matrix += 0.01*randn(size(elite_matrix)))
        else
            rethrow(ex)
        end
    end
    println("iteration $i")
    @show mean(d)
    @show det(cov(d))
    @show ev = eigvals(cov(d))
    for j in 1:length(ev)
        @show eigvecs(cov(d))[:,j]
    end
end


text:
######################################################################
# GenerateProperties UTs
# -----
# Licensed under MIT License
using Test
using GenerateProperties

function noop(args...; kwargs...) end

@testset "GenerateProperties" begin
    @testset "flat" begin
        mutable struct TestFlatStruct
            size::NTuple{2, Float32}
        end
        TestFlatStruct() = TestFlatStruct((0, 0))

        @generate_properties TestFlatStruct begin
            @get width = self.size[1]
            @set width = self.size = (value, self.size[2])
            @get height = self.size[2]
            @set height = self.size = (self.size[1], value)
        end

        let inst = TestFlatStruct()
            @test inst.size == (0, 0) && inst.width == 0 && inst.height == 0

            @test (inst.width = 69) == 69 && (inst.height = 420) == 420
            @test inst.size == (69, 420) && inst.width == 69 && inst.height == 420

            @test (inst.size = (24, 25)) == (24, 25)
            @test inst.size == (24, 25) && inst.width == 24 && inst.height == 25
        end
    end

    @testset "nested" begin
        mutable struct SizeSimple
            width::Float64
            height::Float64
        end

        mutable struct TestNestedStruct
            size::SizeSimple
        end
        TestNestedStruct() = TestNestedStruct(SizeSimple(0, 0))

        @generate_properties TestNestedStruct begin
            @get width = self.size.width
            @set width = self.size.width = value
            @get height = self.size.height
            @set height = self.size.height = value
            @get size = (self.size.width, self.size.height)
            @set size = self.size = SizeSimple(value[1], value[2])
        end

        let inst = TestNestedStruct()
            @test inst.size == (0, 0) && inst.width == 0 && inst.height == 0

            @test (inst.width = 24) == 24 && (inst.height = 25) == 25
            @test inst.size == (24, 25) && inst.width == 24 && inst.height == 25

            @test (inst.size = (69, 69)) == (69, 69)
            @test inst.size == (69, 69) && inst.width == 69 && inst.height == 69
        end
    end

    @testset "complex" begin
        mutable struct TestComplexStruct
            size::NTuple{2, Int}
            dirty::Bool
            callback
        end
        TestComplexStruct(cb) = TestComplexStruct((0, 0), false, cb)
        TestComplexStruct() = TestComplexStruct((0, 0), false, noop)

        @generate_properties TestComplexStruct begin
            @set size = (self.dirty = true; self.callback(); self.size = value)

            @get width = self.size[1]
            @set width = (self.dirty = true; self.callback(); self.size = (value, self.size[2]))

            @get height = self.size[1]
            @set height = (self.dirty = true; self.callback(); self.size = (self.size[1], value))
        end

        let inst = TestComplexStruct(), callback_called = false
            @test inst.size == (0, 0) && inst.width == 0 && inst.height == 0 && !inst.dirty
            inst.callback() = callback_called = true

            @test (inst.width = 42) == 42
            @test inst.size == (42, 0) && inst.width == 42 && inst.dirty
            @test callback_called
        end
    end
end


text:
using StringDistances, Test

# Compare
@test compare("", "abc", Hamming()) ≈ 0.0 atol = 1e-4
@test compare("acc", "abc", Hamming()) ≈ 2/3 atol = 1e-4
@test compare("saturday", "sunday", Hamming()) ≈ 1/8 atol = 1e-4

@test compare("", "abc", QGram(1)) ≈ 0.0 atol = 1e-4
@test compare("abc", "cba", QGram(1)) ≈ 1.0 atol = 1e-4
@test compare("abc", "ccc", QGram(1)) ≈ 1/3 atol = 1e-4

@test compare("", "abc", Jaccard(2)) ≈ 0.0 atol = 1e-4

@test compare("martha", "martha", Jaccard(2)) ≈ 1.0 atol = 1e-4
@test compare("martha", "martha", Cosine(2)) ≈ 1.0 atol = 1e-4
@test compare("martha", "martha", Jaccard(2)) ≈ 1.0 atol = 1e-4
@test compare("martha", "martha", Overlap(2)) ≈ 1.0 atol = 1e-4
@test compare("martha", "martha", SorensenDice(2)) ≈ 1.0 atol = 1e-4

# Winkler
@test compare("martha", "marhta", Winkler(Jaro(), 0.1, 0.0, 4)) ≈ 0.9611 atol = 1e-4
@test compare("dwayne", "duane", Winkler(Jaro(), 0.1, 0.0, 4)) ≈ 0.84 atol = 1e-4
@test compare("dixon", "dicksonx", Winkler(Jaro(), 0.1, 0.0, 4)) ≈ 0.81333 atol = 1e-4
@test compare("william", "williams", Winkler(Jaro(), 0.1, 0.0, 4)) ≈ 0.975 atol = 1e-4
@test compare("", "foo", Winkler(Jaro(), 0.1, 0.0, 4)) ≈ 0.0 atol = 1e-4
@test compare("a", "a", Winkler(Jaro(), 0.1, 0.0, 4)) ≈ 1.0 atol = 1e-4
@test compare("abc", "xyz", Winkler(Jaro(), 0.1, 0.0, 4)) ≈ 0.0 atol = 1e-4

strings = [
("martha", "marhta"),
("dwayne", "duane") ,
("dixon", "dicksonx"),
("william", "williams"),
("", "foo")
]
solutions = [0.03888889 0.16000000 0.18666667 0.02500000 1.00000000]
for i in 1:length(solutions)
	@test compare(strings[i]..., Winkler(Jaro(), 0.1, 0.0, 4)) ≈ (1 - solutions[i]) atol = 1e-4
end

# Partial
@test compare("aa", "aa ", Partial(Jaccard(2))) ≈ 1.0

@test compare("New York Yankees",  "Yankees", Partial(RatcliffObershelp())) ≈ 1.0
@test compare("New York Yankees",  "", Partial(RatcliffObershelp())) ≈ 0.0
@test compare("mariners vs angels", "los angeles angels at seattle mariners", Partial(RatcliffObershelp())) ≈ 0.444444444444

s = "HSINCHUANG"
@test compare(s, "SINJHUAN", Partial(RatcliffObershelp())) ≈ 0.875
@test compare(s, "LSINJHUANG DISTRIC", Partial(RatcliffObershelp())) ≈ 0.8
@test compare(s, "SINJHUANG DISTRICT", Partial(RatcliffObershelp())) ≈ 0.8
@test compare(s,  "SINJHUANG", Partial(RatcliffObershelp())) ≈ 0.8888888888888

@test compare("New York Yankees",  "Yankees", Partial(Hamming())) ≈ 1
@test compare("New York Yankees",  "", Partial(Hamming())) ≈ 1

# Token
@test compare("New York Mets vs Atlanta Braves", "Atlanta Braves vs New York Mets", TokenSort(RatcliffObershelp()))  ≈ 1.0
@test compare("mariners vs angels", "los angeles angels of anaheim at seattle mariners", TokenSet(RatcliffObershelp())) ≈ 1.0 - 0.09090909090909094

@test compare("New York Mets vs Atlanta Braves", "", RatcliffObershelp())  ≈ 0.0

@test compare("New York Mets vs Atlanta Braves", "", TokenSort(RatcliffObershelp()))  ≈ 0.0

# ADD AGAIN
@test compare("mariners vs angels", "", TokenSet(RatcliffObershelp())) ≈ 0.0

@test compare("mariners", "mariner", TokenMax(RatcliffObershelp())) ≈ 0.933333333333333

#@test_approx_eq compare(TokenSort(RatcliffObershelp()), graphemeiterator("New York Mets vs Atlanta Braves"), graphemeiterator("Atlanta Braves vs New York Mets"))  1.0
#@test_approx_eq compare(TokenSet(RatcliffObershelp()),graphemeiterator("mariners vs angels"), graphemeiterator("los angeles angels of anaheim at seattle mariners")) 1.0 - 0.09090909090909094
#@test_approx_eq compare(TokenSort(RatcliffObershelp()), graphemeiterator("New York Mets vs Atlanta Braves"), graphemeiterator(""))  0.0
#@test_approx_eq compare(TokenSet(RatcliffObershelp()),graphemeiterator("mariners vs angels"), graphemeiterator("")) 0.0

@test compare("mariners vs angels", "los angeles angels at seattle mariners", TokenSet(Partial(RatcliffObershelp()))) ≈ 1.0

@test round(Int, 100 * compare("为人子女者要堂堂正正做人，千万不可作奸犯科，致使父母蒙羞", "此前稍早些时候中国商务部发布消息称，中美经贸高级别磋商双方牵头人通话，中方就美拟9月1日加征关税进行了严正交涉。", RatcliffObershelp())) == 5

# test with fuzz ratio
@test round(Int, 100 * compare("为人子女者要堂堂正正做人，千万不可作奸犯科，致使父母蒙羞", "此前稍早些时候中国商务部发布消息称，中美经贸高级别磋商双方牵头人通话，中方就美拟9月1日加征关税进行了严正交涉。", RatcliffObershelp())) == 5
@test round(Int, 100 * compare("为人子女者要堂堂正正做人，千万不可作奸犯科，致使父母蒙羞", "此前稍早些时候中国商务部发布消息称，中美经贸高级别磋商双方牵头人通话，中方就美拟9月1日加征关税进行了严正交涉。", Partial(RatcliffObershelp()))) == 7
@test round(Int, 100 * compare("mariners", "mariner are playing tomorrow", TokenMax(RatcliffObershelp()))) == 79
@test round(Int, 100 * compare("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow", Partial(RatcliffObershelp()))) == 88
@test round(Int, 100 * compare("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow", TokenSort(RatcliffObershelp()))) == 11
@test round(Int, 100 * compare("mariners", "are mariner playing tomorrow", RatcliffObershelp())) == 39
@test round(Int, 100 * compare("mariners", "are mariner playing tomorrow", Partial(RatcliffObershelp()))) == 88
@test round(Int, 100 * compare("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow", TokenSet(RatcliffObershelp()))) == 39
@test round(Int, 100 * compare("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow", TokenSet(Partial(RatcliffObershelp())))) == 88
# not exactly the same because tokenmax has uses the max of rounded tokenset etc
@test round(Int, 100 * compare("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow", TokenMax(RatcliffObershelp()))) == 52

#= Python code
from fuzzywuzzy import fuzz
fuzz.ratio("为人子女者要堂堂正正做人，千万不可作奸犯科，致使父母蒙羞", "此前稍早些时候中国商务部发布消息称，中美经贸高级别磋商双方牵头人通话，中方就美拟9月1日加征关税进行了严正交涉。")
fuzz.partial_ratio("为人子女者要堂堂正正做人，千万不可作奸犯科，致使父母蒙羞", "此前稍早些时候中国商务部发布消息称，中美经贸高级别磋商双方牵头人通话，中方就美拟9月1日加征关税进行了严正交涉。")
fuzz.WRatio("mariners", "mariner are playing tomorrow")
fuzz.partial_ratio("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow")
fuzz.token_sort_ratio("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow")
fuzz.token_set_ratio("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow")
fuzz.partial_token_set_ratio("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow")
fuzz.WRatio("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow")
fuzz.WRatio("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow")
fuzz.WRatio("mariners", "mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow mariner are playing tomorrow")
=#

using StringDistances, Test

# check with weird utf8 strings
compare("aüa", "aua", TokenMax(RatcliffObershelp()))
compare("aüa", "aua", TokenMax(QGram(2)))
compare("aüa", "aua", DamerauLevenshtein())
compare("aüa", "aua", Hamming())
compare("aüa", "aua", Jaro())
compare("aüa", "aua", Levenshtein())

s1 = "aü☃"
s2 = "aüaüafs"
dist = QGram(4)
@test evaluate(dist, s1, s2) == 4

# check Substrings work
s1 = SubString(s1, 1, 4)
s2 = SubString(s2, 1, 4)
dist = QGram(2)
@test evaluate(dist, s1, s2) == 2

# check missing
@test compare(s1, missing, Levenshtein()) === missing

# check min
for dist in (Levenshtein, DamerauLevenshtein)
	for i in eachindex(strings)
		if compare(strings[i]..., dist()) <  1 / 3
			@test compare(strings[i]..., dist() ; min_score = 1/ 3) ≈ 0.0
			else
			@test compare(strings[i]..., dist() ; min_score = 1/ 3) ≈ compare(strings[i]..., dist())
		end
	end
end

# check find_best and find_all
@test find_best("New York", ["NewYork", "Newark", "San Francisco"], Levenshtein()) == "NewYork"
@test find_best("New York", ["NewYork", "Newark", "San Francisco"], Jaro()) == "NewYork"
@test find_all("New York", ["NewYork", "Newark", "San Francisco"], Levenshtein()) == ["NewYork"]
@test find_all("New York", ["NewYork", "Newark", "San Francisco"], Jaro()) == ["NewYork", "Newark"]


text:
# If p is the perimeter of a right angle triangle with integral length sides,
# {a,b,c}, there are exactly three solutions for p = 120.
#
# {20,48,52}, {24,45,51}, {30,40,50}
#
# For which value of p ≤ 1000, is the number of solutions maximised?

using ProjectEulerSolutions

# Simple approach that cycles through legal ranges for a and b and storing
# counts of integer values of c.  Solution is the max of that array.  An even
# faster solution would involve directly generating Pythagorean triplets.
function p039solution(n::Integer=12)::Integer
    solutions = zeros(Integer, n)

    for a in 3:fld(n,3) # Range between 3 and n/3 (3 could be larger)
        for b in (a+1):fld(n,2)
            c = sqrt(a * a + b * b)
            if c - floor(c) == 0 && a + b + c <= n
                solutions[Integer(a + b + c)] += 1
            end
        end
    end

    return findmax(solutions)[2]
end

p039 = Problems.Problem(p039solution)

Problems.benchmark(p039, 1000)

max_stars_repo_name: gnujosh/julia-euler-project

max_issues_repo_name: gnujosh/julia-euler-project

max_forks_repo_name: gnujosh/julia-euler-project


text:
# positive diagonal matrix

immutable PDiagMat{T<:Real,V<:AbstractVector} <: AbstractPDMat{T}
  dim::Int
  diag::V
  inv_diag::V
  PDiagMat(d::Int,v::AbstractVector{T},inv_v::AbstractVector{T}) = new(d,v,inv_v)
end

function PDiagMat(v::AbstractVector,inv_v::AbstractVector)
  @check_argdims length(v) == length(inv_v)
  PDiagMat{eltype(v),typeof(v)}(length(v), v, inv_v)
end

PDiagMat(v::Vector) = PDiagMat(v, ones(v)./v)

### Conversion
convert{T<:Real}(::Type{PDiagMat{T}}, a::PDiagMat) = PDiagMat(convert(Vector{T}, a.diag))

### Basics

dim(a::PDiagMat) = a.dim
full(a::PDiagMat) = diagm(a.diag)
diag(a::PDiagMat) = copy(a.diag)

### Arithmetics

function pdadd!(r::Matrix, a::Matrix, b::PDiagMat, c)
    @check_argdims size(r) == size(a) == size(b)
    if is(r, a)
        _adddiag!(r, b.diag, c)
    else
        _adddiag!(copy!(r, a), b.diag, c)
    end
    return r
end

*{T<:Real}(a::PDiagMat, c::T) = PDiagMat(a.diag * c)
*(a::PDiagMat, x::StridedVecOrMat) = a.diag .* x
\(a::PDiagMat, x::StridedVecOrMat) = a.inv_diag .* x

### Algebra

inv(a::PDiagMat) = PDiagMat(a.inv_diag, a.diag)
logdet(a::PDiagMat) = sum(log, a.diag)
eigmax(a::PDiagMat) = maximum(a.diag)
eigmin(a::PDiagMat) = minimum(a.diag)

### whiten and unwhiten

function whiten!(r::StridedVector, a::PDiagMat, x::StridedVector)
    n = dim(a)
    @check_argdims length(r) == length(x) == n
    v = a.inv_diag
    for i = 1:n
        r[i] = x[i] * sqrt(v[i])
    end
    return r
end

function unwhiten!(r::StridedVector, a::PDiagMat, x::StridedVector)
    n = dim(a)
    @check_argdims length(r) == length(x) == n
    v = a.diag
    for i = 1:n
        r[i] = x[i] * sqrt(v[i])
    end
    return r
end

whiten!(r::StridedMatrix, a::PDiagMat, x::StridedMatrix) =
    broadcast!(*, r, x, @compat(sqrt.(a.inv_diag)))

unwhiten!(r::StridedMatrix, a::PDiagMat, x::StridedMatrix) =
    broadcast!(*, r, x, @compat(sqrt.(a.diag)))

### quadratic forms

quad(a::PDiagMat, x::Vector) = wsumsq(a.diag, x)
invquad(a::PDiagMat, x::Vector) = wsumsq(a.inv_diag, x)

quad!(r::AbstractArray, a::PDiagMat, x::Matrix) = At_mul_B!(r, @compat(abs2.(x)), a.diag)
invquad!(r::AbstractArray, a::PDiagMat, x::Matrix) = At_mul_B!(r, @compat(abs2.(x)), a.inv_diag)

### tri products

function X_A_Xt(a::PDiagMat, x::StridedMatrix)
    z = x .* reshape(@compat(sqrt.(a.diag)), 1, dim(a))
    A_mul_Bt(z, z)
end

function Xt_A_X(a::PDiagMat, x::StridedMatrix)
    z = x .* @compat(sqrt.(a.diag))
    At_mul_B(z, z)
end

function X_invA_Xt(a::PDiagMat, x::StridedMatrix)
    z = x .* reshape(@compat(sqrt.(a.inv_diag)), 1, dim(a))
    A_mul_Bt(z, z)
end

function Xt_invA_X(a::PDiagMat, x::StridedMatrix)
    z = x .* @compat(sqrt.(a.inv_diag))
    At_mul_B(z, z)
end


text:
delete!(ENV,"DISPLAY")

using ImageMagick
using APTDecoder
using SatelliteToolbox
using Dates
using Base64
using JSON
using Twitter
import APTDecoder
using PyPlot
using PyCall
using TimeZones
#using TOML

plt.ioff()
#using Pkg
#const TOML = Pkg.TOML

#config = TOML.parsefile("APTDecoder.toml")
config = JSON.parsefile("APTDecoder.json")

tles = APTDecoder.get_tle(:weather)

eop_IAU1980 = get_iers_eop();

const satellites = Dict(
    "NOAA 19" => (frequency = 137_100_000,
                  protocol = :APT),
    "NOAA 18" => (frequency = 137_912_500,
                  protocol = :APT),
    "NOAA 15" => (frequency = 137_620_000,
                  protocol = :APT),
#    "METEOR-M 2" => (frequency = 137_900_000,
#                  protocol = :MM),
)

lt(dt::DateTime) = astimezone(ZonedDateTime(dt,tz"UTC"),localzone())

function get_tle(satellite_name,tles = APTDecoder.get_tle(:weather))
    return [t for t in tles if t.name == satellite_name][1]
end

function sat_time(eop_IAU1980,ground_station,tle,t0,t1)
    orbp = init_orbit_propagator(Val(:sgp4), tle)
    ground_station_rad = (ground_station[2] * pi/180,ground_station[1] * pi/180 ,ground_station[3])
    # predict for the next 3 days since epoch of the satellite
    Δt = 24*60*60*3
    out = ground_station_accesses(orbp, ground_station_rad,Δt,TEME(),ITRF(),eop_IAU1980; θ = 30*pi/180)
    # keep only time between t0 and t1
    sel = (t0 .<= out[:,1]) .& (out[:,2] .< t1)
    #@show tle.name, out
    out = out[sel,:]
    return out
end

function twitter_upload(auth,fname)
    media = read(fname)
    r = Twitter.post_oauth("https://upload.twitter.com/1.1/media/upload.json",Dict("media" => base64encode(media)))
    resp = JSON.parse(String(r.body))
    return resp["media_id_string"]
end

function publish(auth,message,fnames)
    twitterauth(auth["consumer_key"], auth["consumer_token"], auth["access_token"], auth["access_secret"])
    Twitter.post_status_update(
        status = message,
        media_ids =
        join([twitter_upload(auth,fname) for fname in fnames],","))
end

function process(config,tles,eop_IAU1980,t0; debug = false, tz_offset = Dates.Hour(2))
    pygc = PyCall.pyimport("gc")

    ground_station = (
        config["ground_station"]["latitude"],
        config["ground_station"]["longitude"],
        config["ground_station"]["altitude"])

    basedir = config["basedir"]
    mkpath(basedir)

    t1 = t0 + Dates.Day(1)

    outdir = joinpath(basedir,Dates.format(t0,"yyyy-mm-dd"))
    mkpath(outdir)

    pass_satellite_name = String[]
    pass_time = Matrix{DateTime}(undef,0,2)

    for satellite_name in keys(satellites)
        tle = get_tle(satellite_name)
        out = sat_time(eop_IAU1980,ground_station,tle,t0,t1)

        append!(pass_satellite_name,fill(satellite_name,size(out,1)))
        pass_time = vcat(pass_time,out)
    end

    ind = sortperm(pass_time[:,1])
    pass_time = pass_time[ind,:]
    pass_satellite_name = pass_satellite_name[ind]

    for i = 1:size(pass_time,1)
        pass_duration = Dates.value(pass_time[i,2] - pass_time[i,1])/1000
        println("$(pass_satellite_name[i]): $(lt(pass_time[i,1])) → $(lt(pass_time[i,2]))  $(round(pass_duration/60,digits=1)) min")
    end

    for i = 1:size(pass_time,1)
        sleep_time = pass_time[i,1] - Dates.now(Dates.UTC)
        # debug
	    if debug
            sleep_time = Dates.Second(1)
	    end

        if sleep_time > Dates.Millisecond(0)
            println("wait upto $(lt(pass_time[i,1])) for $(pass_satellite_name[i]) $sleep_time ")
            sleep(sleep_time)
        end

        if Dates.now(Dates.UTC) < pass_time[i,2]
            dt = Dates.now(Dates.UTC)
            println("Now $(lt(dt)) and should be $(lt(pass_time[i,1]))")
            pass_duration = pass_time[i,2] - dt
            # debug
	        if debug
	            pass_duration = Dates.Second(10)
	        end
            frequency = satellites[pass_satellite_name[i]].frequency
            protocol = satellites[pass_satellite_name[i]].protocol

	    if protocol == :APT
		wavname = joinpath(outdir,"APTDecoder_$(Dates.format(dt,"yyyymmdd"))_$(Dates.format(dt,"HHMMSS"))_$(frequency).wav")
		@info("start recording $(pass_satellite_name[i]) to file $wavname")

		# satellite is still in the sky
		#record = run(pipeline(`rtl_fm -f $(frequency) -s 60k -g 45 -p 55 -E wav -E deemp -F 9 -`,`sox -t raw -r 60000 -e signed -b 32 - $(wavname)`), wait = false);

		    # https://web.archive.org/web/20191007192042/http://ajoo.blog/intro-to-rtl-sdr-part-ii-software.html
		    gain = 10
		    sampling_rate = 60_000
		    sampling_rate = 48_000
		    ppm_error = 55
		    ppm_error = 0
		    fir_size = 9
		    #fir_size = 0

		#to check
		#arctan_method = "fast"
		# -E offset
		# -A $(arctan_method)
		    #record = run(pipeline(`rtl_fm -f $(frequency) -s 60k -g 45 -p 55 -E wav -E deemp -F 9 - `,`sox -t wav - $wavname rate 11025`), wait = false);
		    record = run(pipeline(`rtl_fm -f $(frequency) -s $(sampling_rate) -g $(gain) -p $(ppm_error) -E wav -E deemp -F $(fir_size) -E offset - `,`sox -t wav - $wavname rate 11025`), wait = false);
		    # get FM radio for debugging
		#record = run(pipeline(`rtl_fm -M wbfm -f 88.5e6 -E wav`, `sox -t raw -e signed -c 1 -b 16 -r 32k - $wavname`), wait = false);
		println("Recording during ",pass_duration)
		sleep(pass_duration)
		kill.(record.processes,Base.SIGINT)

		println("Finish recording\n")
	        sleep(10)
            # debug
	        if debug
                wavname_example = joinpath(dirname(pathof(APTDecoder)),"..","examples","gqrx_20190823_173900_137620000.wav")
                cp(wavname_example,wavname,force=true)
                pass_satellite_name[i] = "NOAA 15"
	        end

            println("Making plots")
	        @show wavname,pass_satellite_name[i]
                imagenames = APTDecoder.makeplots(wavname,pass_satellite_name[i]; eop = eop_IAU1980)
                close("all")
                images = [imagenames.rawname,imagenames.channel_a,imagenames.channel_b]
            else
		pngname = joinpath(outdir,"APTDecoder_$(Dates.format(dt,"yyyymmdd"))_$(Dates.format(dt,"HHMMSS"))_$(frequency).png")
	        run(`/home/pi/.julia/dev/APTDecoder/examples/record_meteor.sh $(Dates.value(pass_duration)/1000) $pngname`)
		images =
		   if filesize(pngname) > 0
		      [pngname]
		   else
		      []
		   end
	    end

            #if i < 3
            message = "$(pass_satellite_name[i]) $(lt(dt))"
            if i < length(pass_satellite_name)
                message *= " - next at $(lt(pass_time[i+1,1]))"
            end
	    try
                publish(config["twitter"],message,images)
	    catch e
	        @warn "message cannot be posted"
		@show e
	    end
            #end
        end

        pygc.collect()
	GC.gc()
    end

end

#if isdir("/tmp/APTDecoder")
#    run(`rm -R /tmp/APTDecoder/`)
#end
# time frame of selected passes
t0 = Dates.now(Dates.UTC);
process(config,tles,eop_IAU1980,t0,
   #debug=true
)

max_stars_repo_name: Alexander-Barth/APTDecoder

max_issues_repo_name: Alexander-Barth/APTDecoder

max_forks_repo_name: Alexander-Barth/APTDecoder


text:
# ---
# title: 387. First Unique Character in a String
# id: problem387
# author: zhwang
# date: 2022-01-23
# difficulty: Easy
# categories: Hash Table, String
# link: <https://leetcode.com/problems/first-unique-character-in-a-string/description/>
# hidden: true
# ---
#
# Given a string, find the first non-repeating character in it and return its
# index. If it doesn't exist, return -1.
#
# **Examples:**
#
#
#
#     s = "leetcode"
#     return 0.
#
#     s = "loveleetcode"
#     return 2.
#
#
#
#
# **Note:** You may assume the string contains only lowercase English letters.
#
#
## @lc code=start
using LeetCode

function first_unique_char(s::String)::Int
    table = Dict{Char,Bool}()
    for i in s
        table[i] = !haskey(table, i)
    end
    for (i, st) in enumerate(s)
        table[st] && return i
    end
    -1
end

## @lc code=end


text:
include("./probs.jl")

module Pccf
using Distributions
export pccf, pccf_exact, write_pccf

normalize = vec -> vec / sum(vec)

function weights_matrix(T)
  n = T
  M = zeros(n,n)
  M[1,:] = 1:n
  for i = 2:n
	  for j = i:n
		  M[i,j] = M[i-1, j-1]
	  end
  end
  M'
end

function gaussPdf(x, mu, sigma)
    k = 1/(sigma * sqrt(2*pi))
    p = k * exp(-((x-mu)^2/(2*sigma^2)))
end

function pccf_exact(T, mu, sigma)
    # Analytic solution
    t = 1:T
    chp_probs = zeros(T)
    for dist_i in 1:T
        dist = Normal(dist_i * mu, sqrt(dist_i*sigma^2))
        chp_probs += pdf(dist, t)
    end
    # normalize(chp_probs)
    chp_probs
end

function pccf(T, mu, sigma)
	gaussDist = Normal(mu, sigma)
    P         = zeros(T, T)
    P[:,1]    = pdf(gaussDist, 1:T)
    W         = pdf(gaussDist, weights_matrix(T))
	for i = 1:T-1
		P[i+1:T, i+1] = W[1:T-i, 1:T-i] * P[i:end-1, i]
	end
	normalize( sum(P,2) ) # change probabilities
end

function write_pccf(filepath, T = 100, mu = 25.0, sigma = 3.2)
	# r = pccf(T, mu, sigma)
	r = pccf_exact(T, mu, sigma)
	f = open(filepath, "w")
	writedlm(f, r)
	close(f)
	println("... PCCF function is written into $filepath")
end
end

max_stars_repo_name: av-maslov/Recurrency

max_issues_repo_name: av-maslov/Recurrency

max_forks_repo_name: av-maslov/Recurrency


text:
using ArgParse

function parse_commandline()
	s = ArgParseSettings()
	@add_arg_table s begin
		"--dest_range"
			help = "Distance between the initial position and the destination of the ego agent"
			arg_type = Float64
			default = 10000.0 # [m]
		"--sensing_range"
			help = "Radius of the alerting perimeter"
			arg_type = Float64
			default = 1000.0 # [m]

		"--penalty_action" # max =  - 100 * pen
			help = "Reward function parameter: penalty on action"
			arg_type = Float64
			default = 2.0
		"--penalty_conflict" # max =  - pen
			help = "Reward function parameter: penalty on conflict"
			arg_type = Float64
			default = 50.0
		"--penalty_closeness" # max = - pen (on NMAC) or - pen * 2.71 (on collision)
			help = "Reward function parameter: penalty on closeness between agents"
			arg_type = Float64
			default = 500.0
		"--penalty_nmac" # max = - pen
			help = "Reward function parameter: penalty on near mid-air collisions"
			arg_type = Float64
			default = 7000.0

		"--penalty_deviation" # max = - 180 * pen
			help = "Reward function parameter: penalty on direction deviation from destination"
			arg_type = Float64
			default = 0.8
		"--penalty_digression" # max =
			help = "Reward function parameter: penalty on digression from destination"
			arg_type = Float64
			default = 50.0
		"--reward_destination" # max = rew
			help = "Reward function parameter: reward on reaching destination"
			arg_type = Float64
			default = 0.0
	end
	return parse_args(s)
end

parsed_args = parse_commandline()

const SPAWN_RATE_SET = [25, 35, 45]
const CONST_NUM_AC_SET = [1]
# SPAWN_RATE = rand(SPAWN_RATE_SET)
const BEARING_DIST =   [[0.1047 0.0489];
   						[0.3142 0.0474];
   						[0.5236 0.0474];
   						[0.7330 0.0459];
   						[0.9425 0.0425];
   						[1.1519 0.0403];
   						[1.3614 0.0365];
   						[1.5708 0.0333];
   						[1.7802 0.0304];
   						[1.9897 0.0269];
   						[2.1991 0.0237];
   						[2.4086 0.0210];
   						[2.6180 0.0194];
   						[2.8274 0.0183];
   						[3.0369 0.0181];
   						[3.2463 0.0181];
   						[3.4558 0.0183];
   						[3.6652 0.0194];
   						[3.8746 0.0210];
   						[4.0841 0.0237];
   						[4.2935 0.0269];
   						[4.5029 0.0304];
   						[4.7124 0.0333];
   						[4.9218 0.0365];
   						[5.1313 0.0403];
   						[5.3407 0.0425];
   						[5.5501 0.0459];
   						[5.7596 0.0474];
   						[5.9690 0.0474];
   						[6.1785 0.0489];]

const DT = 1.0 # [s]
const V_MIN = 50.0 # [m/s]
const V_MAX = 50.0 # [m/s], currently using single value for speed
const AIRSPACE_DIM = 1500  # [m]
const STATE_DIM = 5
const AUG_STATE_DIM = 3

const DEST_CRITERION = 120.0 # [m]
const NMAC_RANGE = 150.0 # [m]
const NUM_SECTIONS = 4
const RELAX_FACTOR = 1.2 # for train
# const RELAX_FACTOR = 1.0 # for resTime evaluation

const TERM_VAR = terminal_state_var # imported from CAS_QMDP

# state ind
# s = [ρ, θ, ϕ, v_own, v_int]
const IND_rho   = 1
const IND_theta = 2
const IND_phi   = 3
const IND_v_own = 4
const IND_v_int = 5
const IND_deviation = STATE_DIM * NUM_SECTIONS + 1
const IND_dist_to_dest = STATE_DIM * NUM_SECTIONS + 2
const IND_prev_dist_to_dest = STATE_DIM * NUM_SECTIONS + 3

const SENSING_RANGE = parsed_args["sensing_range"]
const DEST_RANGE = parsed_args["dest_range"]

# Reward weights for the correction network
const PEN_ACTION = parsed_args["penalty_action"]
const PEN_CLOSENESS = parsed_args["penalty_closeness"]
const PEN_NMAC = parsed_args["penalty_nmac"]
const PEN_CONFLICT = parsed_args["penalty_conflict"]
const PEN_DEVIATION = parsed_args["penalty_deviation"]
const PEN_DIGRESSION = parsed_args["penalty_digression"]
const REW_DESTINATION = parsed_args["reward_destination"]

# Leaving out the huge positive reward from reaching destination:
const POSSIBLE_MAX_REW = V_MAX * DT * PEN_DIGRESSION
# Keeping the huge positive reward from reaching destination:
# const POSSIBLE_MAX_REW = REW_DESTINATION + V_MAX * DT * PEN_DIGRESSION

# Leaving out the huge negative reward from NMAC:
# const POSSIBLE_MIN_REW = - PEN_CONFLICT - PEN_ACTION * 10^2 - PEN_CLOSENESS * e - 180 * PEN_DEVIATION - V_MAX * DT * PEN_DIGRESSION
# Keeping the huge negative reward from NMAC:
const POSSIBLE_MIN_REW = - PEN_CONFLICT - PEN_ACTION * 10^2 - PEN_NMAC - PEN_CLOSENESS * e - 180 * PEN_DEVIATION - V_MAX * DT * PEN_DIGRESSION

const LOW_FI_POLICY = "mid3_maxdist_2km_nmac_150m_Discount_0.95_ActWeight_0.5_IfSample_false_PenAction_3.0_PenConflict_50.0_PenCloseness_500.0_PenNmac_7000.0_Sigma_v_5.0_alert_5.0_theta_3.0_phi_7.0_coc_3.0"
const LOW_FI_POLICY_FILENAME =
	"../../VICAS/policies/" * LOW_FI_POLICY * ".jld"

# Step reward bounds from VICAS
# These values need to match those used to train VICAS
# Read them from LOW_FI_POLICY
const penalty_action_VICAS = 3.0
const penalty_conflict_VICAS = 50.0
const penalty_closeness_VICAS = 500.0
const penalty_nmac_VICAS = 7000.0

const POSSIBLE_MAX_REW_VICAS = 0.0
const POSSIBLE_MIN_REW_VICAS = - penalty_conflict_VICAS - penalty_action_VICAS * 10.^2 - penalty_nmac_VICAS - penalty_closeness_VICAS * e

max_stars_repo_name: parachutel/DeepCorrectionCAS


text:
#    Copyright (c) 2021 J.A. Duffek
#    Copyright (c) 2000 D.M. Spink
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, see <http://www.gnu.org/licenses/>.

"""
    nrbreverse(nurbs::NURBS{I,F}
            )::NURBS{I,F} where {I<:Integer,F<:AbstractFloat}

Utility function to reverse the evaluation direction of a NURBS curve or
surface.

# Arguments:
- `nurbs`: NURBS data structure (see nrbmak for details).

# Output:
- `rnurbs`: The transformed NURBS data structure.

# Examples:
```julia
julia> rnurbs = nrbreverse(nurbs)
```
"""
function nrbreverse(nurbs::NURBS{I,F}
                   )::NURBS{I,F} where {I<:Integer,F<:AbstractFloat}
if typeof(nurbs)<:NURBS2D
  # reverse a NURBS surface
  return nrbmak(reverse(nurbs.coefs,dims=(2,3)),
                [(1.0 .-reverse(nurbs.knots[1])),
                 (1.0 .-reverse(nurbs.knots[2]))]);
else
  # reverse a NURBS curve
  return nrbmak(reverse(nurbs.coefs,dims=2),1.0 .- reverse(nurbs.knots));
end # if
end # nrbreverse


text:
module TestExp
using GaussianProcesses, Distributions
using Test, Random
Random.seed!(123)

@testset "VI" begin
    n = 20
    X = collect(range(-3,stop=3,length=n));
    f = 2*cos.(2*X);
    Y = [rand(Poisson(exp.(f[i]))) for i in 1:n];

    k = Matern(3/2,0.0,0.0)   # Matern 3/2 kernel
    l = PoisLik()             # Poisson likelihood
    gp = GP(X, vec(Y), MeanZero(), k, l)
    set_priors!(gp.kernel,[Normal(-2.0,4.0),Normal(-2.0,4.0)])

    @testset "Basic" begin
        V = cov(gp.kernel, gp.x, gp.data)
        m = mean(gp.mean, gp.x)
        print(variational_expectation(l, Y, m, V))
    end
end
end


text:
roundc(r) = round.(real(r)) + im*round.(imag(r));
#round{Td}(r::Td) = Td<:Complex?round(real(r)) + im*round(imag(r)):round(r);

#################################################################
function scodes(M,Ctype)
#C = scodes(M,Ctype)
#  Return a constellation of M signals, where <Ctype> is 'PSK', 'QAM',
#  or 'PAM'.
#[C,d] = scodes(M,Ctype)
#  Also return the minimum distance between constellation points.
#[C,d,Cr] = scodes(M,Ctype)
#  Returns the underlying real PAM constellation for square (M=m^2)
#  QAM constellations

# By Christian Peel  (chris.peel@ieee.org)
# Last Modified: Sun 14 Apr 19, 6:53pm
#

#if nargin==0
#  error("Bad arguments. Try again.")
#end
if Ctype=="PSK"
    C=exp(im*2*pi*[1:M]'/M);
elseif Ctype=="QAM"
    if abs(sqrt(M)-round(sqrt(M)))< 1e-3
        # Make QAM constellations if M is a square
        m = round(Integer,sqrt(M))
        C = complex(zeros(m,m))
        Cr = complex([-(m-1):2:(m-1);])
        for ix = 1:m
            for jx = 1:m
                C[jx,ix] = Cr[ix] +im*Cr[jx];
            end
        end
    else
        error("Can only handle square QAM constellations.")
        #     [x y] = qaskenco(M);
        #     C = x+im*y;
    end
elseif Ctype=="PAM"
    C = [-(M-1):2:(M-1);];
    Cr = C;
else
  error("Bad args.");
end

C = C[:]; # Turn into column vector
# for QAM, gam = sqrt(2/3*(M-1))
gam = sqrt(C'*C/length(C));

C = C/gam;
#if nargout ==3
  Cr = Cr/gam;
#end

d2 = real(C[2:end] .- C[1]);
id = findall(abs.(d2).>0);
d = minimum(abs.(d2[id]));
return (C, d, Cr, gam)
end

#######################################################################
function mimo_slice(Y,H,C)
M = size(Y,1);
Td = size(Y,2);
Zd = zeros(M,Td);
Mc = length(C);
dy = zeros(M,Mc);
for t=1:Td
    for i = 1:Mc
        dd = Y[:,t]-H[:,t]*C[i];
        dy[:,i] = abs.(dd).^2
    end
    for m = 1:M
        mn,zd = findmin(dy[m,:]);
        Zd[m,t] = zd[1]-1.0;
    end
end
return Zd
end

#################################################################
function siso_demod(y,C)
Mc = length(C);
dy = zeros(Mc,1);
for ix = 1:Mc
    dy[ix] = abs(y[1]-C[ix])
end
m,zd = findmin(dy);
sd = C[zd];
return sd[1]
end

max_stars_repo_name: christianpeel/MUMIMO

max_issues_repo_name: christianpeel/MUMIMO

max_forks_repo_name: christianpeel/MUMIMO


text:
module ProjectIO

using CSV, DataFrames

function read_spectrum(datafile, col_names=["X", "Y"])
    #TODO: Get meta-data from the spectrum file.
    datarows = 0

    metadata = CSV.File(datafile, limit=18)
    for row in metadata
        if row.TITLE == "XUNITS"
            if row.Column2 == "1/CM"
                col_names[1] = "Wavenumber"
            end
        end

        if row.TITLE == "YUNITS"
            col_names[2] = titlecase(row.Column2)
        end

        if row.TITLE == "NPOINTS"
            datarows = parse(Int, row.Column2)
        end
    end

    if datarows > 0
        df = DataFrame(CSV.File(datafile, skipto=20, limit=datarows))
    else
        df = DataFrame(CSV.File(datafile, skipto=20, footerskip=17))
    end

    rename!(df, col_names)
    return df
end

function read_angle_data_from_dir(directory, format=".csv")

    angle_data = []

    for (root, dirs, files) in walkdir(directory)
        for spectrum_file in files
            if endswith(spectrum_file, format)
                str_start = findfirst("deg", spectrum_file)[end] + 1
                str_end = findlast(format, spectrum_file)[1] - 1

                if tryparse(Int, spectrum_file[str_start:str_end]) === nothing
                    angle = parse(Int, spectrum_file[1:str_start-4])
                else
                    angle = parse(Int, spectrum_file[str_start:str_end])
                end
                dataframe = read_spectrum(joinpath(root, spectrum_file))
                push!(angle_data, [angle, dataframe])
            end

        end
    end
    return sort(angle_data)
end

end # module

max_stars_repo_name: garrekstemo/projectIO

max_issues_repo_name: garrekstemo/projectIO

max_forks_repo_name: garrekstemo/projectIO


text:
using RadiativeTransfer
using RadiativeTransfer.Architectures
using RadiativeTransfer.Absorption
using RadiativeTransfer.Scattering
using RadiativeTransfer.vSmartMOM
using RadiativeTransfer.SolarModel
using Test
using DelimitedFiles
using Statistics
using ProgressMeter
using WignerSymbols
using Distributions
using JLD2

# Test the Absorption module
@testset "RadiativeTransfer.Absorption" begin include("test_Absorption.jl") end

# Test the Scattering module
@testset "RadiativeTransfer.Scattering" begin include("test_Scattering.jl") end

# Test the vSmartMOM module
@testset "RadiativeTransfer.vSmartMOM" begin include("test_vSmartMOM.jl") end

# Test the SolarModel module
@testset "RadiativeTransfer.SolarModel" begin include("test_SolarModel.jl") end


text:
# This is a Julia script for plotting
# the time evolution of MEGNOs

# Define the floating point type used across the script
F = Float64

# Define the integer type used across the script
I = UInt64

# Define default values for optional arguments
POSTFIX = ""
H = 0.01

# Define fixed parameters
I_M = round(UInt, 1 / H)

"Check if the value of the option is the last argument"
function check_last(i)
    if i + 1 == length(ARGS)
        println("The last argument should be the input directory.")
        exit(1)
    end
end

# Parse the options
for i in eachindex(ARGS)
    # Time step
    if ARGS[i] == "-h"
        check_last(i)
        try
            global H = parse(F, ARGS[i+1])
        catch
            println("Couldn't parse the value of the `-h` argument.")
            exit(1)
        end
    end
    # A postfix for the names of output files
    if ARGS[i] == "--postfix"
        check_last(i)
        try
            global POSTFIX = " ($(ARGS[i+1]))"
        catch
            println("Couldn't parse the value of the `--postfix` argument.")
            exit(1)
        end
    end
end

# Check for required arguments
if length(ARGS) == 0
    println("""
        Usage:
        julia --project=. scripts/megnos.jl [-h <H>] [--postfix <POSTFIX>] <INPUT> """
    )
    exit(1)
end

# Multiply the time step
H *= π / 2

# Define the input directory
INPUT_DIR = ARGS[end]

println('\n', " "^4, "> Loading the packages...")

using LaTeXStrings
using Plots

# Use the GR backend for plots
gr()

# Change some of the default parameters for plots
default(fontfamily = "Computer Modern", dpi = 300, legend = :topright)

# Define the paths to output directories
CURRENT_DIR = @__DIR__
ROOT_DIR = basename(CURRENT_DIR) == "scripts" ? dirname(CURRENT_DIR) : CURRENT_DIR
PLOTS_DIR = joinpath(ROOT_DIR, "plots")
OUTPUT_DIR = joinpath(PLOTS_DIR, "megnos")

# Make sure the needed directories exist
mkpath(OUTPUT_DIR)

# Define the path to the binary file
megno_path = joinpath(INPUT_DIR, "megno.bin")
mean_megno_path = joinpath(INPUT_DIR, "mean_megno.bin")

"Read binary files in the `bincode` format"
function read_bincode(path::AbstractString)::Tuple{I, Vector{F}}
    open(path, "r") do io
        n = read(io, I)
        a = reinterpret(F, read(io, sizeof(F) * n))
        n, a
    end
end

# Plot the Poincaré map if the corresponding data files exist
if isfile(megno_path) && isfile(mean_megno_path)
    # Read the data
    n_megno, megno = read_bincode(megno_path)
    n_mean_megno, mean_megno = read_bincode(mean_megno_path)

    # Check if the lengths match
    if n_megno != n_mean_megno
        println(" "^4, "> [!] Lengths of the files for MEGNOs and mean MEGNOs don't match")
        return
    end

    # Compute the time scale
    n = n_megno
    time = [ (i + I_M) * H / (2 * π) for i in 0:(n-1) ]

    println(" "^4, "> Plotting the time evolution of MEGNOs...")

    # Plot the time evolution of MEGNOs
    p = plot(
        time,
        megno;
        label = "",
        title = "Time evolution of MEGNOs",
        xlabel = L"t \; \textrm{[2 \pi]}",
        ylabel = L"Y",
        titlefontsize = 12,
        size = (400, 400),
    )

    # Save the figure as PDF and PNG
    savefig(p, joinpath(OUTPUT_DIR, "MEGNOs$(POSTFIX).pdf"))
    savefig(p, joinpath(OUTPUT_DIR, "MEGNOs$(POSTFIX).png"))

    println(" "^4, "> Plotting the time evolution of mean MEGNOs...")

    # Plot the time evolution of mean MEGNOs
    p = plot(
        time,
        mean_megno;
        label = "",
        title = "Time evolution of mean MEGNOs",
        xlabel = L"t \; \textrm{[2 \pi]}",
        ylabel = L"\overline{Y}",
        titlefontsize = 12,
        size = (400, 400),
    )

    # Save the figure as PDF and PNG
    savefig(p, joinpath(OUTPUT_DIR, "Mean MEGNOs$(POSTFIX).pdf"))
    savefig(p, joinpath(OUTPUT_DIR, "Mean MEGNOs$(POSTFIX).png"))
end

println()


text:
"""
Struct for a Libxc functional and some basic information
"""
mutable struct Functional
    identifier::Symbol
    n_spin::Int
    name::String
    kind::Symbol
    family::Symbol
    flags::Vector{Symbol}
    derivatives::Vector{Int}  # Derivatives supported by the functional
    references::Vector  # Related article references as list of named tuples

    # Spin dimensions libxc expects for various quantities
    # Note: Only the symbols actually meaningful for this functional
    # contain valid information
    spin_dimensions

    # Pointer holding the Libxc representation of this functional
    pointer_::Ptr{xc_func_type}
end

"""
    Functional(identifier::Symbol; n_spin::Integer = 1)

Construct a Functional from a libxc `identifier` and the number
of spins `n_spin` to consider. `
"""
function Functional(identifier::Symbol; n_spin::Integer = 1)
    n_spin in (1, 2) || error("n_spin needs to be 1 or 2")

    number = xc_functional_get_number(string(identifier))
    number == -1 && error("Functional $identifier is not known.")

    function pointer_cleanup(ptr::Ptr{xc_func_type})
        if ptr != C_NULL
            xc_func_end(ptr)
            xc_func_free(ptr)
        end
    end

    pointer = xc_func_alloc()
    ret = xc_func_init(pointer, number, n_spin)
    ret != 0 && error("Something went wrong initialising the functional")

    try
        funcinfo = xc_func_get_info(pointer)
        kind     = KINDMAP[xc_func_info_get_kind(funcinfo)]
        family   = FAMILIYMAP[xc_func_info_get_family(funcinfo)]
        flags    = extract_flags(xc_func_info_get_flags(funcinfo))
        name     = unsafe_string(xc_func_info_get_name(funcinfo))
        references = extract_references(funcinfo)
        dimensions = unsafe_load(pointer).dim

        # Flags for having 0th to 4th derivative
        derivative_flags = (:exc, :vxc, :fxc, :kxc, :lxc)
        derivatives = [i-1 for (i, flag) in enumerate(derivative_flags) if flag in flags]

        # Make functional and attach finalizer for cleaning up the pointer
        func = Functional(identifier, n_spin, name, kind, family, flags, derivatives,
                          references, dimensions, pointer)
        finalizer(cls -> pointer_cleanup(cls.pointer_), func)
        return func
    catch
        pointer_cleanup(pointer)
        rethrow()
    end
end

"""
Return the list of derivatives supported by the functional
with `0` denoting the energy, `1` the potential, `2` the kernel and so on.
"""
supported_derivatives(func::Functional) = func.derivatives

"""Is the functional an LDA or hybrid LDA functional"""
is_lda(func::Functional)    = func.family in (:lda, :hyb_lda)

"""Is the functional a GGA or hybrid GGA functional"""
is_gga(func::Functional)    = func.family in (:gga, :hyb_gga)

"""Is the functional a meta-GGA or hybrid meta-GGA functional"""
is_mgga(func::Functional)   = func.family in (:mgga, :hyb_mgga)

"""Is the functional a hybrid functional (global or range-separated)"""
is_hybrid(func::Functional) = func.family in (:hyb_gga, :hyb_lda, :hyb_mgga)

"""Is the functional a VV10-type non-local density functional"""
is_vv10(func::Functional)   = :vv10 in func.flags

"""Is the functional a range-separated hybrid functional"""
function is_range_separated(func::Functional)
    is_hybrid(func) || return false
    any(flag in (:hyb_cam, :hyb_camy, :hyb_lc, :hyb_lcy) for flag in func.flags)
end

"""Is the functional a global hybrid functional"""
is_global_hybrid(func::Functional) = is_hybrid(func) && !is_range_separated(func)

"""Does the function need the laplacian of the density"""
needs_laplacian(func::Functional) = :needs_laplacian in func.flags

# Supported properties:
#     - density_threshold  Density threshold below which functional will not be evaluated
#     - zeta_threshold     Spin polarization threshold below which spin components
#                          will not be evaluated
#     - sigma_threshold    Enforced lower bound for σ = √γ, smaller values get overwritten
#     - tau_threshold      Enforced lower bound for τ, smaller values get overwritten
#     - exx_coefficient    Exact exchange for global hybrid functionals
#     - cam_omega          Range separation constant for range-separated hybrids
#     - cam_alpha          Long-range exact exchange for range-separated hybrids
#     - cam_beta           Additional exchange for short-range for range-separated hybrids
#                          (i.e. short-range exact exchange is cam_alpha + cam_beta)
#     - nlc_b              Parameter for the VV10-type functionals
#     - nlc_C              Parameter for the VV10-type functionals

import Base.getproperty, Base.setproperty!, Base.propertynames
function Base.propertynames(func::Functional, private::Bool=false)
    ret = [:density_threshold, :zeta_threshold, :sigma_threshold, :tau_threshold,
           :exx_coefficient, :cam_alpha, :cam_beta, :cam_omega, :nlc_b, :nlc_C]
    append!(ret, fieldnames(Functional))
end

function Base.getproperty(func::Functional, s::Symbol)
    if s == :density_threshold
        return Float64(unsafe_load(func.pointer_).dens_threshold)
    elseif s in (:zeta_threshold, :sigma_threshold, :tau_threshold)
        return Float64(getproperty(unsafe_load(func.pointer_), s))
    elseif s == :exx_coefficient
        return is_global_hybrid(func) ? Float64(xc_hyb_exx_coef(func.pointer_)) : nothing
    elseif s in (:cam_alpha, :cam_beta, :cam_omega)
        is_range_separated(func) || return nothing
        data = (cam_omega = Ref(0.0), cam_alpha = Ref(0.0), cam_beta  = Ref(0.0))
        xc_hyb_cam_coef(func.pointer_, data.cam_omega, data.cam_alpha, data.cam_beta)
        return getproperty(data, s)[]
    elseif s in (:nlc_b, :nlc_C)
        is_vv10(func) || return nothing
        data = (nlc_b=Ref(0.0), nlc_C=Ref(0.0))
        xc_nlc_coef(func.pointer_, data.nlc_b, data.nlc_C)
        return getproperty(data, s)[]
    else
        getfield(func, s)
    end
end

function Base.setproperty!(func::Functional, s::Symbol, v)
    setmap = Dict(
        :density_threshold => xc_func_set_dens_threshold,
        :zeta_threshold    => xc_func_set_zeta_threshold,
        :sigma_threshold   => xc_func_set_sigma_threshold,
        :tau_threshold     => xc_func_set_tau_threshold,
    )
    if s in keys(setmap)
        v < 0 && error("Threshold values cannot be negative.")
        setmap[s](func.pointer_, Cdouble(v))
    else
        error("Setting property $s is not allowed or implemented.")
    end
end

# Ideas:
#    https://github.com/psi4/psi4/blob/master/psi4/src/psi4/libfunctional/LibXCfunctional.cc
#    https://github.com/psi4/psi4/blob/master/psi4/src/psi4/libfunctional/LibXCfunctional.h
function external_parameter_defaults(func)
    params = Dict()
    n_extparams = xc_func_info_get_n_ext_params(func.pointer_)
    for i in 1:n_extparams
        name = xc_func_info_get_ext_params_name(func.pointer_, i - 1)
        params[unsafe_string(name)] = xc_func_info_get_ext_params_default_value(func.pointer_, i - 1)
    end
    params
end

# Provide maps which translate between the conventions
# used in Libxc.jl and libxc

const KINDMAP = Dict(
    XC_EXCHANGE             => :exchange,
    XC_CORRELATION          => :correlation,
    XC_EXCHANGE_CORRELATION => :exchange_correlation,
    XC_KINETIC              => :kinetic,
)

const FAMILIYMAP = Dict(
    XC_FAMILY_UNKNOWN   => :unknown,
    XC_FAMILY_LDA       => :lda,
    XC_FAMILY_GGA       => :gga,
    XC_FAMILY_MGGA      => :mgga,
    XC_FAMILY_LCA       => :lca,
    XC_FAMILY_OEP       => :oep,
    XC_FAMILY_HYB_GGA   => :hyb_gga,
    XC_FAMILY_HYB_MGGA  => :hyb_mgga,
    XC_FAMILY_HYB_LDA   => :hyb_lda,
)

const FLAGMAP = Dict(
    XC_FLAGS_HAVE_EXC        => :exc,
    XC_FLAGS_HAVE_VXC        => :vxc,
    XC_FLAGS_HAVE_FXC        => :fxc,
    XC_FLAGS_HAVE_KXC        => :kxc,
    XC_FLAGS_HAVE_LXC        => :lxc,
    XC_FLAGS_1D              => :dim1,
    XC_FLAGS_2D              => :dim2,
    XC_FLAGS_3D              => :dim3,
    XC_FLAGS_HYB_CAM         => :hyb_cam,
    XC_FLAGS_HYB_CAMY        => :hym_camy,
    XC_FLAGS_VV10            => :vv10,
    XC_FLAGS_HYB_LC          => :hyb_lc,
    XC_FLAGS_HYB_LCY         => :hyb_lcy,
    XC_FLAGS_STABLE          => :stable,
    XC_FLAGS_DEVELOPMENT     => :development,
    XC_FLAGS_NEEDS_LAPLACIAN => :needs_laplacian,
)

function extract_flags(flags)
    ret = Symbol[]
    for (flag, sym) in pairs(FLAGMAP)
        flag & flags > 0 && push!(ret, sym)
    end
    ret
end

function extract_references(info::Ptr{xc_func_info_type})
    # Range of set references
    refrange = filter(iref -> xc_func_info_get_references(info, iref) != C_NULL,
                      0:XC_MAX_REFERENCES - 1)

    map(refrange) do iref
        ref_ptr = xc_func_info_get_references(info, iref)
        (reference=unsafe_string(xc_func_reference_get_ref(ref_ptr)),
         doi=unsafe_string(xc_func_reference_get_doi(ref_ptr)),
         bibtex=unsafe_string(xc_func_reference_get_bibtex(ref_ptr)))
    end
end


text:
import Base: LineEdit, REPL, REPLCompletions

function return_callback(s)
    status = render(Compat.String(LineEdit.buffer(s)))[3]
    status == 1 || status >= 3
end

function generate_inline_julia_code(symdict::OrderedDict)
    blk_ld = Expr(:block)
    for (rsym, expr) in symdict
        push!(blk_ld.args,:(env[$rsym] = $(expr)))
    end
    quote
        let env = RCall.reval_p(RCall.rparse_p("`#JL` <- new.env()"))
            $blk_ld
            nothing
        end
    end
end

function repl_eval(script::Compat.String, stdout::IO, stderr::IO)
    local status
    local val
    script, symdict, status, msg = render(script)
    if status != 1
        write(stderr, "Error: $msg\n")
        return nothing
    end
    try
        if length(symdict) > 0
            eval(Main, generate_inline_julia_code(symdict))
        end
        expr = protect(sexp(parseVector(sexp(script))[1]))
        for e in expr
            val, status = tryEval(e, sexp(Const.GlobalEnv))
            flush_print_buffer(stdout)
            # print warning and error messages
            if status != 0 || nb_available(errorBuffer) != 0
                write(stderr, takebuf_string(errorBuffer))
            end
            status != 0 && return nothing
        end
    catch e
        display_error(stderr, e)
        return nothing
    finally
        unprotect(1)
    end
    # print if the last expression is visible
    if status == 0 && unsafe_load(cglobal((:R_Visible, libR),Int)) == 1
         rprint(stdout, sexp(val))
    end
    return nothing
end

function bracketed_paste_callback(s, o...)
    input = LineEdit.bracketed_paste(s)
    sbuffer = LineEdit.buffer(s)
    curspos = position(sbuffer)
    seek(sbuffer, 0)
    shouldeval = (nb_available(sbuffer) == curspos && search(sbuffer, UInt8('\n')) == 0)
    seek(sbuffer, curspos)
    if curspos == 0
        # if pasting at the beginning, strip leading whitespace
        input = lstrip(input)
    end

    if !shouldeval
        LineEdit.edit_insert(s, input)
        return
    end

    LineEdit.edit_insert(sbuffer, input)
    input = takebuf_string(sbuffer)

    oldpos = start(input)
    nextpos = 0
    # parse the input line by line
    while !done(input, oldpos)
        nextpos = search(input, '\n', nextpos+1)
        if nextpos == 0
            nextpos = endof(input)
        end
        block = input[oldpos:nextpos]
        status = render(block)[3]

        if status >= 3  || (status == 2 && done(input, nextpos+1)) ||
                (done(input, nextpos+1) && !endswith(input, '\n'))
            # error / continue but no the end / at the end but no new line
            LineEdit.replace_line(s, input[oldpos:end])
            LineEdit.refresh_line(s)
            break
        elseif status == 2 && !done(input, nextpos+1)
            continue
        end

        if !isempty(strip(block))
            # put the line on the screen and history
            LineEdit.replace_line(s, strip(block))
            LineEdit.commit_line(s)
            # execute the statement
            terminal = LineEdit.terminal(s)
            REPL.raw!(terminal, false) && LineEdit.disable_bracketed_paste(terminal)
            LineEdit.mode(s).on_done(s, LineEdit.buffer(s), true)
            REPL.raw!(terminal, true) && LineEdit.enable_bracketed_paste(terminal)
        end
        oldpos = nextpos + 1
    end
    LineEdit.refresh_line(s)
end

function respond(repl, main)
    (s, buf, ok) -> begin
        if !ok
            return REPL.transition(s, :abort)
        end
        script = takebuf_string(buf)
        if !isempty(strip(script))
            REPL.reset(repl)
            repl_eval(script, repl.t.out_stream, repl.t.err_stream)
        end
        REPL.prepare_next(repl)
        REPL.reset_state(s)
        s.current_mode.sticky || REPL.transition(s, main)
    end
end

type RCompletionProvider <: LineEdit.CompletionProvider
    r::REPL.LineEditREPL
end

function LineEdit.complete_line(c::RCompletionProvider, s)
    buf = s.input_buffer
    partial = Compat.String(buf.data[1:buf.ptr-1])
    # complete latex
    full = LineEdit.input_string(s)
    ret, range, should_complete = REPLCompletions.bslash_completions(full, endof(partial))[2]
    if length(ret) > 0 && should_complete
        return ret, partial[range], true
    end

    # complete r
    rcall(rlang(Symbol(":::"), :utils, Symbol(".assignLinebuffer")), partial)
    rcall(rlang(Symbol(":::"), :utils, Symbol(".assignEnd")), length(partial))
    token = rcopy(rcall(rlang(Symbol(":::"), :utils, Symbol(".guessTokenFromLine"))))
    rcall(rlang(Symbol(":::"), :utils, Symbol(".completeToken")))
    ret = rcopy(Array, rcall(rlang(Symbol(":::"), :utils, Symbol(".retrieveCompletions"))))
    if length(ret) > 0
        return ret, token, true
    end

    return Compat.String[], 0:-1, false
end

function create_r_repl(repl, main)
    r_mode = LineEdit.Prompt("R> ";
        prompt_prefix=Base.text_colors[:blue],
        prompt_suffix=main.prompt_suffix,
        on_enter=return_callback,
        on_done= respond(repl, main),
        sticky=true)

    hp = main.hist
    hp.mode_mapping[:r] = r_mode
    r_mode.hist = hp
    r_mode.complete = RCompletionProvider(repl)
    const bracketed_paste_mode_keymap = Dict{Any,Any}(
        "\e[200~" => bracketed_paste_callback
    )

    search_prompt, skeymap = LineEdit.setup_search_keymap(hp)
    prefix_prompt, prefix_keymap = LineEdit.setup_prefix_keymap(hp, r_mode)

    mk = REPL.mode_keymap(main)
    # ^C should not exit prompt
    delete!(mk, "^C")

    b = Dict{Any,Any}[
        bracketed_paste_mode_keymap,
        skeymap, mk, prefix_keymap, LineEdit.history_keymap,
        LineEdit.default_keymap, LineEdit.escape_defaults
    ]
    r_mode.keymap_dict = LineEdit.keymap(b)

    r_mode
end

function repl_init(repl)
    mirepl = isdefined(repl,:mi) ? repl.mi : repl
    main_mode = mirepl.interface.modes[1]
    r_mode = create_r_repl(mirepl, main_mode)
    push!(mirepl.interface.modes,r_mode)

    const r_prompt_keymap = Dict{Any,Any}(
        '$' => function (s,args...)
            if isempty(s) || position(LineEdit.buffer(s)) == 0
                buf = copy(LineEdit.buffer(s))
                LineEdit.transition(s, r_mode) do
                    LineEdit.state(s, r_mode).input_buffer = buf
                end
            else
                LineEdit.edit_insert(s, '$')
            end
        end
    )

    main_mode.keymap_dict = LineEdit.keymap_merge(main_mode.keymap_dict, r_prompt_keymap);
    nothing
end