text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: timestream_query
using AWS.Compat
using AWS.UUIDs

"""
    cancel_query(query_id)
    cancel_query(query_id, params::Dict{String,<:Any})

 Cancels a query that has been issued. Cancellation is provided only if the query has not
completed running before the cancellation request was issued. Because cancellation is an
idempotent operation, subsequent cancellation requests will return a CancellationMessage,
indicating that the query has already been canceled. See code sample for details.

# Arguments
- `query_id`:  The ID of the query that needs to be cancelled. QueryID is returned as part
  of the query result.

"""
function cancel_query(QueryId; aws_config::AbstractAWSConfig=global_aws_config())
    return timestream_query(
        "CancelQuery",
        Dict{String,Any}("QueryId" => QueryId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function cancel_query(
    QueryId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return timestream_query(
        "CancelQuery",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("QueryId" => QueryId), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_scheduled_query(error_report_configuration, name, notification_configuration, query_string, schedule_configuration, scheduled_query_execution_role_arn)
    create_scheduled_query(error_report_configuration, name, notification_configuration, query_string, schedule_configuration, scheduled_query_execution_role_arn, params::Dict{String,<:Any})

 Create a scheduled query that will be run on your behalf at the configured schedule.
Timestream assumes the execution role provided as part of the
ScheduledQueryExecutionRoleArn parameter to run the query. You can use the
NotificationConfiguration parameter to configure notification for your scheduled query
operations.

# Arguments
- `error_report_configuration`: Configuration for error reporting. Error reports will be
  generated when a problem is encountered when writing the query results.
- `name`: Name of the scheduled query.
- `notification_configuration`: Notification configuration for the scheduled query. A
  notification is sent by Timestream when a query run finishes, when the state is updated or
  when you delete it.
- `query_string`: The query string to run. Parameter names can be specified in the query
  string @ character followed by an identifier. The named Parameter @scheduled_runtime is
  reserved and can be used in the query to get the time at which the query is scheduled to
  run. The timestamp calculated according to the ScheduleConfiguration parameter, will be the
  value of @scheduled_runtime paramater for each query run. For example, consider an instance
  of a scheduled query executing on 2021-12-01 00:00:00. For this instance, the
  @scheduled_runtime parameter is initialized to the timestamp 2021-12-01 00:00:00 when
  invoking the query.
- `schedule_configuration`: The schedule configuration for the query.
- `scheduled_query_execution_role_arn`: The ARN for the IAM role that Timestream will
  assume when running the scheduled query.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ClientToken"`: Using a ClientToken makes the call to CreateScheduledQuery idempotent,
  in other words, making the same request repeatedly will produce the same result. Making
  multiple identical CreateScheduledQuery requests has the same effect as making a single
  request.     If CreateScheduledQuery is called without a ClientToken, the Query SDK
  generates a ClientToken on your behalf.    After 8 hours, any request with the same
  ClientToken is treated as a new request.
- `"KmsKeyId"`: The Amazon KMS key used to encrypt the scheduled query resource, at-rest.
  If the Amazon KMS key is not specified, the scheduled query resource will be encrypted with
  a Timestream owned Amazon KMS key. To specify a KMS key, use the key ID, key ARN, alias
  name, or alias ARN. When using an alias name, prefix the name with alias/  If
  ErrorReportConfiguration uses SSE_KMS as encryption type, the same KmsKeyId is used to
  encrypt the error report at rest.
- `"Tags"`: A list of key-value pairs to label the scheduled query.
- `"TargetConfiguration"`: Configuration used for writing the result of a query.
"""
function create_scheduled_query(
    ErrorReportConfiguration,
    Name,
    NotificationConfiguration,
    QueryString,
    ScheduleConfiguration,
    ScheduledQueryExecutionRoleArn;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "CreateScheduledQuery",
        Dict{String,Any}(
            "ErrorReportConfiguration" => ErrorReportConfiguration,
            "Name" => Name,
            "NotificationConfiguration" => NotificationConfiguration,
            "QueryString" => QueryString,
            "ScheduleConfiguration" => ScheduleConfiguration,
            "ScheduledQueryExecutionRoleArn" => ScheduledQueryExecutionRoleArn,
            "ClientToken" => string(uuid4()),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_scheduled_query(
    ErrorReportConfiguration,
    Name,
    NotificationConfiguration,
    QueryString,
    ScheduleConfiguration,
    ScheduledQueryExecutionRoleArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "CreateScheduledQuery",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "ErrorReportConfiguration" => ErrorReportConfiguration,
                    "Name" => Name,
                    "NotificationConfiguration" => NotificationConfiguration,
                    "QueryString" => QueryString,
                    "ScheduleConfiguration" => ScheduleConfiguration,
                    "ScheduledQueryExecutionRoleArn" => ScheduledQueryExecutionRoleArn,
                    "ClientToken" => string(uuid4()),
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_scheduled_query(scheduled_query_arn)
    delete_scheduled_query(scheduled_query_arn, params::Dict{String,<:Any})

Deletes a given scheduled query. This is an irreversible operation.

# Arguments
- `scheduled_query_arn`: The ARN of the scheduled query.

"""
function delete_scheduled_query(
    ScheduledQueryArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return timestream_query(
        "DeleteScheduledQuery",
        Dict{String,Any}("ScheduledQueryArn" => ScheduledQueryArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_scheduled_query(
    ScheduledQueryArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "DeleteScheduledQuery",
        Dict{String,Any}(
            mergewith(
                _merge, Dict{String,Any}("ScheduledQueryArn" => ScheduledQueryArn), params
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_endpoints()
    describe_endpoints(params::Dict{String,<:Any})

DescribeEndpoints returns a list of available endpoints to make Timestream API calls
against. This API is available through both Write and Query. Because the Timestream SDKs
are designed to transparently work with the service’s architecture, including the
management and mapping of the service endpoints, it is not recommended that you use this
API unless:   You are using VPC endpoints (Amazon Web Services PrivateLink) with Timestream
    Your application uses a programming language that does not yet have SDK support   You
require better control over the client-side implementation   For detailed information on
how and when to use and implement DescribeEndpoints, see The Endpoint Discovery Pattern.

"""
function describe_endpoints(; aws_config::AbstractAWSConfig=global_aws_config())
    return timestream_query(
        "DescribeEndpoints"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function describe_endpoints(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return timestream_query(
        "DescribeEndpoints", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    describe_scheduled_query(scheduled_query_arn)
    describe_scheduled_query(scheduled_query_arn, params::Dict{String,<:Any})

Provides detailed information about a scheduled query.

# Arguments
- `scheduled_query_arn`: The ARN of the scheduled query.

"""
function describe_scheduled_query(
    ScheduledQueryArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return timestream_query(
        "DescribeScheduledQuery",
        Dict{String,Any}("ScheduledQueryArn" => ScheduledQueryArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_scheduled_query(
    ScheduledQueryArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "DescribeScheduledQuery",
        Dict{String,Any}(
            mergewith(
                _merge, Dict{String,Any}("ScheduledQueryArn" => ScheduledQueryArn), params
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    execute_scheduled_query(invocation_time, scheduled_query_arn)
    execute_scheduled_query(invocation_time, scheduled_query_arn, params::Dict{String,<:Any})

 You can use this API to run a scheduled query manually.

# Arguments
- `invocation_time`: The timestamp in UTC. Query will be run as if it was invoked at this
  timestamp.
- `scheduled_query_arn`: ARN of the scheduled query.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ClientToken"`: Not used.
"""
function execute_scheduled_query(
    InvocationTime, ScheduledQueryArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return timestream_query(
        "ExecuteScheduledQuery",
        Dict{String,Any}(
            "InvocationTime" => InvocationTime,
            "ScheduledQueryArn" => ScheduledQueryArn,
            "ClientToken" => string(uuid4()),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function execute_scheduled_query(
    InvocationTime,
    ScheduledQueryArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "ExecuteScheduledQuery",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "InvocationTime" => InvocationTime,
                    "ScheduledQueryArn" => ScheduledQueryArn,
                    "ClientToken" => string(uuid4()),
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_scheduled_queries()
    list_scheduled_queries(params::Dict{String,<:Any})

Gets a list of all scheduled queries in the caller's Amazon account and Region.
ListScheduledQueries is eventually consistent.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of items to return in the output. If the total number
  of items available is more than the value specified, a NextToken is provided in the output.
  To resume pagination, provide the NextToken value as the argument to the subsequent call to
  ListScheduledQueriesRequest.
- `"NextToken"`:  A pagination token to resume pagination.
"""
function list_scheduled_queries(; aws_config::AbstractAWSConfig=global_aws_config())
    return timestream_query(
        "ListScheduledQueries"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_scheduled_queries(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return timestream_query(
        "ListScheduledQueries",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_tags_for_resource(resource_arn)
    list_tags_for_resource(resource_arn, params::Dict{String,<:Any})

List all tags on a Timestream query resource.

# Arguments
- `resource_arn`: The Timestream resource with tags to be listed. This value is an Amazon
  Resource Name (ARN).

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of tags to return.
- `"NextToken"`: A pagination token to resume pagination.
"""
function list_tags_for_resource(
    ResourceARN; aws_config::AbstractAWSConfig=global_aws_config()
)
    return timestream_query(
        "ListTagsForResource",
        Dict{String,Any}("ResourceARN" => ResourceARN);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_tags_for_resource(
    ResourceARN,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "ListTagsForResource",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ResourceARN" => ResourceARN), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    prepare_query(query_string)
    prepare_query(query_string, params::Dict{String,<:Any})

A synchronous operation that allows you to submit a query with parameters to be stored by
Timestream for later running. Timestream only supports using this operation with the
PrepareQueryRequestValidateOnly set to true.

# Arguments
- `query_string`: The Timestream query string that you want to use as a prepared statement.
  Parameter names can be specified in the query string @ character followed by an identifier.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ValidateOnly"`: By setting this value to true, Timestream will only validate that the
  query string is a valid Timestream query, and not store the prepared query for later use.
"""
function prepare_query(QueryString; aws_config::AbstractAWSConfig=global_aws_config())
    return timestream_query(
        "PrepareQuery",
        Dict{String,Any}("QueryString" => QueryString);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function prepare_query(
    QueryString,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "PrepareQuery",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("QueryString" => QueryString), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    query(query_string)
    query(query_string, params::Dict{String,<:Any})

 Query is a synchronous operation that enables you to run a query against your Amazon
Timestream data. Query will time out after 60 seconds. You must update the default timeout
in the SDK to support a timeout of 60 seconds. See the code sample for details.  Your query
request will fail in the following cases:    If you submit a Query request with the same
client token outside of the 5-minute idempotency window.     If you submit a Query request
with the same client token, but change other parameters, within the 5-minute idempotency
window.     If the size of the row (including the query metadata) exceeds 1 MB, then the
query will fail with the following error message:   Query aborted as max page response size
has been exceeded by the output result row     If the IAM principal of the query initiator
and the result reader are not the same and/or the query initiator and the result reader do
not have the same query string in the query requests, the query will fail with an Invalid
pagination token error.

# Arguments
- `query_string`:  The query to be run by Timestream.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ClientToken"`:  Unique, case-sensitive string of up to 64 ASCII characters specified
  when a Query request is made. Providing a ClientToken makes the call to Query idempotent.
  This means that running the same query repeatedly will produce the same result. In other
  words, making multiple identical Query requests has the same effect as making a single
  request. When using ClientToken in a query, note the following:     If the Query API is
  instantiated without a ClientToken, the Query SDK generates a ClientToken on your behalf.
  If the Query invocation only contains the ClientToken but does not include a NextToken,
  that invocation of Query is assumed to be a new query run.   If the invocation contains
  NextToken, that particular invocation is assumed to be a subsequent invocation of a prior
  call to the Query API, and a result set is returned.    After 4 hours, any request with the
  same ClientToken is treated as a new request.
- `"MaxRows"`:  The total number of rows to be returned in the Query output. The initial
  run of Query with a MaxRows value specified will return the result set of the query in two
  cases:    The size of the result is less than 1MB.   The number of rows in the result set
  is less than the value of maxRows.   Otherwise, the initial invocation of Query only
  returns a NextToken, which can then be used in subsequent calls to fetch the result set. To
  resume pagination, provide the NextToken value in the subsequent command. If the row size
  is large (e.g. a row has many columns), Timestream may return fewer rows to keep the
  response size from exceeding the 1 MB limit. If MaxRows is not provided, Timestream will
  send the necessary number of rows to meet the 1 MB limit.
- `"NextToken"`:  A pagination token used to return a set of results. When the Query API is
  invoked using NextToken, that particular invocation is assumed to be a subsequent
  invocation of a prior call to Query, and a result set is returned. However, if the Query
  invocation only contains the ClientToken, that invocation of Query is assumed to be a new
  query run.  Note the following when using NextToken in a query:   A pagination token can be
  used for up to five Query invocations, OR for a duration of up to 1 hour – whichever
  comes first.   Using the same NextToken will return the same set of records. To keep
  paginating through the result set, you must to use the most recent nextToken.   Suppose a
  Query invocation returns two NextToken values, TokenA and TokenB. If TokenB is used in a
  subsequent Query invocation, then TokenA is invalidated and cannot be reused.   To request
  a previous result set from a query after pagination has begun, you must re-invoke the Query
  API.   The latest NextToken should be used to paginate until null is returned, at which
  point a new NextToken should be used.    If the IAM principal of the query initiator and
  the result reader are not the same and/or the query initiator and the result reader do not
  have the same query string in the query requests, the query will fail with an Invalid
  pagination token error.
"""
function query(QueryString; aws_config::AbstractAWSConfig=global_aws_config())
    return timestream_query(
        "Query",
        Dict{String,Any}("QueryString" => QueryString, "ClientToken" => string(uuid4()));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function query(
    QueryString,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "Query",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "QueryString" => QueryString, "ClientToken" => string(uuid4())
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    tag_resource(resource_arn, tags)
    tag_resource(resource_arn, tags, params::Dict{String,<:Any})

Associate a set of tags with a Timestream resource. You can then activate these
user-defined tags so that they appear on the Billing and Cost Management console for cost
allocation tracking.

# Arguments
- `resource_arn`: Identifies the Timestream resource to which tags should be added. This
  value is an Amazon Resource Name (ARN).
- `tags`: The tags to be assigned to the Timestream resource.

"""
function tag_resource(ResourceARN, Tags; aws_config::AbstractAWSConfig=global_aws_config())
    return timestream_query(
        "TagResource",
        Dict{String,Any}("ResourceARN" => ResourceARN, "Tags" => Tags);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function tag_resource(
    ResourceARN,
    Tags,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "TagResource",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("ResourceARN" => ResourceARN, "Tags" => Tags),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    untag_resource(resource_arn, tag_keys)
    untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any})

Removes the association of tags from a Timestream query resource.

# Arguments
- `resource_arn`: The Timestream resource that the tags will be removed from. This value is
  an Amazon Resource Name (ARN).
- `tag_keys`: A list of tags keys. Existing tags of the resource whose keys are members of
  this list will be removed from the Timestream resource.

"""
function untag_resource(
    ResourceARN, TagKeys; aws_config::AbstractAWSConfig=global_aws_config()
)
    return timestream_query(
        "UntagResource",
        Dict{String,Any}("ResourceARN" => ResourceARN, "TagKeys" => TagKeys);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function untag_resource(
    ResourceARN,
    TagKeys,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "UntagResource",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("ResourceARN" => ResourceARN, "TagKeys" => TagKeys),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_scheduled_query(scheduled_query_arn, state)
    update_scheduled_query(scheduled_query_arn, state, params::Dict{String,<:Any})

Update a scheduled query.

# Arguments
- `scheduled_query_arn`: ARN of the scheuled query.
- `state`: State of the scheduled query.

"""
function update_scheduled_query(
    ScheduledQueryArn, State; aws_config::AbstractAWSConfig=global_aws_config()
)
    return timestream_query(
        "UpdateScheduledQuery",
        Dict{String,Any}("ScheduledQueryArn" => ScheduledQueryArn, "State" => State);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_scheduled_query(
    ScheduledQueryArn,
    State,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return timestream_query(
        "UpdateScheduledQuery",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "ScheduledQueryArn" => ScheduledQueryArn, "State" => State
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end


text:
export AdamsMoulton

struct AdamsMoulton <: AbstractStateContractorName
    steps::Int
end

mutable struct AdamsMoultonFunctor{S} <: AbstractStateContractor
    f!
    Jx!
    Jp!
    nx
    np
    method_step::Int64
    η::Interval{Float64}
    μX::Vector{S}
    ρP::Vector{S}
    Dk::Vector{S}
    Jxsto::FixedCircularBuffer{Matrix{S}}
    Jpsto::FixedCircularBuffer{Matrix{S}}
    Jxsum::Vector{S}
    Jpsum::Matrix{S}
    Jxvec::Vector{S}
    Jpvec::Vector{S}
    fval::FixedCircularBuffer{Vector{Float64}}
    fk_apriori::FixedCircularBuffer{Vector{S}}
    Rk::Vector{S}
    Y0::Matrix{Float64}
    Y::Matrix{Float64}
    Jxmid_sto::Matrix{S}
    precond::LinearAlgebra.LU{Float64,Array{Float64,2}}
    JxAff::Matrix{S}
    YJxAff::Matrix{S}
    YJxΔx::Vector{S}
    Xj_delta::Vector{S}
    Ysumx::Vector{S}
    YsumP::Matrix{S}
    YJpΔp::Vector{S}
    coeffs::Vector{Float64}
    Δⱼ₊₁::Vector{S}
    is_adaptive::Bool
    γ::Float64
    lohners_start::LohnersFunctor
    A_Q::FixedCircularBuffer{Matrix{Float64}}
    A_inv::FixedCircularBuffer{Matrix{Float64}}
    Δ::FixedCircularBuffer{Vector{S}}
    X::FixedCircularBuffer{Vector{S}}
    xval::FixedCircularBuffer{Vector{Float64}}
end

function AdamsMoultonFunctor(f::F, Jx!::JX, Jp!::JP, nx::Int, np::Int, s::S,
                             t::T, steps::Int, lohners_start) where {F,JX,JP,S,T}
    η = Interval{T}(0.0,1.0)
    μX = zeros(S, nx)
    ρP = zeros(S, np)

    method_step = steps
    Dk = zeros(S, nx)

    lu_mat = zeros(nx, nx)
    for i = 1:nx
        lu_mat[i,i] = 1.0
    end
    precond = lu(lu_mat)
    Y0 = zeros(nx, nx)
    Y = zeros(nx, nx)
    Jxmid_sto = zeros(S, nx, nx)
    YJxAff = zeros(S, nx, nx)
    JxAff = zeros(S, nx, nx)
    Xj_delta = zeros(S, nx)
    YJxΔx = zeros(S, nx)
    Ysumx = zeros(S, nx)
    YsumP = zeros(S, nx, nx)
    YJpΔp = zeros(S, nx)

    Jxsto = FixedCircularBuffer{Matrix{S}}(method_step)
    Jpsto = FixedCircularBuffer{Matrix{S}}(method_step)
    for i = 1:method_step
        push!(Jxsto, zeros(S, nx, nx))
        push!(Jpsto, zeros(S, nx, np))
    end
    Jxsum = zeros(S, nx)
    Jpsum = zeros(S, nx, nx)
    Jxvec = zeros(S, nx)
    Jpvec = zeros(S, nx)

    fval = FixedCircularBuffer{Vector{Float64}}(method_step)
    fk_apriori = FixedCircularBuffer{Vector{S}}(method_step)
    A_Q = FixedCircularBuffer{Matrix{Float64}}(method_step)
    A_inv = FixedCircularBuffer{Matrix{Float64}}(method_step)
    Δ = FixedCircularBuffer{Vector{S}}(method_step)
    X = FixedCircularBuffer{Vector{S}}(method_step)
    xval = FixedCircularBuffer{Vector{Float64}}(method_step)
    for i = 1:method_step
        push!(xval, zeros(Float64, nx))
        push!(fval, zeros(Float64, nx))
        push!(fk_apriori, zeros(S, nx))
        push!(A_Q, Float64.(Matrix(I, nx, nx)))
        push!(A_inv, Float64.(Matrix(I, nx, nx)))
        push!(X, zeros(S, nx))
        push!(Δ, zeros(S, nx))
    end

    Rk = zeros(S, nx)
    coeffs = zeros(Float64, method_step + 1)
    Δⱼ₊₁ = zeros(S, nx)

    is_adaptive = false
    γ = 0.0

    AdamsMoultonFunctor{S}(f, Jx!, Jp!, nx, np, method_step, η, μX, ρP,
                           Dk, Jxsto, Jpsto, Jxsum, Jpsum, Jxvec, Jpvec, fval,
                           fk_apriori, Rk, Y0, Y, Jxmid_sto, precond, JxAff, YJxAff,
                           YJxΔx, Xj_delta, Ysumx, YsumP, YJpΔp, coeffs, Δⱼ₊₁,
                           is_adaptive, γ, lohners_start, A_Q, A_inv,
                           Δ, X, xval)
end

function compute_coefficients!(d::AdamsMoultonFunctor{S}, h::Float64, t::Float64, s::Int) where S
    if !d.is_adaptive
        if s == 1
            d.coeffs[1] = 1.0
            d.coeffs[2] = 0.5
        elseif s == 2
            d.coeffs[1] = 0.5
            d.coeffs[2] = 0.5
            d.coeffs[3] = -1.0/12.0
        elseif s == 3
            d.coeffs[1] = 5.0/12.0
            d.coeffs[2] = 8.0/12.0
            d.coeffs[3] = -1.0/12.0
            d.coeffs[4] = -1.0/24.0
        elseif s == 4
            d.coeffs[1] = 9.0/24.0
            d.coeffs[2] = 19.0/24.0
            d.coeffs[3] = -5.0/24.0
            d.coeffs[4] = 1.0/24.0
            d.coeffs[5] = -19.0/720.0
        else
            #compute_fixed_higher_coeffs!(d, s)
        end
    else
        #compute_adaptive_coeffs!(d, h, t, s)
    end

    d.γ = d.coeffs[s + 1]

    return nothing
end

function compute_Rk!(d::AdamsMoultonFunctor{T}, contract::ContractorStorage{T},
                     h::Float64, s::Int) where T<:Number

    #println("------------")
    #println("-compute_Rk-")
    #println("------------")

    coeff = d.γ*h^(d.method_step + 1)
    cycle_copyto!(d.fk_apriori, contract.fk_apriori, contract.step_count - 1)

    @__dot__ d.Rk = d.fk_apriori[1]
    #println("d.Rk[1] = $(d.Rk)")
    for i = 2:s
        @__dot__ d.Rk = d.Rk ∪ d.fk_apriori[i]
        #println("d.fk_apriori[$i] = $(d.fk_apriori[i])")
        #println(" d.Rk[$i] = $(d.Rk)")
    end
    #@show d.γ
    #@show h^(d.method_step + 1)
    @__dot__ d.Rk *= coeff

    return nothing
end

# TODO: Check block
function compute_real_sum!(d::AdamsMoultonFunctor{T}, contract::ContractorStorage{T},
                           result::StepResult{T}, h::Float64, t::Float64,
                           s::Int) where T<:Number

    old_xval = mid.(contract.Xj_0)
    cycle_eval!(d.f!, d.fval, old_xval, contract.pval, t)
    @__dot__ d.Dk = old_xval
    #@show old_xval
    for i = 1:s
        @__dot__ d.Dk += h*d.coeffs[i]*d.fval[i]
        #println("$i-th coeffs = $(d.coeffs[i]), fvals = $(d.fval[i])")
    end
    return nothing
end

function compute_jacobian_sum!(d::AdamsMoultonFunctor{T},
                           contract::ContractorStorage{T},
                           h::Float64, t::Float64, s::Int) where T<:Number

    μ!(d.μX, contract.Xj_0, contract.xval, d.η)
    ρ!(d.ρP, contract.P, contract.pval, d.η)
    cycle_eval!(d.Jx!, d.Jxsto, d.μX, d.ρP, t)
    cycle_eval!(d.Jp!, d.Jpsto, d.μX, d.ρP, t)

    #println("------------")
    #println("-compute_jacobian_sum!-")
    #println("------------")
    #@show d.Jxsto
    #@show d.Jpsto

    @__dot__ d.JxAff = d.Jxsto[1]

    #@show d.JxAff

    # contract.Xj_apriori GOOD
    # d.Xj_delta GOOD
    @__dot__ d.Xj_delta = contract.Xj_apriori - mid(contract.Xj_apriori)

    # TODO: CHECK RIGHT DELTAS...
    d.Jxsum = (h*d.coeffs[1])*d.Jxsto[1]*d.Xj_delta
    @show h, d.coeffs[1], d.Jxsto[1], d.Xj_delta
    if s > 1
        d.Jxsum += ((d.η*I + h*d.coeffs[2]*d.Jxsto[2])*contract.A_Q[1])*contract.Δ[1]
        @show h, d.coeffs[2], d.Jxsto[2], contract.A_Q[1], contract.Δ[1]
    end
    for i = 3:s
        d.Jxsum += (h*d.coeffs[i])*(d.Jxsto[i]*contract.A_Q[i])*contract.Δ[i]
        #@show h, d.coeffs[i], d.Jxsto[i], contract.A_Q[i], contract.Δ[i]
    end

    # JpSum is correct
    @__dot__ d.Jpsum = h*d.coeffs[1]*d.Jpsto[1]
    for i = 2:s
        @__dot__ d.Jpsum += h*d.coeffs[i]*d.Jpsto[i]
    end

    return nothing
end

function compute_X!(d::AdamsMoultonFunctor{T}, contract::ContractorStorage{S}) where {S, T<:Number}

    #println("------------")
    #println("-compute_X!-")
    #println("------------")

    #mul!(d.Jxvec, d.JxAff, d.Xj_delta)
    mul!(d.Jpvec, d.Jpsum, contract.rP)

    #@show d.Jxvec
    @show d.Jxsum
    # d.Jpvec is correct...
    @show d.Jpvec
    @show d.Dk
    @show d.Rk
    #@__dot__ contract.X_computed = d.Jxvec + d.Jxsum + d.Jpvec + d.Dk + d.Rk
    @__dot__ contract.X_computed = d.Jxsum + d.Jpvec + d.Dk + d.Rk
    @show contract.X_computed
    @show contract.Xj_apriori
    @__dot__ contract.X_computed = contract.X_computed ∩ contract.Xj_apriori
    @show contract.X_computed
    return nothing
end

function compute_xval!(d::AdamsMoultonFunctor{T}, contract::ContractorStorage{S}, t) where {S, T<:Number}
    @__dot__ contract.xval_computed = mid(contract.X_computed)
    @show contract.xval_computed
    d.f!(d.fval[1], contract.xval_computed, contract.pval, t)
    return nothing
end

function compute_Ainv!(d::AdamsMoultonFunctor{T}, contract::ContractorStorage{S}, s::Int) where {S, T<:Number}
    if s > 1
        mul!(d.Jxmid_sto, d.Jxsto[1], contract.A_Q[2])
        @__dot__ contract.B = mid(d.Jxmid_sto)
        calculateQ!(contract.A_Q[1], contract.B, d.nx)
        calculateQinv!(contract.A_inv[1], contract.A_Q[1], d.nx)
    end
    return nothing
end

function update_delta!(d::AdamsMoultonFunctor{T}, contract::ContractorStorage{S}, s::Int) where {S, T<:Number}
    println("update delta for s = $s order")
    if s > 0
        println("ran delta update...")
        @show d.Y0
        @show contract.A_Q[2]
        d.Y = I - d.Y0*contract.A_Q[2]
        @show d.Y
        d.precond = lu!(d.Y)
        d.YJxAff = d.precond\d.JxAff
        @show d.YJxAff
        mul!(d.YJxΔx, d.YJxAff, d.Xj_delta)
        @show d.YJxΔx
        d.Ysumx = d.precond\d.Jxsum
        d.YsumP = d.precond\d.Jpsum
        @show d.Ysumx
        @show d.YsumP
        mul!(d.YJpΔp, d.YsumP, contract.rP)
        @show d.YJpΔp
        @__dot__ d.Δⱼ₊₁ = d.YJxΔx + d.Ysumx + d.YJpΔp
        @show d.Δⱼ₊₁
    end
    return nothing
end

function store_starting_buffer!(d::AdamsMoultonFunctor{T},
                                contract::ContractorStorage{T},
                                result::StepResult{T}, t::Float64) where T

    count = contract.step_count - 1
    cycle_copyto!(d.X, result.Xⱼ, count)
    cycle_copyto!(d.xval, result.xⱼ, count)
    cycle_copyto!(d.fk_apriori, contract.fk_apriori, count)
    cycle_copyto!(d.Δ, result.Δ[1], count)
    cycle_copyto!(d.A_Q, result.A_Q[1], count)
    cycle_copyto!(d.A_inv, result.A_inv[1], count)

    # update Jacobian storage
    μ!(d.μX, result.Xⱼ, result.xⱼ, d.η)
    ρ!(d.ρP, contract.P, contract.pval, d.η)

    cycle_eval!(d.Jx!, d.Jxsto, d.μX, d.ρP, t)
    cycle_eval!(d.Jp!, d.Jpsto, d.μX, d.ρP, t)
    cycle_eval!(d.f!, d.fval, result.xⱼ, contract.pval, t)

    return nothing
end

function (d::AdamsMoultonFunctor{T})(contract::ContractorStorage{S},
                                  result::StepResult{S},
                                  count::Int) where {S, T<:Number}

    println("\n BEGIN MAIN - step: $(contract.step_count-1), method step: $(d.method_step) \n")

    t = contract.times[1]
    s = min(contract.step_count-1, d.method_step)
    #@show s
    #@show d.method_step
    if s < d.method_step - 1
        #println("---- LOHNERS STEP -----")
        d.lohners_start(contract, result, count)
        (count == 0) && store_starting_buffer!(d, contract, result, t)
        return nothing
    end

    #println("---- PILMS STEP -----")
    h = contract.hj_computed
    #@show contract.hj_computed
    compute_coefficients!(d, h, t, s)
    compute_Rk!(d, contract, h, s)
    compute_real_sum!(d, contract, result, h, t, s)
    compute_jacobian_sum!(d, contract, h, t, s)
    compute_X!(d, contract)
    compute_xval!(d, contract, t)
    compute_Ainv!(d, contract, s)
    update_delta!(d, contract, s)
    return nothing
end

function get_Δ(d::AdamsMoultonFunctor)
    if true
        return copy(get_Δ(d.lohners_start))
    end
    return copy(d.Δⱼ₊₁)
end
function advance_contractor_buffer!(d::AdamsMoultonFunctor)
    return nothing
end

function state_contractor(m::AdamsMoulton, f, Jx!, Jp!, nx, np, style, s, h)
    lohners_functor = state_contractor(LohnerContractor{m.steps}(), f, Jx!, Jp!, nx, np, style, s, h)
    AdamsMoultonFunctor(f, Jx!, Jp!, nx, np, style, s, m.steps, lohners_functor)
end
state_contractor_k(m::AdamsMoulton) = m.steps + 1
state_contractor_γ(m::AdamsMoulton) = 0.0
state_contractor_steps(m::AdamsMoulton) = m.steps
state_contractor_integrator(m::AdamsMoulton) = CVODE_Adams()

ext: jl


text:
using Documenter, ResultTypes

makedocs(;
    modules=[ResultTypes],
    format=:html,
    pages=[
        "Home" => "index.md",
        "API" => "pages/api.md",
    ],
    repo="https://github.com/iamed2/ResultTypes.jl/blob/{commit}{path}#L{line}",
    sitename="ResultTypes.jl",
    authors="Eric Davies",
    assets=[],
)

deploydocs(;
    repo="github.com/iamed2/ResultTypes.jl",
    target="build",
    julia="0.6",
    deps=nothing,
    make=nothing,
)


text:
#########
# PartialDerivative{k}
# takes a partial derivative in the k-th index.
#########

struct PartialDerivative{k,T,Ax<:Inclusion} <: LazyQuasiMatrix{T}
    axis::Ax
end

PartialDerivative{k,T}(axis::Inclusion) where {k,T} = PartialDerivative{k,T,typeof(axis)}(axis)
PartialDerivative{k,T}(domain) where {k,T} = PartialDerivative{k,T}(Inclusion(domain))
PartialDerivative{k}(axis) where k = PartialDerivative{k,eltype(eltype(axis))}(axis)

axes(D::PartialDerivative) = (D.axis, D.axis)
==(a::PartialDerivative{k}, b::PartialDerivative{k}) where k = a.axis == b.axis
copy(D::PartialDerivative{k}) where k = PartialDerivative{k}(copy(D.axis))

^(D::PartialDerivative, k::Integer) = ApplyQuasiArray(^, D, k)

abstract type MultivariateOrthogonalPolynomial{d,T} <: Basis{T} end
const BivariateOrthogonalPolynomial{T} = MultivariateOrthogonalPolynomial{2,T}
const BlockOneTo = BlockRange{1,Tuple{OneTo{Int}}}

getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, JR::BlockOneTo) where D = error("Overload")
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, J::Block{1}) where D = P[xy, Block.(OneTo(Int(J)))][J]
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, JR::BlockRange{1}) where D = P[xy, Block.(OneTo(Int(maximum(JR))))][JR]
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, Jj::BlockIndex{1}) where D = P[xy, block(Jj)][blockindex(Jj)]
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, j::Integer) where D = P[xy, findblockindex(axes(P,2), j)]
getindex(P::MultivariateOrthogonalPolynomial{D}, xy::StaticVector{D}, jr::AbstractVector{<:Integer}) where D = P[xy, Block.(OneTo(Int(findblock(axes(P,2), maximum(jr)))))][jr]

const FirstInclusion = BroadcastQuasiVector{<:Any, typeof(first), <:Tuple{Inclusion}}
const LastInclusion = BroadcastQuasiVector{<:Any, typeof(last), <:Tuple{Inclusion}}

function Base.broadcasted(::LazyQuasiArrayStyle{2}, ::typeof(*), x::FirstInclusion, P::MultivariateOrthogonalPolynomial)
    axes(x,1) == axes(P,1) || throw(DimensionMismatch())
    P*jacobimatrix(Val(1), P)
end

function Base.broadcasted(::LazyQuasiArrayStyle{2}, ::typeof(*), x::LastInclusion, P::MultivariateOrthogonalPolynomial)
    axes(x,1) == axes(P,1) || throw(DimensionMismatch())
    P*jacobimatrix(Val(2), P)
end

"""
   forwardrecurrence!(v, A, B, C, (x,y))

evaluates the bivaraite orthogonal polynomials at points `(x,y)` ,
where `A`, `B`, and `C` are `AbstractVector`s containing the recurrence coefficients
matrices. In particular, note that for any OPs we have

    P[N+1,x] = (A[N]* [x*I; y*I] + B[N]) * P[N,x] - C[N] * P[N-1,x]

where A[N] is (N+1) x 2N, B[N] and C[N] are (N+1) x N.

"""
# function forwardrecurrence!(v::AbstractBlockVector{T}, A::AbstractVector, B::AbstractVector, C::AbstractVector, xy) where T
#     N = blocklength(v)
#     N == 0 && return v
#     length(A)+1 ≥ N && length(B)+1 ≥ N && length(C)+1 ≥ N || throw(ArgumentError("A, B, C must contain at least $(N-1) entries"))
#     v[Block(1)] .= one(T)
#     N = 1 && return v
#     p_1 = view(v,Block(2))
#     p_0 = view(v,Block(1))
#     mul!(p_1, B[1], p_0)
#     xy_muladd!(xy, A[1], p_0, one(T), p_1)

#     @inbounds for n = 2:N-1
#         p_2 = view(v,Block(n+1))
#         mul!(p_2, B[n], p_1)
#         xy_muladd!(xy, A[n], p_1, one(T), p_2)
#         muladd!(-one(T), C[n], p_0, one(T), p_2)
#         p_1,p_0 = p_2,p_1
#     end
#     v
# end

# forwardrecurrence(N::Block{1}, A::AbstractVector, B::AbstractVector, C::AbstractVector, xy) =
#     forwardrecurrence!(PseudoBlockVector{promote_type(eltype(eltype(A)),eltype(eltype(B)),eltype(eltype(C)),eltype(xy))}(undef, 1:Int(N)), A, B, C, xy)

# use block expansion
ContinuumArrays.transform_ldiv(V::SubQuasiArray{<:Any,2,<:MultivariateOrthogonalPolynomial,<:Tuple{Inclusion,BlockSlice{BlockOneTo}}}, B::AbstractQuasiArray, _) =
    factorize(V) \ B

factorize(::SubQuasiArray{<:Any,2,<:MultivariateOrthogonalPolynomial,<:Tuple{<:Inclusion,<:BlockSlice{BlockRange1{OneTo{Int}}}}}) = error("Overload")
function factorize(V::SubQuasiArray{<:Any,2,<:MultivariateOrthogonalPolynomial,<:Tuple{Inclusion,AbstractVector{Int}}})
    P = parent(V)
    _,jr = parentindices(V)
    J = findblock(axes(P,2),maximum(jr))
    ProjectionFactorization(factorize(P[:,Block.(OneTo(Int(J)))]), jr)
end

# Make sure block structure matches. Probably should do this for all block mul
QuasiArrays.mul(A::MultivariateOrthogonalPolynomial, b::AbstractVector) =
    ApplyQuasiArray(*, A, PseudoBlockVector(b, (axes(A,2),)))


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

mutable struct ResourceSkuCapacity <: SwaggerModel
    minimum::Any # spec type: Union{ Nothing, Int64 } # spec name: minimum
    maximum::Any # spec type: Union{ Nothing, Int64 } # spec name: maximum
    default::Any # spec type: Union{ Nothing, Int64 } # spec name: default
    scaleType::Any # spec type: Union{ Nothing, String } # spec name: scaleType

    function ResourceSkuCapacity(;minimum=nothing, maximum=nothing, default=nothing, scaleType=nothing)
        o = new()
        validate_property(ResourceSkuCapacity, Symbol("minimum"), minimum)
        setfield!(o, Symbol("minimum"), minimum)
        validate_property(ResourceSkuCapacity, Symbol("maximum"), maximum)
        setfield!(o, Symbol("maximum"), maximum)
        validate_property(ResourceSkuCapacity, Symbol("default"), default)
        setfield!(o, Symbol("default"), default)
        validate_property(ResourceSkuCapacity, Symbol("scaleType"), scaleType)
        setfield!(o, Symbol("scaleType"), scaleType)
        o
    end
end # type ResourceSkuCapacity

const _property_map_ResourceSkuCapacity = Dict{Symbol,Symbol}(Symbol("minimum")=>Symbol("minimum"), Symbol("maximum")=>Symbol("maximum"), Symbol("default")=>Symbol("default"), Symbol("scaleType")=>Symbol("scaleType"))
const _property_types_ResourceSkuCapacity = Dict{Symbol,String}(Symbol("minimum")=>"Int64", Symbol("maximum")=>"Int64", Symbol("default")=>"Int64", Symbol("scaleType")=>"String")
Base.propertynames(::Type{ ResourceSkuCapacity }) = collect(keys(_property_map_ResourceSkuCapacity))
Swagger.property_type(::Type{ ResourceSkuCapacity }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_ResourceSkuCapacity[name]))}
Swagger.field_name(::Type{ ResourceSkuCapacity }, property_name::Symbol) =  _property_map_ResourceSkuCapacity[property_name]

const _allowed_ResourceSkuCapacity_scaleType = ["Automatic", "Manual", "None"]

function check_required(o::ResourceSkuCapacity)
    true
end

function validate_property(::Type{ ResourceSkuCapacity }, name::Symbol, val)
    if name === Symbol("scaleType")
        Swagger.validate_param(name, "ResourceSkuCapacity", :enum, val, _allowed_ResourceSkuCapacity_scaleType)
    end
end


text:
function hom⁻¹(v::StaticVector)
    if isapprox(v[end], 0.0; atol = 1e-14)
        pop(v)
    else
        pop(v / v[end])
    end
end

function hom(v::StaticVector)
    push(v,1)
end


text:
# ---
# title: 155. Min Stack
# id: problem155
# author: zhwang
# date: 2022-02-15
# difficulty: Easy
# categories: Stack, Design
# link: <https://leetcode.com/problems/min-stack/description/>
# hidden: true
# ---
#
# Design a stack that supports push, pop, top, and retrieving the minimum
# element in constant time.
#
#   * push(x) -- Push element x onto stack.
#   * pop() -- Removes the element on top of the stack.
#   * top() -- Get the top element.
#   * getMin() -- Retrieve the minimum element in the stack.
#
#
#
# **Example 1:**
#
#
#
#     **Input**
#     ["MinStack","push","push","push","getMin","pop","top","getMin"]
#     [[],[-2],[0],[-3],[],[],[],[]]
#
#     **Output**
#     [null,null,null,null,-3,null,0,-2]
#
#     **Explanation**
#     MinStack minStack = new MinStack();
#     minStack.push(-2);
#     minStack.push(0);
#     minStack.push(-3);
#     minStack.getMin(); // return -3
#     minStack.pop();
#     minStack.top();    // return 0
#     minStack.getMin(); // return -2
#
#
#
#
# **Constraints:**
#
#   * Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
#
#
## @lc code=start
using LeetCode
Base.@kwdef struct MinStack{V<:Number}
    nums::Vector{V} = Int[]
    min_nums::Vector{V} = Int[]
end

function Base.push!(stack::MinStack, val::Int)::Nothing
    Base.push!(stack.nums, val)
    if isempty(stack.min_nums) || val <= stack.min_nums[end]
        Base.push!(stack.min_nums, val)
    end
    return nothing
end

function Base.pop!(stack::MinStack)::Nothing
    if Base.pop!(stack.nums) == stack.min_nums[end]
        Base.pop!(stack.min_nums)
    end
    return nothing
end

top(stack::MinStack)::Int = stack.nums[end]

get_min(stack::MinStack)::Int = stack.min_nums[end]
## @lc code=end


text:
# Scalar moment file currently does not exist. Oksana needs to make it.

## Read scalar moments from a single dedicated file
# I currently created this as a dummy file
function read_scalar_moments(ds :: DataSettings)
    fPath = joinpath(data_dir(ds), "scalar_moments.csv");
    csvFile = CSV.File(fPath, header = [:name, :value],
        delim = ',', comment = commentStr);
    return csvFile |> DataFrame
end

"""
	$(SIGNATURES)

Read one scalar moments from the scalar moments file.
"""
function read_scalar_moment(ds :: DataSettings, name :: String)
    df = read_scalar_moments(ds);
    outV = df[df.name .== name, :value];
    @assert length(outV) == 1
    outVal = outV[1];
    return outVal :: Float64
end

## Fraction entering college
function frac_enter(ds :: DataSettings)
    fracEnter = read_all_from_delim_file(raw_entry_gpa_parental(ds));
    cnt = read_all_from_delim_file(raw_entry_gpa_parental(ds; momentType = :count));
    @assert check_float(fracEnter, lb = 0.45, ub = 0.65);
    ses = (fracEnter * (1.0 - fracEnter) / cnt) ^ 0.5;
    return fracEnter, ses, cnt
end

## Graduation rate (conditional on entry)
function grad_rate(ds :: DataSettings)
    gradRate = read_all_from_delim_file(raw_grad_rate_qual_gpa(ds));
    cnt = read_all_from_delim_file(raw_grad_rate_qual_gpa(ds; momentType = :count));
    @assert check_float(gradRate, lb = 0.3, ub = 0.7);
    ses = (gradRate * (1.0 - gradRate) / cnt) ^ 0.5;
    return gradRate, ses, cnt
end

## Correlation HS GPA / parental income
# in which units? +++
function corr_gpa_yp(ds :: DataSettings)
    corr = read_scalar_moment(ds, "corrGpaYp");
    @assert corr > 0.3  &&  corr < 0.8
    return corr, 0.0, 1000
    # return ScalarDeviation{Double}(name = :corrGpaYp, dataV = corr, modelV = 0.0,
    #     wtV = 1.0 ./ corr,
    #     shortStr = "corrGpaYp", longStr = "Correlation HSgpa/parental background")
end

# Number of college entrants in the sample
# Useful for computing std errors
function n_entrants(ds :: DataSettings)
    cntM = read_matrix_by_xy(count_file(ds, :fracEnter_gpM));
    cnt = round(Int, sum(cntM));
    @assert 4000 < cnt < 7_000
    return cnt
end

## Average study time
#=
We have NLSY79 moments in xls, but not 97 moments.
This is based on Babcock/Marks 2011, table 2, HERI and NSSE
For full time 4 year students. So likely a bit high

Setting `wtV = 1/dataV` makes this a percentage deviation.
=#
# function dev_mean_study_time(ds :: DataSettings)
#     dataV = mean_study_time(ds; modelUnits = true);
#     return ScalarDeviation{Double}(name = :meanStudyTime, dataV = dataV, modelV = dataV,
#         wtV = 1 ./ dataV,
#         shortStr = "meanStudyTime", longStr = "Mean study time, hours per week")
# end

# Mean study time (hours per week)
# function mean_study_time(; modelUnits :: Bool = true)
#     mst = 25.0;
#     if modelUnits
#         mst = hours_per_week_to_mtu(mst);
#     end
#     return mst
# end

## Average work hours in college
#=
No good basis right now +++
=#
# function mean_work_time(; modelUnits :: Bool = true)
#     mwt = 15.0;
#     if modelUnits
#         mwt = hours_per_week_to_mtu(mwt);
#     end
#     return mwt
# end

## Wage earned in college (per hour worked)
#=
Based on xls table "Average hourly wage" which does not seem to vary by quality
=#
# function college_wage(ds :: DataSettings; modelUnits :: Bool = true)
#     wage = 7.0;
#     if modelUnits
#         wage = dollars_data_to_model(wage, :perHour);
#     end
#     return wage
# end

# function mean_course_load(; modelUnits :: Bool = true)
#     mcl = 10;
#     if !modelUnits
#         mcl = mcl * dataCoursesPerCourse;
#     end
#     return mcl
# end

# ------------


text:
"""
    struct TemperedSampler{T} <: AbstractMCMC.AbstractSampler
        internal_sampler :: T
        Δ                :: Vector{<:Real}
        Δ_init           :: Vector{<:Integer}
        N_swap           :: Integer
        swap_strategy    :: Symbol
    end

A `TemperedSampler` struct wraps an `internal_sampler` (could just be an algorithm) alongside:
- A temperature ladder `Δ` containing a list of inverse temperatures `β`s
- The initial state of the tempered chains `Δ_init` in terms of which `β` each chain should begin at
- The number of steps between each temperature swap attempt `N_swap`
- The `swap_strategy` defining how these swaps should be carried out
"""
struct TemperedSampler{A} <: AbstractMCMC.AbstractSampler
    internal_sampler :: A
    Δ                :: Vector{<:Real}
    Δ_init           :: Vector{<:Integer}
    N_swap           :: Integer
    swap_strategy    :: Symbol
    adapt            :: Bool
    Ρ                :: Vector{AdaptiveState}
end

"""
    tempered(internal_sampler, Δ; <keyword arguments>)
    OR
    tempered(internal_sampler, Nt; <keyword arguments>)

# Arguments
- `internal_sampler` is an algorithm or sampler object to be used for underlying sampling and to apply tempering to
- The temperature schedule can be defined either explicitly or just as an integer number of temperatures, i.e. as:
    - `Δ::Vector{<:Real}` containing a sequence of 'inverse temperatures' {β₀, ..., βₙ} where 0 ≤ βₙ < ... < β₁ < β₀ = 1
        OR
    - `Nt::Integer`, specifying the number of inverse temperatures to include in a generated `Δ`
- `swap_strategy::Symbol` is the way in which temperature swaps are made, one of:
   `:standard` as in original proposed algorithm, a single randomly picked swap is proposed
   `:nonrev` alternate even/odd swaps as in Syed, Bouchard-Côté, Deligiannidis, Doucet, arXiv:1905.02939 such that a reverse swap cannot be made in immediate succession
   `:randperm` generates a permutation in order to swap in a random order
- `Δ_init::Vector{<:Integer}` is a list containing a sequence including the integers `1:length(Δ)` and determines the starting temperature of each chain
    i.e. [3, 1, 2, 4] across temperatures [1.0, 0.1, 0.01, 0.001] would mean the first chain starts at temperature 0.01, second starts at 1.0, etc.
- `N_swap::Integer` steps are carried out between each tempering swap step attempt
"""
function tempered(
    internal_sampler,
    Δ::Vector{<:Real};
    swap_strategy::Symbol = :standard,
    kwargs...
)
    return tempered(internal_sampler, check_Δ(Δ), swap_strategy; kwargs...)
end
function tempered(
    internal_sampler,
    Nt::Integer;
    swap_strategy::Symbol = :standard,
    kwargs...
)
    return tempered(internal_sampler, generate_Δ(Nt, swap_strategy), swap_strategy; kwargs...)
end
function tempered(
    internal_sampler,
    Δ::Vector{<:Real},
    swap_strategy::Symbol;
    Δ_init::Vector{<:Integer} = collect(1:length(Δ)),
    N_swap::Integer = 1,
    adapt::Bool = true,
    adapt_target::Real = 0.234,
    adapt_scale::Real = get_scaling_val(length(Δ), swap_strategy),
    adapt_step::Real = 0.66,
    kwargs...
)
    length(Δ) > 1 || error("More than one inverse temperatures must be provided.")
    N_swap >= 1 || error("This must be a positive integer.")
    Ρ = init_adaptation(Δ, adapt_target, adapt_scale, adapt_step)
    return TemperedSampler(internal_sampler, Δ, Δ_init, N_swap, swap_strategy, adapt, Ρ)
end


text:
# Autogenerated wrapper script for HiGHSstatic_jll for x86_64-w64-mingw32
export highs

JLLWrappers.@generate_wrapper_header("HiGHSstatic")
JLLWrappers.@declare_executable_product(highs)
function __init__()
    JLLWrappers.@generate_init_header()
    JLLWrappers.@init_executable_product(
        highs,
        "bin\\highs.exe",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
"""
# module InverseMatrices

# Examples

```jldoctest
julia>
```
"""
module InverseMatrices

using LinearAlgebra

export inverse

function inverse(m::Diagonal)  # Note 6 in Section 2.5.
    diagonals = diag(m)
    iszero(diagonals) ? error("Not supported!") : Diagonal(1 ./ diagonals)
end

end


text:
import Base.*

export S¹
export U1

"""
    Represents a point in a one-sphere.
"""
abstract type S¹ end

"""
    Represents a point in U(1).

field: α.
"""
struct U1 <: S¹
    r::Float64
    U1(z::Complex) = begin
        @assert(isapprox(abs(z), 1), "The magnitude must be equal to 1.")
        new(angle(z))
    end
    U1(α::Real) = begin
        #@assert(-pi ≤ α ≤ pi, "The phase angle must be in the interval [-π, π].")
        new(float(α))
    end
end

Base.angle(u::U1) = u.r
*(u1::U1, u2::U1) = U1(u1.r + u2.r)
Base.isapprox(u1::U1, u2::U1) = isapprox(u1.r, u2.r)


text:
# This file was generated, do not modify it. # hide
speedup = round(Int,minimum(slow).time / minimum(fast).time) #hide
print("**$speedup× speedup**") #hide

max_stars_repo_name: cscherrer/InformativePrior

max_issues_repo_name: cscherrer/InformativePrior

max_forks_repo_name: cscherrer/InformativePrior


text:
module Issue743

using Gridap
using LinearAlgebra
using Gridap.FESpaces
using Test

model = CartesianDiscreteModel((0,2π,0,2π),(10,10);isperiodic=(true,true))
order = 2
reffe = ReferenceFE(lagrangian,Float64,order)
V = TestFESpace(model,reffe;constraint=:zeromean)
U = TrialFESpace(V)
degree = 2*order
Ω = Triangulation(model)
dΩ = Measure(Ω,degree)
f(x) = cos(x[1])+sin(x[2])
a(u,v) = ∫( ∇(v)⋅∇(u) )*dΩ
b(v) = ∫( v*f )*dΩ
op = AffineFEOperator(a,b,U,V)
uh = solve(op)
A = get_matrix(op)
@test cond(Matrix(A)) < 1.e5
@test abs(sum(∫(uh)dΩ)) < 1.e-10

#writevtk(Ω,"results",nsubcells=10,cellfields=["uh"=>uh])

end # module


text:
mdpath, targetpath, baselinepath = ARGS
using PkgBenchmark: PkgBenchmark, baseline_result, export_markdown, target_result
group_target = PkgBenchmark.readresults(targetpath)
group_baseline = PkgBenchmark.readresults(baselinepath)
judgement = PkgBenchmark.judge(group_target, group_baseline)

function printresultmd(io, judgement)
    println(io, "# Judge result")
    export_markdown(io, judgement)
    println(io)
    println(io)
    println(io, "---")
    println(io, "# Target result")
    export_markdown(io, target_result(judgement))
    println(io)
    println(io)
    println(io, "---")
    println(io, "# Baseline result")
    export_markdown(io, baseline_result(judgement))
    println(io)
end

if mdpath == "-"
    printresultmd(stdout, judgement)
else
    open(mdpath, write = true) do io
        printresultmd(io, judgement)
    end
end


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

mutable struct AddressSpace <: SwaggerModel
    addressPrefixes::Any # spec type: Union{ Nothing, Vector{String} } # spec name: addressPrefixes

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

const _property_map_AddressSpace = Dict{Symbol,Symbol}(Symbol("addressPrefixes")=>Symbol("addressPrefixes"))
const _property_types_AddressSpace = Dict{Symbol,String}(Symbol("addressPrefixes")=>"Vector{String}")
Base.propertynames(::Type{ AddressSpace }) = collect(keys(_property_map_AddressSpace))
Swagger.property_type(::Type{ AddressSpace }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_AddressSpace[name]))}
Swagger.field_name(::Type{ AddressSpace }, property_name::Symbol) =  _property_map_AddressSpace[property_name]

function check_required(o::AddressSpace)
    true
end

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


text:
"""
INITIAL POSITIONS: (-1,0), (1,0), (0,0)
INITIAL VELOCITIES: (p1,p2), (p1,p2), (-2p1,-2p2)
"""
function generate_example_3body(p1, p2)
    [
        Particle([1., 0., 0.], [p1, p2, 0.], 1.),
        Particle([-1., 0., 0.], [p1, p2, 0.], 1.),
        Particle([-0., 0., 0.], [-2p1, -2p2, 0.])
    ]
end

function generate_example_Nbody(N)
    e = [Particle(
            2rand(Float32, 3) .- 1.,
            2rand(Float32, 3) .- 1.
            )
        for i=1:N]
end

example_figure_8 = generate_example_3body(0.347111, 0.532728)
example_seq_I_2_A = generate_example_3body(0.306893, 0.125507)

example_2body = [
    Particle([1., 0., 0.], [0., .5, 0.], 1.),
    Particle([0., 0., 0.], [0., -.5, 0.], 1.),
]


text:
module Pkg3Dev

using Pkg3
using MicroLogging

const DEFAULT_DEPOT = Ref{String}()

include("depots.jl")     # create a new depot, make a different one default, etc
include("registries.jl") # create a new registry in a depot, git push registry, etc
include("packages.jl")   # create a new package, register a package to a registry, etc
include("versions.jl")   # create a new version of a package, modify, push, etc

function __init__()
    DEFAULT_DEPOT[] = Pkg3.depots()[1]
end

end # module


text:
#this file holds functions related to data processing

#reads in a CSV type
function readSingleTypeCSV(path::String; colType=Union{Missing, String},
    streamer::Function = (p::String)->GzipDecompressorStream(open(p)))::DataFrame

  #count the number of cols
  iStream = streamer(path)
  df::DataFrame = CSV.read(iStream, strings=:raw, categorical=false, rows=2)
  close(iStream)
  nCols::Int = size(df,2)

  #set the type
  types::Dict = Dict(i=>Union{String,Missing} for i ∈ 1:nCols)
  iStream = streamer(path)
  df = CSV.read(iStream, strings=:raw, categorical=false, types=types)
  close(iStream)

  return df
end

#same as the read version only returns nothing and just checks for errors
function validateSingleTypeCSV(path::String; colType=Union{Missing, String},
  streamer::Function = (p::String)->GzipDecompressorStream(open(p)))::Nothing

  #count the number of cols

  iStream = streamer(path)
  df::DataFrame = CSV.read(iStream, strings=:raw, categorical=false, rows=2)
  close(iStream)
  nCols::Int = size(df,2)

  #set the type

  types::Dict = Dict(i=>Union{String,Missing} for i ∈ 1:nCols)
  iStream = streamer(path)
  CSV.validate(iStream, strings=:raw, categorical=false, types=types)
  close(iStream)

end

#reads in the metadata and creates type tuples
function readMetaIndex(;indexPath::String = DOCUMENTATION_PATH,
  fileName::String = META_INDEX_NAME)::DataFrame

  iStream::IOStream = open("$indexPath\\$fileName.csv")
  df::DataFrame = CSV.read(iStream, strings=:raw, categorical=false)
  close(iStream)

  return df

end

#froms the vector of Metadata Dictionaries
function formMetadata(indexPath::String = DOCUMENTATION_PATH,
  indexName::String = META_INDEX_NAME)::Vector{MetaDictionary}

  #first get a list of the paths
  indexDF::DataFrame = readMetaIndex()
  names::Vector{String} = indexDF[:name]
  dataNames::Vector{String} = indexDF[:dataName]
  NFiles::Int = length(names)

  metadata::Vector{MetaDictionary} = (MetaDictionary).(dataNames, names)

  return metadata
end

#checks for and removes metadata fields not actually in the file
function validateMetaDictionary!(meta::MetaDictionary, keeperList::Vector{Symbol}; nccsPath::String = NCCS_PATH,
  streamer::Function = I_CSV_STREAMER)::MetaDictionary

  #these are the column names that we expect
  expectedCols::Vector{Symbol} = collect(keys(meta.dictionary))

  path::String = "$nccsPath\\$(meta.dataFileName).csv.gz"
  iStream = streamer(path)
  df::DataFrame = CSV.read(iStream, strings=:raw, categorical=false, rows=2)
  close(iStream)

  #check first that the column names are correct
  actualCols::Vector{Symbol} = (s::Symbol->Symbol(lowercase(string(s)))).(names(df))

  #get the list of files we don't want
  expectedNotFound::Vector{Symbol} = setdiff(expectedCols, actualCols)
  expectedNotWanted::Vector{Symbol} = setdiff(expectedCols, keeperList)
  fieldsToRemove::Vector{Symbol} = unique([expectedNotFound; expectedNotWanted])

  #remove the offending fields
  if length(fieldsToRemove) > 0
    #=if contains(meta.dataFileName,"2009") || contains(meta.dataFileName,"2008")
      println("$(meta.dataFileName) pre: $(intersect(keys(meta.dictionary), fieldsToRemove))")
    end=#
    removeFields!(meta, fieldsToRemove)
    println("Validated $(meta.dataFileName). Removed $(length(fieldsToRemove)) fields from metadata.")
  else
    println("Validated $(meta.dataFileName).")
  end

  #=if contains(meta.dataFileName,"2009") || contains(meta.dataFileName,"2008")
    println("$(meta.dataFileName) post: $(intersect(keys(meta.dictionary), fieldsToRemove))")
  end=#

  return meta

end

function validateMetadata(metadata::Vector{MetaDictionary}; indexPath::String = DOCUMENTATION_PATH,
    keeperName::String=KEEPER_NAME)::Vector{MetaDictionary}

  metadata = deepcopy(metadata) #its hard to do this without some modifications AND copies
                                #hence err on the side of caution here

  metadata = removeDictionary(metadata, "LEGACY")
  NMeta::Int = length(metadata)

  #get list of kept columns
  iStream::IOStream = open("$indexPath\\$keeperName.csv")
  keeperDF::DataFrame = CSV.read(iStream, strings=:raw, categorical=false)
  close(iStream)
  keeperList::Vector{Symbol} = (Symbol).(keeperDF[:keeper])

  #this can take a while so multi-thread it
  println("Beginning file validation")

  futures::Vector{Future} = Vector{Future}()

  #use this to check orders
  metaNames::Vector{String} = (m::MetaDictionary->m.metaFileName).(metadata)

  #=metaDict::Dict = meta2Index(metadata)
  i2008::Int = metaDict["Core 2008 PC"]

  println("Core 2008 PC pre [$(length(metadata[i2008].metaTuples))]:
    $(keys(metadata[i2008].dictionary))")=#
  #assign and retrieve the work
  for i::Int ∈ 1:NMeta
    push!(futures, (@spawn validateMetaDictionary!(metadata[i], keeperList)))
  end
  metadata .= (fetch).(futures)

  #=
  println("Core 2008 PC post1 [$(length(metadata[i2008].metaTuples))]:
    $(keys(metadata[i2008].dictionary))")=#

  return metadata
end

#this function either forms or loads the metadata
function getMetadata(;refreshMetadata::Bool = true, metadataPath::String = DOCUMENTATION_PATH,
  metadataName::String = METADATA_NAME)

  metadataFilePath::String = "$metadataPath\\$metadataName.jls"

  #load the metadata if we don't need to redo the validation
  if refreshMetadata || !(isfile(metadataFilePath))
    metadata::Vector{MetaDictionary}= formMetadata()
    metadata = validateMetadata(metadata)

    #=  metaDict::Dict = meta2Index(metadata)
    i2008::Int = metaDict["Core 2008 PC"]

    println("Core 2008 PC post2 [$(length(metadata[i2008].metaTuples))]:
      $(keys(metadata[i2008].dictionary))")
    warn("breakpoint")=#

    oStream::IOStream = open(metadataFilePath, "w")
    serialize(oStream, metadata)
    close(oStream)
  else
    iStream::IOStream = open(metadataFilePath)
    metadata = deserialize(iStream)
    close(iStream)
  end

  return metadata
end

function preProcessData(; update::Bool=false, validateDownloads::Bool = true,
  nccsPath::String = NCCS_PATH,  refreshMetadata::Bool = true, refreshData::Bool = true)::Nothing

  #println("got here 1")
  getNCCSFiles(NCCS_PATH, update=update, #=delay=0.001,=# validate=validateDownloads)
  metadata::Vector{MetaDictionary} = getMetadata(refreshMetadata = refreshMetadata)
  loadNCCSFiles(metadata, refresh=refreshData, serializeOnly = true, mode=:parallel)

  return nothing
end

max_stars_repo_name: clintonTE/CCA

max_issues_repo_name: clintonTE/CCA

max_forks_repo_name: clintonTE/CCA


text:
julia> bool(-2:2)
5-element Bool Array:
  true
  true
 false
  true
  true

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
function getAlignKernel{T <: FloatingPoint}(:: Type{T})
        nType = T == Float64 ? "double" : "float"
        nPi = T == Float64 ? "M_PI" : "M_PI_F"

        return "
        #if defined(cl_khr_fp64)  // Khronos extension available?
        #pragma OPENCL EXTENSION cl_khr_fp64 : enable
        #elif defined(cl_amd_fp64)  // AMD extension available?
        #pragma OPENCL EXTENSION cl_amd_fp64 : enable
        #endif
        #define number $nType
        #define number8 $(nType)8
        #define PI $nPi

        #define Conc(x,y) a[y*D2 + x]
        #define Dir(x,y)  b[y*D2 + x]

        #define Newdir(x,y) out[y*D2 + x]

        static number sum(const number8 n) {
            return n.s0 + n.s1 +n.s2 + n.s3 + n.s4 + n.s5 + n.s6 + n.s7;
        }

        __kernel void align(
                      __global const number *a,
                      __global const number *b,
                      __global number *out,
                      const int D1,
                      const int D2,
                      const number attraction,
                      const number step) {

        int i = get_global_id(0);
        int j = get_global_id(1);
        int west = j-1;
        int east = j+1;
        int north = i+1;
        int south = i-1;

        if(j == 0)
            west = D2 - 1;
        if(j == D2 - 1)
            east = 0;
        if(i == D1 - 1)
            north = 0;
        if(i == 0)
            south = D1 - 1;

        // Getting the data and storing it in two eight vectors
        number direction = Dir(i, j);

        number8 conc;
        conc.s0 = Conc(south,west);
        conc.s1 = Conc(south,j   );
        conc.s2 = Conc(south,east);
        conc.s3 = Conc(i    ,east);
        conc.s4 = Conc(north,east);
        conc.s5 = Conc(north,j   );
        conc.s6 = Conc(north,west);
        conc.s7 = Conc(i    ,west);

        number8 dir;
        dir.s0 = Dir(south,west);
        dir.s1 = Dir(south,j   );
        dir.s2 = Dir(south,east);
        dir.s3 = Dir(i    ,east);
        dir.s4 = Dir(north,east);
        dir.s5 = Dir(north,j   );
        dir.s6 = Dir(north,west);
        dir.s7 = Dir(i    ,west);

        // Calculate
        number8 diff;

        diff = direction - dir;
        diff = fmod(diff, PI);
        diff = -sin(2 * diff);

        number dtheta = sum(conc * diff);

        dtheta = attraction * dtheta / 8;
        number ndir = direction + dtheta * step;

        Newdir(i,j) = fmod(ndir,PI);

    }
    "
end

function alignCL!{T <: FloatingPoint}(
    a_buff, b_buff,
    out_buff,
    attraction :: T, step :: T, d1 :: Int64, d2 :: Int64,
    ctx, queue, program)

    k = Kernel(program, "align")

    call(queue, k, (d1,d2), nothing, a_buff, b_buff, out_buff, int32(d1), int32(d2), attraction, step)
end


text:
include("../../../../math/common/sparse/src/sparse_module.jl")

module mtx
using ..sparse

# mtrx is a file format for storing sparse matrices
# coming from https://sparse.tamu.edu/?per_page=100
#
# there is a heading which seems to be 13 lines
#
# the first non header row contains the number of cols, rows and nnz
#
# extracted files consist of 3 cols
# first col = column index in 1 based indexing
# second col = row index in 1 based indexing
# third col = data
#
# there is a space between the cols

struct MtxBody
    n_row::Int
    n_col::Int
    nnz::Int
    row_index::Vector{Int}
    col_index::Vector{Int}
    data::Vector{Float64}
end

struct MtxFileContent{T}
    header::Vector{T}
    body::MtxBody
end

function read_mtx(url::String)
    iostr = open(url, "r");
    iobuff = read(iostr, String);
    close(iostr);

    mtx_content = parse_mtx(iobuff)
    return mtx_content
end

function find_first_nonheader_index(lines)
    Ll = length(lines)
    kk = 0
    for outer kk = 1:Ll
        line = strip( lines[kk] )
        if line[1] == '%'
            continue
        else
            break
        end
    end
    first_non_header_index = kk
    return first_non_header_index
end

function extract_header(lines, first_non_header_index)
    header = lines[1:first_non_header_index-1]
    return header
end

function interpret_body(lines, first_non_header_index)

    L = length(lines)-1

    # handle first row separately
    line    = lines[first_non_header_index]
    strvec  = split(line, " ")
    n_row   = parse(Int, strvec[1])
    n_col   = parse(Int, strvec[2])
    nnz     = parse(Int, strvec[3])

    row_index = zeros(Int, nnz)
    col_index = zeros(Int, nnz)
    data      = zeros(Float64, nnz)

    ii = 0
    for kk = (first_non_header_index+1):L
        ii += 1

        strvec = split(lines[kk], " ")
        rr     = parse(Int, strvec[1])
        cc     = parse(Int, strvec[2])
        dd     = parse(Float64, strvec[3])

        row_index[ii]   = rr
        col_index[ii]   = cc
        data[ii]        = dd
    end

    body = MtxBody(n_row, n_col, nnz, row_index, col_index, data)
    return body
end

function parse_mtx(iobuff)

    mtx_content = iobuff
    lines       = split(iobuff, "\n")

    first_non_header_index = find_first_nonheader_index(lines)
    header = extract_header(lines, first_non_header_index)
    body   = interpret_body(lines, first_non_header_index)

    mtx_content = MtxFileContent(header, body)
    return mtx_content
end

function mtx_to_sparse_csc(mtx_content::MtxFileContent)

    return sparse.SparseMatrixCSC(
        mtx_content.body.n_row,
        mtx_content.body.n_col,
        mtx_content.body.data,
        mtx_content.body.row_index,
        mtx_content.body.col_index)

end

end # module

max_stars_repo_name: HomoModelicus/julia

max_issues_repo_name: HomoModelicus/julia

max_forks_repo_name: HomoModelicus/julia


text:
include(joinpath(@__DIR__, "bind_generator.jl"))

# Read in the API definition macros from the definitions file
defs = read(joinpath(@__DIR__, "api_defs.jl"), String)
# Have Julia expand/run the @bind macro to generate expressions for all of the functions
exprs = Base.include_string(@__MODULE__, "@macroexpand1 begin\n" * defs * "\nend", "api_defs.jl")
# Definitions which are not automatically generated, but should still be documented as
# part of the raw low-level API:
append!(bound_api["H5P"],
        ["h5p_get_class_name(pcid::hid_t)"])                  # defined in src/api_helpers.jl
append!(bound_api["H5T"],
        ["h5t_get_member_name(type_id::hid_t, index::Cuint)", # defined in src/api_helpers.jl
         "h5t_get_tag(type_id::hid_t)"])                      # defined in src/api_helpers.jl

# Now dump the text representation to disk
exprs = Base.remove_linenums!(exprs)
open(joinpath(@__DIR__, "..", "src", "api.jl"), "w") do fid
    println(fid, """
# This file is autogenerated by HDF5.jl's `gen/gen_wrappers.jl` and should not be editted.
#
# To add new bindings, define the binding in `gen/api_defs.jl`, re-run
# `gen/gen_wrappers.jl`, and commit the updated `src/api.jl`.
""")
    for func in exprs.args
        write(fid, string(func), "\n\n")
    end
end

# Also generate auto-docs that simply list all of the bound API functions
apidocs = ""
for (mod, desc, urltail) in (
    ("H5", "General Library Functions", "Library"),
    ("H5A", "Attribute Interface", "Attributes"),
    ("H5D", "Dataset Interface", "Datasets"),
    ("H5E", "Error Interface", "Error+Handling"),
    ("H5F", "File Interface", "Files"),
    ("H5G", "Group Interface", "Groups"),
    ("H5I", "Identifier Interface", "Identifiers"),
    ("H5L", "Link Interface", "Links"),
    ("H5O", "Object Interface", "Objects"),
    ("H5P", "Property Interface", "Property+Lists"),
    ("H5R", "Reference Interface", "References"),
    ("H5S", "Dataspace Interface", "Dataspaces"),
    ("H5T", "Datatype Interface", "Datatypes"),
    ("H5Z", "Filter Interface", "Filters"),
    ("H5DO", "Optimized Functions Interface", "Optimizations"),
    ("H5DS", "Dimension Scale Interface", "Dimension+Scales"),
    ("H5LT", "Lite Interface", "Lite"),
    ("H5TB", "Table Interface", "Tables"),
    )
    global apidocs
    funcs = join(sort!(bound_api[mod]), "\n")
    apidocs *= """
        ## [`$mod`](https://portal.hdfgroup.org/display/HDF5/$urltail) — $desc
        ```julia
        $funcs
        ```

        """
end

open(joinpath(@__DIR__, "..", "docs", "src", "api_bindings.md"), "w") do fid
    write(fid,
"""
```@raw html
<!-- This file is auto-generated and should not be manually editted. To update, run the
gen/gen_wrappers.jl script -->
```
# Low-level library bindings

At the lowest level, `HDF5.jl` operates by calling the public API of the HDF5 shared
library through a set of `ccall` wrapper functions.
This page documents the function names and nominal C argument types of the API which
have bindings in this package.
Note that in many cases, high-level data types are valid arguments through automatic
`ccall` conversions.
For instance, `HDF5Datatype` objects will be automatically converted to their `hid_t` ID
by Julia's `cconvert`+`unsafe_convert` `ccall` rules.

There are additional helper wrappers (often for out-argument functions) which are not
documented here.

$apidocs
"""
    )
end


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

using Markdown
using InteractiveUtils

# ╔═╡ 15b8afb9-ace9-4b5b-894e-dce9dda5bf5f
begin
	using Pkg

# 	try
# 		using UnicodePlots

# 	catch ArgumentError
# 		Pkg.add("UnicodePlots")
# 		using UnicodePlots
# 	end

	using Test
	using PlutoUI
end

# ╔═╡ 45d72214-919c-11eb-2e69-23c0786baacb
md"""
### Scope of variables

Src: [Julia 1.0 Cookbook -  Bogumił Kamiński , Przemysław Szufel - 2018](https://www.packtpub.com/product/julia-1-0-programming-cookbook/9781788998369)
"""

# ╔═╡ 1cab379d-d483-43fc-84f7-3bad9e583e77
md"""
A variable can be defined in one of two scopes — either *local* or *global*.
"""

# ╔═╡ bbc9bdb0-3b28-4f89-a980-d597b98e7880
a, b = 1, 2;

# ╔═╡ c2f716f9-98be-4bdf-be71-d915b02fc8a6
with_terminal() do

	let a=30, b=40
		let b=500
			println("inner scope $a $b")
		end
		println("outer scope $a $b")
	end
end

# ╔═╡ ee5589bd-3ee5-4a19-9870-b9ef03122639
with_terminal() do
	println("global scope $a $b")
end

# ╔═╡ e091acba-3fb1-4d96-a976-58cb051656a6
x = 5;

# ╔═╡ f73be67c-5989-4be2-8102-0c4023815756
with_terminal() do
	let
		println(x+1)   ## Expect 6
	end
end

# ╔═╡ a6d11cc6-0628-4a2b-9e46-89823839786f
md"""
However:
"""

# ╔═╡ 05276c9e-b4f7-400e-bb17-2ef4211c19cd
let
	x = x + 1   ## No Error, with Julia 1.6 / PLuto
end

# ╔═╡ 2687c6b0-727d-4e0d-aed3-377a57867279
with_terminal() do
	let
		println(x)   ## Expect 5
	end
end

# ╔═╡ 82bd8ebd-63af-4de2-a673-d2b147c82bca
## Will fail
function twogram(s::AbstractString)
	twograms = String[]
	for (i, c) in enumerate(s)
		prev = if i == 1
			c
		else
			push!(twograms, string(prev, c))
			c
		end
	end
	twograms
end

# ╔═╡ 82c70730-535f-45ac-ac8a-f2d9e0ab5454
twogram("ABCD")   ## Error expected

# ╔═╡ 1ae57919-8890-4bac-b80e-fb1981ce2552
md"""
The `prev` variable has been declared in a loop scope, and hence its value is lost in each pass of the loop.

This can be corrected (we have added `local prev` before the loop in order to declare prev in an *outer local scope*):
"""

# ╔═╡ d3a817d8-3b7b-4a12-b305-cb756d839524
function twogram2(s::AbstractString)
	twograms = String[]
	local prev

	for (i, c) ∈ enumerate(s)
		prev = if i==1
			c
		else
			push!(twograms, string(prev, c))
			c
		end
	end
	twograms
end

# ╔═╡ 5c69604a-63a3-4288-bb7a-bf47f614d917
twogram2("ABCD")

# ╔═╡ 2e481224-fed9-417e-9d4e-89c190fab2d2
md"""
Note however that the code of `twograms2` will not run as expected, if copied directly to the Julia command line.

We need to define a local scope to make it work using a `let` construct or prepending `global` in front of `prev` inside the function.
"""

# ╔═╡ bbce4433-d567-43f4-8b04-ba4aa242d5c5
md"""
Note that each module has its own global scope. The `Julia` command line works in the global scope of the `Main` module. If you define some code within a module, it will be global within this module. All the presented rules are valid. For example, consider the following module:
"""

# ╔═╡ 7895d933-105b-4618-a9dd-368c17cef35c
module B
	x=1

	function getxplusone()
		x + 1
	end

	function increasex()
		x += 1
	end

	function increasexglob()
		global x += 1
	end
end

# ╔═╡ 1d409947-442f-42e8-9524-e99a245c00d8
B.getxplusone()

# ╔═╡ 27714280-7dff-40ee-8442-023c5182e1b5
B.increasex()   ## Error expected

# ╔═╡ 61b1330e-7fcd-483d-bbee-000ef0b479a1
B.increasexglob()

# ╔═╡ b522199d-ef3b-4be6-8aee-d828037d202b
md"""
Any function creates a new local scope.
Scoping within a function (*local scope*) and within the `Julia` command line (*global scope*) exposes completely different behavior.

Consider the following code:
"""

# ╔═╡ b1be6114-5cd1-47bf-b400-e996ee0a9181
function f()
	x = 1
	for a ∈ 1:10
		x += 1
	end
	x
end

# ╔═╡ 9bb77ec4-3857-4a27-a74b-37b8bdbf368f
f()

# ╔═╡ cb51498d-baf4-42f8-975d-ef08ee7271d1
z = 1

# ╔═╡ c3529a34-c2e4-45d9-8aef-d91786f342e4
for _ ∈ 1:10
	z += 1       ## No problem anynore with `Julia ≥ 1.6`
end

# ╔═╡ 48d99279-a9a0-448d-b23d-2511d1c2fd52
u = 5; [(x = u + i; x) for i ∈ 1:2]

# ╔═╡ bb20dc58-b9c8-447b-a7a2-1fb553d6888b
u

# ╔═╡ dce5f294-48db-4ea6-a405-4f74b1aa3f97
v = 5; [(v = v + i; v) for i in 1:2]  # No problem anynore

# ╔═╡ 03ee4abd-268a-4a1c-9be0-5dbfdb50b41a
v

# ╔═╡ Cell order:
# ╟─45d72214-919c-11eb-2e69-23c0786baacb
# ╠═15b8afb9-ace9-4b5b-894e-dce9dda5bf5f
# ╟─1cab379d-d483-43fc-84f7-3bad9e583e77
# ╠═bbc9bdb0-3b28-4f89-a980-d597b98e7880
# ╠═c2f716f9-98be-4bdf-be71-d915b02fc8a6
# ╠═ee5589bd-3ee5-4a19-9870-b9ef03122639
# ╠═e091acba-3fb1-4d96-a976-58cb051656a6
# ╠═f73be67c-5989-4be2-8102-0c4023815756
# ╟─a6d11cc6-0628-4a2b-9e46-89823839786f
# ╠═05276c9e-b4f7-400e-bb17-2ef4211c19cd
# ╠═2687c6b0-727d-4e0d-aed3-377a57867279
# ╠═82bd8ebd-63af-4de2-a673-d2b147c82bca
# ╠═82c70730-535f-45ac-ac8a-f2d9e0ab5454
# ╟─1ae57919-8890-4bac-b80e-fb1981ce2552
# ╠═d3a817d8-3b7b-4a12-b305-cb756d839524
# ╠═5c69604a-63a3-4288-bb7a-bf47f614d917
# ╟─2e481224-fed9-417e-9d4e-89c190fab2d2
# ╟─bbce4433-d567-43f4-8b04-ba4aa242d5c5
# ╠═7895d933-105b-4618-a9dd-368c17cef35c
# ╠═1d409947-442f-42e8-9524-e99a245c00d8
# ╠═27714280-7dff-40ee-8442-023c5182e1b5
# ╠═61b1330e-7fcd-483d-bbee-000ef0b479a1
# ╟─b522199d-ef3b-4be6-8aee-d828037d202b
# ╠═b1be6114-5cd1-47bf-b400-e996ee0a9181
# ╠═9bb77ec4-3857-4a27-a74b-37b8bdbf368f
# ╠═cb51498d-baf4-42f8-975d-ef08ee7271d1
# ╠═c3529a34-c2e4-45d9-8aef-d91786f342e4
# ╠═48d99279-a9a0-448d-b23d-2511d1c2fd52
# ╠═bb20dc58-b9c8-447b-a7a2-1fb553d6888b
# ╠═dce5f294-48db-4ea6-a405-4f74b1aa3f97
# ╠═03ee4abd-268a-4a1c-9be0-5dbfdb50b41a

max_stars_repo_name: pascal-p/julia-notebooks

max_issues_repo_name: pascal-p/julia-notebooks

max_forks_repo_name: pascal-p/julia-notebooks


text:
using CayleyDickson
using Base.Test: @testset

@testset "Binion" begin include("binion_test.jl") end
@testset "SplitBinion" begin include("splitbinion_test.jl") end
@testset "Exo1Real" begin include("exo1real_test.jl") end
@testset "Quaternion" begin include("quaternion_test.jl") end
@testset "SplitQuaternion" begin include("splitquaternion_test.jl") end
@testset "Exo1Binion" begin include("exo1binion_test.jl") end
@testset "Exo1SplitBinion" begin include("exo1splitbinion_test.jl") end
@testset "Exo2Real" begin include("exo2real_test.jl") end
@testset "Octonion" begin include("octonion_test.jl") end
@testset "SplitOctonion" begin include("splitoctonion_test.jl") end
@testset "Exo1Quaternion" begin include("exo1quaternion_test.jl") end
@testset "Exo1SplitQuaternion" begin include("exo1splitquaternion_test.jl") end
@testset "Exo2Binion" begin include("exo2binion_test.jl") end
@testset "Exo2SplitBinion" begin include("exo2splitbinion_test.jl") end
@testset "Exo3Real" begin include("exo3real_test.jl") end
@testset "Sedenion" begin include("sedenion_test.jl") end
@testset "Exo4Real" begin include("exo4real_test.jl") end


text:
@testset "hc_compression" begin
    text = b"""
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean sollicitudin
    mauris non nisi consectetur, a dapibus urna pretium. Vestibulum non posuere
    erat. Donec luctus a turpis eget aliquet. Cras tristique iaculis ex, eu
    malesuada sem interdum sed. Vestibulum ante ipsum primis in faucibus orci luctus
    et ultrices posuere cubilia Curae; Etiam volutpat, risus nec gravida ultricies,
    erat ex bibendum ipsum, sed varius ipsum ipsum vitae dui.
    """

    @testset "Transcoding" begin
        @test LZ4HCCompressorStream <: TranscodingStream

        compressed = transcode(LZ4HCCompressor, text)
        @test sizeof(compressed) < sizeof(text)

        decompressed = transcode(LZ4SafeDecompressor, compressed)
        @test sizeof(decompressed) > sizeof(compressed)
        @test decompressed == Vector{UInt8}(text)

        test_roundtrip_fileio(LZ4HCCompressor, LZ4SafeDecompressor)
        test_roundtrip_transcode(LZ4HCCompressor, LZ4SafeDecompressor)

        file = IOBuffer(text)
        stream = LZ4SafeDecompressorStream(LZ4HCCompressorStream(file))
        flush(stream)

        @test read(stream) == text
        close(stream)
        close(file)

        file = IOBuffer(text)
        stream = LZ4SafeDecompressorStream(LZ4HCCompressorStream(file; compressionlevel = 5))
        flush(stream)

        @test read(stream) == text
        close(stream)
        close(file)

        file = IOBuffer("")
        stream = LZ4SafeDecompressorStream(LZ4HCCompressorStream(file))
        flush(stream)

        @test read(stream) == b""
        close(stream)
        close(file)

        teststring = rand(UInt8, 10000)
        file = IOBuffer(teststring)
        stream = LZ4SafeDecompressorStream(LZ4HCCompressorStream(file; block_size = 2048); block_size = 2048)
        flush(stream)

        @test read(stream) == teststring
        close(stream)
        close(file)
    end

    @testset "Errors" begin
        # Uninitialized
        input = Memory(Vector{UInt8}(text))
        output = Memory(Vector{UInt8}(undef, 1280))
        not_initialized = LZ4HCCompressor()
        @test TranscodingStreams.startproc(not_initialized, :read, Error()) == :error
        @test TranscodingStreams.process(not_initialized, input, output, Error()) == (0, 0, :error)

        # Compression into too-small buffer
        output = Memory(Vector{UInt8}(undef, 1))
        compressor = LZ4HCCompressor()
        try
            @test_nowarn TranscodingStreams.initialize(compressor)
            @test TranscodingStreams.startproc(compressor, :read, Error()) == :ok
            err = Error()
            @test TranscodingStreams.process(compressor, input, output, err) == (0, 0, :error)

            @test err[] isa BoundsError
        finally
            TranscodingStreams.finalize(compressor)
        end

        # Block size too large
        @test_throws ArgumentError LZ4HCCompressor(; block_size = CodecLz4.LZ4_MAX_INPUT_SIZE + 1)
    end

    @testset "dst size fix" begin
        teststring = rand(UInt8, 800000)
        io = IOBuffer(teststring)
        stream = LZ4HCCompressorStream(io)
        result = read(stream)
        @test_nowarn close(stream)
        close(io)

        io = IOBuffer(result)
        stream = LZ4SafeDecompressorStream(io)
        result = read(stream)
        @test result == teststring
        @test_nowarn close(stream)
        close(io)
    end

end


text:
function write_input_diffusion(	file_path::String,
								solid_structure_path::String,
								diffusion_map_path::String,
								D0::Float64,
								D1::Float64,
								deltat_coarse::Float64,
								number_of_time_points_coarse::Int64,
								number_of_time_points_fine_per_coarse::Int64,
								number_of_diffusers::Int64,
								number_of_cells_x::Int64,
								number_of_cells_y::Int64,
								number_of_cells_z::Int64,
								boundary_condition::String,
								output_file_path::String)

	file_stream::IOStream = open(file_path, "w")

	@printf(file_stream, "%s", "<input_diffusion>\n")

	write_key(file_stream, "solid_structure_path", solid_structure_path)
	write_key(file_stream, "diffusion_map_path", diffusion_map_path)
	write_key(file_stream, "D0", D0)
	write_key(file_stream, "D1", D1)
	write_key(file_stream, "deltat_coarse", deltat_coarse)
	write_key(file_stream, "number_of_time_points_coarse", number_of_time_points_coarse)
	write_key(file_stream, "number_of_time_points_fine_per_coarse", number_of_time_points_fine_per_coarse)
	write_key(file_stream, "number_of_diffusers", number_of_diffusers)
	write_key(file_stream, "number_of_cells_x", number_of_cells_x)
	write_key(file_stream, "number_of_cells_y", number_of_cells_y)
	write_key(file_stream, "number_of_cells_z", number_of_cells_z)
	write_key(file_stream, "boundary_condition", boundary_condition)
	write_key(file_stream, "output_file_path", output_file_path)

	@printf(file_stream, "%s", "</input_diffusion>")

	close(file_stream)

	nothing
end


text:
# This file was generated, do not modify it. # hide
const dim = 8

db = MatrixDatabase(randn(Float32, dim, 10^4))
dist = SqL2Distance()
G = SearchGraph(; dist, db)
index!(G)
nothing # hide

max_stars_repo_name: sadit/SimilaritySearchDemos

max_issues_repo_name: sadit/SimilaritySearchDemos

max_forks_repo_name: sadit/SimilaritySearchDemos