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

"""
    add_notification_channels(channels, profiling_group_name)
    add_notification_channels(channels, profiling_group_name, params::Dict{String,<:Any})

Add up to 2 anomaly notifications channels for a profiling group.

# Arguments
- `channels`: One or 2 channels to report to when anomalies are detected.
- `profiling_group_name`: The name of the profiling group that we are setting up
  notifications for.

"""
function add_notification_channels(
    channels, profilingGroupName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "POST",
        "/profilingGroups/$(profilingGroupName)/notificationConfiguration",
        Dict{String,Any}("channels" => channels);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function add_notification_channels(
    channels,
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "POST",
        "/profilingGroups/$(profilingGroupName)/notificationConfiguration",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("channels" => channels), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

 Returns the time series of values for a requested list of frame metrics from a time period.

# Arguments
- `profiling_group_name`:  The name of the profiling group associated with the the frame
  metrics used to return the time series values.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"endTime"`:  The end time of the time period for the returned time series values. This
  is specified using the ISO 8601 format. For example, 2020-06-01T13:15:02.001Z represents 1
  millisecond past June 1, 2020 1:15:02 PM UTC.
- `"frameMetrics"`:  The details of the metrics that are used to request a time series of
  values. The metric includes the name of the frame, the aggregation type to calculate the
  metric value for the frame, and the thread states to use to get the count for the metric
  value of the frame.
- `"period"`:  The duration of the frame metrics used to return the time series values.
  Specify using the ISO 8601 format. The maximum period duration is one day (PT24H or P1D).
- `"startTime"`:  The start time of the time period for the frame metrics used to return
  the time series values. This is specified using the ISO 8601 format. For example,
  2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
- `"targetResolution"`: The requested resolution of time steps for the returned time series
  of values. If the requested target resolution is not available due to data not being
  retained we provide a best effort result by falling back to the most granular available
  resolution after the target resolution. There are 3 valid values.     P1D — 1 day
  PT1H — 1 hour     PT5M — 5 minutes
"""
function batch_get_frame_metric_data(
    profilingGroupName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "POST",
        "/profilingGroups/$(profilingGroupName)/frames/-/metrics";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function batch_get_frame_metric_data(
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "POST",
        "/profilingGroups/$(profilingGroupName)/frames/-/metrics",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

 Used by profiler agents to report their current state and to receive remote configuration
updates. For example, ConfigureAgent can be used to tell an agent whether to profile or not
and for how long to return profiling data.

# Arguments
- `profiling_group_name`:  The name of the profiling group for which the configured agent
  is collecting profiling data.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"fleetInstanceId"`:  A universally unique identifier (UUID) for a profiling instance.
  For example, if the profiling instance is an Amazon EC2 instance, it is the instance ID. If
  it is an AWS Fargate container, it is the container's task ID.
- `"metadata"`:  Metadata captured about the compute platform the agent is running on. It
  includes information about sampling and reporting. The valid fields are:
  COMPUTE_PLATFORM - The compute platform on which the agent is running     AGENT_ID - The ID
  for an agent instance.     AWS_REQUEST_ID - The AWS request ID of a Lambda invocation.
  EXECUTION_ENVIRONMENT - The execution environment a Lambda function is running on.
  LAMBDA_FUNCTION_ARN - The Amazon Resource Name (ARN) that is used to invoke a Lambda
  function.     LAMBDA_MEMORY_LIMIT_IN_MB - The memory allocated to a Lambda function.
  LAMBDA_REMAINING_TIME_IN_MILLISECONDS - The time in milliseconds before execution of a
  Lambda function times out.     LAMBDA_TIME_GAP_BETWEEN_INVOKES_IN_MILLISECONDS - The time
  in milliseconds between two invocations of a Lambda function.
  LAMBDA_PREVIOUS_EXECUTION_TIME_IN_MILLISECONDS - The time in milliseconds for the previous
  Lambda invocation.
"""
function configure_agent(
    profilingGroupName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "POST",
        "/profilingGroups/$(profilingGroupName)/configureAgent";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function configure_agent(
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "POST",
        "/profilingGroups/$(profilingGroupName)/configureAgent",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_profiling_group(client_token, profiling_group_name)
    create_profiling_group(client_token, profiling_group_name, params::Dict{String,<:Any})

Creates a profiling group.

# Arguments
- `client_token`:  Amazon CodeGuru Profiler uses this universally unique identifier (UUID)
  to prevent the accidental creation of duplicate profiling groups if there are failures and
  retries.
- `profiling_group_name`: The name of the profiling group to create.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"agentOrchestrationConfig"`:  Specifies whether profiling is enabled or disabled for the
  created profiling group.
- `"computePlatform"`:  The compute platform of the profiling group. Use AWSLambda if your
  application runs on AWS Lambda. Use Default if your application runs on a compute platform
  that is not AWS Lambda, such an Amazon EC2 instance, an on-premises server, or a different
  platform. If not specified, Default is used.
- `"tags"`:  A list of tags to add to the created profiling group.
"""
function create_profiling_group(
    clientToken, profilingGroupName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "POST",
        "/profilingGroups",
        Dict{String,Any}(
            "clientToken" => clientToken, "profilingGroupName" => profilingGroupName
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_profiling_group(
    clientToken,
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "POST",
        "/profilingGroups",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "clientToken" => clientToken, "profilingGroupName" => profilingGroupName
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deletes a profiling group.

# Arguments
- `profiling_group_name`: The name of the profiling group to delete.

"""
function delete_profiling_group(
    profilingGroupName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "DELETE",
        "/profilingGroups/$(profilingGroupName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_profiling_group(
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "DELETE",
        "/profilingGroups/$(profilingGroupName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

 Returns a  ProfilingGroupDescription  object that contains information about the requested
profiling group.

# Arguments
- `profiling_group_name`:  The name of the profiling group to get information about.

"""
function describe_profiling_group(
    profilingGroupName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "GET",
        "/profilingGroups/$(profilingGroupName)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_profiling_group(
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "GET",
        "/profilingGroups/$(profilingGroupName)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

 Returns a list of  FindingsReportSummary  objects that contain analysis results for all
profiling groups in your AWS account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"dailyReportsOnly"`: A Boolean value indicating whether to only return reports from
  daily profiles. If set to True, only analysis data from daily profiles is returned. If set
  to False, analysis data is returned from smaller time windows (for example, one hour).
- `"maxResults"`: The maximum number of results returned by
  GetFindingsReportAccountSummary in paginated output. When this parameter is used,
  GetFindingsReportAccountSummary only returns maxResults results in a single page along with
  a nextToken response element. The remaining results of the initial request can be seen by
  sending another GetFindingsReportAccountSummary request with the returned nextToken value.
- `"nextToken"`: The nextToken value returned from a previous paginated
  GetFindingsReportAccountSummary request where maxResults was used and the results exceeded
  the value of that parameter. Pagination continues from the end of the previous results that
  returned the nextToken value.   This token should be treated as an opaque identifier that
  is only used to retrieve the next items in a list and not for other programmatic purposes.
"""
function get_findings_report_account_summary(;
    aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "GET",
        "/internal/findingsReports";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_findings_report_account_summary(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "GET",
        "/internal/findingsReports",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Get the current configuration for anomaly notifications for a profiling group.

# Arguments
- `profiling_group_name`: The name of the profiling group we want to get the notification
  configuration for.

"""
function get_notification_configuration(
    profilingGroupName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "GET",
        "/profilingGroups/$(profilingGroupName)/notificationConfiguration";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_notification_configuration(
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "GET",
        "/profilingGroups/$(profilingGroupName)/notificationConfiguration",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

 Returns the JSON-formatted resource-based policy on a profiling group.

# Arguments
- `profiling_group_name`: The name of the profiling group.

"""
function get_policy(profilingGroupName; aws_config::AbstractAWSConfig=global_aws_config())
    return codeguruprofiler(
        "GET",
        "/profilingGroups/$(profilingGroupName)/policy";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_policy(
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "GET",
        "/profilingGroups/$(profilingGroupName)/policy",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

 Gets the aggregated profile of a profiling group for a specified time range. Amazon
CodeGuru Profiler collects posted agent profiles for a profiling group into aggregated
profiles.   <note>
 Because aggregated profiles expire over time
GetProfile is not idempotent.
 </note>

Specify the time range for the requested aggregated profile using 1 or 2 of the following
parameters: startTime, endTime,
period. The maximum time range allowed is 7 days. If you specify
all 3 parameters, an exception is thrown. If you specify only
period, the latest aggregated profile is returned.

 Aggregated profiles are available with aggregation periods of 5 minutes, 1 hour,
and 1 day, aligned to UTC. The aggregation period of an aggregated profile determines how
long it is retained. For more information, see  AggregatedProfileTime . The aggregated
profile's aggregation period determines how long it is retained by CodeGuru Profiler.

 If the aggregation period is 5 minutes, the
aggregated profile is retained for 15 days.

 If
the aggregation period is 1 hour, the aggregated profile is retained for 60 days.

 If the aggregation period is 1 day, the
aggregated profile is retained for 3 years.

There are two use cases for calling GetProfile.

 If you want to return an aggregated profile that already
exists, use  ListProfileTimes  to view the time ranges of
existing aggregated profiles. Use them in a GetProfile request to
return a specific, existing aggregated profile.

If you want to return an aggregated profile for a time range that doesn't align with an
existing aggregated profile, then CodeGuru Profiler makes a best effort to combine existing
aggregated profiles from the requested time range and return them as one aggregated
profile.

 If aggregated profiles do not exist for the full time range
requested, then aggregated profiles for a smaller time range are returned. For example, if
the requested time range is from 00:00 to 00:20, and the existing aggregated profiles are
from 00:15 and 00:25, then the aggregated profiles from 00:15 to 00:20 are returned.

# Arguments
- `profiling_group_name`: The name of the profiling group to get.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Accept"`:  The format of the returned profiling data. The format maps to the Accept and
  Content-Type headers of the HTTP request. You can specify one of the following: or the
  default .

 application/json —
  standard JSON format

  application/x-amzn-ion — the Amazon Ion data format. For more
  information, see Amazon
  Ion.

- `"endTime"`:  The end time of the requested profile. Specify using the ISO 8601 format.
  For example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM
  UTC.   If you specify endTime, then you must also specify period or startTime, but not
  both.
- `"maxDepth"`:  The maximum depth of the stacks in the code that is represented in the
  aggregated profile. For example, if CodeGuru Profiler finds a method A, which calls method
  B, which calls method C, which calls method D, then the depth is 4. If the maxDepth is set
  to 2, then the aggregated profile contains representations of methods A and B.
- `"period"`:  Used with startTime or endTime to specify the time range for the returned
  aggregated profile. Specify using the ISO 8601 format. For example, P1DT1H1M1S.

  To get the latest aggregated profile, specify only period.

- `"startTime"`: The start time of the profile to get. Specify using the ISO 8601 format.
  For example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM
  UTC.
 If you specify startTime, then you must also
  specify period or endTime, but not both.

"""
function get_profile(profilingGroupName; aws_config::AbstractAWSConfig=global_aws_config())
    return codeguruprofiler(
        "GET",
        "/profilingGroups/$(profilingGroupName)/profile";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_profile(
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "GET",
        "/profilingGroups/$(profilingGroupName)/profile",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_recommendations(end_time, profiling_group_name, start_time)
    get_recommendations(end_time, profiling_group_name, start_time, params::Dict{String,<:Any})

 Returns a list of  Recommendation  objects that contain recommendations for a profiling
group for a given time period. A list of  Anomaly  objects that contains details about
anomalies detected in the profiling group for the same time period is also returned.

# Arguments
- `end_time`:  The start time of the profile to get analysis data about. You must specify
  startTime and endTime. This is specified using the ISO 8601 format. For example,
  2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
- `profiling_group_name`:  The name of the profiling group to get analysis data about.
- `start_time`:  The end time of the profile to get analysis data about. You must specify
  startTime and endTime. This is specified using the ISO 8601 format. For example,
  2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"locale"`:  The language used to provide analysis. Specify using a string that is one of
  the following BCP 47 language codes.     de-DE - German, Germany     en-GB - English,
  United Kingdom     en-US - English, United States     es-ES - Spanish, Spain     fr-FR -
  French, France     it-IT - Italian, Italy     ja-JP - Japanese, Japan     ko-KR - Korean,
  Republic of Korea     pt-BR - Portugese, Brazil     zh-CN - Chinese, China     zh-TW -
  Chinese, Taiwan
"""
function get_recommendations(
    endTime,
    profilingGroupName,
    startTime;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "GET",
        "/internal/profilingGroups/$(profilingGroupName)/recommendations",
        Dict{String,Any}("endTime" => endTime, "startTime" => startTime);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_recommendations(
    endTime,
    profilingGroupName,
    startTime,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "GET",
        "/internal/profilingGroups/$(profilingGroupName)/recommendations",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("endTime" => endTime, "startTime" => startTime),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_findings_reports(end_time, profiling_group_name, start_time)
    list_findings_reports(end_time, profiling_group_name, start_time, params::Dict{String,<:Any})

List the available reports for a given profiling group and time range.

# Arguments
- `end_time`:  The end time of the profile to get analysis data about. You must specify
  startTime and endTime. This is specified using the ISO 8601 format. For example,
  2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.
- `profiling_group_name`: The name of the profiling group from which to search for analysis
  data.
- `start_time`:  The start time of the profile to get analysis data about. You must specify
  startTime and endTime. This is specified using the ISO 8601 format. For example,
  2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"dailyReportsOnly"`: A Boolean value indicating whether to only return reports from
  daily profiles. If set to True, only analysis data from daily profiles is returned. If set
  to False, analysis data is returned from smaller time windows (for example, one hour).
- `"maxResults"`: The maximum number of report results returned by ListFindingsReports in
  paginated output. When this parameter is used, ListFindingsReports only returns maxResults
  results in a single page along with a nextToken response element. The remaining results of
  the initial request can be seen by sending another ListFindingsReports request with the
  returned nextToken value.
- `"nextToken"`: The nextToken value returned from a previous paginated
  ListFindingsReportsRequest request where maxResults was used and the results exceeded the
  value of that parameter. Pagination continues from the end of the previous results that
  returned the nextToken value.   This token should be treated as an opaque identifier that
  is only used to retrieve the next items in a list and not for other programmatic purposes.
"""
function list_findings_reports(
    endTime,
    profilingGroupName,
    startTime;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "GET",
        "/internal/profilingGroups/$(profilingGroupName)/findingsReports",
        Dict{String,Any}("endTime" => endTime, "startTime" => startTime);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_findings_reports(
    endTime,
    profilingGroupName,
    startTime,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "GET",
        "/internal/profilingGroups/$(profilingGroupName)/findingsReports",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("endTime" => endTime, "startTime" => startTime),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_profile_times(end_time, period, profiling_group_name, start_time)
    list_profile_times(end_time, period, profiling_group_name, start_time, params::Dict{String,<:Any})

Lists the start times of the available aggregated profiles of a profiling group for an
aggregation period within the specified time range.

# Arguments
- `end_time`: The end time of the time range from which to list the profiles.
- `period`:  The aggregation period. This specifies the period during which an aggregation
  profile collects posted agent profiles for a profiling group. There are 3 valid values.
  P1D — 1 day     PT1H — 1 hour     PT5M — 5 minutes
- `profiling_group_name`: The name of the profiling group.
- `start_time`: The start time of the time range from which to list the profiles.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of profile time results returned by ListProfileTimes
  in paginated output. When this parameter is used, ListProfileTimes only returns maxResults
  results in a single page with a nextToken response element. The remaining results of the
  initial request can be seen by sending another ListProfileTimes request with the returned
  nextToken value.
- `"nextToken"`: The nextToken value returned from a previous paginated ListProfileTimes
  request where maxResults was used and the results exceeded the value of that parameter.
  Pagination continues from the end of the previous results that returned the nextToken
  value.   This token should be treated as an opaque identifier that is only used to retrieve
  the next items in a list and not for other programmatic purposes.
- `"orderBy"`: The order (ascending or descending by start time of the profile) to use when
  listing profiles. Defaults to TIMESTAMP_DESCENDING.
"""
function list_profile_times(
    endTime,
    period,
    profilingGroupName,
    startTime;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "GET",
        "/profilingGroups/$(profilingGroupName)/profileTimes",
        Dict{String,Any}(
            "endTime" => endTime, "period" => period, "startTime" => startTime
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_profile_times(
    endTime,
    period,
    profilingGroupName,
    startTime,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "GET",
        "/profilingGroups/$(profilingGroupName)/profileTimes",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "endTime" => endTime, "period" => period, "startTime" => startTime
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

 Returns a list of profiling groups. The profiling groups are returned as
ProfilingGroupDescription  objects.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"includeDescription"`: A Boolean value indicating whether to include a description. If
  true, then a list of  ProfilingGroupDescription  objects that contain detailed information
  about profiling groups is returned. If false, then a list of profiling group names is
  returned.
- `"maxResults"`: The maximum number of profiling groups results returned by
  ListProfilingGroups in paginated output. When this parameter is used, ListProfilingGroups
  only returns maxResults results in a single page along with a nextToken response element.
  The remaining results of the initial request can be seen by sending another
  ListProfilingGroups request with the returned nextToken value.
- `"nextToken"`: The nextToken value returned from a previous paginated ListProfilingGroups
  request where maxResults was used and the results exceeded the value of that parameter.
  Pagination continues from the end of the previous results that returned the nextToken
  value.   This token should be treated as an opaque identifier that is only used to retrieve
  the next items in a list and not for other programmatic purposes.
"""
function list_profiling_groups(; aws_config::AbstractAWSConfig=global_aws_config())
    return codeguruprofiler(
        "GET", "/profilingGroups"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_profiling_groups(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "GET",
        "/profilingGroups",
        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})

 Returns a list of the tags that are assigned to a specified resource.

# Arguments
- `resource_arn`:  The Amazon Resource Name (ARN) of the resource that contains the tags to
  return.

"""
function list_tags_for_resource(
    resourceArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "GET",
        "/tags/$(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 codeguruprofiler(
        "GET",
        "/tags/$(resourceArn)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    post_agent_profile(content-_type, agent_profile, profiling_group_name)
    post_agent_profile(content-_type, agent_profile, profiling_group_name, params::Dict{String,<:Any})

 Submits profiling data to an aggregated profile of a profiling group. To get an aggregated
profile that is created with this profiling data, use  GetProfile .

# Arguments
- `content-_type`:  The format of the submitted profiling data. The format maps to the
  Accept and Content-Type headers of the HTTP request. You can specify one of the following:
  or the default .

  application/json — standard JSON format

 application/x-amzn-ion — the Amazon Ion
  data format. For more information, see Amazon Ion.

- `agent_profile`:  The submitted profiling data.
- `profiling_group_name`:  The name of the profiling group with the aggregated profile that
  receives the submitted profiling data.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"profileToken"`:  Amazon CodeGuru Profiler uses this universally unique identifier
  (UUID) to prevent the accidental submission of duplicate profiling data if there are
  failures and retries.
"""
function post_agent_profile(
    Content_Type,
    agentProfile,
    profilingGroupName;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "POST",
        "/profilingGroups/$(profilingGroupName)/agentProfile",
        Dict{String,Any}(
            "agentProfile" => agentProfile,
            "profileToken" => string(uuid4()),
            "headers" => Dict{String,Any}("Content-Type" => Content_Type),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function post_agent_profile(
    Content_Type,
    agentProfile,
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "POST",
        "/profilingGroups/$(profilingGroupName)/agentProfile",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "agentProfile" => agentProfile,
                    "profileToken" => string(uuid4()),
                    "headers" => Dict{String,Any}("Content-Type" => Content_Type),
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    put_permission(action_group, principals, profiling_group_name)
    put_permission(action_group, principals, profiling_group_name, params::Dict{String,<:Any})

 Adds permissions to a profiling group's resource-based policy that are provided using an
action group. If a profiling group doesn't have a resource-based policy, one is created for
it using the permissions in the action group and the roles and users in the principals
parameter.
 The one supported action group that can be added is
agentPermission which grants
ConfigureAgent and PostAgent permissions.
For more information, see Resource-based policies in CodeGuru Profiler in the Amazon
CodeGuru Profiler User Guide,  ConfigureAgent , and  PostAgentProfile .

 The
first time you call PutPermission on a profiling group, do not
specify a revisionId because it doesn't have a resource-based
policy. Subsequent calls must provide a revisionId to specify
which revision of the resource-based policy to add the permissions to.

The response contains the profiling group's JSON-formatted resource policy.

# Arguments
- `action_group`:  Specifies an action group that contains permissions to add to a
  profiling group resource. One action group is supported, agentPermissions, which grants
  permission to perform actions required by the profiling agent, ConfigureAgent and
  PostAgentProfile permissions.
- `principals`:  A list ARNs for the roles and users you want to grant access to the
  profiling group. Wildcards are not are supported in the ARNs.
- `profiling_group_name`: The name of the profiling group to grant access to.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"revisionId"`:  A universally unique identifier (UUID) for the revision of the policy
  you are adding to the profiling group. Do not specify this when you add permissions to a
  profiling group for the first time. If a policy already exists on the profiling group, you
  must specify the revisionId.
"""
function put_permission(
    actionGroup,
    principals,
    profilingGroupName;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "PUT",
        "/profilingGroups/$(profilingGroupName)/policy/$(actionGroup)",
        Dict{String,Any}("principals" => principals);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function put_permission(
    actionGroup,
    principals,
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "PUT",
        "/profilingGroups/$(profilingGroupName)/policy/$(actionGroup)",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("principals" => principals), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    remove_notification_channel(channel_id, profiling_group_name)
    remove_notification_channel(channel_id, profiling_group_name, params::Dict{String,<:Any})

Remove one anomaly notifications channel for a profiling group.

# Arguments
- `channel_id`: The id of the channel that we want to stop receiving notifications.
- `profiling_group_name`: The name of the profiling group we want to change notification
  configuration for.

"""
function remove_notification_channel(
    channelId, profilingGroupName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "DELETE",
        "/profilingGroups/$(profilingGroupName)/notificationConfiguration/$(channelId)";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function remove_notification_channel(
    channelId,
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "DELETE",
        "/profilingGroups/$(profilingGroupName)/notificationConfiguration/$(channelId)",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    remove_permission(action_group, profiling_group_name, revision_id)
    remove_permission(action_group, profiling_group_name, revision_id, params::Dict{String,<:Any})

 Removes permissions from a profiling group's resource-based policy that are provided using
an action group. The one supported action group that can be removed is agentPermission
which grants ConfigureAgent and PostAgent permissions. For more information, see
Resource-based policies in CodeGuru Profiler in the Amazon CodeGuru Profiler User Guide,
ConfigureAgent , and  PostAgentProfile .

# Arguments
- `action_group`:  Specifies an action group that contains the permissions to remove from a
  profiling group's resource-based policy. One action group is supported, agentPermissions,
  which grants ConfigureAgent and PostAgentProfile permissions.
- `profiling_group_name`: The name of the profiling group.
- `revision_id`:  A universally unique identifier (UUID) for the revision of the
  resource-based policy from which you want to remove permissions.

"""
function remove_permission(
    actionGroup,
    profilingGroupName,
    revisionId;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "DELETE",
        "/profilingGroups/$(profilingGroupName)/policy/$(actionGroup)",
        Dict{String,Any}("revisionId" => revisionId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function remove_permission(
    actionGroup,
    profilingGroupName,
    revisionId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "DELETE",
        "/profilingGroups/$(profilingGroupName)/policy/$(actionGroup)",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("revisionId" => revisionId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    submit_feedback(anomaly_instance_id, profiling_group_name, type)
    submit_feedback(anomaly_instance_id, profiling_group_name, type, params::Dict{String,<:Any})

Sends feedback to CodeGuru Profiler about whether the anomaly detected by the analysis is
useful or not.

# Arguments
- `anomaly_instance_id`: The universally unique identifier (UUID) of the  AnomalyInstance
  object that is included in the analysis data.
- `profiling_group_name`: The name of the profiling group that is associated with the
  analysis data.
- `type`:  The feedback tpye. Thee are two valid values, Positive and Negative.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"comment"`: Optional feedback about this anomaly.
"""
function submit_feedback(
    anomalyInstanceId,
    profilingGroupName,
    type;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "POST",
        "/internal/profilingGroups/$(profilingGroupName)/anomalies/$(anomalyInstanceId)/feedback",
        Dict{String,Any}("type" => type);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function submit_feedback(
    anomalyInstanceId,
    profilingGroupName,
    type,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "POST",
        "/internal/profilingGroups/$(profilingGroupName)/anomalies/$(anomalyInstanceId)/feedback",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("type" => type), 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})

 Use to assign one or more tags to a resource.

# Arguments
- `resource_arn`:  The Amazon Resource Name (ARN) of the resource that the tags are added
  to.
- `tags`:  The list of tags that are added to the specified resource.

"""
function tag_resource(resourceArn, tags; aws_config::AbstractAWSConfig=global_aws_config())
    return codeguruprofiler(
        "POST",
        "/tags/$(resourceArn)",
        Dict{String,Any}("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 codeguruprofiler(
        "POST",
        "/tags/$(resourceArn)",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("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})

 Use to remove one or more tags from a resource.

# Arguments
- `resource_arn`:  The Amazon Resource Name (ARN) of the resource that contains the tags to
  remove.
- `tag_keys`:  A list of tag keys. Existing tags of resources with keys in this list are
  removed from the specified resource.

"""
function untag_resource(
    resourceArn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config()
)
    return codeguruprofiler(
        "DELETE",
        "/tags/$(resourceArn)",
        Dict{String,Any}("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 codeguruprofiler(
        "DELETE",
        "/tags/$(resourceArn)",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tagKeys" => tagKeys), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_profiling_group(agent_orchestration_config, profiling_group_name)
    update_profiling_group(agent_orchestration_config, profiling_group_name, params::Dict{String,<:Any})

Updates a profiling group.

# Arguments
- `agent_orchestration_config`:  Specifies whether profiling is enabled or disabled for a
  profiling group.
- `profiling_group_name`: The name of the profiling group to update.

"""
function update_profiling_group(
    agentOrchestrationConfig,
    profilingGroupName;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "PUT",
        "/profilingGroups/$(profilingGroupName)",
        Dict{String,Any}("agentOrchestrationConfig" => agentOrchestrationConfig);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_profiling_group(
    agentOrchestrationConfig,
    profilingGroupName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return codeguruprofiler(
        "PUT",
        "/profilingGroups/$(profilingGroupName)",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("agentOrchestrationConfig" => agentOrchestrationConfig),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end


text:
# New matplotlib colormaps by Nathaniel J. Smith, Stefan van der Walt,
# and (in the case of viridis) Eric Firing.
#
# This file and the colormaps in it are released under the CC0 license /
# public domain dedication. We would appreciate credit if you use or
# redistribute these colormaps, but do not impose any legal restrictions.
#
# To the extent possible under law, the persons who associated CC0 with
# mpl-colormaps have waived all copyright and related or neighboring rights
# to mpl-colormaps.
#
# You should have received a copy of the CC0 legalcode along with this
# work.  If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
#
# Adapted for Julia by Jagot

module colormaps
using PyCall
using PyPlot

const COL = PyNULL()

function __init__()
    copy!(COL, pyimport_conda("matplotlib.colors", "matplotlib"))
end

function get_cmap(args...)
    plt.cm.get_cmap(args...)
end

function (cmap::PyPlot.ColorMap)(i::Int)
    if :colors in propertynames(cmap)
        vec(cmap.colors[i,:])
    else
        pycall(cmap, PyAny, i)
    end
end

function lerp(a,b,t)
    (1-t)*a + t*b
end

function lerp(a::Tuple, b::Tuple, t)
    tuple([lerp(a[i],b[i],t) for i = 1:length(a)]...)
end

function (cmap::PyPlot.ColorMap)(f::Real)
    i = clamp(1+f*(cmap.N-1),1,cmap.N)
    fl,ce = floor(Integer,i), ceil(Integer, i)
    lerp(cmap(fl),cmap(ce),f)
end

(cmap::PyPlot.ColorMap)(i::Integer, l::Integer) =
    l > 1 ? cmap((i-1)/(l-1)) : cmap(0.5)

export get_cmap, call

end

ext: jl


text:
#### GitHub Actions

abstract type GitHubAction end

"""
    DocBuild

# Fields
$(DocStringExtensions.FIELDS)
"""
Base.@kwdef struct DocBuild <: GitHubAction
    "Build name"
    build_name::String
    "Julia version"
    julia_version::String
end

function yaml(gha::DocBuild)
    return "name: Documentation

on:
  push:
    branches:
      - master
      - trying
      - staging
    tags: '*'
  pull_request:

jobs:
  $(gha.build_name):
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: julia-actions/setup-julia@latest
        with:
          version: $(gha.julia_version)
      - name: Install dependencies
        run: julia --project=docs/ -e 'using Pkg; Pkg.develop(PackageSpec(path=pwd())); Pkg.instantiate()'
      - name: Build and deploy
        env:
          GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }} # For authentication with GitHub Actions token
          DOCUMENTER_KEY: \${{ secrets.DOCUMENTER_KEY }} # For authentication with SSH deploy key
        run: julia --project=docs/ docs/make.jl
"
end

Base.@kwdef struct TagBot <: GitHubAction
end

function yaml(::TagBot)
    return "name: TagBot
on:
  schedule:
    - cron: 0 * * * *
jobs:
  TagBot:
    runs-on: ubuntu-latest
    steps:
      - uses: JuliaRegistries/TagBot@v1
        with:
          token: \${{ secrets.GITHUB_TOKEN }}
"
end

Base.@kwdef struct CompatHelper <: GitHubAction
  julia_version::String
end

function yaml(gha::CompatHelper)
    return "name: CompatHelper

on:
  schedule:
    - cron: '00 00 * * *'

jobs:
  CompatHelper:
    runs-on: ubuntu-latest
    steps:
      - uses: julia-actions/setup-julia@latest
        with:
          version: $(gha.julia_version)
      - name: Pkg.add(\"CompatHelper\")
        run: julia -e 'using Pkg; Pkg.add(\"CompatHelper\")'
      - name: CompatHelper.main()
        env:
          GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
        run: julia -e 'using CompatHelper; CompatHelper.main()'
"
end

Base.@kwdef struct CodeCov <: GitHubAction
    "Package name (with extension)"
    pkg_name::String
    "Julia version"
    julia_version::String
end

function yaml(gha::CodeCov)
    return "name: CodeCov

on:
  schedule:
    # * is a special character in YAML so you have to quote this string
    # Run at 2am every day:
    - cron:  '0 2 * * *'

jobs:
  coverage:
    runs-on: ubuntu-16.04
    strategy:
      matrix:
        julia-version: ['$(gha.julia_version)']
        project: ['$(gha.pkg_name)']

    steps:
    - uses: actions/checkout@v1.0.0
    - name: \"Set up Julia\"
      uses: julia-actions/setup-julia@v1
      with:
        version: \${{ matrix.julia-version }}

    - name: Install deps
      run: |
        set -o xtrace
        sudo apt-get update

    - name: Test with coverage
      env:
        JULIA_PROJECT: \"@.\"
      run: |
        julia --project=@. -e 'using Pkg; Pkg.instantiate()'
        julia --project=@. -e 'using Pkg; Pkg.test(coverage=true)'

    - name: Generate coverage file
      env:
        JULIA_PROJECT: \"@.\"
      run: julia --project=@. -e 'using Pkg; Pkg.add(\"Coverage\");
                                  using Coverage;
                                  LCOV.writefile(\"coverage-lcov.info\", Codecov.process_folder())'
      if: success()
    - name: Submit coverage
      uses: codecov/codecov-action@v1.0.2
      with:
        token: \${{secrets.CODECOV_TOKEN}}
      if: success()

"
end

Base.@kwdef struct FormatterCheck <: GitHubAction
    julia_version::String
end

function yaml(gha::FormatterCheck)
    return "name: JuliaFormatter

on: [pull_request]

jobs:
  format:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
      with:
        fetch-depth: 0
    - run: git fetch origin
    - uses: julia-actions/setup-julia@latest
      with:
        version: $(gha.julia_version)
    - name: Apply JuliaFormatter
      run: |
        julia --project=.dev .dev/format.jl
    - name: Check formatting diff
      run: |
        git diff --color=always --exit-code
"
end

max_stars_repo_name: charleskawczynski/PkgTemplates

max_issues_repo_name: charleskawczynski/PkgTemplates

max_forks_repo_name: charleskawczynski/PkgTemplates


text:
# Settings for fitting

"""
    MLEControl(init::parameter, optimizer::String, ci::Bool, maxEval<:Integer)
Structure for esitmation settings.

* `init`: Initial values for optimization
* `optimizer`: Optimizing Routine, "NelderMead", "BFGS" or "LBFGS"
* `ci`: Indicator: Shall confidence intervals be computed?
* `maxEval`: Maximum number of likelihood evaluations
"""
mutable struct MLEControl
    init::parameter
    optimizer::String
    ci::Bool
    maxEval::T where T<:Integer
end


text:
"""
This enables the backward gradient computations via Z.
Notice at the end, we basically return Z (binary tensor).
But we make use of the smoothed Z, which is differentiable.
We detach (Z - smoothed_Z) so that the gradients are not
computed, and then add back smoothed_Z for the return.
The only gradient will then be that of smoothed Z.
"""
function compute_Z(v::AbstractArray, H::AbstractArray;
                   use_stickbreak::Bool=false, tau::Float64=.001)
  v_rs = reshape(v, 1, length(v))
  p = use_stickbreak ? cumprod(v_rs, dims=2) : v_rs
  r = ADVI.logit_safe.(p) .- ADVI.logit_safe.(H)
  smoothed_Z = ADVI.sigmoid_safe.(r / tau)
  Z = (p .> H)
  return Tracker.data(Z - smoothed_Z) + smoothed_Z
end

max_stars_repo_name: luiarthur/CytofResearch

max_issues_repo_name: luiarthur/CytofResearch


text:
module SoftSquishyMatter

"""
Flush output so that jobs can be monitored on cluster.
"""
@inline println(args...) = println(stdout, args...)
@inline function println(io::IO, args...)
    Base.println(io, args...)
    flush(io)
end

using Random
using Serialization
using DataStructures
using Plots

include("definitions.jl")
include("runsimulation.jl")
include("activeforces.jl")
include("particle.jl")
include("integrators.jl")
include("celllist.jl")
include("interactions.jl")
include("externalforces.jl")

include("analysis/visualize.jl")

println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
println("SoftSquishyMatter Loaded!")
println("Michael Wang")
println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

end


text:
module j3dloader

    using Libdl
    libJulia3D = dlopen("../build/libJulia3D.so")

    # CORE
    # window
    window_create = dlsym(libJulia3D, "j3d_window_create")
    window_initialize = dlsym(libJulia3D, "j3d_window_initialize")
    window_destroy = dlsym(libJulia3D, "j3d_window_destroy")
    window_is_close = dlsym(libJulia3D, "j3d_window_is_close")
    window_set_title = dlsym(libJulia3D, "j3d_window_set_title")
    window_poll_event = dlsym(libJulia3D, "j3d_window_poll_event")
    window_clear = dlsym(libJulia3D, "j3d_window_clear")
    window_display = dlsym(libJulia3D, "j3d_window_display")
    # keyboard
    keyboard_is_key_pressed = dlsym(libJulia3D, "j3d_keyboard_is_key_pressed")
    keyboard_is_key_upped = dlsym(libJulia3D, "j3d_keyboard_is_key_upped")
    keyboard_is_key_downed = dlsym(libJulia3D, "j3d_keyboard_is_key_downed")

    # NON-COMPONENT CLASSES
    # texture
    texture_load = dlsym(libJulia3D, "j3d_texture_load")
    texture_create = dlsym(libJulia3D, "j3d_texture_create")
    texture_destroy = dlsym(libJulia3D, "j3d_texture_destroy")

    # COMPONENTS
    # transform
    transform_init = dlsym(libJulia3D, "j3d_transform_init")
    transform_set_position = dlsym(libJulia3D, "j3d_transform_set_position")
    transform_set_rotation = dlsym(libJulia3D, "j3d_transform_set_rotation")
    transform_set_scale = dlsym(libJulia3D, "j3d_transform_set_scale")
    transform_set_rotation_x = dlsym(libJulia3D, "j3d_transform_set_rotation_x")
    transform_set_rotation_y = dlsym(libJulia3D, "j3d_transform_set_rotation_y")
    transform_set_rotation_z = dlsym(libJulia3D, "j3d_transform_set_rotation_z")
    # sprite renderer
    sprite_renderer_init = dlsym(libJulia3D, "j3d_sprite_renderer_init")
    sprite_renderer_draw = dlsym(libJulia3D, "j3d_sprite_renderer_draw")
    sprite_renderer_destroy = dlsym(libJulia3D, "j3d_sprite_renderer_destroy")
    sprite_renderer_set_texture = dlsym(libJulia3D, "j3d_sprite_renderer_set_texture")
    #camera
    camera_init_as_perspective = dlsym(libJulia3D, "j3d_camera_init_as_perspective")
    camera_init_as_orthographic = dlsym(libJulia3D, "j3d_camera_init_as_orthographic")
end


text:
function job_path(req)
    id = findnext(isequal('/'), req.target, 2)
    if length(req.target) < id + 1
        return ""
    else
        return req.target[id+1:end]
    end
end

save_job(req) = Service.save(job_path(req), JSON3.read(req.body, Dict{String, String}))
HTTP.@register(ROUTER, "POST", "/jobs", save_job)

submit_job(req) = Service.submit(job_path(req))
HTTP.@register(ROUTER, "PUT", "/jobs/*", submit_job)

get_job(req) = Service.load_job(job_path(req))
HTTP.@register(ROUTER, "GET", "/jobs/*", get_job)
HTTP.@register(ROUTER, "GET", "/jobs/", get_job)

job_state(req) = Service.state(job_path(req))
HTTP.@register(ROUTER, "GET", "/job_state/*", job_state)

function job_submission_time(req)
    scriptpath = joinpath(job_path(req), "job.tt")
    if ispath(scriptpath)
        return mtime(scriptpath)
    else
        return 0
    end
end
HTTP.@register(ROUTER, "GET", "/job_submission_time/*", job_submission_time)

registered_jobs(req) = Service.registered_jobs(job_path(req))
HTTP.@register(ROUTER, "GET", "/registered_jobs/*", registered_jobs)
HTTP.@register(ROUTER, "GET", "/registered_jobs/", registered_jobs)

job_versions(req) = Service.job_versions(job_path(req))
HTTP.@register(ROUTER, "GET", "/job_versions/*", job_versions)

rm_version!(req) = Service.rm_version!(job_path(req), JSON3.read(req.body, Int))
HTTP.@register(ROUTER, "PUT", "/rm_version/*", rm_version!)

last_running_calculation(req) = Service.last_running_calculation(job_path(req))
HTTP.@register(ROUTER, "GET", "/last_running_calculation/*", last_running_calculation)

outputdata(req) = Service.outputdata(job_path(req), JSON3.read(req.body, Vector{String}))
HTTP.@register(ROUTER, "GET", "/outputdata/*", outputdata)

running_jobs(req) = Service.running_jobs(job_path(req))
HTTP.@register(ROUTER, "GET", "/running_jobs/", running_jobs)
HTTP.@register(ROUTER, "GET", "/running_jobs/*", running_jobs)


text:
function _make_kkt_solver!(ws::COSMO.Workspace)

	ws.kkt_solver = ws.settings.kkt_solver(SparseMatrixCSC(ws.p.P),
						SparseMatrixCSC(ws.p.A),
						ws.settings.sigma,
						ws.ρvec)
end

function _make_accelerator!(ws::COSMO.Workspace{T}) where {T <: AbstractFloat}
  # if the user passed in a custom AbstractAccelerator, e.g. with different value for memory, don't change it
	m, n = ws.p.model_size
	ws.accelerator = ws.settings.accelerator(m + n)
end

function setup!(ws::COSMO.Workspace)

  	allocate_set_memory!(ws)
	# scale problem data
	if ws.settings.scaling != 0 && !ws.states.IS_SCALED
		if ws.settings.verbose_timing
			ws.times.scaling_time = @elapsed scale_ruiz!(ws)
		else
			scale_ruiz!(ws)
		end
		ws.states.IS_SCALED = true
	else
		# even if the problem data is already scaled, we still have to scale our (potentially warm-started) variables
		scale_variables!(ws.vars.x, ws.vars.μ, ws.vars.s, ws.sm.Dinv, ws.sm.Einv, ws.sm.E, ws.sm.c)
		ws.times.scaling_time = 0.
	end

	# construct a set index --> row range map
	ws.row_ranges = get_set_indices(ws.p.C.sets)
	classify_constraints!(ws)

	# only set ρ to settings value if this is the first time solving, otherwise keep ρ in sync with value used in KKT-factorisation
	if !ws.states.IS_OPTIMIZED
		set_rho_vec!(ws)
	end

	# instantiate accelerator
	if !ws.states.KKT_FACTORED
		_make_accelerator!(ws)
	else
		CA.restart!(ws.accelerator)
		ws.accelerator_active = false
	end

	# create a KKT solver object populated with our data
	if !ws.states.KKT_FACTORED
		if ws.settings.verbose_timing
			ws.times.init_factor_time = @elapsed _make_kkt_solver!(ws)
		else
			_make_kkt_solver!(ws)
		end
		ws.states.KKT_FACTORED = true
	end

end

function allocate_set_memory!(ws::COSMO.Workspace)
	if !ws.states.IS_OPTIMIZED
		for (k, C) in enumerate(ws.p.C.sets)
			allocate_memory!(C)
		end
	end
end

"For inequality and box constraints, check if any constraints are obviously loose or tight."
function classify_constraints!(ws::COSMO.Workspace)
	for (k, C) in enumerate(ws.p.C.sets)
		if C isa Nonnegatives
			b = view(ws.p.b, ws.row_ranges[k])
			classify_constraints!(C.constr_type, b, ws.settings.COSMO_INFTY, ws.settings.MIN_SCALING)
		elseif C isa Box
			classify_box_constraints!(C, ws.settings.COSMO_INFTY, ws.settings.MIN_SCALING, ws.settings.RHO_TOL)
		end
	end
	return nothing
end


text:
GQL_FRAGMENT_FACTORS = """
  fragment factor_skeleton_fields on Factor {
    label
    tags
    _variableOrderSymbols
  }
  fragment factor_summary_fields on Factor {
    timestamp
    _version
  }
  fragment factor_full_fields on Factor {
    fnctype
    solvable
    data
  }
  """

GQL_GETFACTOR = """
  query sdk_get_factor(
      \$userId: ID!,
      \$robotId: ID!,
      \$sessionId: ID!,
      \$label: ID!) {
      users(where:{id:\$userId}) {
        robots(where:{id: \$robotId}) {
          sessions(where:{id: \$sessionId}) {
            factors(where:{label: \$label}) {
            ...factor_skeleton_fields
            ...factor_summary_fields
            ...factor_full_fields
          }
        }
      }
    }
  }"""

GQL_GETFACTORS = """
  query sdk_get_factors(
      \$userId: ID!,
      \$robotId: ID!,
      \$sessionId: ID!,
      \$fields_summary: Boolean! = false,
      \$fields_full: Boolean! = false){
    users(where:{id:\$userId}) {
      name
      robots(where:{id: \$robotId}) {
        name
        sessions(where:{id: \$sessionId}){
          name
          factors {
            ...factor_skeleton_fields
            ...factor_summary_fields @include(if: \$fields_summary)
            ...factor_full_fields @include(if: \$fields_full)
          }
        }
      }
    }
  }"""

GQL_GETFACTORSFILTERED = """
  query sdk_get_factors(
      \$userId: ID!,
      \$robotIds: [ID!]!,
      \$sessionIds: [ID!]!,
      \$factor_label_regexp: String = ".*",
      \$factor_tags: [String] = ["FACTOR"],
      \$solvable: Int! = 0,
      \$fields_summary: Boolean! = false,
      \$fields_full: Boolean! = false){
    users(where:{id:\$userId}) {
      name
      robots(where:{id_IN: \$robotIds}) {
        name
        sessions(where:{id_IN: \$sessionIds}){
          name
          factors(where:{
            label_MATCHES: \$factor_label_regexp,
          	tags: \$factor_tags,
          	solvable_GTE: \$solvable}) {
            ...factor_skeleton_fields
            ...factor_summary_fields @include(if: \$fields_summary)
            ...factor_full_fields @include(if: \$fields_full)
          }
        }
      }
    }
  }"""


text:
@safetestset "POST form payload" begin

  using Genie, HTTP, Genie.Router, Genie.Requests

  route("/") do
    "GET"
  end

  route("/", method = POST) do
    params(:greeting)
  end

  route("/data", method = POST) do
    fields = postpayload(Symbol("fields[]"))
    fields[1] * fields[2] * postpayload(:single)
  end

  port = nothing
  port = rand(8500:8900)

  up(port; open_browser = false)

  response = HTTP.request("POST", "http://localhost:$port/", ["Content-Type" => "application/x-www-form-urlencoded"], "greeting=Hello")
  @test response.status == 200
  @test String(response.body) == "Hello"

  response = HTTP.request("POST", "http://localhost:$port/", ["Content-Type" => "application/x-www-form-urlencoded"], "greeting=Hey you there")
  @test response.status == 200
  @test String(response.body) == "Hey you there"

  response = HTTP.request("GET", "http://localhost:$port/", ["Content-Type" => "application/x-www-form-urlencoded"], "greeting=Hello")
  @test response.status == 200
  @test String(response.body) == "GET"

  response = HTTP.request("POST", "http://localhost:$port/data", ["Content-Type" => "application/x-www-form-urlencoded"], "fields%5B%5D=Hey you there&fields%5B%5D=&single=")
  @test response.status == 200
  @test String(response.body) == "Hey you there"

  response = HTTP.request("POST", "http://localhost:$port/data", ["Content-Type" => "application/x-www-form-urlencoded"], "fields%5B%5D=1&fields%5B%5D=2&single=3")
  @test response.status == 200
  @test String(response.body) == "123"

  response = HTTP.post("http://localhost:$port", [], HTTP.Form(Dict("greeting" => "Hello")))
  @test response.status == 200
  @test String(response.body) == "Hello"

  response = HTTP.post("http://localhost:$port", [], HTTP.Form(Dict("greeting" => "Hey you there")))
  @test response.status == 200
  @test String(response.body) == "Hey you there"

  down()
  sleep(1)
  server = nothing
  port = nothing
end


text:
using StaticArrays

# OpenVR uses something like "hungarian notation"
#   https://en.wikipedia.org/wiki/Hungarian_notation
# the german Wikipedia has more complete tables about that
#  https://de.wikipedia.org/wiki/Ungarische_Notation

# opaque pointers / forward declarations from openVR0.h:27
const VkDevice_T = Nothing
const VkPhysicalDevice_T = Nothing
const VkInstance_T = Nothing
const VkQueue_T = Nothing
const ID3D12Resource = Nothing
const ID3D12CommandQueue = Nothing

# pointer_from_objref cannot be used on immutable objects

# TODO: the SArray needs to be
#   SArray{Tuple{N₁,…,Nₙ},Int64,n,N₁*…*Nₙ}
# e.g.
#   SArray{Tuple{4},Int64,1,4}
#   SArray{Tuple{4,3},Int64,2,4*3}
#   SArray{Tuple{5,4,3},Int64,3,5*4*3}
# TODO: all these need to be immutable structs, that are _safely allocated_ when Ref is used they are not assumed to be constant anymore

# NOTE: https://en.wikipedia.org/wiki/Row-_and_column-major_order#Programming_languages_and_libraries
#  Row-major order is used in C/C++/Objective-C (for C-style arrays), PL/I, Pascal, Speakeasy, SAS, and Rasdaman.
#  Column-major order is used in Fortran, MATLAB, GNU Octave, S-Plus, R, Julia, and Scilab.

# clang-query -c="set output dump" -c="set bind-root false" -c=" match decl(eachOf(cxxRecordDecl(allOf(isExpansionInMainFile(),isStruct(),hasDefinition())).bind(\"r\"),recordDecl(allOf(isExpansionInMainFile(),isStruct(),forEach(fieldDecl().bind(\"f\")))),typedefDecl(isExpansionInMainFile()).bind(\"t\")))" -extra-arg-before=-xc++ /home/christianl/src/openvr/headers/openvr.h | sed -r "s/[[:cntrl:]]\[([0-9]{1,3};)*[0-9]{1,3}m//g" | grep -E "^CXXRecordDecl|^FieldDecl|^TypedefDecl" | sed -e "s/^FieldDecl.* \([^ ]\+\) '\([^']\+\)'.*/  \1 :: \2/" -e "s/^CXXRecordDecl.* \([^ ]\+\) definition/struct \1/" -e"s/^TypedefDecl.* \([^ ]\+\) 'union \(.\+\)'$/# const \1 = Union{\2} # NOTE: C unions are not supported in Julia/" -e "s/^TypedefDecl.* \([^ ]\+\) '\([^']\+\)'.*/const \1 = \2/" -e "s/vr:://" -e "s/float/Float32/" -e "s/double/Float64/" -e "s/char/Cchar/" -e "s/uint\([^ ]*\)_t/UInt\1/" -e "s/int\([^ ]*\)_t/Int\1/" -e "s/bool/Bool/" -e "s/\(const\)\{0,1\} *void \*/ Ptr{Nothing}/" -e "s/\(const\)\{0,1\} *\([^ ]\+\) \*/Ptr{\2}/" -e "s/ \([^ ]\+\) \[\(.*\)\]/ SArray{Tuple{\2},\1}/" -e "s/\(Tuple{.*\)\]\[\(.*}\)/\1,\2/" -e "s/\(Tuple{.*\)\]\[\(.*}\)/\1,\2/" | sed -e ":0;/^ /b1;p;z;N;s/^\n//;b0;:1;/^[^ ]/{i\\" -e "end" -e ";b0};p;z;N;s/^\n//;b1"

const SpatialAnchorHandle_t = UInt32
const glSharedTextureHandle_t = Ptr{Nothing}
const glInt_t = Int32
const glUInt_t = UInt32
struct HmdMatrix34_t
  m :: SArray{Tuple{4,3},Float32,2,3*4} # NOTE: C is row-major, Julia is column-major
end
struct HmdMatrix33_t
  m :: SArray{Tuple{3,3},Float32,2,3*3} # NOTE: C is row-major, Julia is column-major
end
struct HmdMatrix44_t
  m :: SArray{Tuple{4,4},Float32,2,4*4} # NOTE: C is row-major, Julia is column-major
end
struct HmdVector3_t
  v :: SArray{Tuple{3},Float32,1,3}
end
struct HmdVector4_t
  v :: SArray{Tuple{4},Float32,1,4}
end
struct HmdVector3d_t
  v :: SArray{Tuple{3},Float64,1,3}
end
struct HmdVector2_t
  v :: SArray{Tuple{2},Float32,1,2}
end
struct HmdQuaternion_t
  w :: Float64
  x :: Float64
  y :: Float64
  z :: Float64
end
struct HmdQuaternionf_t
  w :: Float32
  x :: Float32
  y :: Float32
  z :: Float32
end
struct HmdColor_t
  r :: Float32
  g :: Float32
  b :: Float32
  a :: Float32
end
struct HmdQuad_t
  vCorners :: SArray{Tuple{4},HmdVector3_t,1,4}
end
struct HmdRect2_t
  vTopLeft :: HmdVector2_t
  vBottomRight :: HmdVector2_t
end
struct DistortionCoordinates_t
  rfRed :: SArray{Tuple{2},Float32,1,2}
  rfGreen :: SArray{Tuple{2},Float32,1,2}
  rfBlue :: SArray{Tuple{2},Float32,1,2}
end
struct Texture_t
  handle :: Ptr{Nothing}
  eType :: ETextureType
  eColorSpace :: EColorSpace
end
const SharedTextureHandle_t = UInt64
const DriverId_t = UInt32
const TrackedDeviceIndex_t = UInt32
struct TrackedDevicePose_t
  mDeviceToAbsoluteTracking :: HmdMatrix34_t
  vVelocity :: HmdVector3_t
  vAngularVelocity :: HmdVector3_t
  eTrackingResult :: ETrackingResult
  bPoseIsValid :: Bool
  bDeviceIsConnected :: Bool
end
const WebConsoleHandle_t = UInt64
const PropertyContainerHandle_t = UInt64
const PropertyTypeTag_t = UInt32
const DriverHandle_t = PropertyContainerHandle_t
const VRActionHandle_t = UInt64
const VRActionSetHandle_t = UInt64
const VRInputValueHandle_t = UInt64
struct VRTextureBounds_t
  uMin :: Float32
  vMin :: Float32
  uMax :: Float32
  vMax :: Float32
end
struct VRTextureWithPose_t
  mDeviceToAbsoluteTracking :: HmdMatrix34_t
end
struct VRTextureDepthInfo_t
  handle :: Ptr{Nothing}
  mProjection :: HmdMatrix44_t
  vRange :: HmdVector2_t
end
struct VRTextureWithDepth_t
  depth :: VRTextureDepthInfo_t
end
struct VRTextureWithPoseAndDepth_t
  depth :: VRTextureDepthInfo_t
end
struct VRVulkanTextureData_t
  m_nImage :: UInt64
  m_pDevice ::Ptr{VkDevice_T}
  m_pPhysicalDevice ::Ptr{VkPhysicalDevice_T}
  m_pInstance ::Ptr{VkInstance_T}
  m_pQueue ::Ptr{VkQueue_T}
  m_nQueueFamilyIndex :: UInt32
  m_nWidth :: UInt32
  m_nHeight :: UInt32
  m_nFormat :: UInt32
  m_nSampleCount :: UInt32
end
struct D3D12TextureData_t
  m_pResource ::Ptr{ID3D12Resource}
  m_pCommandQueue ::Ptr{ID3D12CommandQueue}
  m_nNodeMask :: UInt32
end
struct VREvent_Controller_t
  button :: UInt32
end
struct VREvent_Mouse_t
  x :: Float32
  y :: Float32
  button :: UInt32
end
struct VREvent_Scroll_t
  xdelta :: Float32
  ydelta :: Float32
  repeatCount :: UInt32
end
struct VREvent_TouchPadMove_t
  bFingerDown :: Bool
  flSecondsFingerDown :: Float32
  fValueXFirst :: Float32
  fValueYFirst :: Float32
  fValueXRaw :: Float32
  fValueYRaw :: Float32
end
struct VREvent_Notification_t
  ulUserValue :: UInt64
  notificationId :: UInt32
end
struct VREvent_Process_t
  pid :: UInt32
  oldPid :: UInt32
  bForced :: Bool
  bConnectionLost :: Bool
end
struct VREvent_Overlay_t
  overlayHandle :: UInt64
  devicePath :: UInt64
end
struct VREvent_Status_t
  statusState :: UInt32
end
struct VREvent_Keyboard_t
  cNewInput :: SArray{Tuple{8},Cchar,1,8}
  uUserValue :: UInt64
end
struct VREvent_Ipd_t
  ipdMeters :: Float32
end
struct VREvent_Chaperone_t
  m_nPreviousUniverse :: UInt64
  m_nCurrentUniverse :: UInt64
end
struct VREvent_Reserved_t
  reserved0 :: UInt64
  reserved1 :: UInt64
  reserved2 :: UInt64
  reserved3 :: UInt64
  reserved4 :: UInt64
  reserved5 :: UInt64
end
struct VREvent_PerformanceTest_t
  m_nFidelityLevel :: UInt32
end
struct VREvent_SeatedZeroPoseReset_t
  bResetBySystemMenu :: Bool
end
struct VREvent_Screenshot_t
  handle :: UInt32
  type :: UInt32
end
struct VREvent_ScreenshotProgress_t
  progress :: Float32
end
struct VREvent_ApplicationLaunch_t
  pid :: UInt32
  unArgsHandle :: UInt32
end
struct VREvent_EditingCameraSurface_t
  overlayHandle :: UInt64
  nVisualMode :: UInt32
end
struct VREvent_MessageOverlay_t
  unVRMessageOverlayResponse :: UInt32
end
struct VREvent_Property_t
  container :: PropertyContainerHandle_t
  prop :: ETrackedDeviceProperty
end
struct VREvent_DualAnalog_t
  x :: Float32
  y :: Float32
  transformedX :: Float32
  transformedY :: Float32
  which :: EDualAnalogWhich
end
struct VREvent_HapticVibration_t
  containerHandle :: UInt64
  componentHandle :: UInt64
  fDurationSeconds :: Float32
  fFrequency :: Float32
  fAmplitude :: Float32
end
struct VREvent_WebConsole_t
  webConsoleHandle :: WebConsoleHandle_t
end
struct VREvent_InputBindingLoad_t
  ulAppContainer :: PropertyContainerHandle_t
  pathMessage :: UInt64
  pathUrl :: UInt64
  pathControllerType :: UInt64
end
struct VREvent_InputActionManifestLoad_t
  pathAppKey :: UInt64
  pathMessage :: UInt64
  pathMessageParam :: UInt64
  pathManifestPath :: UInt64
end
struct VREvent_SpatialAnchor_t
  unHandle :: SpatialAnchorHandle_t
end
struct VREvent_ProgressUpdate_t
  ulApplicationPropertyContainer :: UInt64
  pathDevice :: UInt64
  pathInputSource :: UInt64
  pathProgressAction :: UInt64
  pathIcon :: UInt64
  fProgress :: Float32
end
struct VREvent_ShowUI_t
  eType :: EShowUIType
end
# const VREvent_Data_t = Union{VREvent_Data_t':'VREvent_Data_t} # NOTE: C unions are not supported in Julia
struct VREvent_Data_t
  data :: NTuple{Int64(VREvent_Data_tLen),UInt8}
end
struct VREvent_t
  eventType :: UInt32
  trackedDeviceIndex :: TrackedDeviceIndex_t
  eventAgeSeconds :: Float32
  data :: VREvent_Data_t
end
struct HiddenAreaMesh_t
  pVertexData :: Ptr{HmdVector2_t}
  unTriangleCount :: UInt32
end
struct VRControllerAxis_t
  x :: Float32
  y :: Float32
end
struct VRControllerState001_t
  unPacketNum :: UInt32
  ulButtonPressed :: UInt64
  ulButtonTouched :: UInt64
  rAxis :: SArray{Tuple{5},VRControllerAxis_t,1,5}
end
const VRControllerState_t = VRControllerState001_t
struct Compositor_OverlaySettings
  size :: UInt32
  curved :: Bool
  antialias :: Bool
  scale :: Float32
  distance :: Float32
  alpha :: Float32
  uOffset :: Float32
  vOffset :: Float32
  uScale :: Float32
  vScale :: Float32
  gridDivs :: Float32
  gridWidth :: Float32
  gridScale :: Float32
  transform :: HmdMatrix44_t
end
const VROverlayHandle_t = UInt64
struct VRBoneTransform_t
  position :: HmdVector4_t
  orientation :: HmdQuaternionf_t
end
const BoneIndex_t = Int32
const TrackedCameraHandle_t = UInt64
struct CameraVideoStreamFrameHeader_t
  eFrameType :: EVRTrackedCameraFrameType
  nWidth :: UInt32
  nHeight :: UInt32
  nBytesPerPixel :: UInt32
  nFrameSequence :: UInt32
  standingTrackedDevicePose :: TrackedDevicePose_t
  ulFrameExposureTime :: UInt64
end
const ScreenshotHandle_t = UInt32
struct DriverDirectMode_FrameTiming
  m_nSize :: UInt32
  m_nNumFramePresents :: UInt32
  m_nNumMisPresented :: UInt32
  m_nNumDroppedFrames :: UInt32
  m_nReprojectionFlags :: UInt32
end
struct ImuSample_t
  fSampleTime :: Float64
  vAccel :: HmdVector3d_t
  vGyro :: HmdVector3d_t
  unOffScaleFlags :: UInt32
end
struct AppOverrideKeys_t
  pchKey :: Ptr{Cchar}
  pchValue :: Ptr{Cchar}
end
struct Compositor_FrameTiming
  m_nSize :: UInt32
  m_nFrameIndex :: UInt32
  m_nNumFramePresents :: UInt32
  m_nNumMisPresented :: UInt32
  m_nNumDroppedFrames :: UInt32
  m_nReprojectionFlags :: UInt32
  m_flSystemTimeInSeconds :: Float64
  m_flPreSubmitGpuMs :: Float32
  m_flPostSubmitGpuMs :: Float32
  m_flTotalRenderGpuMs :: Float32
  m_flCompositorRenderGpuMs :: Float32
  m_flCompositorRenderCpuMs :: Float32
  m_flCompositorIdleCpuMs :: Float32
  m_flClientFrameIntervalMs :: Float32
  m_flPresentCallCpuMs :: Float32
  m_flWaitForPresentCpuMs :: Float32
  m_flSubmitFrameMs :: Float32
  m_flWaitGetPosesCalledMs :: Float32
  m_flNewPosesReadyMs :: Float32
  m_flNewFrameReadyMs :: Float32
  m_flCompositorUpdateStartMs :: Float32
  m_flCompositorUpdateEndMs :: Float32
  m_flCompositorRenderStartMs :: Float32
  m_HmdPose :: TrackedDevicePose_t
  m_nNumVSyncsReadyForUse :: UInt32
  m_nNumVSyncsToFirstView :: UInt32
end
struct Compositor_CumulativeStats
  m_nPid :: UInt32
  m_nNumFramePresents :: UInt32
  m_nNumDroppedFrames :: UInt32
  m_nNumReprojectedFrames :: UInt32
  m_nNumFramePresentsOnStartup :: UInt32
  m_nNumDroppedFramesOnStartup :: UInt32
  m_nNumReprojectedFramesOnStartup :: UInt32
  m_nNumLoading :: UInt32
  m_nNumFramePresentsLoading :: UInt32
  m_nNumDroppedFramesLoading :: UInt32
  m_nNumReprojectedFramesLoading :: UInt32
  m_nNumTimedOut :: UInt32
  m_nNumFramePresentsTimedOut :: UInt32
  m_nNumDroppedFramesTimedOut :: UInt32
  m_nNumReprojectedFramesTimedOut :: UInt32
end
struct NotificationBitmap_t
  m_pImageData :: Ptr{Nothing}
  m_nWidth :: Int32
  m_nHeight :: Int32
  m_nBytesPerPixel :: Int32
end
const VRNotificationId = UInt32
struct VROverlayIntersectionParams_t
  vSource :: HmdVector3_t
  vDirection :: HmdVector3_t
  eOrigin :: ETrackingUniverseOrigin
end
struct VROverlayIntersectionResults_t
  vPoint :: HmdVector3_t
  vNormal :: HmdVector3_t
  vUVs :: HmdVector2_t
  fDistance :: Float32
end
struct IntersectionMaskRectangle_t
  m_flTopLeftX :: Float32
  m_flTopLeftY :: Float32
  m_flWidth :: Float32
  m_flHeight :: Float32
end
struct IntersectionMaskCircle_t
  m_flCenterX :: Float32
  m_flCenterY :: Float32
  m_flRadius :: Float32
end
# const VROverlayIntersectionMaskPrimitive_Data_t = Union{VROverlayIntersectionMaskPrimitive_Data_t':'VROverlayIntersectionMaskPrimitive_Data_t} # NOTE: C unions are not supported in Julia
struct VROverlayIntersectionMaskPrimitive_Data_t
  data :: NTuple{Int64(VROverlayIntersectionMaskPrimitive_Data_tLen),UInt8}
end
struct VROverlayIntersectionMaskPrimitive_t
  m_nPrimitiveType :: EVROverlayIntersectionMaskPrimitiveType
  m_Primitive :: VROverlayIntersectionMaskPrimitive_Data_t
end
const VRComponentProperties = UInt32
struct RenderModel_ComponentState_t
  mTrackingToComponentRenderModel :: HmdMatrix34_t
  mTrackingToComponentLocal :: HmdMatrix34_t
  uProperties :: VRComponentProperties
end
struct RenderModel_Vertex_t
  vPosition :: HmdVector3_t
  vNormal :: HmdVector3_t
  rfTextureCoord :: SArray{Tuple{2},Float32,1,2}
end
struct RenderModel_TextureMap_t
  unWidth :: UInt16
  unHeight :: UInt16
  rubTextureMapData1 :: UInt32 # Ptr{UInt8}
  rubTextureMapData2 :: UInt32 # Ptr{UInt8}
end
const TextureID_t = Int32
struct RenderModel_t
  rVertexData :: Ptr{RenderModel_Vertex_t} # const RenderModel_Vertex_t *rVertexData; // Vertex data for the mesh
  unVertexCount :: UInt32                  # uint32_t unVertexCount;                  // Number of vertices in the vertex data
  rIndexData1 :: UInt32 # Ptr{…}
  rIndexData2 :: UInt32 # Ptr{…}                # const uint16_t *rIndexData;              // Indices into the vertex data for each triangle
  unTriangleCount :: UInt32                # uint32_t unTriangleCount;                // Number of triangles in the mesh. Index count is 3 * TriangleCount
  diffuseTextureId :: TextureID_t          # TextureID_t diffuseTextureId;
end
struct RenderModel_ControllerMode_State_t
  bScrollWheelVisible :: Bool
end
struct InputAnalogActionData_t
  bActive :: Bool
  activeOrigin :: VRInputValueHandle_t
  x :: Float32
  y :: Float32
  z :: Float32
  deltaX :: Float32
  deltaY :: Float32
  deltaZ :: Float32
  fUpdateTime :: Float32
end
struct InputDigitalActionData_t
  bActive :: Bool
  activeOrigin :: VRInputValueHandle_t
  bState :: Bool
  bChanged :: Bool
  fUpdateTime :: Float32
end
struct InputPoseActionData_t
  bActive :: Bool
  activeOrigin :: VRInputValueHandle_t
  pose :: TrackedDevicePose_t
end
struct InputSkeletalActionData_t
  bActive :: Bool
  activeOrigin :: VRInputValueHandle_t
end
struct InputOriginInfo_t
  devicePath :: VRInputValueHandle_t
  trackedDeviceIndex :: TrackedDeviceIndex_t
  rchRenderModelComponentName :: SArray{Tuple{128},Cchar,1,128}
end
struct VRActiveActionSet_t
  ulActionSet :: VRActionSetHandle_t
  ulRestrictedToDevice :: VRInputValueHandle_t
  ulSecondaryActionSet :: VRActionSetHandle_t
  unPadding :: UInt32
  nPriority :: Int32
end
struct VRSkeletalSummaryData_t
  flFingerCurl :: SArray{Tuple{5},Float32,1,5}
  flFingerSplay :: SArray{Tuple{4},Float32,1,4}
end
const IOBufferHandle_t = UInt64
struct SpatialAnchorPose_t
  mAnchorToAbsoluteTracking :: HmdMatrix34_t
end
const HmdError = EVRInitError
const Hmd_Eye = EVREye
const ColorSpace = EColorSpace
const HmdTrackingResult = ETrackingResult
const TrackedDeviceClass = ETrackedDeviceClass
const TrackingUniverseOrigin = ETrackingUniverseOrigin
const TrackedDeviceProperty = ETrackedDeviceProperty
const TrackedPropertyError = ETrackedPropertyError
const VRSubmitFlags_t = EVRSubmitFlags
const VRState_t = EVRState
const CollisionBoundsStyle_t = ECollisionBoundsStyle
const VROverlayError = EVROverlayError
const VRFirmwareError = EVRFirmwareError
const VRCompositorError = EVRCompositorError
const VRScreenshotsError = EVRScreenshotError


text:
# Julia code
# Copyright (c) 2022 the SLICOTMath.jl developers
# Portions extracted from SLICOT-Reference distribution:
# Copyright (c) 2002-2020 NICONET e.V.

function run_mb02ed(datfile, io=stdout)
    NIN = 5
    NOUT = 6
    KMAX = 20
    NMAX = 20
    LDB = KMAX*NMAX
    LDT = KMAX*NMAX
    LDWORK = NMAX*KMAX*KMAX + ( NMAX+2 )*KMAX
    T = Array{Float64,2}(undef, LDT,KMAX*NMAX)
    B = Array{Float64,2}(undef, LDB,KMAX*NMAX)
    DWORK = Array{Float64,1}(undef, LDWORK)
    f = open(datfile,"r")
    readline(f)
    vs = split(readline(f))
    N = parse(BlasInt, vs[1])
    K = parse(BlasInt, vs[2])
    NRHS = parse(BlasInt, vs[3])
    TYPET =  vs[4][1]
    M = N*K
if ( N<=0 || N>NMAX )
else
if ( K<=0 || K>KMAX )
else
if ( NRHS<=0 || NRHS>KMAX*NMAX )
else
if ( LSAME( TYPET, 'R' ) )

    vs = String[]
    _isz,_jsz = (K,M)
    while length(vs) < _isz*_jsz
        append!(vs, replace.(split(readline(f)),'D'=>'E'))
    end
    for i in 1:_isz
       _i0 = (i-1)*_jsz
       T[i,1:_jsz] .= parsex.(Float64, vs[_i0+1:_i0+_jsz])
    end
else

    vs = String[]
    _isz,_jsz = (M,K)
    while length(vs) < _isz*_jsz
        append!(vs, replace.(split(readline(f)),'D'=>'E'))
    end
    for i in 1:_isz
       _i0 = (i-1)*_jsz
       T[i,1:_jsz] .= parsex.(Float64, vs[_i0+1:_i0+_jsz])
    end
end # if
if ( LSAME( TYPET, 'R' ) )

    vs = String[]
    _isz,_jsz = (NRHS,M)
    while length(vs) < _isz*_jsz
        append!(vs, replace.(split(readline(f)),'D'=>'E'))
    end
    for i in 1:_isz
       _i0 = (i-1)*_jsz
       B[i,1:_jsz] .= parsex.(Float64, vs[_i0+1:_i0+_jsz])
    end
else

    vs = String[]
    _isz,_jsz = (M,NRHS)
    while length(vs) < _isz*_jsz
        append!(vs, replace.(split(readline(f)),'D'=>'E'))
    end
    for i in 1:_isz
       _i0 = (i-1)*_jsz
       B[i,1:_jsz] .= parsex.(Float64, vs[_i0+1:_i0+_jsz])
    end
end # if
# interp call 1

    INFO = SLICOT.mb02ed!(TYPET, K, N, NRHS, T, B, LDWORK)
    @test INFO == 0
    INFO == 0 || return

if ( INFO!=0 )
else
if ( LSAME( TYPET, 'R' ) )
# interp output 1
    println(io,"B:")
    _nc = M
    _nr = NRHS
    show(io,"text/plain",B[1:_nr,1:_nc])
    println(io,)

else
# interp output 2
    println(io,"B:")
    _nc = NRHS
    _nr = M
    show(io,"text/plain",B[1:_nr,1:_nc])
    println(io,)

end # if
end # if
end # if
end # if
end # if
    close(f)
end # run_X()


text:
println("\t\"He came riding fast, like a phoenix out of fire-flames.\" -- The Dancer, PJ Harvey" )

function randH(SiteEnergy, Edisorder, Jdisorder, modelJ, N)
# Random Trace / diagonal elements
    S=SiteEnergy + Edisorder*randn(N)
# Random Off-diag elements
    E=modelJ(0) + Jdisorder*randn(N-1)
    return (S,E)
end

function prepare_model2()
    S,E=randH(5.0,Edisorder, Jdisorder, modelJ, N)
    H=diagm(E,-1)+diagm(S)+diagm(E,1) #build full matrix from diagonal elements; for comparison
    psi=eigvecs(H)[:,1] # 1=gnd state

    #    Plot_H(H)
    #    TODO: UPDATE THIS FOR PLOTS.jl

    ## Construct initial dipoles structure
    density = conj(psi).*psi

    return S,E,H,psi,density
end

function FieldFromDensity(density)
    Field=zeros(N)
    for i in 1:N
        Fsum=zero(eltype(density)) # Calculate total field at each
        for j in 1:N
            if (j==i)
                continue # avoid infinite self energies
            end
            Fsum+=sign(i-j)*density[j]/(i-j)^2 # How much do the dipoles respond to the electron density?
        end                         # check power of r for field from point charge.
        Field[i]=Fsum/r^2
    end
    return Field
end

function FieldFromDipole(dipole)
    FieldDI=zeros(N)
    for i in 1:N
        FDIsum=zero(eltype(dipole)) # Calculate total field at each
        for j in 1:N
            if (j==i)
                continue # avoid infinite self energies
            end
            FDIsum+=-9*sign(j-i)*dipole[j]/((r*(j-i))^7) # How much do the dipoles respond to the electron density?
        end
        FieldDI[i]=FDIsum
    end
    return FieldDI
end

" Decompose Hamiltonian into Diagonal/S/PE and Off-diag/J/KE elements"
function Decompose_H(H)
    S=eye(N).*H # elementwise to select for just diagonal terms
    J=H-S
    return S,J
end

function Propagate(H,psi,dt)
    U=eye(H) # identiy matrix same size + type as H

    S,J=Decompose_H(H) # split into diagonal and off-diag terms
    #Trotter decomposition
    U*=expm(-im*J*dt/2*hbar)*expm(-im*S*dt/hbar)*expm(-im*J*dt/2*hbar)
    psi = U*psi
    #psi=eigvecs(H)[:,1]
    En = eigvals(H)
    normalisation = norm(psi)
    psi = psi/normalisation

    density = conj(psi).*psi
    return psi, density
end

function UpdateDipole(Field,density,dipole)
    alphainv = -1*ones(N)#(221*N*density)#
    M = diagm(alphainv)
    n=0
    n2=1
    for i in 1:N
        for j in 1:N
            if (j==i)
                #M[n+j] = alpha[i]
                continue
            end
            M[n+j] = 1/(r*(j-i))^3
        end
        n+=N
    end
    new_dipole = \(M,Field)
    dipole += 0.5*(new_dipole-dipole)
    return dipole

end

function UpdateEnergy(dipole,density,FieldDI, Field,S,E)
    Vpq = (dipole.*(Field)+ density.*(FieldDI))
    norm_vpq = norm(Vpq)
    #plot(real(Vpq), label = "Vpq")
    Vpp = dipole.*(FieldDI)
    norm_vpp = norm(Vpp)
    #plot!(real(Vpp), label = "Vpp")
    Vqq = N*density.*(Field)
    norm_vqq = norm(Vqq)
    #plot!(real(Vqq), label = "Vqq")
    #KE = S - V
    #E=?
    S=Vpq+Vpp+Vqq
    norm_S = norm(S)
    #plot!(real(S), label = "Total")
    println("norms: vpq", norm_vpq, "vpp", norm_vpp, "vqq", norm_vqq, "total", norm_S)

    H=diagm(E,-1)+diagm(S)+diagm(E,1) #build full matrix from diagonal elements; for comparison
    return S,E,H
end

function UpdateEnergy2(dipole,Field,S,E)
    S=zeros(N)
    for i in 1:N
        for j in 1:N
            if (j==i)
                continue # avoid infinity in self energies
            end
            S[i]+=sign(j-i)*dipole[j]/(r*(j-i))^2 # Contribution to site energy (1 e- at site) from dipoles
        end
#        @printf("Site: i %d SiteEnergy: S[i] %f\n",i,S[i])
    end
    H=diagm(E,-1)+diagm(S)+diagm(E,1)
    return S,E,H
end

function nondispersive_wavepacket(x0, λ)
    ψ=[ exp(-(x-x0)^2)*(cos(2π*(x-x0)/λ) - im * sin(2π*(x-x0)/λ) ) for x=1:N ]
    return ψ
end

"""
Think about which way the energy, dipoles and fields should be....
Think about magnitudes of dipoles and densities vs Fields (hence which have the most weight for energy)
"""