text:
__all__ = ["IMDb", "IMDbError", "Movie", "Person", "Character", "Company", "available_access_systems"]

# URLs of the main pages for movies, persons, characters and queries.
imdbURL_base = 'https://www.imdb.com/'

# NOTE: the urls below will be removed in a future version.
#       please use the values in the 'urls' attribute
#       of the IMDbBase subclass instance.
# http://www.imdb.com/title/
imdbURL_movie_base = "$(imdbURL_base)title/"
# http://www.imdb.com/title/tt%s/
imdbURL_movie_main = imdbURL_movie_base * "tt%s/"
# http://www.imdb.com/name/
imdbURL_person_base = "$(imdbURL_base)name/"
# http://www.imdb.com/name/nm%s/
imdbURL_person_main = imdbURL_person_base * "nm%s/"
# http://www.imdb.com/character/
imdbURL_character_base = "$(imdbURL_base)character/"
# http://www.imdb.com/character/ch%s/
imdbURL_character_main = imdbURL_character_base * "ch%s/"
# http://www.imdb.com/company/
imdbURL_company_base = "$(imdbURL_base)company/"
# http://www.imdb.com/company/co%s/
imdbURL_company_main = imdbURL_company_base * "co%s/"
# http://www.imdb.com/keyword/%s/
imdbURL_keyword_main = imdbURL_base * "search/keyword/?keywords=%s"
# http://www.imdb.com/chart/top
imdbURL_top250 = imdbURL_base * "chart/top"
# http://www.imdb.com/chart/bottom
imdbURL_bottom100 = imdbURL_base * "chart/bottom"
# http://www.imdb.com/find?%s
imdbURL_find = imdbURL_base * "find?%s"
# http://www.imdb.com/list/
imdbURL_list_base = imdbURL_base * "list/"

 """
 A case-sensitive parser for configuration files.
 """
struct ConfigParserWithCase
    defaults
    conf_file

    # constructor function
    """
    Initialize the parser.
        *defaults* -- defaults values.
        *confFile* -- the file (or list of files) to parse.
    """
    function ConfigParserWithCase(defaults=nothing, conf_file=nothing, args...; kwds...)
        # super(configparser.ConfigParser, self).__init__(defaults=defaults)

        if isnothing(conf_file)
            dot_file_name = "." * conf_file_name
            # Current and home directory
            conf_file = [
                joinpath(pwd(), conf_file_name),
                joinpath(pwd(), dot_file_name),
                joinpath(homedir(), conf_file_name),
                joinpath(homedir(), dot_file_name)
            ]

            if Sys.iswindows()
            else
            end
        end
    end
end

"""
Return an instance of the appropriate class.
The accessSystem parameter is used to specify the kind of the preferred access system.
"""
function IMDb(access_system=nothing, arguments...; keywords...)
    if isnothing(access_system) || access_system ∈ ["auto", "config"]
        try
            cfg_file =
        catch
        end
    end
end


text:
#===============================================================================

    ClusterAnalysisResult.jl

    clustering analysis result
    from a possible combination of expected genotypes

    Author: Tom Price
    Date:   July 2019

===============================================================================#

import Clustering.ClusteringResult

struct ClusterAnalysisResult
    init_centers        ::Array{Float_T,2} ## no longer necessary because it represents one combination of genotypes, but different combinations of genotypes with the same number of genotypes may result in the same clustering results
    dist_mtx_winit      ::Array{Float_T,2}
    cluster_result      ::ClusteringResult
    centers             ::Array{Float_T,2}
    slhts               ::Vector{Float_T}
    slht_mean           ::Float_T
    check_dist_mtx      ::Array{Float_T,2}
    check_dist_bool     ::Bool
end

ext: jl

max_stars_repo_name: MakerButt/chaipcr

max_issues_repo_name: MakerButt/chaipcr

max_forks_repo_name: MakerButt/chaipcr


text:
using SFML

# Create the window
window = RenderWindow("Image and Texture Example", 800, 600)
# Set the framerate limit
set_framerate_limit(window, 60)
event = Event()

# Load the texture for the image
texture = Texture(joinpath(dirname(@__FILE__),"..","..","assets","sfmljl_logo.png"))
set_smooth(texture, true)
texture_size = get_size(texture)

# Create the logo sprite and add the texture to it
logo = Sprite()
set_texture(logo, texture)
set_position(logo, Vector2f(400, 300))
set_origin(logo, Vector2f(texture_size.x / 2, texture_size.y / 2))
# Scale it down a bit
scale(logo, Vector2f(0.3, 0.3))

while isopen(window)
    # Check for any events
    while pollevent(window, event)
        if get_type(event) == EventType.CLOSED
            close(window)
        end
    end

    # Rotate the sprite by 2 degrees
    rotate(logo, 2)

    # Clear the screen and redraw the sprite
    clear(window, SFML.white)
    draw(window, logo)
    display(window)
end


text:
#
# Input and output of queries.
#

include("flow/outputflow.jl")
include("flow/inputflow.jl")

max_stars_repo_name: rbt-lang/rbt-proto

max_issues_repo_name: rbt-lang/rbt-proto

max_forks_repo_name: rbt-lang/rbt-proto


text:
# ---
# title: 496. Next Greater Element I
# id: problem496
# author: Indigo
# date: 2022-03-03
# difficulty: Easy
# categories: Stack
# link: <https://leetcode.com/problems/next-greater-element-i/description/>
# hidden: true
# ---
#
# You are given two arrays **(without duplicates)** `nums1` and `nums2` where
# `nums1`’s elements are subset of `nums2`. Find all the next greater numbers
# for `nums1`'s elements in the corresponding places of `nums2`.
#
# The Next Greater Number of a number **x** in `nums1` is the first greater
# number to its right in `nums2`. If it does not exist, output -1 for this
# number.
#
# **Example 1:**
#
#
#
#     Input: **nums1** = [4,1,2], **nums2** = [1,3,4,2].
#     Output: [-1,3,-1]
#     Explanation:
#         For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
#         For number 1 in the first array, the next greater number for it in the second array is 3.
#         For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
#
#
# **Example 2:**
#
#
#
#     Input: **nums1** = [2,4], **nums2** = [1,2,3,4].
#     Output: [3,-1]
#     Explanation:
#         For number 2 in the first array, the next greater number for it in the second array is 3.
#         For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
#
#
# **Note:**
#
#   1. All elements in `nums1` and `nums2` are unique.
#   2. The length of both `nums1` and `nums2` would not exceed 1000.
#
#
## @lc code=start
using LeetCode

function next_greater_element(num1::Vector{Int}, num2::Vector{Int})
    stk = Int[]
    res = fill(-1, length(num2))
    inv_idx = Dict{Int,Int}()
    for i in length(num2):-1:1
        inv_idx[num2[i]] = i
        while !isempty(stk) && stk[end] <= num2[i]
            pop!(stk)
        end
        res[i] = isempty(stk) ? -1 : stk[end]
        push!(stk, num2[i])
    end
    return [res[inv_idx[item]] for item in num1]
end
## @lc code=end


text:
using RecyclePermanent
using RNGPool
using JLD2

include("../models/bpModel.jl")

setRNGs(12345)

θ = BPθ(500, 2, 8)
model = makeBPModel(θ)
ys = simulateModel(model, 1000)

@save "data/bpData.jld" ys θ


text:
# Automatically generated using Clang.jl wrap_c

# Skipping MacroDefinition: HSA_EXPORT_DECORATOR __attribute__ ( ( visibility ( "default" ) ) )

const HSA_VERSION_1_0 = 1

@cenum(hsa_status_t,
    HSA_STATUS_SUCCESS = 0,
    HSA_STATUS_INFO_BREAK = 1,
    HSA_STATUS_ERROR = 4096,
    HSA_STATUS_ERROR_INVALID_ARGUMENT = 4097,
    HSA_STATUS_ERROR_INVALID_QUEUE_CREATION = 4098,
    HSA_STATUS_ERROR_INVALID_ALLOCATION = 4099,
    HSA_STATUS_ERROR_INVALID_AGENT = 4100,
    HSA_STATUS_ERROR_INVALID_REGION = 4101,
    HSA_STATUS_ERROR_INVALID_SIGNAL = 4102,
    HSA_STATUS_ERROR_INVALID_QUEUE = 4103,
    HSA_STATUS_ERROR_OUT_OF_RESOURCES = 4104,
    HSA_STATUS_ERROR_INVALID_PACKET_FORMAT = 4105,
    HSA_STATUS_ERROR_RESOURCE_FREE = 4106,
    HSA_STATUS_ERROR_NOT_INITIALIZED = 4107,
    HSA_STATUS_ERROR_REFCOUNT_OVERFLOW = 4108,
    HSA_STATUS_ERROR_INCOMPATIBLE_ARGUMENTS = 4109,
    HSA_STATUS_ERROR_INVALID_INDEX = 4110,
    HSA_STATUS_ERROR_INVALID_ISA = 4111,
    HSA_STATUS_ERROR_INVALID_ISA_NAME = 4119,
    HSA_STATUS_ERROR_INVALID_CODE_OBJECT = 4112,
    HSA_STATUS_ERROR_INVALID_EXECUTABLE = 4113,
    HSA_STATUS_ERROR_FROZEN_EXECUTABLE = 4114,
    HSA_STATUS_ERROR_INVALID_SYMBOL_NAME = 4115,
    HSA_STATUS_ERROR_VARIABLE_ALREADY_DEFINED = 4116,
    HSA_STATUS_ERROR_VARIABLE_UNDEFINED = 4117,
    HSA_STATUS_ERROR_EXCEPTION = 4118,
    HSA_STATUS_ERROR_INVALID_CODE_SYMBOL = 4120,
    HSA_STATUS_ERROR_INVALID_EXECUTABLE_SYMBOL = 4121,
    HSA_STATUS_ERROR_INVALID_FILE = 4128,
    HSA_STATUS_ERROR_INVALID_CODE_OBJECT_READER = 4129,
    HSA_STATUS_ERROR_INVALID_CACHE = 4130,
    HSA_STATUS_ERROR_INVALID_WAVEFRONT = 4131,
    HSA_STATUS_ERROR_INVALID_SIGNAL_GROUP = 4132,
    HSA_STATUS_ERROR_INVALID_RUNTIME_STATE = 4133,
)

struct hsa_dim3_s
    x::UInt32
    y::UInt32
    z::UInt32
end

const hsa_dim3_t = hsa_dim3_s

@cenum(hsa_access_permission_t,
    HSA_ACCESS_PERMISSION_RO = 1,
    HSA_ACCESS_PERMISSION_WO = 2,
    HSA_ACCESS_PERMISSION_RW = 3,
)

const hsa_file_t = Cint

@cenum(hsa_endianness_t,
    HSA_ENDIANNESS_LITTLE = 0,
    HSA_ENDIANNESS_BIG = 1,
)
@cenum(hsa_machine_model_t,
    HSA_MACHINE_MODEL_SMALL = 0,
    HSA_MACHINE_MODEL_LARGE = 1,
)
@cenum(hsa_profile_t,
    HSA_PROFILE_BASE = 0,
    HSA_PROFILE_FULL = 1,
)
@cenum(hsa_system_info_t,
    HSA_SYSTEM_INFO_VERSION_MAJOR = 0,
    HSA_SYSTEM_INFO_VERSION_MINOR = 1,
    HSA_SYSTEM_INFO_TIMESTAMP = 2,
    HSA_SYSTEM_INFO_TIMESTAMP_FREQUENCY = 3,
    HSA_SYSTEM_INFO_SIGNAL_MAX_WAIT = 4,
    HSA_SYSTEM_INFO_ENDIANNESS = 5,
    HSA_SYSTEM_INFO_MACHINE_MODEL = 6,
    HSA_SYSTEM_INFO_EXTENSIONS = 7,
)
@cenum(hsa_extension_t,
    HSA_EXTENSION_FINALIZER = 0,
    HSA_EXTENSION_IMAGES = 1,
    HSA_EXTENSION_PERFORMANCE_COUNTERS = 2,
    HSA_EXTENSION_PROFILING_EVENTS = 3,
    HSA_EXTENSION_STD_LAST = 3,
    HSA_AMD_FIRST_EXTENSION = 512,
    HSA_EXTENSION_AMD_PROFILER = 512,
    HSA_EXTENSION_AMD_LOADER = 513,
    HSA_EXTENSION_AMD_AQLPROFILE = 514,
    HSA_AMD_LAST_EXTENSION = 514,
)

struct hsa_agent_s
    handle::UInt64
end

const hsa_agent_t = hsa_agent_s

@cenum(hsa_agent_feature_t,
    HSA_AGENT_FEATURE_KERNEL_DISPATCH = 1,
    HSA_AGENT_FEATURE_AGENT_DISPATCH = 2,
)
@cenum(hsa_device_type_t,
    HSA_DEVICE_TYPE_CPU = 0,
    HSA_DEVICE_TYPE_GPU = 1,
    HSA_DEVICE_TYPE_DSP = 2,
)
@cenum(hsa_default_float_rounding_mode_t,
    HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT = 0,
    HSA_DEFAULT_FLOAT_ROUNDING_MODE_ZERO = 1,
    HSA_DEFAULT_FLOAT_ROUNDING_MODE_NEAR = 2,
)
@cenum(hsa_agent_info_t,
    HSA_AGENT_INFO_NAME = 0,
    HSA_AGENT_INFO_VENDOR_NAME = 1,
    HSA_AGENT_INFO_FEATURE = 2,
    HSA_AGENT_INFO_MACHINE_MODEL = 3,
    HSA_AGENT_INFO_PROFILE = 4,
    HSA_AGENT_INFO_DEFAULT_FLOAT_ROUNDING_MODE = 5,
    HSA_AGENT_INFO_BASE_PROFILE_DEFAULT_FLOAT_ROUNDING_MODES = 23,
    HSA_AGENT_INFO_FAST_F16_OPERATION = 24,
    HSA_AGENT_INFO_WAVEFRONT_SIZE = 6,
    HSA_AGENT_INFO_WORKGROUP_MAX_DIM = 7,
    HSA_AGENT_INFO_WORKGROUP_MAX_SIZE = 8,
    HSA_AGENT_INFO_GRID_MAX_DIM = 9,
    HSA_AGENT_INFO_GRID_MAX_SIZE = 10,
    HSA_AGENT_INFO_FBARRIER_MAX_SIZE = 11,
    HSA_AGENT_INFO_QUEUES_MAX = 12,
    HSA_AGENT_INFO_QUEUE_MIN_SIZE = 13,
    HSA_AGENT_INFO_QUEUE_MAX_SIZE = 14,
    HSA_AGENT_INFO_QUEUE_TYPE = 15,
    HSA_AGENT_INFO_NODE = 16,
    HSA_AGENT_INFO_DEVICE = 17,
    HSA_AGENT_INFO_CACHE_SIZE = 18,
    HSA_AGENT_INFO_ISA = 19,
    HSA_AGENT_INFO_EXTENSIONS = 20,
    HSA_AGENT_INFO_VERSION_MAJOR = 21,
    HSA_AGENT_INFO_VERSION_MINOR = 22,
)
@cenum(hsa_exception_policy_t,
    HSA_EXCEPTION_POLICY_BREAK = 1,
    HSA_EXCEPTION_POLICY_DETECT = 2,
)

struct hsa_cache_s
    handle::UInt64
end

const hsa_cache_t = hsa_cache_s

@cenum(hsa_cache_info_t,
    HSA_CACHE_INFO_NAME_LENGTH = 0,
    HSA_CACHE_INFO_NAME = 1,
    HSA_CACHE_INFO_LEVEL = 2,
    HSA_CACHE_INFO_SIZE = 3,
)

struct hsa_signal_s
    handle::UInt64
end

const hsa_signal_t = hsa_signal_s
const hsa_signal_value_t = Int64

@cenum(hsa_signal_condition_t,
    HSA_SIGNAL_CONDITION_EQ = 0,
    HSA_SIGNAL_CONDITION_NE = 1,
    HSA_SIGNAL_CONDITION_LT = 2,
    HSA_SIGNAL_CONDITION_GTE = 3,
)
@cenum(hsa_wait_state_t,
    HSA_WAIT_STATE_BLOCKED = 0,
    HSA_WAIT_STATE_ACTIVE = 1,
)

struct hsa_signal_group_s
    handle::UInt64
end

const hsa_signal_group_t = hsa_signal_group_s

struct hsa_region_s
    handle::UInt64
end

const hsa_region_t = hsa_region_s

@cenum(hsa_queue_type_t,
    HSA_QUEUE_TYPE_MULTI = 0,
    HSA_QUEUE_TYPE_SINGLE = 1,
)

const hsa_queue_type32_t = UInt32

@cenum(hsa_queue_feature_t,
    HSA_QUEUE_FEATURE_KERNEL_DISPATCH = 1,
    HSA_QUEUE_FEATURE_AGENT_DISPATCH = 2,
)

struct hsa_queue_s
    type::hsa_queue_type32_t
    features::UInt32
    base_address::Ptr{Cvoid}
    doorbell_signal::hsa_signal_t
    size::UInt32
    reserved1::UInt32
    id::UInt64
end

const hsa_queue_t = hsa_queue_s

@cenum(hsa_packet_type_t,
    HSA_PACKET_TYPE_VENDOR_SPECIFIC = 0,
    HSA_PACKET_TYPE_INVALID = 1,
    HSA_PACKET_TYPE_KERNEL_DISPATCH = 2,
    HSA_PACKET_TYPE_BARRIER_AND = 3,
    HSA_PACKET_TYPE_AGENT_DISPATCH = 4,
    HSA_PACKET_TYPE_BARRIER_OR = 5,
)
@cenum(hsa_fence_scope_t,
    HSA_FENCE_SCOPE_NONE = 0,
    HSA_FENCE_SCOPE_AGENT = 1,
    HSA_FENCE_SCOPE_SYSTEM = 2,
)
@cenum(hsa_packet_header_t,
    HSA_PACKET_HEADER_TYPE = 0,
    HSA_PACKET_HEADER_BARRIER = 8,
    HSA_PACKET_HEADER_SCACQUIRE_FENCE_SCOPE = 9,
    HSA_PACKET_HEADER_ACQUIRE_FENCE_SCOPE = 9,
    HSA_PACKET_HEADER_SCRELEASE_FENCE_SCOPE = 11,
    HSA_PACKET_HEADER_RELEASE_FENCE_SCOPE = 11,
)
@cenum(hsa_packet_header_width_t,
    HSA_PACKET_HEADER_WIDTH_TYPE = 8,
    HSA_PACKET_HEADER_WIDTH_BARRIER = 1,
    HSA_PACKET_HEADER_WIDTH_SCACQUIRE_FENCE_SCOPE = 2,
    HSA_PACKET_HEADER_WIDTH_ACQUIRE_FENCE_SCOPE = 2,
    HSA_PACKET_HEADER_WIDTH_SCRELEASE_FENCE_SCOPE = 2,
    HSA_PACKET_HEADER_WIDTH_RELEASE_FENCE_SCOPE = 2,
)
@cenum(hsa_kernel_dispatch_packet_setup_t,
    HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS = 0,
)
@cenum(hsa_kernel_dispatch_packet_setup_width_t,
    HSA_KERNEL_DISPATCH_PACKET_SETUP_WIDTH_DIMENSIONS = 2,
)

struct hsa_kernel_dispatch_packet_s
    header::UInt16
    setup::UInt16
    workgroup_size_x::UInt16
    workgroup_size_y::UInt16
    workgroup_size_z::UInt16
    reserved0::UInt16
    grid_size_x::UInt32
    grid_size_y::UInt32
    grid_size_z::UInt32
    private_segment_size::UInt32
    group_segment_size::UInt32
    kernel_object::UInt64
    kernarg_address::Ptr{Cvoid}
    reserved2::UInt64
    completion_signal::hsa_signal_t
end

const hsa_kernel_dispatch_packet_t = hsa_kernel_dispatch_packet_s

struct hsa_agent_dispatch_packet_s
    header::UInt16
    type::UInt16
    reserved0::UInt32
    return_address::Ptr{Cvoid}
    arg::NTuple{4, UInt64}
    reserved2::UInt64
    completion_signal::hsa_signal_t
end

const hsa_agent_dispatch_packet_t = hsa_agent_dispatch_packet_s

struct hsa_barrier_and_packet_s
    header::UInt16
    reserved0::UInt16
    reserved1::UInt32
    dep_signal::NTuple{5, hsa_signal_t}
    reserved2::UInt64
    completion_signal::hsa_signal_t
end

const hsa_barrier_and_packet_t = hsa_barrier_and_packet_s

struct hsa_barrier_or_packet_s
    header::UInt16
    reserved0::UInt16
    reserved1::UInt32
    dep_signal::NTuple{5, hsa_signal_t}
    reserved2::UInt64
    completion_signal::hsa_signal_t
end

const hsa_barrier_or_packet_t = hsa_barrier_or_packet_s

@cenum(hsa_region_segment_t,
    HSA_REGION_SEGMENT_GLOBAL = 0,
    HSA_REGION_SEGMENT_READONLY = 1,
    HSA_REGION_SEGMENT_PRIVATE = 2,
    HSA_REGION_SEGMENT_GROUP = 3,
    HSA_REGION_SEGMENT_KERNARG = 4,
)
@cenum(hsa_region_global_flag_t,
    HSA_REGION_GLOBAL_FLAG_KERNARG = 1,
    HSA_REGION_GLOBAL_FLAG_FINE_GRAINED = 2,
    HSA_REGION_GLOBAL_FLAG_COARSE_GRAINED = 4,
)
@cenum(hsa_region_info_t,
    HSA_REGION_INFO_SEGMENT = 0,
    HSA_REGION_INFO_GLOBAL_FLAGS = 1,
    HSA_REGION_INFO_SIZE = 2,
    HSA_REGION_INFO_ALLOC_MAX_SIZE = 4,
    HSA_REGION_INFO_ALLOC_MAX_PRIVATE_WORKGROUP_SIZE = 8,
    HSA_REGION_INFO_RUNTIME_ALLOC_ALLOWED = 5,
    HSA_REGION_INFO_RUNTIME_ALLOC_GRANULE = 6,
    HSA_REGION_INFO_RUNTIME_ALLOC_ALIGNMENT = 7,
)

struct hsa_isa_s
    handle::UInt64
end

const hsa_isa_t = hsa_isa_s

@cenum(hsa_isa_info_t,
    HSA_ISA_INFO_NAME_LENGTH = 0,
    HSA_ISA_INFO_NAME = 1,
    HSA_ISA_INFO_CALL_CONVENTION_COUNT = 2,
    HSA_ISA_INFO_CALL_CONVENTION_INFO_WAVEFRONT_SIZE = 3,
    HSA_ISA_INFO_CALL_CONVENTION_INFO_WAVEFRONTS_PER_COMPUTE_UNIT = 4,
    HSA_ISA_INFO_MACHINE_MODELS = 5,
    HSA_ISA_INFO_PROFILES = 6,
    HSA_ISA_INFO_DEFAULT_FLOAT_ROUNDING_MODES = 7,
    HSA_ISA_INFO_BASE_PROFILE_DEFAULT_FLOAT_ROUNDING_MODES = 8,
    HSA_ISA_INFO_FAST_F16_OPERATION = 9,
    HSA_ISA_INFO_WORKGROUP_MAX_DIM = 12,
    HSA_ISA_INFO_WORKGROUP_MAX_SIZE = 13,
    HSA_ISA_INFO_GRID_MAX_DIM = 14,
    HSA_ISA_INFO_GRID_MAX_SIZE = 16,
    HSA_ISA_INFO_FBARRIER_MAX_SIZE = 17,
)
@cenum(hsa_fp_type_t,
    HSA_FP_TYPE_16 = 1,
    HSA_FP_TYPE_32 = 2,
    HSA_FP_TYPE_64 = 4,
)
@cenum(hsa_flush_mode_t,
    HSA_FLUSH_MODE_FTZ = 1,
    HSA_FLUSH_MODE_NON_FTZ = 2,
)
@cenum(hsa_round_method_t,
    HSA_ROUND_METHOD_SINGLE = 1,
    HSA_ROUND_METHOD_DOUBLE = 2,
)

struct hsa_wavefront_s
    handle::UInt64
end

const hsa_wavefront_t = hsa_wavefront_s

@cenum(hsa_wavefront_info_t,
    HSA_WAVEFRONT_INFO_SIZE = 0,
)

struct hsa_code_object_reader_s
    handle::UInt64
end

const hsa_code_object_reader_t = hsa_code_object_reader_s

struct hsa_executable_s
    handle::UInt64
end

const hsa_executable_t = hsa_executable_s

@cenum(hsa_executable_state_t,
    HSA_EXECUTABLE_STATE_UNFROZEN = 0,
    HSA_EXECUTABLE_STATE_FROZEN = 1,
)

struct hsa_loaded_code_object_s
    handle::UInt64
end

const hsa_loaded_code_object_t = hsa_loaded_code_object_s

@cenum(hsa_executable_info_t,
    HSA_EXECUTABLE_INFO_PROFILE = 1,
    HSA_EXECUTABLE_INFO_STATE = 2,
    HSA_EXECUTABLE_INFO_DEFAULT_FLOAT_ROUNDING_MODE = 3,
)

struct hsa_executable_symbol_s
    handle::UInt64
end

const hsa_executable_symbol_t = hsa_executable_symbol_s

@cenum(hsa_symbol_kind_t,
    HSA_SYMBOL_KIND_VARIABLE = 0,
    HSA_SYMBOL_KIND_KERNEL = 1,
    HSA_SYMBOL_KIND_INDIRECT_FUNCTION = 2,
)
@cenum(hsa_symbol_linkage_t,
    HSA_SYMBOL_LINKAGE_MODULE = 0,
    HSA_SYMBOL_LINKAGE_PROGRAM = 1,
)
@cenum(hsa_variable_allocation_t,
    HSA_VARIABLE_ALLOCATION_AGENT = 0,
    HSA_VARIABLE_ALLOCATION_PROGRAM = 1,
)
@cenum(hsa_variable_segment_t,
    HSA_VARIABLE_SEGMENT_GLOBAL = 0,
    HSA_VARIABLE_SEGMENT_READONLY = 1,
)
@cenum(hsa_executable_symbol_info_t,
    HSA_EXECUTABLE_SYMBOL_INFO_TYPE = 0,
    HSA_EXECUTABLE_SYMBOL_INFO_NAME_LENGTH = 1,
    HSA_EXECUTABLE_SYMBOL_INFO_NAME = 2,
    HSA_EXECUTABLE_SYMBOL_INFO_MODULE_NAME_LENGTH = 3,
    HSA_EXECUTABLE_SYMBOL_INFO_MODULE_NAME = 4,
    HSA_EXECUTABLE_SYMBOL_INFO_AGENT = 20,
    HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS = 21,
    HSA_EXECUTABLE_SYMBOL_INFO_LINKAGE = 5,
    HSA_EXECUTABLE_SYMBOL_INFO_IS_DEFINITION = 17,
    HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ALLOCATION = 6,
    HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_SEGMENT = 7,
    HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ALIGNMENT = 8,
    HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_SIZE = 9,
    HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_IS_CONST = 10,
    HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT = 22,
    HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_SIZE = 11,
    HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_ALIGNMENT = 12,
    HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE = 13,
    HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE = 14,
    HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_DYNAMIC_CALLSTACK = 15,
    HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_CALL_CONVENTION = 18,
    HSA_EXECUTABLE_SYMBOL_INFO_INDIRECT_FUNCTION_OBJECT = 23,
    HSA_EXECUTABLE_SYMBOL_INFO_INDIRECT_FUNCTION_CALL_CONVENTION = 16,
)

struct hsa_code_object_s
    handle::UInt64
end

const hsa_code_object_t = hsa_code_object_s

struct hsa_callback_data_s
    handle::UInt64
end

const hsa_callback_data_t = hsa_callback_data_s

@cenum(hsa_code_object_type_t,
    HSA_CODE_OBJECT_TYPE_PROGRAM = 0,
)
@cenum(hsa_code_object_info_t,
    HSA_CODE_OBJECT_INFO_VERSION = 0,
    HSA_CODE_OBJECT_INFO_TYPE = 1,
    HSA_CODE_OBJECT_INFO_ISA = 2,
    HSA_CODE_OBJECT_INFO_MACHINE_MODEL = 3,
    HSA_CODE_OBJECT_INFO_PROFILE = 4,
    HSA_CODE_OBJECT_INFO_DEFAULT_FLOAT_ROUNDING_MODE = 5,
)

struct hsa_code_symbol_s
    handle::UInt64
end

const hsa_code_symbol_t = hsa_code_symbol_s

@cenum(hsa_code_symbol_info_t,
    HSA_CODE_SYMBOL_INFO_TYPE = 0,
    HSA_CODE_SYMBOL_INFO_NAME_LENGTH = 1,
    HSA_CODE_SYMBOL_INFO_NAME = 2,
    HSA_CODE_SYMBOL_INFO_MODULE_NAME_LENGTH = 3,
    HSA_CODE_SYMBOL_INFO_MODULE_NAME = 4,
    HSA_CODE_SYMBOL_INFO_LINKAGE = 5,
    HSA_CODE_SYMBOL_INFO_IS_DEFINITION = 17,
    HSA_CODE_SYMBOL_INFO_VARIABLE_ALLOCATION = 6,
    HSA_CODE_SYMBOL_INFO_VARIABLE_SEGMENT = 7,
    HSA_CODE_SYMBOL_INFO_VARIABLE_ALIGNMENT = 8,
    HSA_CODE_SYMBOL_INFO_VARIABLE_SIZE = 9,
    HSA_CODE_SYMBOL_INFO_VARIABLE_IS_CONST = 10,
    HSA_CODE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_SIZE = 11,
    HSA_CODE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_ALIGNMENT = 12,
    HSA_CODE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE = 13,
    HSA_CODE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE = 14,
    HSA_CODE_SYMBOL_INFO_KERNEL_DYNAMIC_CALLSTACK = 15,
    HSA_CODE_SYMBOL_INFO_KERNEL_CALL_CONVENTION = 18,
    HSA_CODE_SYMBOL_INFO_INDIRECT_FUNCTION_CALL_CONVENTION = 16,
)

const HSA_AMD_INTERFACE_VERSION_MAJOR = 1
const HSA_AMD_INTERFACE_VERSION_MINOR = 0

@cenum(hsa_amd_agent_info_s,
    HSA_AMD_AGENT_INFO_CHIP_ID = 40960,
    HSA_AMD_AGENT_INFO_CACHELINE_SIZE = 40961,
    HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT = 40962,
    HSA_AMD_AGENT_INFO_MAX_CLOCK_FREQUENCY = 40963,
    HSA_AMD_AGENT_INFO_DRIVER_NODE_ID = 40964,
    HSA_AMD_AGENT_INFO_MAX_ADDRESS_WATCH_POINTS = 40965,
    HSA_AMD_AGENT_INFO_BDFID = 40966,
    HSA_AMD_AGENT_INFO_MEMORY_WIDTH = 40967,
    HSA_AMD_AGENT_INFO_MEMORY_MAX_FREQUENCY = 40968,
    HSA_AMD_AGENT_INFO_PRODUCT_NAME = 40969,
    HSA_AMD_AGENT_INFO_MAX_WAVES_PER_CU = 40970,
    HSA_AMD_AGENT_INFO_NUM_SIMDS_PER_CU = 40971,
    HSA_AMD_AGENT_INFO_NUM_SHADER_ENGINES = 40972,
    HSA_AMD_AGENT_INFO_NUM_SHADER_ARRAYS_PER_SE = 40973,
)

const hsa_amd_agent_info_t = hsa_amd_agent_info_s

@cenum(hsa_amd_region_info_s,
    HSA_AMD_REGION_INFO_HOST_ACCESSIBLE = 40960,
    HSA_AMD_REGION_INFO_BASE = 40961,
    HSA_AMD_REGION_INFO_BUS_WIDTH = 40962,
    HSA_AMD_REGION_INFO_MAX_CLOCK_FREQUENCY = 40963,
)

const hsa_amd_region_info_t = hsa_amd_region_info_s

@cenum(hsa_amd_coherency_type_s,
    HSA_AMD_COHERENCY_TYPE_COHERENT = 0,
    HSA_AMD_COHERENCY_TYPE_NONCOHERENT = 1,
)

const hsa_amd_coherency_type_t = hsa_amd_coherency_type_s

struct hsa_amd_profiling_dispatch_time_s
    start::UInt64
    _end::UInt64
end

const hsa_amd_profiling_dispatch_time_t = hsa_amd_profiling_dispatch_time_s

struct hsa_amd_profiling_async_copy_time_s
    start::UInt64
    _end::UInt64
end

const hsa_amd_profiling_async_copy_time_t = hsa_amd_profiling_async_copy_time_s

@cenum(hsa_amd_signal_attribute_t,
    HSA_AMD_SIGNAL_AMD_GPU_ONLY = 1,
    HSA_AMD_SIGNAL_IPC = 2,
)

const hsa_amd_signal_handler = Ptr{Cvoid}

@cenum(hsa_amd_segment_t,
    HSA_AMD_SEGMENT_GLOBAL = 0,
    HSA_AMD_SEGMENT_READONLY = 1,
    HSA_AMD_SEGMENT_PRIVATE = 2,
    HSA_AMD_SEGMENT_GROUP = 3,
)

struct hsa_amd_memory_pool_s
    handle::UInt64
end

const hsa_amd_memory_pool_t = hsa_amd_memory_pool_s

@cenum(hsa_amd_memory_pool_global_flag_s,
    HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_KERNARG_INIT = 1,
    HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED = 2,
    HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED = 4,
)

const hsa_amd_memory_pool_global_flag_t = hsa_amd_memory_pool_global_flag_s

@cenum(hsa_amd_memory_pool_info_t,
    HSA_AMD_MEMORY_POOL_INFO_SEGMENT = 0,
    HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS = 1,
    HSA_AMD_MEMORY_POOL_INFO_SIZE = 2,
    HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED = 5,
    HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_GRANULE = 6,
    HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALIGNMENT = 7,
    HSA_AMD_MEMORY_POOL_INFO_ACCESSIBLE_BY_ALL = 15,
)
@cenum(hsa_amd_memory_pool_access_t,
    HSA_AMD_MEMORY_POOL_ACCESS_NEVER_ALLOWED = 0,
    HSA_AMD_MEMORY_POOL_ACCESS_ALLOWED_BY_DEFAULT = 1,
    HSA_AMD_MEMORY_POOL_ACCESS_DISALLOWED_BY_DEFAULT = 2,
)
@cenum(hsa_amd_link_info_type_t,
    HSA_AMD_LINK_INFO_TYPE_HYPERTRANSPORT = 0,
    HSA_AMD_LINK_INFO_TYPE_QPI = 1,
    HSA_AMD_LINK_INFO_TYPE_PCIE = 2,
    HSA_AMD_LINK_INFO_TYPE_INFINBAND = 3,
)

struct hsa_amd_memory_pool_link_info_s
    min_latency::UInt32
    max_latency::UInt32
    min_bandwidth::UInt32
    max_bandwidth::UInt32
    atomic_support_32bit::Bool
    atomic_support_64bit::Bool
    coherent_support::Bool
    link_type::hsa_amd_link_info_type_t
end

const hsa_amd_memory_pool_link_info_t = hsa_amd_memory_pool_link_info_s

@cenum(hsa_amd_agent_memory_pool_info_t,
    HSA_AMD_AGENT_MEMORY_POOL_INFO_ACCESS = 0,
    HSA_AMD_AGENT_MEMORY_POOL_INFO_NUM_LINK_HOPS = 1,
    HSA_AMD_AGENT_MEMORY_POOL_INFO_LINK_INFO = 2,
)

struct hsa_amd_image_descriptor_s
    version::UInt32
    deviceID::UInt32
    data::NTuple{1, UInt32}
end

const hsa_amd_image_descriptor_t = hsa_amd_image_descriptor_s

@cenum(hsa_amd_pointer_type_t,
    HSA_EXT_POINTER_TYPE_UNKNOWN = 0,
    HSA_EXT_POINTER_TYPE_HSA = 1,
    HSA_EXT_POINTER_TYPE_LOCKED = 2,
    HSA_EXT_POINTER_TYPE_GRAPHICS = 3,
    HSA_EXT_POINTER_TYPE_IPC = 4,
)

struct hsa_amd_pointer_info_s
    size::UInt32
    type::hsa_amd_pointer_type_t
    agentBaseAddress::Ptr{Cvoid}
    hostBaseAddress::Ptr{Cvoid}
    sizeInBytes::Csize_t
    userData::Ptr{Cvoid}
    agentOwner::hsa_agent_t
end

const hsa_amd_pointer_info_t = hsa_amd_pointer_info_s

struct hsa_amd_ipc_memory_s
    handle::NTuple{8, UInt32}
end

const hsa_amd_ipc_memory_t = hsa_amd_ipc_memory_s
const hsa_amd_ipc_signal_t = hsa_amd_ipc_memory_t
const BrigModuleHeader = Cvoid
const BrigModule_t = Ptr{BrigModuleHeader}
const hsa_ext_module_t = BrigModule_t

struct hsa_ext_program_s
    handle::UInt64
end

const hsa_ext_program_t = hsa_ext_program_s

@cenum(hsa_ext_program_info_t,
    HSA_EXT_PROGRAM_INFO_MACHINE_MODEL = 0,
    HSA_EXT_PROGRAM_INFO_PROFILE = 1,
    HSA_EXT_PROGRAM_INFO_DEFAULT_FLOAT_ROUNDING_MODE = 2,
)
@cenum(hsa_ext_finalizer_call_convention_t::Int32,
    HSA_EXT_FINALIZER_CALL_CONVENTION_AUTO = -1,
)

struct hsa_ext_control_directives_s
    control_directives_mask::UInt64
    break_exceptions_mask::UInt16
    detect_exceptions_mask::UInt16
    max_dynamic_group_size::UInt32
    max_flat_grid_size::UInt64
    max_flat_workgroup_size::UInt32
    reserved1::UInt32
    required_grid_size::NTuple{3, UInt64}
    required_workgroup_size::hsa_dim3_t
    required_dim::UInt8
    reserved2::NTuple{75, UInt8}
end

const hsa_ext_control_directives_t = hsa_ext_control_directives_s

struct hsa_ext_finalizer_1_00_pfn_s
    hsa_ext_program_create::Ptr{Cvoid}
    hsa_ext_program_destroy::Ptr{Cvoid}
    hsa_ext_program_add_module::Ptr{Cvoid}
    hsa_ext_program_iterate_modules::Ptr{Cvoid}
    hsa_ext_program_get_info::Ptr{Cvoid}
    hsa_ext_program_finalize::Ptr{Cvoid}
end

const hsa_ext_finalizer_1_00_pfn_t = hsa_ext_finalizer_1_00_pfn_s

struct hsa_ext_image_s
    handle::UInt64
end

const hsa_ext_image_t = hsa_ext_image_s

@cenum(hsa_ext_image_geometry_t,
    HSA_EXT_IMAGE_GEOMETRY_1D = 0,
    HSA_EXT_IMAGE_GEOMETRY_2D = 1,
    HSA_EXT_IMAGE_GEOMETRY_3D = 2,
    HSA_EXT_IMAGE_GEOMETRY_1DA = 3,
    HSA_EXT_IMAGE_GEOMETRY_2DA = 4,
    HSA_EXT_IMAGE_GEOMETRY_1DB = 5,
    HSA_EXT_IMAGE_GEOMETRY_2DDEPTH = 6,
    HSA_EXT_IMAGE_GEOMETRY_2DADEPTH = 7,
)
@cenum(hsa_ext_image_channel_type_t,
    HSA_EXT_IMAGE_CHANNEL_TYPE_SNORM_INT8 = 0,
    HSA_EXT_IMAGE_CHANNEL_TYPE_SNORM_INT16 = 1,
    HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT8 = 2,
    HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT16 = 3,
    HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT24 = 4,
    HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_SHORT_555 = 5,
    HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_SHORT_565 = 6,
    HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_SHORT_101010 = 7,
    HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT8 = 8,
    HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT16 = 9,
    HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT32 = 10,
    HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT8 = 11,
    HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT16 = 12,
    HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT32 = 13,
    HSA_EXT_IMAGE_CHANNEL_TYPE_HALF_FLOAT = 14,
    HSA_EXT_IMAGE_CHANNEL_TYPE_FLOAT = 15,
)

const hsa_ext_image_channel_type32_t = UInt32

@cenum(hsa_ext_image_channel_order_t,
    HSA_EXT_IMAGE_CHANNEL_ORDER_A = 0,
    HSA_EXT_IMAGE_CHANNEL_ORDER_R = 1,
    HSA_EXT_IMAGE_CHANNEL_ORDER_RX = 2,
    HSA_EXT_IMAGE_CHANNEL_ORDER_RG = 3,
    HSA_EXT_IMAGE_CHANNEL_ORDER_RGX = 4,
    HSA_EXT_IMAGE_CHANNEL_ORDER_RA = 5,
    HSA_EXT_IMAGE_CHANNEL_ORDER_RGB = 6,
    HSA_EXT_IMAGE_CHANNEL_ORDER_RGBX = 7,
    HSA_EXT_IMAGE_CHANNEL_ORDER_RGBA = 8,
    HSA_EXT_IMAGE_CHANNEL_ORDER_BGRA = 9,
    HSA_EXT_IMAGE_CHANNEL_ORDER_ARGB = 10,
    HSA_EXT_IMAGE_CHANNEL_ORDER_ABGR = 11,
    HSA_EXT_IMAGE_CHANNEL_ORDER_SRGB = 12,
    HSA_EXT_IMAGE_CHANNEL_ORDER_SRGBX = 13,
    HSA_EXT_IMAGE_CHANNEL_ORDER_SRGBA = 14,
    HSA_EXT_IMAGE_CHANNEL_ORDER_SBGRA = 15,
    HSA_EXT_IMAGE_CHANNEL_ORDER_INTENSITY = 16,
    HSA_EXT_IMAGE_CHANNEL_ORDER_LUMINANCE = 17,
    HSA_EXT_IMAGE_CHANNEL_ORDER_DEPTH = 18,
    HSA_EXT_IMAGE_CHANNEL_ORDER_DEPTH_STENCIL = 19,
)

const hsa_ext_image_channel_order32_t = UInt32

struct hsa_ext_image_format_s
    channel_type::hsa_ext_image_channel_type32_t
    channel_order::hsa_ext_image_channel_order32_t
end

const hsa_ext_image_format_t = hsa_ext_image_format_s

struct hsa_ext_image_descriptor_s
    geometry::hsa_ext_image_geometry_t
    width::Csize_t
    height::Csize_t
    depth::Csize_t
    array_size::Csize_t
    format::hsa_ext_image_format_t
end

const hsa_ext_image_descriptor_t = hsa_ext_image_descriptor_s

@cenum(hsa_ext_image_capability_t,
    HSA_EXT_IMAGE_CAPABILITY_NOT_SUPPORTED = 0,
    HSA_EXT_IMAGE_CAPABILITY_READ_ONLY = 1,
    HSA_EXT_IMAGE_CAPABILITY_WRITE_ONLY = 2,
    HSA_EXT_IMAGE_CAPABILITY_READ_WRITE = 4,
    HSA_EXT_IMAGE_CAPABILITY_READ_MODIFY_WRITE = 8,
    HSA_EXT_IMAGE_CAPABILITY_ACCESS_INVARIANT_DATA_LAYOUT = 16,
)
@cenum(hsa_ext_image_data_layout_t,
    HSA_EXT_IMAGE_DATA_LAYOUT_OPAQUE = 0,
    HSA_EXT_IMAGE_DATA_LAYOUT_LINEAR = 1,
)

struct hsa_ext_image_data_info_s
    size::Csize_t
    alignment::Csize_t
end

const hsa_ext_image_data_info_t = hsa_ext_image_data_info_s

struct hsa_ext_image_region_s
    offset::hsa_dim3_t
    range::hsa_dim3_t
end

const hsa_ext_image_region_t = hsa_ext_image_region_s

struct hsa_ext_sampler_s
    handle::UInt64
end

const hsa_ext_sampler_t = hsa_ext_sampler_s

@cenum(hsa_ext_sampler_addressing_mode_t,
    HSA_EXT_SAMPLER_ADDRESSING_MODE_UNDEFINED = 0,
    HSA_EXT_SAMPLER_ADDRESSING_MODE_CLAMP_TO_EDGE = 1,
    HSA_EXT_SAMPLER_ADDRESSING_MODE_CLAMP_TO_BORDER = 2,
    HSA_EXT_SAMPLER_ADDRESSING_MODE_REPEAT = 3,
    HSA_EXT_SAMPLER_ADDRESSING_MODE_MIRRORED_REPEAT = 4,
)

const hsa_ext_sampler_addressing_mode32_t = UInt32

@cenum(hsa_ext_sampler_coordinate_mode_t,
    HSA_EXT_SAMPLER_COORDINATE_MODE_UNNORMALIZED = 0,
    HSA_EXT_SAMPLER_COORDINATE_MODE_NORMALIZED = 1,
)

const hsa_ext_sampler_coordinate_mode32_t = UInt32

@cenum(hsa_ext_sampler_filter_mode_t,
    HSA_EXT_SAMPLER_FILTER_MODE_NEAREST = 0,
    HSA_EXT_SAMPLER_FILTER_MODE_LINEAR = 1,
)

const hsa_ext_sampler_filter_mode32_t = UInt32

struct hsa_ext_sampler_descriptor_s
    coordinate_mode::hsa_ext_sampler_coordinate_mode32_t
    filter_mode::hsa_ext_sampler_filter_mode32_t
    address_mode::hsa_ext_sampler_addressing_mode32_t
end

const hsa_ext_sampler_descriptor_t = hsa_ext_sampler_descriptor_s

struct hsa_ext_images_1_00_pfn_s
    hsa_ext_image_get_capability::Ptr{Cvoid}
    hsa_ext_image_data_get_info::Ptr{Cvoid}
    hsa_ext_image_create::Ptr{Cvoid}
    hsa_ext_image_destroy::Ptr{Cvoid}
    hsa_ext_image_copy::Ptr{Cvoid}
    hsa_ext_image_import::Ptr{Cvoid}
    hsa_ext_image_export::Ptr{Cvoid}
    hsa_ext_image_clear::Ptr{Cvoid}
    hsa_ext_sampler_create::Ptr{Cvoid}
    hsa_ext_sampler_destroy::Ptr{Cvoid}
end

const hsa_ext_images_1_00_pfn_t = hsa_ext_images_1_00_pfn_s

struct hsa_ext_images_1_pfn_s
    hsa_ext_image_get_capability::Ptr{Cvoid}
    hsa_ext_image_data_get_info::Ptr{Cvoid}
    hsa_ext_image_create::Ptr{Cvoid}
    hsa_ext_image_destroy::Ptr{Cvoid}
    hsa_ext_image_copy::Ptr{Cvoid}
    hsa_ext_image_import::Ptr{Cvoid}
    hsa_ext_image_export::Ptr{Cvoid}
    hsa_ext_image_clear::Ptr{Cvoid}
    hsa_ext_sampler_create::Ptr{Cvoid}
    hsa_ext_sampler_destroy::Ptr{Cvoid}
    hsa_ext_image_get_capability_with_layout::Ptr{Cvoid}
    hsa_ext_image_data_get_info_with_layout::Ptr{Cvoid}
    hsa_ext_image_create_with_layout::Ptr{Cvoid}
end

const hsa_ext_images_1_pfn_t = hsa_ext_images_1_pfn_s


text:
using PyCall
using DataFrames

#using Winston

@pyimport re
@pyimport pandas as pd
@pyimport numpy as np
@pyimport os

unshift!(PyVector(pyimport("sys")["path"]),
            "/home/benmo/OneDrive/GitHub/PyPackages/Algos")
@pyimport ModelsML

include("./myPandasIO.jl")
include("./tradingFuncs.jl")

models_loc = "/home/benmo/Data/Databases/Models/LSTM/"

function save_model(mdl, dir)
    pd.Series(stocksⱼ)[:to_csv](dir*"stocksj.csv")
    mdl[:save_weights](dir*"model.h5")

    open(dir*"mdl.json", "w") do f
            write(f, mdl[:to_json]())
    end
end

function LSTM_J(R, stockᵢ, stocksⱼ; sclr="std")
    scaler = ModelsML.scale(py"$R", how=sclr)
    R̃ = scaler[:tfm](py"$R")

    mdl = ModelsML.ts_LSTM(R̃, stockᵢ)
    ŷ, y_test = py"$mdl.yhat.astype('float64'), $mdl.y_test.astype('float64')"

    ŷ , y_test = (ŷ, y_test) .|> ((x) -> x * techRtnσ[stockᵢ][:tolist]() +
                                                            techRtnμ[stockᵢ][:tolist]()) .|>
                                                            transpose .|> DataFrame
    if os.path[:exists](models_loc*"$stockᵢ") == false
        os.mkdir(models_loc*"$stockᵢ")
        save_model(mdl, models_loc*"$stockᵢ/")
    else
        i=1
        while os.path[:exists](models_loc*"$stockᵢ$i") i+=1 end
        os.mkdir(models_loc*"$stockᵢ$i")
        save_model(mdl, models_loc*"$stockᵢ$i/")
    end
end

max_stars_repo_name: benzomo/PyPackages

max_issues_repo_name: benzomo/PyPackages

max_forks_repo_name: benzomo/PyPackages


text:
module TiledIteration

using OffsetArrays
using Base: tail, Indices, @propagate_inbounds
using Base.IteratorsMD: inc

export TileIterator, EdgeIterator, padded_tilesize, TileBuffer

### TileIterator ###

const L1cachesize = 2^15
const cachelinesize = 64

struct TileIterator{N,I,UR}
    inds::I
    sz::Dims{N}
    R::CartesianIndices{N,UR}
end
rangetype(::CartesianIndices{N,T}) where {N,T} = T
function TileIterator(inds::Indices{N}, sz::Dims{N}) where N
    ls = map(length, inds)
    ns = map(ceildiv, ls, sz)
    R = CartesianIndices(ns)
    TileIterator{N,typeof(inds),rangetype(R)}(inds, sz, R)
end

Iterators.IteratorEltype(::Type{<:TileIterator}) = Iterators.HasEltype()

ceildiv(l, s) = ceil(Int, l/s)

Base.length(iter::TileIterator) = length(iter.R)
Base.eltype(iter::TileIterator{N}) where {N} = NTuple{N,UnitRange{Int}}

function Base.iterate(iter::TileIterator)
    iterR = iterate(iter.R)
    iterR === nothing && return nothing
    I, state = iterR
    return getindices(iter, I), state
end
function Base.iterate(iter::TileIterator, state)
    iterR = iterate(iter.R, state)
    iterR === nothing && return nothing
    I, newstate = iterR
    return getindices(iter, I), newstate
end

Base.show(io::IO, iter::TileIterator) = print(io, "TileIterator(", iter.inds, ", ", iter.sz, ')')

@inline function getindices(iter::TileIterator, I::CartesianIndex)
    map3(_getindices, iter.inds, iter.sz, I.I)
end
_getindices(ind, s, i) = first(ind)+(i-1)*s : min(last(ind),first(ind)+i*s-1)
map3(f, ::Tuple{}, ::Tuple{}, ::Tuple{}) = ()
@inline map3(f, a::Tuple, b::Tuple, c::Tuple) = (f(a[1], b[1], c[1]), map3(f, tail(a), tail(b), tail(c))...)

### EdgeIterator ###

struct EdgeIterator{N,UR1,UR2}
    outer::CartesianIndices{N,UR1}
    inner::CartesianIndices{N,UR2}
    function EdgeIterator{N,UR1,UR2}(outer::CartesianIndices{N}, inner::CartesianIndices{N}) where {N,UR1,UR2}
        ((first(inner) ∈ outer) & (last(inner) ∈ outer)) || throw(DimensionMismatch("$inner must be in the interior of $outer"))
        new(outer, inner)
    end
end
EdgeIterator(outer::CartesianIndices{N,UR1}, inner::CartesianIndices{N,UR2}) where {N,UR1,UR2} =
    EdgeIterator{N,UR1,UR2}(outer, inner)
EdgeIterator(outer::Indices{N}, inner::Indices{N}) where N =
    EdgeIterator(promote(CartesianIndices(outer), CartesianIndices(inner))...)

"""
    EdgeIterator(outer, inner)

A Cartesian iterator that efficiently visits sites that are in `outer`
but not in `inner`. This can be useful for calculating edge values
that may require special treatment or boundary conditions.
"""
EdgeIterator

Iterators.IteratorEltype(::Type{<:EdgeIterator}) = Iterators.HasEltype()

Base.eltype(::Type{EdgeIterator{N,UR1,UR2}}) where {N,UR1,UR2} = CartesianIndex{N}
Base.length(iter::EdgeIterator) = length(iter.outer) - length(iter.inner)

function Base.iterate(iter::EdgeIterator)
    iterouter = iterate(iter.outer)
    iterouter === nothing && return nothing
    item = nextedgeitem(iter, iterouter[2])
    item ∉ iter.outer && return nothing
    return item, item
end
function Base.iterate(iter::EdgeIterator, state)
    iterouter = iterate(iter.outer, state)
    iterouter === nothing && return nothing
    item = nextedgeitem(iter, iterouter[2])
    item.I[end] > last(iter.outer.indices[end]) && return nothing
    return item, item
end

@inline function nextedgeitem(iter::EdgeIterator, I::CartesianIndex)
    !(I ∈ iter.inner) && return I
    newI = CartesianIndex(inc((last(iter.inner)[1], tail(I.I)...), first(iter.outer).I, last(iter.outer).I))
    nextedgeitem(iter, newI)
end

Base.show(io::IO, iter::EdgeIterator) = print(io, "EdgeIterator(", iter.outer.indices, ", ", iter.inner.indices, ')')

### Calculating the size of tiles ###

# If kernelsize-1 is the amount of padding, and s is the extra width of the tile along
# each axis, then the fraction of useful to total work is
# prod(s)/prod(s+kernelsize); this ratio is maximized if s is proportional to
# kernelsize.
"""
    padded_tilesize(T::Type, kernelsize::Dims, [ncache=2]) -> tilesize::Dims

Calculate a suitable tile size to approximately maximize the amount of
productive work, given a stencil of size `kernelsize`. The element
type of the array is `T`. Optionally specify `ncache`, the number of
such arrays that you'd like to have fit simultaneously in L1 cache.

This favors making the first dimension larger, since the first
dimension corresponds to individual cache lines.

# Examples
julia> padded_tilesize(UInt8, (3,3))
(768,18)

julia> padded_tilesize(UInt8, (3,3), 4)
(512,12)

julia> padded_tilesize(Float64, (3,3))
(96,18)

julia> padded_tilesize(Float32, (3,3,3))
(64,6,6)
"""
function padded_tilesize(::Type{T}, kernelsize::Dims, ncache = 2) where T
    nd = max(1, sum(x->x>1, kernelsize))
    # isbits(T) || return map(zero, kernelsize)
    # don't be too minimalist on the cache-friendly dim (use at least 2 cachelines)
    dim1minlen = 2*cachelinesize÷sizeof(T)
    psz = (max(kernelsize[1], dim1minlen), tail(kernelsize)...)
    L = sizeof(T)*prod(psz)
    # try to stay in L1 cache, but in the end we want a reasonably
    # favorable work ratio. f is the constant of proportionality in
    #      s+kernelsize ∝ kernelsize
    f = max(floor(Int, (L1cachesize/(ncache*L))^(1/nd)), 2)
    return _padded_tilesize_scale(f, psz)
end

@noinline _padded_tilesize_scale(f, psz) = map(x->x <= 1 ? x : f*x, psz) # see #15276

### Tile shaping and coordinate transformation

struct TileBuffer{T,N,P} <: AbstractArray{T,N}
    view::OffsetArray{T,N,Array{T,N}}  # the currently-active view
    buf::Array{T,P}                    # the original backing buffer
end

"""
    TileBuffer(a, inds::Indices) -> v

Return a buffer-view `v` whose indices match `inds`, using the array
`a` for storage. `inds` does not necessarily have to match the size of
`a` (which allows tiles to be of different sizes, e.g., at the edges).
"""
@inline function TileBuffer(a::Array, inds::Indices)
    l = map(length, inds)
    tilev = OffsetArray(_tileview(a, l), inds)
    TileBuffer(tilev, a)
end

"""
    TileBuffer(T, inds::Indices) -> v

Return a TileBuffer, allocating a new backing array of element type `T`
and size determined by `inds`.
"""
function TileBuffer(::Type{T}, inds::Indices) where T
    l = map(length, inds)
    TileBuffer(Array{T}(undef, l), inds)
end

TileBuffer(tb::TileBuffer, inds::Indices) = TileBuffer(tb.buf, inds)

@inline function _tileview(a::Array, l::Dims)
    if size(a) == l
        return a
    else
        # returning a SubArray would not be type-stable, we must return an Array
        prod(l) > length(a) && throw(DimensionMismatch("array of size $(size(a)) is not adequate for a tile of size $l"))
        return unsafe_wrap(Array, pointer(a), l)
    end
end

Base.axes(tb::TileBuffer) = axes(tb.view)
Base.size(tb::TileBuffer) = size(tb.view)

@inline @propagate_inbounds Base.getindex(tb::TileBuffer{T,N}, I::Vararg{Int,N}) where {T,N} = tb.view[I...]

@inline @propagate_inbounds Base.setindex!(tb::TileBuffer{T,N}, val, I::Vararg{Int,N}) where {T,N} = tb.view[I...] = val

Base.pointer(tb::TileBuffer) = pointer(parent(tb.view))

Base.parent(tb::TileBuffer) = tb.buf

end # module


text:
module RouteClientTest

using gRPCClient
using Downloads
using Random
using Sockets
using Test

const SERVER_RELEASE = "https://github.com/JuliaComputing/gRPCClient.jl/releases/download/testserver_v0.2/"
function server_binary()
    arch = (Sys.ARCH === :x86_64) ? "amd64" : "386"
    filename = Sys.islinux() ? "routeguide_linux_$(arch)" :
                Sys.iswindows() ? "routeguide_windows_$(arch).exe" :
                Sys.isapple() ? "routeguide_darwin_$(arch)" :
                error("no server binary available for this platform")
    source = string(SERVER_RELEASE, filename)
    destination = joinpath(@__DIR__, filename)
    isfile(destination) || Downloads.download(source, destination)
    ((filemode(destination) & 0o777) == 0o777) || chmod(destination, 0o777)

    destination
end

function start_server()
    serverbin = server_binary()

    @info("starting test server", serverbin)
    serverproc = run(`$serverbin`; wait=false)

    listening = timedwait(120.0; pollint=5.0) do
        try
            sock = connect(ip"127.0.0.1", 10000)
            close(sock)
            true
        catch
            false
        end
    end

    if listening !== :ok
        @warn("test server did not start, stopping server")
        kill(serverproc)
        error("test server did not start")
    end

    serverproc
end

function test_generate()
    @testset "codegen" begin
        dir = joinpath(@__DIR__, "RouteguideClients")
        gRPCClient.generate(joinpath(dir, "route_guide.proto"); outdir=dir)
        @test isfile(joinpath(dir, "route_guide_pb.jl"))
        @test isfile(joinpath(dir, "routeguide.jl"))
        @test isfile(joinpath(dir, "RouteguideClients.jl"))
    end
end

function test_timeout_header_values()
    @testset "timeout header" begin
        @test "100S" == gRPCClient.grpc_timeout_header_val(100)
        @test "100010m" == gRPCClient.grpc_timeout_header_val(100.01)
        @test "100000100u" == gRPCClient.grpc_timeout_header_val(100.0001)
        @test "100000010000n" == gRPCClient.grpc_timeout_header_val(100.00001)
    end
end

# switch off host verification for tests
if isempty(get(ENV, "JULIA_NO_VERIFY_HOSTS", ""))
    ENV["JULIA_NO_VERIFY_HOSTS"] = "**"
end

server_endpoint = isempty(ARGS) ? "http://localhost:10000/" : ARGS[1]
@info("server endpoint: $server_endpoint")

@testset "RouteGuide" begin
    if !Sys.iswindows()
        test_generate()
    else
        @info("skipping code generation on Windows to avoid needing batch file execution permissions")
    end

    test_timeout_header_values()

    include("test_routeclient.jl")
    serverproc = start_server()

    @debug("testing routeclinet...")
    test_clients(server_endpoint)

    @debug("testing async safety...")
    test_task_safety(server_endpoint)

    kill(serverproc)
    @info("stopped test server")
end

end # module RouteClientTest


text:
using MLStyle

function allow_patterns(node)
    @match node begin
        :(case($(targets...)) do
            $(cases...)
        end) => let target = length(targets) === 1 ? targets[1] : Expr(:tuple, targets...),
                   cases = map(allow_patterns, cases)
                   quote
                     $MLStyle.@match $target begin
                         $(cases...)
                     end
                   end
               end
        Expr(hd, tl...) => Expr(hd, map(allow_patterns, tl)...)
        a => a
    end
end

macro allow_patterns(node)
    allow_patterns(node) |> esc
end

# @allow_patterns module SyntaxExtended
#      case(1) do
#          2        => error(1)
#          5:10     => error(2)
#          1:4 && a =>
#          case(a + 1) do
#              a => 5a
#          end
#      end |> println
# end

max_stars_repo_name: thautwarm/MLStyle-Playground

max_issues_repo_name: thautwarm/MLStyle-Playground

max_forks_repo_name: thautwarm/MLStyle-Playground


text:
using LinearAlgebra

"""
Cartesian version of build_matrix
"""
function build_matrix(geometry::Cartesian;
    k,
    background,
    phys
    )

    solution = background[geometry]

    N = phys[geometry].grid.N
    g = phys[geometry].g

    kx2 = k^2
    ik = 1im*k

     u = solution.u
     h = solution.η .+ phys[geometry].grid.H
    Dy = phys[geometry].grid.D

     U   = diagm(0 => u)
     H   = diagm(0 => h)
    dUdy = diagm(0 => Dy*u)
     F   = diagm(0 => phys[geometry].coriolis)
     I   = diagm(0 => ones(N+1))

    # Form 1L-RSW Matrix
    #   [u1, v1, h1]

    A = [  U             (-F+dUdy)[:, 2:N]         g*I;
          -F[2:N,:]/kx2          U[2:N,2:N]  -g/kx2*Dy[2:N,:];
           H                  Dy*H[:,  2:N]          U];

    return A
end

"""
Spherical version of build_matrix
"""
function build_matrix(geometry::Spherical;
    k,
    background,
    phys
    )

    solution = background[geometry]

    a = phys[geometry].grid.a
    N = phys[geometry].grid.N
    g = phys[geometry].g

    kλ2 = k^2
    ik = 1im*k

         u = solution.u
         h = solution.η .+ phys[geometry].grid.H
        Dy = phys[geometry].grid.D / a
         ϕ = phys[geometry].grid.ϕ
    axcos = a * cos.(ϕ)

       IoACos = diagm(0=>1 ./ axcos)
            F = diagm(0=>phys[geometry].coriolis);    #
       UoACos = diagm(0=>u./axcos)
      UxTanoA = diagm(0=>u.*tan.(ϕ)/a)
       HoACos = diagm(0=>h./axcos)
       HxACos = diagm(0=>h.*axcos)
         dUdy = diagm(0=>Dy*u);

    # Form 1L-RSW Matrix
    #   [u1, v1, h1]

    A = [  UoACos                      (-F + dUdy - UxTanoA)[:, 2:N]     g*IoACos;
          -(F + 2*UxTanoA)[2:N,:]/kλ2                 UoACos[2:N,2:N]   -g/kλ2*Dy[2:N,:];
           HoACos                         (IoACos*Dy*HxACos)[:,  2:N]      UoACos] ;
    return A
end

function compute_spectrum(A, k, phys, Nmodes)

    λ_in, λvec_in = eigen(A);
            index = sortperm(imag(λ_in), rev=true);
             λvec = λvec_in[:,index];
                λ = λ_in[index];

           growth = imag(λ[1:Nmodes]) * k;
             freq = real(λ[1:Nmodes]) * k;
            modes = λvec[:,1:Nmodes];

        return growth, freq, modes
    end


text:
# ---
# title: 1453. Maximum Number of Darts Inside of a Circular Dartboard
# id: problem1453
# author: Tian Jun
# date: 2020-10-31
# difficulty: Hard
# categories: Geometry
# link: <https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/description/>
# hidden: true
# ---
#
# You have a very large square wall and a circular dartboard placed on the wall.
# You have been challenged to throw darts into the board blindfolded. Darts
# thrown at the wall are represented as an array of `points` on a 2D plane.
#
# Return the maximum number of points that are within or lie on  **any**
# circular dartboard of radius `r`.
#
#
#
# **Example 1:**
#
# ![](https://assets.leetcode.com/uploads/2020/04/29/sample_1_1806.png)
#
#
#
#     Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 2
#     Output: 4
#     Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.
#
#
# **Example 2:**
#
# **![](https://assets.leetcode.com/uploads/2020/04/29/sample_2_1806.png)**
#
#
#
#     Input: points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5
#     Output: 5
#     Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).
#
#
# **Example 3:**
#
#
#
#     Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 1
#     Output: 1
#
#
# **Example 4:**
#
#
#
#     Input: points = [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]], r = 2
#     Output: 4
#
#
#
#
# **Constraints:**
#
#   * `1 <= points.length <= 100`
#   * `points[i].length == 2`
#   * `-10^4 <= points[i][0], points[i][1] <= 10^4`
#   * `1 <= r <= 5000`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
################################################################
################################################################
# Numeric_Types
################################################################
################################################################
# # Copy of Julia Functions/Types

################################################################
matlabs = [:double, :single, :int8, :int16, :int32, :int64, :uint8, :uint16, :uint32, :uint64]
julias = [:Float64, :Float32, :Int8, :Int16, :Int32, :Int64, :UInt8, :UInt16, :UInt32, :UInt64]
for n = 1:length(matlabs)
    matFun = matlabs[n]
    jul = julias[n]
    exportFun=Symbol(matFun, "M")

    if occursin("Float",String(jul))
        exampleInput = 12.0
    elseif occursin("UInt",String(jul))
        exampleInput = 10
    elseif occursin("Int",String(jul))
        exampleInput = -10
    end

    @eval begin

        # init
        function $(exportFun) end

        # doc
        @doc """

            $($exportFun)(x)

        Converts to $($jul) type.
        # Examples
        ```julia
        n$($jul) = $($exportFun)($($exampleInput))
        t$($n) = typeof(n$($jul)) # $($jul)
        ```
        """ $(exportFun)

        $(exportFun)(args...) = $(jul)(args...) # real definition

        # exporting
        export $(exportFun)
    end
end
################################################################


text:
const USE_GPU = false
using ParallelStencil
using ParallelStencil.FiniteDifferences2D
@static if USE_GPU
    @init_parallel_stencil(CUDA, Float64, 2)
else
    @init_parallel_stencil(Threads, Float64, 2)
end
using Plots, Printf, Statistics
pyplot()
viz = true

@parallel function compute_flux!(qx::Data.Array, qy::Data.Array, 🔥::Data.Array, λ::Data.Number, ∂x::Data.Number, ∂y::Data.Number)
	@inn_x(qx) = -λ*@d_xa(🔥)/∂x
	@inn_y(qy) = -λ*@d_ya(🔥)/∂y
	return
end

@parallel function update_🔥!(🔥::Data.Array, qx::Data.Array, qy::Data.Array, ∂t::Data.Number, ρCp::Data.Number, ∂x::Data.Number, ∂y::Data.Number)
	@all(🔥) = @all(🔥) - ∂t/ρCp*(@d_xa(qx)/∂x + @d_ya(qy)/∂y)
	return
end

@views function heat_2D_xpu()
	# physics
	lx     = 10.0
	ly     = 10.0
	λ      = 1.0
	ρCp    = 1.0
	nt     = 200
	# numerics
	nx     = 128-1
	ny     = 128-1
	nout   = 10
	∂x     = lx/nx
	∂y     = ly/ny
	xc     = LinRange(∂x/2, lx-∂x/2, nx)
	yc     = LinRange(∂y/2, ly-∂y/2, ny)
	🔥     = @zeros(nx  ,ny  )
	qx     = @zeros(nx+1,ny  )
	qy     = @zeros(nx  ,ny+1)
	🔥     = Data.Array( exp.(.-(xc.-lx./2.0).^2 .-(yc.-ly./2.0)'.^2) )
	∂t     = min(∂x^2,∂y^2)/ρCp/λ/4.1
	# action
	t0     = Base.time()
	for it = 1:nt
		@parallel compute_flux!(qx, qy, 🔥, λ, ∂x, ∂y)
		@parallel update_🔥!(🔥, qx, qy, ∂t, ρCp, ∂x, ∂y)
		if mod(it,nout)==0 && viz
			display(heatmap(xc, yc, Array(🔥)', xlabel="lx", ylabel="ly", title="heat diffusion, it=$it", clims=(0.,1.)))
			# sleep(.01)
		end
	end
	@printf("T_eff = %1.2e GB/s \n", (2/1e9*nx*ny*sizeof(lx))/((Base.time()-t0)/nt))
	return
end

@time heat_2D_xpu()


text:
using HugepageMmap
using Test

@testset "HugepageMmap.jl" begin
    # Write your own tests here.
end


text:
using DelimitedFiles
using Distributed

config = ARGS[1]
out_path = ARGS[2]
println("config path: ", config)
println("output path: ", out_path)
flush(stdout)
flush(stderr)
include("./run.jl")

#bubbleLoc, locQ_sp, locQ_ch, bubble, nlQ_ch, nlQ_sp, nlQ_ch_λ, nlQ_sp_λ, Σ_bare, Σ_ladder, Σ_ladderLoc = run_sim(config)
run_sim(cfg_file=config, res_prefix=out_path*"/", save_results=true)


text:
using ArgCheck

import Base: length, push!, show, minimum, maximum, extrema, isempty

export Extrema, UniqueStrings, MultipleSummaries

mutable struct Extrema{T, S}
    count::T
    min::S
    max::S
end

Extrema(T,S) = Extrema{T,S}(zero(T), typemax(S), typemin(S))

Extrema(S) = Extrema(Int, S)

function push!{T,S}(s::Extrema{T,S}, x::S)
    s.count += one(T)
    s.min = min(s.min, x)
    s.max = max(s.max, x)
    nothing
end

length(s::Extrema) = s.count

isempty(s::Extrema) = s.count == 0

function minimum(s::Extrema)
    @argcheck !isempty(s)
    s.min
end

function maximum(s::Extrema)
    @argcheck !isempty(s)
    s.max
end

function extrema(s::Extrema)
    @argcheck s.count > 0
    (s.min, s.max)
end

function show{T,S}(io::IO, s::Extrema{T,S})
    print(io, "Extrema{$(T),$(S)}: $(s.count) values")
    if s.count > 0
        print(io, ", $(s.min)..$(s.max)")
    end
end

struct UniqueStrings{T}
    dict::Dict{String,T}
end

UniqueStrings(T) = UniqueStrings(Dict{String,T}())

UniqueStrings() = UniqueStrings(Int)

function push!{T}(s::UniqueStrings{T}, x::AbstractString)
    if haskey(s.dict, x)
        s.dict[x] += one(T)
    else
        s.dict[String(x)] = one(T)
    end
    nothing
end

length(s::UniqueStrings) = sum(values(s.dict))

isempty(s::UniqueStrings) = isempty(s.dict)

function show{T}(io::IO, s::UniqueStrings{T})
    len = length(s)
    println(io, "UniqueStrings{$(T)}: $(len) values")
    for (string, count) in sort(collect(s.dict), by = last, rev = true)
        println(io, "    $(string) => ", count_and_perc(count, len))
    end
end

struct MultipleSummaries{T <: Tuple}
    summaries::T
end

push!(s::MultipleSummaries, index::Int, x) = push!(s.summaries[index], x)

length(s::MultipleSummaries) = sum(length, s.summaries)

isempty(s::MultipleSummaries) = all(isempty, s.summaries)

function show(io::IO, s::MultipleSummaries)
    len = length(s)
    println(io, "MultipleSummaries{$(T)}: $(len) values")
    for summary in s.summaries
        count = length(summary)
        println(io, "    ", count_and_perc(count, len), " in ", summary)
    end
end


text:
"""
The data assimilation system (no assimilation example)
Load:
    x_a_init.txt
Save:
    x_b_none.txt
    x_a_none.txt
"""

include("setting.jl");
using DelimitedFiles;
using OrdinaryDiffEq;

# load initial condition
x_a_init = readdlm("data/x_a_init.txt");

# initial x_b: no values at the initial time (assign NaN)
x_b_save = Matrix{Float64}(undef, nT + 1, N);
x_b_save[1, :] .= NaN;

# initial x_a: from x_a_init
x_a_save = similar(x_b_save);
x_a_save[1, :] = x_a_init';

for tt = 1:nT
    tts = tt - 1
    tti = tt + 1
    Ts = tts * dT
    Ta = tt * dT
    println("Cycle = ", tt, ", Ts = ", round(Ts; digits = 3), ", Ta = ", round(Ta; digits = 3))

    #--------------
    # forecast step
    #--------------
    prob = ODEProblem(lorenz96, x_a_save[tt, :], (Ts, Ta))
    sol = solve(prob, Tsit5())
    x_b_save[tti, :] = sol[end]

    #--------------
    # analysis step
    #--------------
    # background
    x_b = sol[end]

    # analysis scheme (no assimilation in this example)
    x_a = x_b

    x_a_save[tti, :] = x_a
end # end tt loop

open("data/x_a_none.txt", "w") do xa
    writedlm(xa, x_a_save)
end

open("data/x_b_none.txt", "w") do xb
    writedlm(xb, x_b_save)
end

max_stars_repo_name: Typas/Data-Assimilation-Project

max_issues_repo_name: Typas/Data-Assimilation-Project

max_forks_repo_name: Typas/Data-Assimilation-Project


text:
@testset "Testset 2 Read-in" begin

    data = joinpath("data", "testset2")
    result = @suppress_err AnymodResult(data)

    @test_logs (:warn,) match_mode=:any AnymodResult(data)
    @test typeof(result) == AnymodResult

    @test result.scenarios == [
        "ntc_11"
        "ntc_16"
        "ntc_1"
        "ntc_21"
        "ntc_26"
        "ntc_31"
        "ntc_6"
    ]
    @test size(result.summarytable) == (74690, 11)
    @test size(result.costtable) == (0, 0)
    @test size(result.exchangetable) == (22232, 10)

    summarytable_names = [
        "variable",
        "value",
        "scenario",
        "region_dispatch_1",
        "region_dispatch_2",
        "technology_1",
        "technology_2",
        "technology_3",
        "carrier_1",
        "carrier_2",
        "timestep_superordinate_dispatch_1"
    ]

    @test names(result.summarytable) == summarytable_names

    exchangetable_names = [
        "value",
        "variable",
        "scenario",
        "region_from_1",
        "region_from_2",
        "region_to_1",
        "region_to_2",
        "carrier_1",
        "carrier_2",
        "timestep_superordinate_dispatch_1"
    ]

    @test names(result.exchangetable) == exchangetable_names
end


text:
"""
    factorial(n::Int)

Compute the factorial of n.
"""
function factorial(n::Int)
    if n < 0
        throw(DomainError("n must be non-negative"))
    end
    result = 1
    for i in 1:n
        result *= i
    end
    return result
end


text:
using Enzyme, BenchmarkTools, Zygote, Random

function mymul!(R, A, B)
    @assert axes(A, 2) == axes(B, 1)
    @inbounds @simd for i in eachindex(R)
        R[i] = 0
    end
    @inbounds for j in axes(B, 2), i in axes(A, 1)
        @inbounds @simd for k in axes(A, 2)
            R[i, j] += A[i, k] * B[k, j]
        end
    end
    nothing
end

A = rand(50, 30)
B = rand(30, 70)

R = zeros(size(A, 1), size(B, 2))
∂z_∂R = rand(size(R)...)  # Some gradient/tangent passed to us

∂z_∂A = zero(A)
∂z_∂B = zero(B)

@benchmark Enzyme.autodiff(mymul!, Const, Duplicated(R, ∂z_∂R), Duplicated(A, ∂z_∂A), Duplicated(B, ∂z_∂B))

@benchmark tmp = Zygote.pullback(*, A, B)[2](∂z_∂R)

∂z_∂A .= 0.0
∂z_∂B .= 0.0
Enzyme.autodiff(mymul!, Const, Duplicated(R, ∂z_∂R), Duplicated(A, ∂z_∂A), Duplicated(B, ∂z_∂B))
tmp = Zygote.pullback(*, A, B)[2](∂z_∂R)

maximum(abs.(tmp[1] - ∂z_∂A)) ≤ eps(10 * maximum(abs.(tmp[1])))
maximum(abs.(tmp[2] - ∂z_∂B)) ≤ eps(10 * maximum(abs.(tmp[2])))

##  Try it on the Lorenz equations
function lorenz!(ṡ, s; σ = 10, ρ = 28, β = 8 / 3)
    x, y, z = s
    ṡ[1] = -σ * (x - y)
    ṡ[2] = -y + (ρ - z) * x
    ṡ[3] = -β * z + x * y
    return nothing
end

function jlorenz!(ṡ, s, sᵃ; σ = 10, ρ = 28, β = 8 / 3)
    x, y, z = s
    xᵃ, yᵃ, zᵃ = sᵃ
    ṡ[1] = σ * (xᵃ - yᵃ)
    ṡ[2] = -yᵃ + (ρ - zᵃ) * x - z * xᵃ
    ṡ[3] = -β * zᵃ + xᵃ * y + x * yᵃ
    return nothing
end

function jᵀlorenz!(ṡ, s, sᵃ; σ = 10, ρ = 28, β = 8 / 3)
    x, y, z = s
    xᵃ, yᵃ, zᵃ = sᵃ
    ṡ[1] = -σ * xᵃ + (ρ - z) * yᵃ + y * zᵃ
    ṡ[2] = σ * xᵃ + -1 * yᵃ + x * zᵃ
    ṡ[3] = 0 * xᵃ + -x * yᵃ + -β * zᵃ
    return nothing
end

ṡ = zeros(3)
s = copy(ṡ)
dṡ = copy(s)
ds = copy(s)

Random.seed!(1234)
dṡ .= randn(3)
ṡ .= 0.0
s .= 0.0
ds .= 0.0
Enzyme.autodiff(lorenz!, Const, Duplicated(ṡ, dṡ), Duplicated(s, ds))
enzyme_answ = copy(ds)

Random.seed!(1234)
dṡ .= randn(3)

jᵀlorenz!(ṡ, s, dṡ; σ = 10, ρ = 28, β = 8 / 3)
analytic_answ = copy(ṡ)

norm(enzyme_answ - analytic_answ)
@benchmark Enzyme.autodiff(lorenz!, Const, Duplicated(ṡ, dṡ), Duplicated(s, ds))
@benchmark jᵀlorenz!(ṡ, s, dṡ; σ = 10, ρ = 28, β = 8 / 3)

max_stars_repo_name: sandreza/GradientLearning

max_issues_repo_name: sandreza/GradientLearning

max_forks_repo_name: sandreza/GradientLearning


text:
#==============================================================================#
# MediaStore.jl
#
# This file is generated from:
# https://github.com/aws/aws-sdk-js/blob/master/apis/mediastore-2017-09-01.normal.json
#==============================================================================#

__precompile__()

module MediaStore

using AWSCore

"""
    using AWSSDK.MediaStore.create_container
    create_container([::AWSConfig], arguments::Dict)
    create_container([::AWSConfig]; ContainerName=)

    using AWSCore.Services.mediastore
    mediastore([::AWSConfig], "CreateContainer", arguments::Dict)
    mediastore([::AWSConfig], "CreateContainer", ContainerName=)

# CreateContainer Operation

Creates a storage container to hold objects. A container is similar to a bucket in the Amazon S3 service.

# Arguments

## `ContainerName = ::String` -- *Required*
The name for the container. The name must be from 1 to 255 characters. Container names must be unique to your AWS account within a specific region. As an example, you could create a container named `movies` in every region, as long as you don’t have an existing container with that name.

# Returns

`CreateContainerOutput`

# Exceptions

`ContainerInUseException`, `LimitExceededException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-2017-09-01/CreateContainer)
"""
@inline create_container(aws::AWSConfig=default_aws_config(); args...) = create_container(aws, args)

@inline create_container(aws::AWSConfig, args) = AWSCore.Services.mediastore(aws, "CreateContainer", args)

@inline create_container(args) = create_container(default_aws_config(), args)

"""
    using AWSSDK.MediaStore.delete_container
    delete_container([::AWSConfig], arguments::Dict)
    delete_container([::AWSConfig]; ContainerName=)

    using AWSCore.Services.mediastore
    mediastore([::AWSConfig], "DeleteContainer", arguments::Dict)
    mediastore([::AWSConfig], "DeleteContainer", ContainerName=)

# DeleteContainer Operation

Deletes the specified container. Before you make a `DeleteContainer` request, delete any objects in the container or in any folders in the container. You can delete only empty containers.

# Arguments

## `ContainerName = ::String` -- *Required*
The name of the container to delete.

# Returns

`DeleteContainerOutput`

# Exceptions

`ContainerInUseException`, `ContainerNotFoundException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-2017-09-01/DeleteContainer)
"""
@inline delete_container(aws::AWSConfig=default_aws_config(); args...) = delete_container(aws, args)

@inline delete_container(aws::AWSConfig, args) = AWSCore.Services.mediastore(aws, "DeleteContainer", args)

@inline delete_container(args) = delete_container(default_aws_config(), args)

"""
    using AWSSDK.MediaStore.delete_container_policy
    delete_container_policy([::AWSConfig], arguments::Dict)
    delete_container_policy([::AWSConfig]; ContainerName=)

    using AWSCore.Services.mediastore
    mediastore([::AWSConfig], "DeleteContainerPolicy", arguments::Dict)
    mediastore([::AWSConfig], "DeleteContainerPolicy", ContainerName=)

# DeleteContainerPolicy Operation

Deletes the access policy that is associated with the specified container.

# Arguments

## `ContainerName = ::String` -- *Required*
The name of the container that holds the policy.

# Returns

`DeleteContainerPolicyOutput`

# Exceptions

`ContainerInUseException`, `ContainerNotFoundException`, `PolicyNotFoundException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-2017-09-01/DeleteContainerPolicy)
"""
@inline delete_container_policy(aws::AWSConfig=default_aws_config(); args...) = delete_container_policy(aws, args)

@inline delete_container_policy(aws::AWSConfig, args) = AWSCore.Services.mediastore(aws, "DeleteContainerPolicy", args)

@inline delete_container_policy(args) = delete_container_policy(default_aws_config(), args)

"""
    using AWSSDK.MediaStore.delete_cors_policy
    delete_cors_policy([::AWSConfig], arguments::Dict)
    delete_cors_policy([::AWSConfig]; ContainerName=)

    using AWSCore.Services.mediastore
    mediastore([::AWSConfig], "DeleteCorsPolicy", arguments::Dict)
    mediastore([::AWSConfig], "DeleteCorsPolicy", ContainerName=)

# DeleteCorsPolicy Operation

Deletes the cross-origin resource sharing (CORS) configuration information that is set for the container.

To use this operation, you must have permission to perform the `MediaStore:DeleteCorsPolicy` action. The container owner has this permission by default and can grant this permission to others.

# Arguments

## `ContainerName = ::String` -- *Required*
The name of the container to remove the policy from.

# Returns

`DeleteCorsPolicyOutput`

# Exceptions

`ContainerInUseException`, `ContainerNotFoundException`, `CorsPolicyNotFoundException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-2017-09-01/DeleteCorsPolicy)
"""
@inline delete_cors_policy(aws::AWSConfig=default_aws_config(); args...) = delete_cors_policy(aws, args)

@inline delete_cors_policy(aws::AWSConfig, args) = AWSCore.Services.mediastore(aws, "DeleteCorsPolicy", args)

@inline delete_cors_policy(args) = delete_cors_policy(default_aws_config(), args)

"""
    using AWSSDK.MediaStore.describe_container
    describe_container([::AWSConfig], arguments::Dict)
    describe_container([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.mediastore
    mediastore([::AWSConfig], "DescribeContainer", arguments::Dict)
    mediastore([::AWSConfig], "DescribeContainer", <keyword arguments>)

# DescribeContainer Operation

Retrieves the properties of the requested container. This request is commonly used to retrieve the endpoint of a container. An endpoint is a value assigned by the service when a new container is created. A container's endpoint does not change after it has been assigned. The `DescribeContainer` request returns a single `Container` object based on `ContainerName`. To return all `Container` objects that are associated with a specified AWS account, use [ListContainers](@ref).

# Arguments

## `ContainerName = ::String`
The name of the container to query.

# Returns

`DescribeContainerOutput`

# Exceptions

`ContainerNotFoundException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-2017-09-01/DescribeContainer)
"""
@inline describe_container(aws::AWSConfig=default_aws_config(); args...) = describe_container(aws, args)

@inline describe_container(aws::AWSConfig, args) = AWSCore.Services.mediastore(aws, "DescribeContainer", args)

@inline describe_container(args) = describe_container(default_aws_config(), args)

"""
    using AWSSDK.MediaStore.get_container_policy
    get_container_policy([::AWSConfig], arguments::Dict)
    get_container_policy([::AWSConfig]; ContainerName=)

    using AWSCore.Services.mediastore
    mediastore([::AWSConfig], "GetContainerPolicy", arguments::Dict)
    mediastore([::AWSConfig], "GetContainerPolicy", ContainerName=)

# GetContainerPolicy Operation

Retrieves the access policy for the specified container. For information about the data that is included in an access policy, see the [AWS Identity and Access Management User Guide](https://aws.amazon.com/documentation/iam/).

# Arguments

## `ContainerName = ::String` -- *Required*
The name of the container.

# Returns

`GetContainerPolicyOutput`

# Exceptions

`ContainerInUseException`, `ContainerNotFoundException`, `PolicyNotFoundException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-2017-09-01/GetContainerPolicy)
"""
@inline get_container_policy(aws::AWSConfig=default_aws_config(); args...) = get_container_policy(aws, args)

@inline get_container_policy(aws::AWSConfig, args) = AWSCore.Services.mediastore(aws, "GetContainerPolicy", args)

@inline get_container_policy(args) = get_container_policy(default_aws_config(), args)

"""
    using AWSSDK.MediaStore.get_cors_policy
    get_cors_policy([::AWSConfig], arguments::Dict)
    get_cors_policy([::AWSConfig]; ContainerName=)

    using AWSCore.Services.mediastore
    mediastore([::AWSConfig], "GetCorsPolicy", arguments::Dict)
    mediastore([::AWSConfig], "GetCorsPolicy", ContainerName=)

# GetCorsPolicy Operation

Returns the cross-origin resource sharing (CORS) configuration information that is set for the container.

To use this operation, you must have permission to perform the `MediaStore:GetCorsPolicy` action. By default, the container owner has this permission and can grant it to others.

# Arguments

## `ContainerName = ::String` -- *Required*
The name of the container that the policy is assigned to.

# Returns

`GetCorsPolicyOutput`

# Exceptions

`ContainerInUseException`, `ContainerNotFoundException`, `CorsPolicyNotFoundException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-2017-09-01/GetCorsPolicy)
"""
@inline get_cors_policy(aws::AWSConfig=default_aws_config(); args...) = get_cors_policy(aws, args)

@inline get_cors_policy(aws::AWSConfig, args) = AWSCore.Services.mediastore(aws, "GetCorsPolicy", args)

@inline get_cors_policy(args) = get_cors_policy(default_aws_config(), args)

"""
    using AWSSDK.MediaStore.list_containers
    list_containers([::AWSConfig], arguments::Dict)
    list_containers([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.mediastore
    mediastore([::AWSConfig], "ListContainers", arguments::Dict)
    mediastore([::AWSConfig], "ListContainers", <keyword arguments>)

# ListContainers Operation

Lists the properties of all containers in AWS Elemental MediaStore.

You can query to receive all the containers in one response. Or you can include the `MaxResults` parameter to receive a limited number of containers in each response. In this case, the response includes a token. To get the next set of containers, send the command again, this time with the `NextToken` parameter (with the returned token as its value). The next set of responses appears, with a token if there are still more containers to receive.

See also [DescribeContainer](@ref), which gets the properties of one container.

# Arguments

## `NextToken = ::String`
Only if you used `MaxResults` in the first command, enter the token (which was included in the previous response) to obtain the next set of containers. This token is included in a response only if there actually are more containers to list.

## `MaxResults = ::Int`
Enter the maximum number of containers in the response. Use from 1 to 255 characters.

# Returns

`ListContainersOutput`

# Exceptions

`InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-2017-09-01/ListContainers)
"""
@inline list_containers(aws::AWSConfig=default_aws_config(); args...) = list_containers(aws, args)

@inline list_containers(aws::AWSConfig, args) = AWSCore.Services.mediastore(aws, "ListContainers", args)

@inline list_containers(args) = list_containers(default_aws_config(), args)

"""
    using AWSSDK.MediaStore.put_container_policy
    put_container_policy([::AWSConfig], arguments::Dict)
    put_container_policy([::AWSConfig]; ContainerName=, Policy=)

    using AWSCore.Services.mediastore
    mediastore([::AWSConfig], "PutContainerPolicy", arguments::Dict)
    mediastore([::AWSConfig], "PutContainerPolicy", ContainerName=, Policy=)

# PutContainerPolicy Operation

Creates an access policy for the specified container to restrict the users and clients that can access it. For information about the data that is included in an access policy, see the [AWS Identity and Access Management User Guide](https://aws.amazon.com/documentation/iam/).

For this release of the REST API, you can create only one policy for a container. If you enter `PutContainerPolicy` twice, the second command modifies the existing policy.

# Arguments

## `ContainerName = ::String` -- *Required*
The name of the container.

## `Policy = ::String` -- *Required*
The contents of the policy, which includes the following:

*   One `Version` tag

*   One `Statement` tag that contains the standard tags for the policy.

# Returns

`PutContainerPolicyOutput`

# Exceptions

`ContainerNotFoundException`, `ContainerInUseException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-2017-09-01/PutContainerPolicy)
"""
@inline put_container_policy(aws::AWSConfig=default_aws_config(); args...) = put_container_policy(aws, args)

@inline put_container_policy(aws::AWSConfig, args) = AWSCore.Services.mediastore(aws, "PutContainerPolicy", args)

@inline put_container_policy(args) = put_container_policy(default_aws_config(), args)

"""
    using AWSSDK.MediaStore.put_cors_policy
    put_cors_policy([::AWSConfig], arguments::Dict)
    put_cors_policy([::AWSConfig]; ContainerName=, CorsPolicy=)

    using AWSCore.Services.mediastore
    mediastore([::AWSConfig], "PutCorsPolicy", arguments::Dict)
    mediastore([::AWSConfig], "PutCorsPolicy", ContainerName=, CorsPolicy=)

# PutCorsPolicy Operation

Sets the cross-origin resource sharing (CORS) configuration on a container so that the container can service cross-origin requests. For example, you might want to enable a request whose origin is http://www.example.com to access your AWS Elemental MediaStore container at my.example.container.com by using the browser's XMLHttpRequest capability.

To enable CORS on a container, you attach a CORS policy to the container. In the CORS policy, you configure rules that identify origins and the HTTP methods that can be executed on your container. The policy can contain up to 398,000 characters. You can add up to 100 rules to a CORS policy. If more than one rule applies, the service uses the first applicable rule listed.

# Arguments

## `ContainerName = ::String` -- *Required*
The name of the container that you want to assign the CORS policy to.

## `CorsPolicy = [[ ... ], ...]` -- *Required*
The CORS policy to apply to the container.
```
 CorsPolicy = [[
        "AllowedOrigins" =>  [::String, ...],
        "AllowedMethods" =>  ["PUT", "GET", "DELETE" or "HEAD", ...],
        "AllowedHeaders" =>  [::String, ...],
        "MaxAgeSeconds" =>  ::Int,
        "ExposeHeaders" =>  [::String, ...]
    ], ...]
```

# Returns

`PutCorsPolicyOutput`

# Exceptions

`ContainerNotFoundException`, `ContainerInUseException` or `InternalServerError`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/mediastore-2017-09-01/PutCorsPolicy)
"""
@inline put_cors_policy(aws::AWSConfig=default_aws_config(); args...) = put_cors_policy(aws, args)

@inline put_cors_policy(aws::AWSConfig, args) = AWSCore.Services.mediastore(aws, "PutCorsPolicy", args)

@inline put_cors_policy(args) = put_cors_policy(default_aws_config(), args)

end # module MediaStore

#==============================================================================#
# End of file
#==============================================================================#