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

"""
    CreateConfigurationSet()

Create a configuration set. Configuration sets are groups of rules that you can apply to the emails you send using Amazon Pinpoint. You apply a configuration set to an email by including a reference to the configuration set in the headers of the email. When you apply a configuration set to an email, all of the rules in that configuration set are applied to the email.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set.

# Optional Parameters
- `DeliveryOptions`: An object that defines the dedicated IP pool that is used to send emails that you send using the configuration set.
- `ReputationOptions`: An object that defines whether or not Amazon Pinpoint collects reputation metrics for the emails that you send that use the configuration set.
- `SendingOptions`: An object that defines whether or not Amazon Pinpoint can send email that you send using the configuration set.
- `Tags`: An array of objects that define the tags (keys and values) that you want to associate with the configuration set.
- `TrackingOptions`: An object that defines the open and click tracking options for emails that you send using the configuration set.
"""
create_configuration_set(ConfigurationSetName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/configuration-sets", Dict{String, Any}("ConfigurationSetName"=>ConfigurationSetName); aws_config=aws_config)
create_configuration_set(ConfigurationSetName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/configuration-sets", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ConfigurationSetName"=>ConfigurationSetName), args)); aws_config=aws_config)

"""
    CreateConfigurationSetEventDestination()

Create an event destination. In Amazon Pinpoint, events include message sends, deliveries, opens, clicks, bounces, and complaints. Event destinations are places that you can send information about these events to. For example, you can send event data to Amazon SNS to receive notifications when you receive bounces or complaints, or you can use Amazon Kinesis Data Firehose to stream data to Amazon S3 for long-term storage. A single configuration set can include more than one event destination.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set that you want to add an event destination to.
- `EventDestination`: An object that defines the event destination.
- `EventDestinationName`: A name that identifies the event destination within the configuration set.

"""
create_configuration_set_event_destination(ConfigurationSetName, EventDestination, EventDestinationName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/configuration-sets/$(ConfigurationSetName)/event-destinations", Dict{String, Any}("EventDestination"=>EventDestination, "EventDestinationName"=>EventDestinationName); aws_config=aws_config)
create_configuration_set_event_destination(ConfigurationSetName, EventDestination, EventDestinationName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/configuration-sets/$(ConfigurationSetName)/event-destinations", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EventDestination"=>EventDestination, "EventDestinationName"=>EventDestinationName), args)); aws_config=aws_config)

"""
    CreateDedicatedIpPool()

Create a new pool of dedicated IP addresses. A pool can include one or more dedicated IP addresses that are associated with your Amazon Pinpoint account. You can associate a pool with a configuration set. When you send an email that uses that configuration set, Amazon Pinpoint sends it using only the IP addresses in the associated pool.

# Required Parameters
- `PoolName`: The name of the dedicated IP pool.

# Optional Parameters
- `Tags`: An object that defines the tags (keys and values) that you want to associate with the pool.
"""
create_dedicated_ip_pool(PoolName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/dedicated-ip-pools", Dict{String, Any}("PoolName"=>PoolName); aws_config=aws_config)
create_dedicated_ip_pool(PoolName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/dedicated-ip-pools", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PoolName"=>PoolName), args)); aws_config=aws_config)

"""
    CreateDeliverabilityTestReport()

Create a new predictive inbox placement test. Predictive inbox placement tests can help you predict how your messages will be handled by various email providers around the world. When you perform a predictive inbox placement test, you provide a sample message that contains the content that you plan to send to your customers. Amazon Pinpoint then sends that message to special email addresses spread across several major email providers. After about 24 hours, the test is complete, and you can use the GetDeliverabilityTestReport operation to view the results of the test.

# Required Parameters
- `Content`: The HTML body of the message that you sent when you performed the predictive inbox placement test.
- `FromEmailAddress`: The email address that the predictive inbox placement test email was sent from.

# Optional Parameters
- `ReportName`: A unique name that helps you to identify the predictive inbox placement test when you retrieve the results.
- `Tags`: An array of objects that define the tags (keys and values) that you want to associate with the predictive inbox placement test.
"""
create_deliverability_test_report(Content, FromEmailAddress; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/deliverability-dashboard/test", Dict{String, Any}("Content"=>Content, "FromEmailAddress"=>FromEmailAddress); aws_config=aws_config)
create_deliverability_test_report(Content, FromEmailAddress, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/deliverability-dashboard/test", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Content"=>Content, "FromEmailAddress"=>FromEmailAddress), args)); aws_config=aws_config)

"""
    CreateEmailIdentity()

Verifies an email identity for use with Amazon Pinpoint. In Amazon Pinpoint, an identity is an email address or domain that you use when you send email. Before you can use an identity to send email with Amazon Pinpoint, you first have to verify it. By verifying an address, you demonstrate that you're the owner of the address, and that you've given Amazon Pinpoint permission to send email from the address. When you verify an email address, Amazon Pinpoint sends an email to the address. Your email address is verified as soon as you follow the link in the verification email.  When you verify a domain, this operation provides a set of DKIM tokens, which you can convert into CNAME tokens. You add these CNAME tokens to the DNS configuration for your domain. Your domain is verified when Amazon Pinpoint detects these records in the DNS configuration for your domain. It usually takes around 72 hours to complete the domain verification process.

# Required Parameters
- `EmailIdentity`: The email address or domain that you want to verify.

# Optional Parameters
- `Tags`: An array of objects that define the tags (keys and values) that you want to associate with the email identity.
"""
create_email_identity(EmailIdentity; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/identities", Dict{String, Any}("EmailIdentity"=>EmailIdentity); aws_config=aws_config)
create_email_identity(EmailIdentity, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/identities", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EmailIdentity"=>EmailIdentity), args)); aws_config=aws_config)

"""
    DeleteConfigurationSet()

Delete an existing configuration set. In Amazon Pinpoint, configuration sets are groups of rules that you can apply to the emails you send. You apply a configuration set to an email by including a reference to the configuration set in the headers of the email. When you apply a configuration set to an email, all of the rules in that configuration set are applied to the email.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set that you want to delete.

"""
delete_configuration_set(ConfigurationSetName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("DELETE", "/v1/email/configuration-sets/$(ConfigurationSetName)"; aws_config=aws_config)
delete_configuration_set(ConfigurationSetName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("DELETE", "/v1/email/configuration-sets/$(ConfigurationSetName)", args; aws_config=aws_config)

"""
    DeleteConfigurationSetEventDestination()

Delete an event destination. In Amazon Pinpoint, events include message sends, deliveries, opens, clicks, bounces, and complaints. Event destinations are places that you can send information about these events to. For example, you can send event data to Amazon SNS to receive notifications when you receive bounces or complaints, or you can use Amazon Kinesis Data Firehose to stream data to Amazon S3 for long-term storage.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set that contains the event destination that you want to delete.
- `EventDestinationName`: The name of the event destination that you want to delete.

"""
delete_configuration_set_event_destination(ConfigurationSetName, EventDestinationName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("DELETE", "/v1/email/configuration-sets/$(ConfigurationSetName)/event-destinations/$(EventDestinationName)"; aws_config=aws_config)
delete_configuration_set_event_destination(ConfigurationSetName, EventDestinationName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("DELETE", "/v1/email/configuration-sets/$(ConfigurationSetName)/event-destinations/$(EventDestinationName)", args; aws_config=aws_config)

"""
    DeleteDedicatedIpPool()

Delete a dedicated IP pool.

# Required Parameters
- `PoolName`: The name of the dedicated IP pool that you want to delete.

"""
delete_dedicated_ip_pool(PoolName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("DELETE", "/v1/email/dedicated-ip-pools/$(PoolName)"; aws_config=aws_config)
delete_dedicated_ip_pool(PoolName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("DELETE", "/v1/email/dedicated-ip-pools/$(PoolName)", args; aws_config=aws_config)

"""
    DeleteEmailIdentity()

Deletes an email identity that you previously verified for use with Amazon Pinpoint. An identity can be either an email address or a domain name.

# Required Parameters
- `EmailIdentity`: The identity (that is, the email address or domain) that you want to delete from your Amazon Pinpoint account.

"""
delete_email_identity(EmailIdentity; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("DELETE", "/v1/email/identities/$(EmailIdentity)"; aws_config=aws_config)
delete_email_identity(EmailIdentity, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("DELETE", "/v1/email/identities/$(EmailIdentity)", args; aws_config=aws_config)

"""
    GetAccount()

Obtain information about the email-sending status and capabilities of your Amazon Pinpoint account in the current AWS Region.

"""
get_account(; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/account"; aws_config=aws_config)
get_account(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/account", args; aws_config=aws_config)

"""
    GetBlacklistReports()

Retrieve a list of the blacklists that your dedicated IP addresses appear on.

# Required Parameters
- `BlacklistItemNames`: A list of IP addresses that you want to retrieve blacklist information about. You can only specify the dedicated IP addresses that you use to send email using Amazon Pinpoint or Amazon SES.

"""
get_blacklist_reports(BlacklistItemNames; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/blacklist-report", Dict{String, Any}("BlacklistItemNames"=>BlacklistItemNames); aws_config=aws_config)
get_blacklist_reports(BlacklistItemNames, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/blacklist-report", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BlacklistItemNames"=>BlacklistItemNames), args)); aws_config=aws_config)

"""
    GetConfigurationSet()

Get information about an existing configuration set, including the dedicated IP pool that it's associated with, whether or not it's enabled for sending email, and more. In Amazon Pinpoint, configuration sets are groups of rules that you can apply to the emails you send. You apply a configuration set to an email by including a reference to the configuration set in the headers of the email. When you apply a configuration set to an email, all of the rules in that configuration set are applied to the email.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set that you want to obtain more information about.

"""
get_configuration_set(ConfigurationSetName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/configuration-sets/$(ConfigurationSetName)"; aws_config=aws_config)
get_configuration_set(ConfigurationSetName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/configuration-sets/$(ConfigurationSetName)", args; aws_config=aws_config)

"""
    GetConfigurationSetEventDestinations()

Retrieve a list of event destinations that are associated with a configuration set. In Amazon Pinpoint, events include message sends, deliveries, opens, clicks, bounces, and complaints. Event destinations are places that you can send information about these events to. For example, you can send event data to Amazon SNS to receive notifications when you receive bounces or complaints, or you can use Amazon Kinesis Data Firehose to stream data to Amazon S3 for long-term storage.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set that contains the event destination.

"""
get_configuration_set_event_destinations(ConfigurationSetName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/configuration-sets/$(ConfigurationSetName)/event-destinations"; aws_config=aws_config)
get_configuration_set_event_destinations(ConfigurationSetName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/configuration-sets/$(ConfigurationSetName)/event-destinations", args; aws_config=aws_config)

"""
    GetDedicatedIp()

Get information about a dedicated IP address, including the name of the dedicated IP pool that it's associated with, as well information about the automatic warm-up process for the address.

# Required Parameters
- `IP`: The IP address that you want to obtain more information about. The value you specify has to be a dedicated IP address that's assocaited with your Amazon Pinpoint account.

"""
get_dedicated_ip(IP; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/dedicated-ips/$(IP)"; aws_config=aws_config)
get_dedicated_ip(IP, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/dedicated-ips/$(IP)", args; aws_config=aws_config)

"""
    GetDedicatedIps()

List the dedicated IP addresses that are associated with your Amazon Pinpoint account.

# Optional Parameters
- `NextToken`: A token returned from a previous call to GetDedicatedIps to indicate the position of the dedicated IP pool in the list of IP pools.
- `PageSize`: The number of results to show in a single call to GetDedicatedIpsRequest. If the number of results is larger than the number you specified in this parameter, then the response includes a NextToken element, which you can use to obtain additional results.
- `PoolName`: The name of the IP pool that the dedicated IP address is associated with.
"""
get_dedicated_ips(; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/dedicated-ips"; aws_config=aws_config)
get_dedicated_ips(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/dedicated-ips", args; aws_config=aws_config)

"""
    GetDeliverabilityDashboardOptions()

Retrieve information about the status of the Deliverability dashboard for your Amazon Pinpoint account. When the Deliverability dashboard is enabled, you gain access to reputation, deliverability, and other metrics for the domains that you use to send email using Amazon Pinpoint. You also gain the ability to perform predictive inbox placement tests. When you use the Deliverability dashboard, you pay a monthly subscription charge, in addition to any other fees that you accrue by using Amazon Pinpoint. For more information about the features and cost of a Deliverability dashboard subscription, see Amazon Pinpoint Pricing.

"""
get_deliverability_dashboard_options(; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard"; aws_config=aws_config)
get_deliverability_dashboard_options(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard", args; aws_config=aws_config)

"""
    GetDeliverabilityTestReport()

Retrieve the results of a predictive inbox placement test.

# Required Parameters
- `ReportId`: A unique string that identifies the predictive inbox placement test.

"""
get_deliverability_test_report(ReportId; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/test-reports/$(ReportId)"; aws_config=aws_config)
get_deliverability_test_report(ReportId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/test-reports/$(ReportId)", args; aws_config=aws_config)

"""
    GetDomainDeliverabilityCampaign()

Retrieve all the deliverability data for a specific campaign. This data is available for a campaign only if the campaign sent email by using a domain that the Deliverability dashboard is enabled for (PutDeliverabilityDashboardOption operation).

# Required Parameters
- `CampaignId`: The unique identifier for the campaign. Amazon Pinpoint automatically generates and assigns this identifier to a campaign. This value is not the same as the campaign identifier that Amazon Pinpoint assigns to campaigns that you create and manage by using the Amazon Pinpoint API or the Amazon Pinpoint console.

"""
get_domain_deliverability_campaign(CampaignId; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/campaigns/$(CampaignId)"; aws_config=aws_config)
get_domain_deliverability_campaign(CampaignId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/campaigns/$(CampaignId)", args; aws_config=aws_config)

"""
    GetDomainStatisticsReport()

Retrieve inbox placement and engagement rates for the domains that you use to send email.

# Required Parameters
- `Domain`: The domain that you want to obtain deliverability metrics for.
- `EndDate`: The last day (in Unix time) that you want to obtain domain deliverability metrics for. The EndDate that you specify has to be less than or equal to 30 days after the StartDate.
- `StartDate`: The first day (in Unix time) that you want to obtain domain deliverability metrics for.

"""
get_domain_statistics_report(Domain, EndDate, StartDate; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/statistics-report/$(Domain)", Dict{String, Any}("EndDate"=>EndDate, "StartDate"=>StartDate); aws_config=aws_config)
get_domain_statistics_report(Domain, EndDate, StartDate, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/statistics-report/$(Domain)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndDate"=>EndDate, "StartDate"=>StartDate), args)); aws_config=aws_config)

"""
    GetEmailIdentity()

Provides information about a specific identity associated with your Amazon Pinpoint account, including the identity's verification status, its DKIM authentication status, and its custom Mail-From settings.

# Required Parameters
- `EmailIdentity`: The email identity that you want to retrieve details for.

"""
get_email_identity(EmailIdentity; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/identities/$(EmailIdentity)"; aws_config=aws_config)
get_email_identity(EmailIdentity, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/identities/$(EmailIdentity)", args; aws_config=aws_config)

"""
    ListConfigurationSets()

List all of the configuration sets associated with your Amazon Pinpoint account in the current region. In Amazon Pinpoint, configuration sets are groups of rules that you can apply to the emails you send. You apply a configuration set to an email by including a reference to the configuration set in the headers of the email. When you apply a configuration set to an email, all of the rules in that configuration set are applied to the email.

# Optional Parameters
- `NextToken`: A token returned from a previous call to ListConfigurationSets to indicate the position in the list of configuration sets.
- `PageSize`: The number of results to show in a single call to ListConfigurationSets. If the number of results is larger than the number you specified in this parameter, then the response includes a NextToken element, which you can use to obtain additional results.
"""
list_configuration_sets(; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/configuration-sets"; aws_config=aws_config)
list_configuration_sets(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/configuration-sets", args; aws_config=aws_config)

"""
    ListDedicatedIpPools()

List all of the dedicated IP pools that exist in your Amazon Pinpoint account in the current AWS Region.

# Optional Parameters
- `NextToken`: A token returned from a previous call to ListDedicatedIpPools to indicate the position in the list of dedicated IP pools.
- `PageSize`: The number of results to show in a single call to ListDedicatedIpPools. If the number of results is larger than the number you specified in this parameter, then the response includes a NextToken element, which you can use to obtain additional results.
"""
list_dedicated_ip_pools(; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/dedicated-ip-pools"; aws_config=aws_config)
list_dedicated_ip_pools(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/dedicated-ip-pools", args; aws_config=aws_config)

"""
    ListDeliverabilityTestReports()

Show a list of the predictive inbox placement tests that you've performed, regardless of their statuses. For predictive inbox placement tests that are complete, you can use the GetDeliverabilityTestReport operation to view the results.

# Optional Parameters
- `NextToken`: A token returned from a previous call to ListDeliverabilityTestReports to indicate the position in the list of predictive inbox placement tests.
- `PageSize`: The number of results to show in a single call to ListDeliverabilityTestReports. If the number of results is larger than the number you specified in this parameter, then the response includes a NextToken element, which you can use to obtain additional results. The value you specify has to be at least 0, and can be no more than 1000.
"""
list_deliverability_test_reports(; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/test-reports"; aws_config=aws_config)
list_deliverability_test_reports(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/test-reports", args; aws_config=aws_config)

"""
    ListDomainDeliverabilityCampaigns()

Retrieve deliverability data for all the campaigns that used a specific domain to send email during a specified time range. This data is available for a domain only if you enabled the Deliverability dashboard (PutDeliverabilityDashboardOption operation) for the domain.

# Required Parameters
- `EndDate`: The last day, in Unix time format, that you want to obtain deliverability data for. This value has to be less than or equal to 30 days after the value of the StartDate parameter.
- `StartDate`: The first day, in Unix time format, that you want to obtain deliverability data for.
- `SubscribedDomain`: The domain to obtain deliverability data for.

# Optional Parameters
- `NextToken`: A token that’s returned from a previous call to the ListDomainDeliverabilityCampaigns operation. This token indicates the position of a campaign in the list of campaigns.
- `PageSize`: The maximum number of results to include in response to a single call to the ListDomainDeliverabilityCampaigns operation. If the number of results is larger than the number that you specify in this parameter, the response includes a NextToken element, which you can use to obtain additional results.
"""
list_domain_deliverability_campaigns(EndDate, StartDate, SubscribedDomain; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/domains/$(SubscribedDomain)/campaigns", Dict{String, Any}("EndDate"=>EndDate, "StartDate"=>StartDate); aws_config=aws_config)
list_domain_deliverability_campaigns(EndDate, StartDate, SubscribedDomain, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/deliverability-dashboard/domains/$(SubscribedDomain)/campaigns", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndDate"=>EndDate, "StartDate"=>StartDate), args)); aws_config=aws_config)

"""
    ListEmailIdentities()

Returns a list of all of the email identities that are associated with your Amazon Pinpoint account. An identity can be either an email address or a domain. This operation returns identities that are verified as well as those that aren't.

# Optional Parameters
- `NextToken`: A token returned from a previous call to ListEmailIdentities to indicate the position in the list of identities.
- `PageSize`: The number of results to show in a single call to ListEmailIdentities. If the number of results is larger than the number you specified in this parameter, then the response includes a NextToken element, which you can use to obtain additional results. The value you specify has to be at least 0, and can be no more than 1000.
"""
list_email_identities(; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/identities"; aws_config=aws_config)
list_email_identities(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/identities", args; aws_config=aws_config)

"""
    ListTagsForResource()

Retrieve a list of the tags (keys and values) that are associated with a specified resource. A tag is a label that you optionally define and associate with a resource in Amazon Pinpoint. Each tag consists of a required tag key and an optional associated tag value. A tag key is a general label that acts as a category for more specific tag values. A tag value acts as a descriptor within a tag key.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) of the resource that you want to retrieve tag information for.

"""
list_tags_for_resource(ResourceArn; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/tags", Dict{String, Any}("ResourceArn"=>ResourceArn); aws_config=aws_config)
list_tags_for_resource(ResourceArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("GET", "/v1/email/tags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn), args)); aws_config=aws_config)

"""
    PutAccountDedicatedIpWarmupAttributes()

Enable or disable the automatic warm-up feature for dedicated IP addresses.

# Optional Parameters
- `AutoWarmupEnabled`: Enables or disables the automatic warm-up feature for dedicated IP addresses that are associated with your Amazon Pinpoint account in the current AWS Region. Set to true to enable the automatic warm-up feature, or set to false to disable it.
"""
put_account_dedicated_ip_warmup_attributes(; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/account/dedicated-ips/warmup"; aws_config=aws_config)
put_account_dedicated_ip_warmup_attributes(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/account/dedicated-ips/warmup", args; aws_config=aws_config)

"""
    PutAccountSendingAttributes()

Enable or disable the ability of your account to send email.

# Optional Parameters
- `SendingEnabled`: Enables or disables your account's ability to send email. Set to true to enable email sending, or set to false to disable email sending.  If AWS paused your account's ability to send email, you can't use this operation to resume your account's ability to send email.
"""
put_account_sending_attributes(; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/account/sending"; aws_config=aws_config)
put_account_sending_attributes(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/account/sending", args; aws_config=aws_config)

"""
    PutConfigurationSetDeliveryOptions()

Associate a configuration set with a dedicated IP pool. You can use dedicated IP pools to create groups of dedicated IP addresses for sending specific types of email.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set that you want to associate with a dedicated IP pool.

# Optional Parameters
- `SendingPoolName`: The name of the dedicated IP pool that you want to associate with the configuration set.
- `TlsPolicy`: Specifies whether messages that use the configuration set are required to use Transport Layer Security (TLS). If the value is Require, messages are only delivered if a TLS connection can be established. If the value is Optional, messages can be delivered in plain text if a TLS connection can't be established.
"""
put_configuration_set_delivery_options(ConfigurationSetName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/configuration-sets/$(ConfigurationSetName)/delivery-options"; aws_config=aws_config)
put_configuration_set_delivery_options(ConfigurationSetName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/configuration-sets/$(ConfigurationSetName)/delivery-options", args; aws_config=aws_config)

"""
    PutConfigurationSetReputationOptions()

Enable or disable collection of reputation metrics for emails that you send using a particular configuration set in a specific AWS Region.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set that you want to enable or disable reputation metric tracking for.

# Optional Parameters
- `ReputationMetricsEnabled`: If true, tracking of reputation metrics is enabled for the configuration set. If false, tracking of reputation metrics is disabled for the configuration set.
"""
put_configuration_set_reputation_options(ConfigurationSetName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/configuration-sets/$(ConfigurationSetName)/reputation-options"; aws_config=aws_config)
put_configuration_set_reputation_options(ConfigurationSetName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/configuration-sets/$(ConfigurationSetName)/reputation-options", args; aws_config=aws_config)

"""
    PutConfigurationSetSendingOptions()

Enable or disable email sending for messages that use a particular configuration set in a specific AWS Region.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set that you want to enable or disable email sending for.

# Optional Parameters
- `SendingEnabled`: If true, email sending is enabled for the configuration set. If false, email sending is disabled for the configuration set.
"""
put_configuration_set_sending_options(ConfigurationSetName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/configuration-sets/$(ConfigurationSetName)/sending"; aws_config=aws_config)
put_configuration_set_sending_options(ConfigurationSetName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/configuration-sets/$(ConfigurationSetName)/sending", args; aws_config=aws_config)

"""
    PutConfigurationSetTrackingOptions()

Specify a custom domain to use for open and click tracking elements in email that you send using Amazon Pinpoint.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set that you want to add a custom tracking domain to.

# Optional Parameters
- `CustomRedirectDomain`: The domain that you want to use to track open and click events.
"""
put_configuration_set_tracking_options(ConfigurationSetName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/configuration-sets/$(ConfigurationSetName)/tracking-options"; aws_config=aws_config)
put_configuration_set_tracking_options(ConfigurationSetName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/configuration-sets/$(ConfigurationSetName)/tracking-options", args; aws_config=aws_config)

"""
    PutDedicatedIpInPool()

Move a dedicated IP address to an existing dedicated IP pool.  The dedicated IP address that you specify must already exist, and must be associated with your Amazon Pinpoint account.  The dedicated IP pool you specify must already exist. You can create a new pool by using the CreateDedicatedIpPool operation.

# Required Parameters
- `DestinationPoolName`: The name of the IP pool that you want to add the dedicated IP address to. You have to specify an IP pool that already exists.
- `IP`: The IP address that you want to move to the dedicated IP pool. The value you specify has to be a dedicated IP address that's associated with your Amazon Pinpoint account.

"""
put_dedicated_ip_in_pool(DestinationPoolName, IP; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/dedicated-ips/$(IP)/pool", Dict{String, Any}("DestinationPoolName"=>DestinationPoolName); aws_config=aws_config)
put_dedicated_ip_in_pool(DestinationPoolName, IP, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/dedicated-ips/$(IP)/pool", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DestinationPoolName"=>DestinationPoolName), args)); aws_config=aws_config)

"""
    PutDedicatedIpWarmupAttributes()

# Required Parameters
- `IP`: The dedicated IP address that you want to update the warm-up attributes for.
- `WarmupPercentage`: The warm-up percentage that you want to associate with the dedicated IP address.

"""
put_dedicated_ip_warmup_attributes(IP, WarmupPercentage; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/dedicated-ips/$(IP)/warmup", Dict{String, Any}("WarmupPercentage"=>WarmupPercentage); aws_config=aws_config)
put_dedicated_ip_warmup_attributes(IP, WarmupPercentage, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/dedicated-ips/$(IP)/warmup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("WarmupPercentage"=>WarmupPercentage), args)); aws_config=aws_config)

"""
    PutDeliverabilityDashboardOption()

Enable or disable the Deliverability dashboard for your Amazon Pinpoint account. When you enable the Deliverability dashboard, you gain access to reputation, deliverability, and other metrics for the domains that you use to send email using Amazon Pinpoint. You also gain the ability to perform predictive inbox placement tests. When you use the Deliverability dashboard, you pay a monthly subscription charge, in addition to any other fees that you accrue by using Amazon Pinpoint. For more information about the features and cost of a Deliverability dashboard subscription, see Amazon Pinpoint Pricing.

# Required Parameters
- `DashboardEnabled`: Specifies whether to enable the Deliverability dashboard for your Amazon Pinpoint account. To enable the dashboard, set this value to true.

# Optional Parameters
- `SubscribedDomains`: An array of objects, one for each verified domain that you use to send email and enabled the Deliverability dashboard for.
"""
put_deliverability_dashboard_option(DashboardEnabled; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/deliverability-dashboard", Dict{String, Any}("DashboardEnabled"=>DashboardEnabled); aws_config=aws_config)
put_deliverability_dashboard_option(DashboardEnabled, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/deliverability-dashboard", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DashboardEnabled"=>DashboardEnabled), args)); aws_config=aws_config)

"""
    PutEmailIdentityDkimAttributes()

Used to enable or disable DKIM authentication for an email identity.

# Required Parameters
- `EmailIdentity`: The email identity that you want to change the DKIM settings for.

# Optional Parameters
- `SigningEnabled`: Sets the DKIM signing configuration for the identity. When you set this value true, then the messages that Amazon Pinpoint sends from the identity are DKIM-signed. When you set this value to false, then the messages that Amazon Pinpoint sends from the identity aren't DKIM-signed.
"""
put_email_identity_dkim_attributes(EmailIdentity; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/identities/$(EmailIdentity)/dkim"; aws_config=aws_config)
put_email_identity_dkim_attributes(EmailIdentity, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/identities/$(EmailIdentity)/dkim", args; aws_config=aws_config)

"""
    PutEmailIdentityFeedbackAttributes()

Used to enable or disable feedback forwarding for an identity. This setting determines what happens when an identity is used to send an email that results in a bounce or complaint event. When you enable feedback forwarding, Amazon Pinpoint sends you email notifications when bounce or complaint events occur. Amazon Pinpoint sends this notification to the address that you specified in the Return-Path header of the original email. When you disable feedback forwarding, Amazon Pinpoint sends notifications through other mechanisms, such as by notifying an Amazon SNS topic. You're required to have a method of tracking bounces and complaints. If you haven't set up another mechanism for receiving bounce or complaint notifications, Amazon Pinpoint sends an email notification when these events occur (even if this setting is disabled).

# Required Parameters
- `EmailIdentity`: The email identity that you want to configure bounce and complaint feedback forwarding for.

# Optional Parameters
- `EmailForwardingEnabled`: Sets the feedback forwarding configuration for the identity. If the value is true, Amazon Pinpoint sends you email notifications when bounce or complaint events occur. Amazon Pinpoint sends this notification to the address that you specified in the Return-Path header of the original email. When you set this value to false, Amazon Pinpoint sends notifications through other mechanisms, such as by notifying an Amazon SNS topic or another event destination. You're required to have a method of tracking bounces and complaints. If you haven't set up another mechanism for receiving bounce or complaint notifications, Amazon Pinpoint sends an email notification when these events occur (even if this setting is disabled).
"""
put_email_identity_feedback_attributes(EmailIdentity; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/identities/$(EmailIdentity)/feedback"; aws_config=aws_config)
put_email_identity_feedback_attributes(EmailIdentity, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/identities/$(EmailIdentity)/feedback", args; aws_config=aws_config)

"""
    PutEmailIdentityMailFromAttributes()

Used to enable or disable the custom Mail-From domain configuration for an email identity.

# Required Parameters
- `EmailIdentity`: The verified email identity that you want to set up the custom MAIL FROM domain for.

# Optional Parameters
- `BehaviorOnMxFailure`: The action that you want Amazon Pinpoint to take if it can't read the required MX record when you send an email. When you set this value to UseDefaultValue, Amazon Pinpoint uses amazonses.com as the MAIL FROM domain. When you set this value to RejectMessage, Amazon Pinpoint returns a MailFromDomainNotVerified error, and doesn't attempt to deliver the email. These behaviors are taken when the custom MAIL FROM domain configuration is in the Pending, Failed, and TemporaryFailure states.
- `MailFromDomain`:  The custom MAIL FROM domain that you want the verified identity to use. The MAIL FROM domain must meet the following criteria:   It has to be a subdomain of the verified identity.   It can't be used to receive email.   It can't be used in a \"From\" address if the MAIL FROM domain is a destination for feedback forwarding emails.
"""
put_email_identity_mail_from_attributes(EmailIdentity; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/identities/$(EmailIdentity)/mail-from"; aws_config=aws_config)
put_email_identity_mail_from_attributes(EmailIdentity, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/identities/$(EmailIdentity)/mail-from", args; aws_config=aws_config)

"""
    SendEmail()

Sends an email message. You can use the Amazon Pinpoint Email API to send two types of messages:    Simple – A standard email message. When you create this type of message, you specify the sender, the recipient, and the message body, and Amazon Pinpoint assembles the message for you.    Raw – A raw, MIME-formatted email message. When you send this type of email, you have to specify all of the message headers, as well as the message body. You can use this message type to send messages that contain attachments. The message that you specify has to be a valid MIME message.

# Required Parameters
- `Content`: An object that contains the body of the message. You can send either a Simple message or a Raw message.
- `Destination`: An object that contains the recipients of the email message.

# Optional Parameters
- `ConfigurationSetName`: The name of the configuration set that you want to use when sending the email.
- `EmailTags`: A list of tags, in the form of name/value pairs, to apply to an email that you send using the SendEmail operation. Tags correspond to characteristics of the email that you define, so that you can publish email sending events.
- `FeedbackForwardingEmailAddress`: The address that Amazon Pinpoint should send bounce and complaint notifications to.
- `FromEmailAddress`: The email address that you want to use as the \"From\" address for the email. The address that you specify has to be verified.
- `ReplyToAddresses`: The \"Reply-to\" email addresses for the message. When the recipient replies to the message, each Reply-to address receives the reply.
"""
send_email(Content, Destination; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/outbound-emails", Dict{String, Any}("Content"=>Content, "Destination"=>Destination); aws_config=aws_config)
send_email(Content, Destination, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/outbound-emails", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Content"=>Content, "Destination"=>Destination), args)); aws_config=aws_config)

"""
    TagResource()

Add one or more tags (keys and values) to a specified resource. A tag is a label that you optionally define and associate with a resource in Amazon Pinpoint. Tags can help you categorize and manage resources in different ways, such as by purpose, owner, environment, or other criteria. A resource can have as many as 50 tags. Each tag consists of a required tag key and an associated tag value, both of which you define. A tag key is a general label that acts as a category for more specific tag values. A tag value acts as a descriptor within a tag key.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) of the resource that you want to add one or more tags to.
- `Tags`: A list of the tags that you want to add to the resource. A tag consists of a required tag key (Key) and an associated tag value (Value). The maximum length of a tag key is 128 characters. The maximum length of a tag value is 256 characters.

"""
tag_resource(ResourceArn, Tags; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/tags", Dict{String, Any}("ResourceArn"=>ResourceArn, "Tags"=>Tags); aws_config=aws_config)
tag_resource(ResourceArn, Tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("POST", "/v1/email/tags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn, "Tags"=>Tags), args)); aws_config=aws_config)

"""
    UntagResource()

Remove one or more tags (keys and values) from a specified resource.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) of the resource that you want to remove one or more tags from.
- `TagKeys`: The tags (tag keys) that you want to remove from the resource. When you specify a tag key, the action removes both that key and its associated tag value. To remove more than one tag from the resource, append the TagKeys parameter and argument for each additional tag to remove, separated by an ampersand. For example: /v1/email/tags?ResourceArn=ResourceArn&TagKeys=Key1&TagKeys=Key2

"""
untag_resource(ResourceArn, TagKeys; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("DELETE", "/v1/email/tags", Dict{String, Any}("ResourceArn"=>ResourceArn, "TagKeys"=>TagKeys); aws_config=aws_config)
untag_resource(ResourceArn, TagKeys, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("DELETE", "/v1/email/tags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArn"=>ResourceArn, "TagKeys"=>TagKeys), args)); aws_config=aws_config)

"""
    UpdateConfigurationSetEventDestination()

Update the configuration of an event destination for a configuration set. In Amazon Pinpoint, events include message sends, deliveries, opens, clicks, bounces, and complaints. Event destinations are places that you can send information about these events to. For example, you can send event data to Amazon SNS to receive notifications when you receive bounces or complaints, or you can use Amazon Kinesis Data Firehose to stream data to Amazon S3 for long-term storage.

# Required Parameters
- `ConfigurationSetName`: The name of the configuration set that contains the event destination that you want to modify.
- `EventDestination`: An object that defines the event destination.
- `EventDestinationName`: The name of the event destination that you want to modify.

"""
update_configuration_set_event_destination(ConfigurationSetName, EventDestination, EventDestinationName; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/configuration-sets/$(ConfigurationSetName)/event-destinations/$(EventDestinationName)", Dict{String, Any}("EventDestination"=>EventDestination); aws_config=aws_config)
update_configuration_set_event_destination(ConfigurationSetName, EventDestination, EventDestinationName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = pinpoint_email("PUT", "/v1/email/configuration-sets/$(ConfigurationSetName)/event-destinations/$(EventDestinationName)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EventDestination"=>EventDestination), args)); aws_config=aws_config)


text:
using DiffRules, SpecialFunctions, NaNMath

for (mod, name, nargs) in keys(DiffRules.DEFINED_DIFFRULES)
    f_ex_head = Expr(:., mod, QuoteNode(name))

    if nargs == 1
        df_ex = DiffRules.diffrule(mod, name, :x)

        name === :abs && continue # exclude abs, it cannot be directly broadcasted

        @eval begin
            $(f_ex_head)(x::Value) = register($(f_ex_head), x)
            gradient(::typeof($(f_ex_head)), grad, output, x) = (grad * $df_ex, )
            gradient(mt::Trait.Broadcasted{typeof($f_ex_head)}, grad, output, x) = (@.(grad * $(df_ex)), )
        end
    elseif nargs == 2
        df_ex = DiffRules.diffrule(mod, name, :x, :y)

        @eval begin

            $(f_ex_head)(x1::Value, x2) = register($f_ex_head, x1, x2)
            $(f_ex_head)(x1, x2::Value) = register($f_ex_head, x1, x2)
            $(f_ex_head)(x1::Value, x2::Value) = register($f_ex_head, x1, x2)

            gradient(::typeof($f_ex_head), grad, output, x, y) =
                (grad * $(df_ex[1]), grad * $(df_ex[2]))
            gradient(::Trait.Broadcasted{typeof($f_ex_head)}, grad, output, x, y) =
                (@.(grad * ($(df_ex[1]))), @.(grad * $(df_ex[2])))
        end
    else
        @info "unknown operator $name"
    end
end

Base.abs(x::Value) = register(Base.abs, x)

@inline abs_gradient(x::Number) =
    if signbit(x)
        -one(x)
    else
        one(x)
    end

gradient(::typeof(Base.abs), grad, output, x) = (grad * abs_gradient(x), )
gradient(::Trait.Broadcasted{typeof(Base.abs)}, grad, output, x) = (@.(grad * abs_gradient(x)), )

ext: jl


text:
##########################
# FunctionCell Interface #
##########################
"""
	dist(d=Distances.Euclidean())

Constructs an untrained function cell using a `d::Distances.PreMetric` function cell. `d` defaults to `Distances.Euclidean()` if not specified.

For more information on the distances allowed, see ?Distances.
"""
dist(d::Distances.PreMetric=Distances.Euclidean()) = FunctionCell(dist, (d,), ModelProperties(), "Distance ($d))")

############################
# DataCell/Array Interface #
############################
"""
	dist(x, d=Distances.Euclidean())

Trains the function cell using a `d::Distances.PreMetric` function and storing the `x` matrix
for future distance calculations.
"""
# Training
dist(x::T where T<:CellData, d::Distances.PreMetric=Distances.Euclidean()) = dist(getx!(x), d)
dist(x::Tuple{T,S} where T<:AbstractArray where S<:AbstractArray, d::Distances.PreMetric=Distances.Euclidean()) = dist(x[1], d)
dist(x::T where T<:AbstractVector, d::Distances.PreMetric=Distances.Euclidean()) = dist(mat(x, LearnBase.ObsDim.Constant{2}()), d)
dist(x::T where T<:AbstractMatrix, d::Distances.PreMetric=Distances.Euclidean()) = begin

	# Build name
	namedist = "Distance ($d)"

	# Build model properties
	modelprops = ModelProperties(nvars(x),nobs(x))

	# Returned trained cell
	FunctionCell(dist, Model((d,getobs(x)), modelprops), namedist)
end

# Execution
dist(x::T where T<:CellData, model::Model{<:Tuple{<:Distances.PreMetric,Matrix}}) =
	datacell(dist(getx!(x), model), gety(x))
dist(x::T where T<:AbstractVector, model::Model{<:Tuple{<:Distances.PreMetric,Matrix}}) =
	dist(mat(x, LearnBase.ObsDim.Constant{2}()), model)
dist(x::T where T<:AbstractMatrix, model::Model{<:Tuple{<:Distances.PreMetric,Matrix}}) =
	Distances.pairwise(model.data[1], model.data[2], getobs(x))


text:
module Q
export K, K_Atom, K_Vector, K_Table, K_KeyTable
export hopen, hclose, hget
export KdbException

using DataFrames

"""
   KDB_HANDLE

The handle to a kdb+ server.  When `Q.jl` is embedded in kdb+, `KDB_HANDLE[]`
is always `0`, which is the handle to the current process.  When `Q.jl` is
loaded in a client process, `KDB_HANDLE[]` is either `-1` indicating that
no connection has been established or a handle to the default kdb+ server.
"""
const KDB_HANDLE = Ref{Int32}(-1)

include("_k.jl")
include("temporal.jl")
include("new.jl")
include("expr.jl")
"""
    K(x)

Construct a kdb+ object.
"""
abstract type K end
K(x) = convert(K, x)  # allow non-K return types
"""
    kpointer(x)

A memory address referring to a kdb+ object.
"""
kpointer

Base.convert(::Type{K_}, x) = r1(kpointer(x))
K_new(x) = r1(kpointer(x))

"""
    ktypecode(x)

Get the numeric type code of a `K` object.
"""
ktypecode(x) = ktypecode(typeof(x))

ktypecode(T::Type{DataType}) = error("Type ", T, " is not known to q.")

"""
    KdbException(s)

A call to kdb resulted in an error. Argument `s` is a descriptive error string
reported by kdb.
"""
struct KdbException <: Exception
    s::String
end

include("serialize.jl")
include("atom.jl")
include("vector.jl")

struct K_Lambda
    a::Vector{K_}
    K_Lambda(x::K_) = new(asarray(x))
end
function Base.show(io::IO, f::K_Lambda)
    x = f.a[end]
    code = unsafe_string(Ptr{G_}(x+16), xn(x))
    write(io, "q(", repr(code), ")")
end
struct K_Other
    a::Array{T,0} where T
    K_Other(x::K_) = new(asarray(x))
end
ktypecode(x::K_Other) = unsafe_load(kpointer(x)).t

include("table.jl")
include("key-table.jl")

for T in (K_symbol, K_char)
    @eval Base.:(==)(x::$T, y) = x[] == y
    @eval Base.:(==)(x, y::$T) = x == y[]
    @eval Base.:(==)(x::$T, y::$T) = x[] == y[]
end
Base.:(==)(x::T, y::T) where {T<:K_Atom} = x.a[] == y.a[]
Base.:(<)(x::K_Atom, y::K_Atom) = x.a[] < y.a[]
Base.:(<)(x::K_symbol, y::K_symbol) = x[] < y[]
function Base.:(==)(x::K_Other, y::K_Other)
    # TODO: Specialize this for λ's etc.
    ktypecode(x) == ktypecode(y) && x.a[] == y.a[]
end
Base.:(==)(x::K_Other, y) = false

kpointer(x::Union{K_Atom,K_Other}) = K_(pointer(x.a)-8)
kpointer(x::Union{K_Vector,K_Lambda,K_guid}) = K_(pointer(x.a)-16)

const TI0 = TI(0, 'k', "any", K_, K, :NA)
typeinfo(t::Integer) = t == 0 ? TI0 : TYPE_INFO[t - (t>2)]

include("list.jl")

# Conversions between C and Julia types
_cast(::Type{T}, x::T) where T = x
_cast(::Type{T}, x::C) where {T,C} = T(x)
_cast(::Type{Symbol}, x::S_) = Symbol(unsafe_string(x))
const K_EPOCH_DATE = Date(2000)
_cast(::Type{Date}, x::I_) =  K_EPOCH_DATE + Dates.Day(x)
_cast(::Type{I_}, x::Date) = I_(DATE_SHIFT + Dates.value(x))
_cast(::Type{K}, x::K_) = K(r1(x))
#_cast(::Type{K_}, x::K) = r1(kpointer(x))

# TODO: replace K_Vector with K below once asarray() transition is complete.
Base.pointer(x::K_Vector, i::Integer=1) = pointer(x.a, i)
Base.show(io::IO, ::Type{K}) = write(io, "K")

include("conversions.jl")

# K[...] constructors
Base.getindex(::Type{K}) = K(ktn(0,0))
function Base.getindex(::Type{K}, v)
    t = K_TYPE[typeof(v)]
    r = K(ktn(t, 1))
    r.a[1] = _cast(eltype(r.a), v)
    r
end
function Base.getindex(::Type{K}, v...)
    n = length(v)
    t = get(K_TYPE, Base.promote_typeof(v...), KK)
    r = K(ktn(t, n))
    C, T = map(eltype, (r.a, r))
    copy!(r.a, map(e->_cast(C, T(e)), v))
    r
end
include("eval.jl")
if GOT_Q
    include("server.jl")
else
    include("client.jl")
end
include("parser.jl")
include("q-prompt.jl")
include("kdb.jl")
include("q-cmd.jl")
end # module Q


text:
using SimpleWeightedGraphs

@testset "SimpleWeightedGraphs" begin
    @info("Ignore warnings relating to adding and removing vertices and edges")
    adjmx1 = [0 1 0; 1 0 1; 0 1 0] # SimpleWeightedGraph
    adjmx2 = [0 1 0; 1 0 1; 1 1 0] # SimpleWeightedDiGraph
    # specific concrete generators - no need for loop
    @test @inferred(eltype(SimpleWeightedGraph())) == Int
    @test @inferred(eltype(SimpleWeightedGraph(adjmx1))) == Int
    @test_throws ErrorException SimpleWeightedGraph(adjmx2)

    @test @inferred(ne(SimpleWeightedGraph(PathDiGraph(5)))) == 4
    @test @inferred(!is_directed(SimpleWeightedGraph))

    @test @inferred(eltype(SimpleWeightedDiGraph())) == Int
    @test @inferred(eltype(SimpleWeightedDiGraph(adjmx2))) == Int
    @test @inferred(ne(SimpleWeightedDiGraph(PathGraph(5)))) == 8
    @test @inferred(is_directed(SimpleWeightedDiGraph))

    for gbig in [SimpleWeightedGraph(0xff), SimpleWeightedDiGraph(0xff)]
        @test @inferred(!add_vertex!(gbig))    # overflow
        @test @inferred(!add_vertices!(gbig, 10))
    end

    gdx = SimpleWeightedDiGraph(PathDiGraph(4))
    gx = SimpleWeightedGraph()
    for g in testgraphs(gx)
        T = eltype(g)
        U = weighttype(g)
        @test sprint(show, g) == "{0, 0} undirected simple $T graph with $U weights"
        @inferred(add_vertices!(g, 5))
        @test sprint(show, g) == "{5, 0} undirected simple $T graph with $U weights"
    end
    gx = SimpleWeightedDiGraph()
    for g in testdigraphs(gx)
        T = eltype(g)
        U = weighttype(g)
        @test sprint(show, g) == "{0, 0} directed simple $T graph with $U weights"
        @inferred(add_vertices!(g, 5))
        @test sprint(show, g) == "{5, 0} directed simple $T graph with $U weights"
    end

    gx = SimpleWeightedGraph(PathGraph(4))

    gc = copy(gx)
    @test_logs (:warn, "Note: adding edges with a zero weight to this graph type has no effect.") add_edge!(gc, 4, 1, 0.0)
    @test !(add_edge!(gc, 4, 1, 0.0))

    for g in testgraphs(gx)
        @test @inferred(vertices(g)) == 1:4
        @test SimpleWeightedEdge(2,3) in edges(g)
        @test @inferred(nv(g)) == 4
        @test @inferred(outneighbors(g,2)) == inneighbors(g,2) == neighbors(g,2)
        @test @inferred(has_edge(g, 2, 3))
        @test @inferred(has_edge(g, 3, 2))

        gc = copy(g)
        @test @inferred(add_edge!(gc, 4=>1)) && gc == SimpleWeightedGraph(CycleGraph(4))
        @test @inferred(has_edge(gc, 4=>1)) && has_edge(gc, 0x04=>0x01)
        gc = copy(g)
        @test @inferred(add_edge!(gc, (4,1))) && gc == SimpleWeightedGraph(CycleGraph(4))
        @test @inferred(has_edge(gc, (4,1))) && has_edge(gc, (0x04, 0x01))
        gc = copy(g)
        @test add_edge!(gc, 4, 1) && gc == SimpleWeightedGraph(CycleGraph(4))

        @test @inferred(inneighbors(g, 2)) == @inferred(outneighbors(g, 2)) == @inferred(neighbors(g,2)) == [1,3]
        @test @inferred(add_vertex!(gc))   # out of order, but we want it for issubset
        @test @inferred(g ⊆ gc)
        @test @inferred(has_vertex(gc, 5))

        @test @inferred(ne(g)) == 3

        @test @inferred(rem_edge!(gc, 1, 2)) && @inferred(!has_edge(gc, 1, 2))
        ga = @inferred(copy(g))
        @test @inferred(rem_vertex!(ga, 2)) && ne(ga) == 1
        @test @inferred(!rem_vertex!(ga, 10))

        @test @inferred(zero(g)) == SimpleWeightedGraph{eltype(g), weighttype(g)}()

        # concrete tests below

        @test @inferred(eltype(g)) == eltype(outneighbors(g,1)) == eltype(nv(g))
        T = @inferred(eltype(g))
        U = @inferred(weighttype(g))
        @test @inferred(nv(SimpleWeightedGraph{T, U}(6))) == 6

        # @test @inferred(eltype(SimpleWeightedGraph(T))) == T
        @test @inferred(eltype(SimpleWeightedGraph{T, U}(adjmx1))) == T

        ga = SimpleWeightedGraph(10)
        @test @inferred(eltype(SimpleWeightedGraph{T, U}(ga))) == T

        for gd in testdigraphs(gdx)
            T2 = eltype(gd)
            @test @inferred(eltype(SimpleWeightedGraph(gd))) == T2
        end

        @test @inferred(edgetype(g)) == SimpleWeightedGraphEdge{T, U}
        @test @inferred(copy(g)) == g
        @test @inferred(!is_directed(g))

        e = first(edges(g))
        @test @inferred(has_edge(g, e))
    end

    gdx = SimpleWeightedDiGraph(PathDiGraph(4))

    gc = copy(gdx)
    @test_logs (:warn, "Note: adding edges with a zero weight to this graph type has no effect.") add_edge!(gc, 4, 1, 0.0)
    @test !(add_edge!(gc, 4, 1, 0.0))

    for g in testdigraphs(gdx)
        @test @inferred(vertices(g)) == 1:4
        @test SimpleWeightedEdge(2,3) in edges(g)
        @test !(SimpleWeightedEdge(3,2) in edges(g))
        @test @inferred(nv(g)) == 4
        @test outneighbors(g, 2) == [3]
        @test inneighbors(g, 2) == [1]

        @test @inferred(has_edge(g, 2, 3))
        @test @inferred(!has_edge(g, 3, 2))

        gc = copy(g)
        @test @inferred(add_edge!(gc, 4=>1)) && gc == SimpleWeightedDiGraph(CycleDiGraph(4))
        @test @inferred(has_edge(gc, 4=>1)) && has_edge(gc, 0x04=>0x01)
        gc = copy(g)
        @test @inferred(add_edge!(gc, (4,1))) && gc == SimpleWeightedDiGraph(CycleDiGraph(4))
        @test @inferred(has_edge(gc, (4,1))) && has_edge(gc, (0x04, 0x01))
        gc = @inferred(copy(g))
        @test @inferred(add_edge!(gc, 4, 1)) && gc == SimpleWeightedDiGraph(CycleDiGraph(4))

        @test @inferred(inneighbors(g, 2)) == [1]
        @test @inferred(outneighbors(g, 2)) == @inferred(neighbors(g,2)) == [3]
        @test @inferred(add_vertex!(gc))   # out of order, but we want it for issubset
        @test @inferred(g ⊆ gc)
        @test @inferred(has_vertex(gc, 5))

        @test @inferred(ne(g)) == 3

        @test @inferred(!rem_edge!(gc, 2, 1))
        @test @inferred(rem_edge!(gc, 1, 2)) && @inferred(!has_edge(gc, 1, 2))
        ga = @inferred(copy(g))
        @test @inferred(rem_vertex!(ga, 2)) && ne(ga) == 1
        @test @inferred(!rem_vertex!(ga, 10))

        @test @inferred(zero(g)) == SimpleWeightedDiGraph{eltype(g), weighttype(g)}()

        # concrete tests below

        @test @inferred(eltype(g)) == eltype(@inferred(outneighbors(g,1))) == eltype(nv(g))
        T = @inferred(eltype(g))
        U = @inferred(weighttype(g))
        @test @inferred(nv(SimpleWeightedDiGraph{T, U}(6))) == 6

        # @test @inferred(eltype(SimpleWeightedDiGraph(T))) == T
        @test @inferred(eltype(SimpleWeightedDiGraph{T, U}(adjmx2))) == T

        ga = SimpleWeightedDiGraph(10)
        @test @inferred(eltype(SimpleWeightedDiGraph{T, U}(ga))) == T

        for gu in testgraphs(gx)
            T2 = @inferred(eltype(gu))
            @test @inferred(eltype(SimpleWeightedDiGraph(gu))) == T2
        end

        @test @inferred(edgetype(g)) == SimpleWeightedDiGraphEdge{T, U}
        @test @inferred(copy(g)) == g
        @test @inferred(is_directed(g))

        e = first(@inferred(edges(g)))
        @test @inferred(has_edge(g, e))
    end

    gdx = SimpleWeightedDiGraph(CompleteDiGraph(4))
    for g in testdigraphs(gdx)
        @test rem_vertex!(g, 2)
        @test nv(g) == 3 && ne(g) == 6
    end
    g = SimpleWeightedGraph(CompleteGraph(3), 3)
    @test sum(weights(g)) == 2 * ne(g) * 3
    @test @inferred(get_weight(g, 1, 2)) == 3

    g = SimpleWeightedDiGraph(PathGraph(5), 4.0)
    @test sum(weights(g)) == ne(g) * 4.0

    gx = Graph(4,3)
    for g in testsimplegraphs(gx)
        @test eltype(SimpleWeightedGraph(g)) == eltype(g)
    end

    gx = DiGraph(4,3)
    for g in testsimpledigraphs(gx)
        @test eltype(SimpleWeightedGraph(g)) == eltype(g)
    end

    s = SimpleWeightedGraph(PathGraph(5), 2)
    s2 = SimpleWeightedGraph([1,2,3,4], [2,3,4,5], [2,2,2,2])
    @test s == s2

    s = SimpleWeightedDiGraph(PathDiGraph(5), 2)
    s2 = SimpleWeightedDiGraph([1,2,3,4], [2,3,4,5], [2,2,2,2])
    @test s == s2

    s = SimpleWeightedGraph([10,20,30,40], [20,30,40,50], [2,2,2,2])
    @test size(s.weights) == (50, 50)

    s = SimpleWeightedDiGraph([10,20,30,40], [20,30,40,50], [2,2,2,2])
    @test size(s.weights) == (50, 50)

    s = SimpleWeightedGraph([1,2,1], [2,1,2], [1,1,1]; combine = +)
    @test s.weights[2,1] == s.weights[1,2] == 3

    s = SimpleWeightedDiGraph([1,2,1], [2,1,2], [1,1,1]; combine = +)
    @test s.weights[1,2] == 1
    @test s.weights[2,1] == 2

    s = SimpleWeightedDiGraph([1,2,1], [2,1,2], [1,1,2]; combine = (x,y) -> y)
    @test s.weights[1,2] == 1
    @test s.weights[2,1] == 2

end


text:
using StatsBase: pweights
using Statistics: mean, std
import Statistics: quantile
using WeightedOnlineStats: WeightedAdaptiveHist

"""
    normalizeTS(c)

Normalize a time series to zero mean and unit variance

**Input Axes** `TimeAxis`

**Output Axes** `TimeAxis`
"""
function normalizeTS(c;kwargs...)
  mapCube(normalizeTS,c;indims=InDims("Time",filter=NValid(3)),outdims=OutDims("Time"),kwargs...)
end
function normalizeTS(xout::AbstractVector,xin::AbstractVector)
  m = mean(skipmissing(xin))
  s = std(skipmissing(xin))
  s = s==zero(s) ? one(s) : s
  map!(x->(x-m)/s,xout,xin)
end

"""
    quantile(c,p=[0.25,0.5,0.75];by=(),nbins=100)

Computes the quantile of a data cube based on fitting a Histogram on the data
using an Online statistic.
"""
function quantile(c::YAXArray,p=[0.25,0.5,0.75];by=(),nbins=100)
  if any(i->isa(i,CategoricalAxis{<:Any,:Hist}),caxes(c)) && any(i->isa(i,RangeAxis{<:Any,:Bin}),caxes(c))
    if isa(p,Number)
      od = OutDims()
    else
      od = OutDims(RangeAxis("Quantile",p))
    end
    mapCube(cquantile,c,p,indims=InDims("Bin","Hist"),outdims=od)
  else
    tfull = CubeTable(data = c,include_axes=(map(axname,caxes(c))...,))
    weights = findAxis("Lat",c) === nothing ? nothing : i->cosd(i.Lat)
    histcube = cubefittable(tfull, WeightedAdaptiveHist(nbins), :data, by=by, weight=weights)
    quantile(histcube,p)
  end
end

function cquantile(xout,xin,p)
  w = xin[:,2]
  nonzero = w.>0
  d = xin[nonzero,1]
  w = Float64.(xin[nonzero,2])
  xout[:] = quantile(d,pweights(w),p)
end


text:
# ======================================
# Construction of the linearized system
# ======================================

"""
    build_matrix(F₁, F₂, N)

Compute the Carleman linearization matrix associated to the quadratic
system ``x' = F₁x + F₂(x⊗x)``, truncated at order ``N``.

### Input

- `F₁` -- sparse matrix of size ``n × n``
- `F₂` -- sparse matrix of size ``n × n^2``
- `N`  -- integer representing the truncation order, should be at least two
- `compress` -- if `true` produces the matrix corresponding to the commutative monomials only

### Output

Sparse matrix `A`.

### Algorithm

See references [1] and [2] of CARLIN.md.
"""
function build_matrix(F₁, F₂, N; compress=false)
    F₁ = sparse(F₁)
    F₂ = sparse(F₂)
    if compress
        n = size(F₁)[1]
        monoms = generate_monomials(n, N)
        nonzero_monoms = firstrest(monoms)[2]
        monom_to_ind = Dict(m => i for (i, m) in enumerate(nonzero_monoms))
        result = spzeros(length(monoms) - 1, length(monoms) - 1)
        for (ind, m) in enumerate(nonzero_monoms)
            for (i, j, c) in zip(findnz(F₁)...)
                if m[i] > 0
                    deriv = m
                    if i != j
                        deriv = m .+ Tuple((k == i) ? -1 : ((k == j) ? 1 : 0) for k in 1:n)
                    end
                    result[ind, monom_to_ind[deriv]] = m[i] * c
                end
            end

            if sum(m) < N
                for (i, j, c) in zip(findnz(F₂)...)
                    j0 = ((j - 1) % n) + 1
                    j1 = ((j - 1) ÷ n) + 1
                    if m[i] > 0
                        deriv = [m...,]
                        deriv[i] -= 1
                        deriv[j0] += 1
                        deriv[j1] += 1
                        deriv = (deriv...,)
                        result[ind, monom_to_ind[deriv]] += m[i] * c
                    end
                end
            end
        end
        return result
    end

    # No compression
    if N < 1
        throw(ArgumentError("expected the truncation order to be at least 1, got N=$N"))
    elseif N == 1
        _build_matrix_N1(F₁, F₂)
    elseif N == 2
        _build_matrix_N2(F₁, F₂)
    elseif N == 3
        _build_matrix_N3(F₁, F₂)
    elseif N == 4
        _build_matrix_N4(F₁, F₂)
    else
        _build_matrix_N(F₁, F₂, N) # general case
    end
end

"""
    lift_vector(x0, N)

returns a vector of monomials in x0 (hyperrectangle) of degree at most N
"""
function lift_vector(x0, N)
    monoms = generate_monomials(dim(x0), N)
    nonzero_monoms = firstrest(monoms)[2]
    result = []
    intervals = [interval(low(x0, i), high(x0, i)) for i in 1:dim(x0)]
    for m in nonzero_monoms
        push!(result, prod(intervals .^ m))
    end
    return Hyperrectangle(low=[i.lo for i in result], high=[i.hi for i in result])
end

"""
    generate_monomials(n, N)

returns a list of n-tuples of nonegative integers with the sum at most N
ordered by the total degree
"""
function generate_monomials(n, N)
    if n == 1
        return [(i,) for i in 0:N]
    end
    result = []
    prev = generate_monomials(n - 1, N)
    for ord in 0:N
        pind = 1
        while pind <= length(prev) && sum(prev[pind]) <= ord
            push!(result, (ord - sum(prev[pind]), prev[pind]...))
            pind += 1
        end
    end
    return result
end

function build_matrix_compressed(F1, F2, N)

end

function _build_matrix_N1(F₁, F₂)
    return F₁
end

function _build_matrix_N2(F₁, F₂)
    n = size(F₁, 1)
    a = hcat(kron_sum(F₁, 1), kron_sum(F₂, 1))
    b = hcat(spzeros(n^2, n), kron_sum(F₁, 2))
    return vcat(a, b)
end

function _build_matrix_N3(F₁, F₂)
    n = size(F₁, 1)
    a = hcat(kron_sum(F₁, 1), kron_sum(F₂, 1), spzeros(n, n^3))
    b = hcat(spzeros(n^2, n), kron_sum(F₁, 2), kron_sum(F₂, 2))
    c = hcat(spzeros(n^3, n), spzeros(n^3, n^2), kron_sum(F₁, 3))
    return vcat(a, b, c)
end

function _build_matrix_N4(F₁, F₂)
    n = size(F₁, 1)
    a = hcat(kron_sum(F₁, 1), kron_sum(F₂, 1), spzeros(n, n^3), spzeros(n, n^4))
    b = hcat(spzeros(n^2, n), kron_sum(F₁, 2), kron_sum(F₂, 2), spzeros(n^2, n^4))
    c = hcat(spzeros(n^3, n), spzeros(n^3, n^2), kron_sum(F₁, 3), kron_sum(F₂, 3))
    d = hcat(spzeros(n^4, n), spzeros(n^4, n^2), spzeros(n^4, n^3), kron_sum(F₁, 4))
    return vcat(a, b, c, d)
end

function _build_matrix_N(F₁, F₂, N)
    @assert N >= 3 "expected N to be at least 3, got N=$N"
    n = size(F₁, 1)

    out = Vector{typeof(F₁)}()
    for j in 1:N
        if j == N
            F12_j = kron_sum(F₁, j)
            Zleft_j = spzeros(n^j, sum(n^i for i in 1:j-1))
            push!(out, hcat(Zleft_j, F12_j))
        else
            F12_j = hcat(kron_sum(F₁, j), kron_sum(F₂, j))
            if j == 1
                Zright_j = spzeros(n^j, sum(n^i for i in j+2:N))
                push!(out, hcat(F12_j, Zright_j))
            elseif j == N-1
                Zleft_j = spzeros(n^j, sum(n^i for i in 1:j-1))
                push!(out, hcat(Zleft_j, F12_j))
            else # general case
                Zleft_j = spzeros(n^j, sum(n^i for i in 1:j-1))
                Zright_j = spzeros(n^j, sum(n^i for i in j+2:N))
                push!(out, hcat(Zleft_j, F12_j, Zright_j))
            end
        end
    end
    return reduce(vcat, out)
end


text:
# SQL functions.

mutable struct FunctionClause <: AbstractSQLClause
    name::Symbol
    args::Vector{SQLClause}

    FunctionClause(;
                   name::Union{Symbol, AbstractString},
                   args = SQLClause[]) =
        new(Symbol(name), args)
end

FunctionClause(name; args = SQLClause[]) =
    FunctionClause(name = name, args = args)

FunctionClause(name, args...) =
    FunctionClause(name, args = SQLClause[args...])

"""
    FUN(; name, args = [])
    FUN(name; args = [])
    FUN(name, args...)

An invocation of a SQL function.

# Examples

```jldoctest
julia> c = FUN(:EXTRACT, OP(:YEAR), KW(:FROM, FUN(:NOW)));

julia> print(render(c))
EXTRACT(YEAR FROM NOW())
```
"""
FUN(args...; kws...) =
    FunctionClause(args...; kws...) |> SQLClause

dissect(scr::Symbol, ::typeof(FUN), pats::Vector{Any}) =
    dissect(scr, FunctionClause, pats)

PrettyPrinting.quoteof(c::FunctionClause, ctx::QuoteContext) =
    Expr(:call, nameof(FUN), string(c.name), quoteof(c.args, ctx)...)


text:
include(Pkg.dir("GenomeAnnotations","src","Config.jl"))
include(Pkg.dir("GenomeAnnotations","src","utils.jl"))

function install_ucsc_annotation(organism, annotation_to_install=["ensGene"] )

    local_store_path = LOCAL_STORE_PATH()

    if( !isdir(local_store_path) )
        println("Local store path does not exist, run setup_genome_annotations")
    end

    organism_path = joinpath( local_store_path, organism )
    println("make directory $organism_path")

    if isdir(organism_path)
         println("$organism_path already exists, skip mkdir")
    else
         mkdir( organism_path )
    end

    for annotation in annotation_to_install
        if annotation == "ensGene"
            println("Installing ensGene for $organism")
            download_ensgene(organism,organism_path)
        else
           println("No installation code for $annotation")
        end
    end
end

function download_ensgene ( organism, download_dir )
    ucsc_ensgene_url = "http://hgdownload.cse.ucsc.edu/goldenPath/$organism/database/ensGene.txt.gz"
    println("Download to $download_dir")
    download_path = joinpath(download_dir,"ensGene.txt.gz")
    if isfile(download_path )
       println("Download path exists: $download_path")
    else
        download_with_curl(ucsc_ensgene_url, download_path)
    end
end


text:
"""Performs a random walk on graph `g` starting at vertex `s` and continuing for
a maximum of `niter` steps. Returns a vector of vertices visited in order.
"""
function randomwalk(g::SimpleGraph, s::Integer, niter::Integer)
  s in vertices(g) || throw(BoundsError())
  visited = Vector{Int}()
  sizehint!(visited, niter)
  currs = s
  i = 1
  while i <= niter
    push!(visited, currs)
    i += 1
    nbrs = out_neighbors(g,currs)
    length(nbrs) == 0 && break
    currs = rand(nbrs)
  end
  return visited[1:i-1]
end

"""Performs a non-backtracking random walk on graph `g` starting at vertex `s` and continuing for
a maximum of `niter` steps. Returns a vector of vertices visited in order.
"""
function non_backtracking_randomwalk(g::Graph, s::Integer, niter::Integer)
    s in vertices(g) || throw(BoundsError())
    visited = Vector{Int}()
    sizehint!(visited, niter)
    currs = s
    prev = -1
    i = 1

    push!(visited, currs)
    i += 1
    nbrs = out_neighbors(g,currs)
    length(nbrs) == 0 && return visited[1:i-1]
    prev = currs
    currs = rand(nbrs)

    while i <= niter
        push!(visited, currs)
        i += 1
        nbrs = out_neighbors(g,currs)
        length(nbrs) == 1 && break
        idnext = rand(1:length(nbrs)-1)
        next = nbrs[idnext]
        if next == prev
            next = nbrs[end]
        end
        prev = currs
        currs = next
    end
    return visited[1:i-1]
end

function non_backtracking_randomwalk(g::DiGraph, s::Integer, niter::Integer)
    s in vertices(g) || throw(BoundsError())
    visited = Vector{Int}()
    sizehint!(visited, niter)
    currs = s
    prev = -1
    i = 1

    while i <= niter
        push!(visited, currs)
        i += 1
        nbrs = out_neighbors(g,currs)
        length(nbrs) == 0 && break
        next = rand(nbrs)
        if next == prev
            length(nbrs) == 1 && break
            idnext = rand(1:length(nbrs)-1)
            next = nbrs[idnext]
            if next == prev
                next = nbrs[end]
            end
        end
        prev = currs
        currs = next
    end
    return visited[1:i-1]
end

"""Performs a [self-avoiding walk](https://en.wikipedia.org/wiki/Self-avoiding_walk)
on graph `g` starting at vertex `s` and continuing for a maximum of `niter` steps.
Returns a vector of vertices visited in order.
"""
function saw(g::SimpleGraph, s::Integer, niter::Integer)
  s in vertices(g) || throw(BoundsError())
  visited = Vector{Int}()
  svisited = Set{Int}()
  sizehint!(visited, niter)
  sizehint!(svisited, niter)
  currs = s
  i = 1
  while i <= niter
    push!(visited, currs)
    push!(svisited, currs)
    i += 1
    nbrs = setdiff(Set(out_neighbors(g,currs)),svisited)
    length(nbrs) == 0 && break
    currs = rand(collect(nbrs))
  end
  return visited[1:i-1]
end


text:
include("stream.jl")
using JLD2
using Parameters
using LaTeXStrings
using OffsetArrays
using BrownianDynamics
using PyPlot
using SparseArrays
rc("text",usetex=true)
rc("font",size=10)
rc("contour",negative_linestyle="solid")
## Read in data.
@load "$(@__DIR__)/../steady_state_double_channel.jld" u_steady params xx yy T0
#V_equilibrium -= minimum(V_equilibrium)

@unpack Pmat,Tmat,Jx,Jy,V,Vxshift,Vyshift,V_x,V_y,dx,dy,A,coupling = params
V .-= minimum(V)
# V_x = rotl90(V_x)
# V_y = rotl90(V_y)
nx,ny = size(V_x)[1]-1,size(V_x)[2]-1
T = reshape(u_steady[(nx*ny+1:end)],nx,ny)
P = reshape(u_steady[1:nx*ny],nx,ny)
Tsol = fill(T0,0:nx+1,0:ny+1)
Tsol[1:nx,1:ny] .= reshape(u_steady[(nx*ny+1):end],nx,ny)
# Periodicity in the x direction.
Tsol[0,1:ny] .= Tsol[nx-1,1:ny]
Tsol[nx+1,1:ny] .= Tsol[2,1:ny]

Psol = fill(0.0,0:nx+1,0:ny+1)
Psol[1:nx,1:ny] .= reshape(u_steady[1:nx*ny],nx,ny)
# Periodicity in the x direction.
Psol[0,1:ny] .= Psol[nx-1,1:ny]
Psol[nx+1,1:ny] .= Psol[2,1:ny]

Jx = [-( 0.5*(Psol[i-1,j]+Psol[i,j])*V_x[i,j]
        +0.5*(Tsol[i-1,j]+Tsol[i,j])*(Psol[i,j]-Psol[i-1,j])/dx) for i in 1:nx, j in 1:ny]
Jy = [-( 0.5*(Psol[i,j-1]+Psol[i,j])*V_y[i,j]
        +0.5*(Tsol[i,j-1]+Tsol[i,j])*(Psol[i,j]-Psol[i,j-1])/dy) for i in 1:nx, j in 1:ny]

Jx = rotl90(Jx)
Jy = -rotl90(Jy)
nablaT_x = [(Tsol[i,j]-Tsol[i-1,j])/dx for i in 1:nx, j in 1:ny]
nablaT_y = [(Tsol[i,j]-Tsol[i,j-1])/dy for i in 1:nx, j in 1:ny]
nablaT_x = rotl90(nablaT_x)
nablaT_y = -rotl90(nablaT_y)
Psol = rotl90(Psol)
Tsol = rotl90(Tsol)
P = rotl90(P)
# Plotting
close("all")
## Potential.
# figure(1,figsize=(3,12))
subplots(sharex=true,figsize=(3.1,9))
subplots_adjust(wspace=1)
p1 = subplot(4,1,1)
# Create a dummy contourf plot, so that we can steal its colorbar.
figure(2)
#V_equilibrium = rotl90(V_equilibrium)
#cbar_ax = contourf(V_equilibrium)
V = rotl90(V) # presume it is these we want rather thatn V_equilibrium - MJ
cbar_ax = contourf(V)

figure(1)
contour(xx,yy,V,linewidths=0.8,levels=range(minimum(V),stop=maximum(V),length=6))
colorbar(cbar_ax)
# colorbar(ticks=linspace(-2.5,18,5))
clim(-2.5,18)
ylabel(L"y/l")
xticks([])

## Probability distribution.
subplot(4,1,2)
nlevels = 5

P.-=minimum(P) # get rid of strange negative values

p3 = contour(xx,yy,P,levels=range(0.01,stop=maximum(P),length=nlevels),linewidths=0.8)
# Make an invisible colorbar, so that everything lines up.
figure(2)
cbar_ax = contourf(P) # want colour bar. Copy T example - MJ
figure(1)
colorbar(cbar_ax,ticks=round.(range(0.0,stop=maximum(P),length=4),digits=2))
#cbar_ax = colorbar()
#cbar_ax[:ax][:set_visible](false)
ylabel(L"y/l")
xticks([])

## Probability current.
p4 = subplot(4,1,3)
stride = 16
# Jx,Jy = density_current((xx,yy),u_steady,params)
# Jx = rotl90(Jx)
# Jy = rotl90(Jy)
ψ = flowfun(Jx,Jy)
contour(xx,yy,ψ,range(minimum(ψ),stop=maximum(ψ),length=8),colors="g",linewidths=1.0)
# Make an invisible colorbar, so that everything lines up.
cbar_ax = colorbar()
cbar_ax.ax.set_visible(false)
quiver(xx[1:stride:end-1],yy[1:stride:end-1],Jx[1:stride:end-1,1:stride:end-1],
    Jy[1:stride:end-1,1:stride:end-1],scale=4,width=0.005,headwidth=4,zorder=2)
xticks([])
ylabel(L"y/l")
## Temperature and heat.
# figure(2,figsize=(1.5,1.5))
p2 = subplot(4,1,4)
stride = 20
T = rotl90(T)
temperature_contour = contour(xx,yy,T,linewidths=0.8)
# Create a dummy contourf plot, so that we can steal its colorbar.
figure(2)
cbar_ax = contourf(T)
figure(1)
colorbar(cbar_ax,ticks=round.(range(minimum(T),stop=maximum(T),length=4),digits=2))
quiver(xx[1:stride:end],yy[1:stride:end],-nablaT_x[1:stride:end,1:stride:end],
    -nablaT_y[1:stride:end,1:stride:end],zorder=2,width=0.005,headwidth=5,scale=3.0)
ylabel(L"y/l")
xlabel(L"x/L")
## Save the plot into the figures directory.
savefig("$(@__DIR__)/../figures/double_channel_offset.pdf",bbox_inches="tight")


text:
module DiffEqBase

using RecipesBase, RecursiveArrayTools, Compat,
      Requires, TableTraits, IteratorInterfaceExtensions, TreeViews

using Roots # callbacks

using StaticArrays # data arrays

using LinearAlgebra, Statistics

# Problems
abstract type DEProblem end
abstract type DEElement end
abstract type DESensitivity end

abstract type AbstractSteadyStateProblem{uType,isinplace} <: DEProblem end

abstract type AbstractNoiseProblem <: DEProblem end

abstract type AbstractODEProblem{uType,tType,isinplace} <: DEProblem end
abstract type AbstractDiscreteProblem{uType,tType,isinplace} <:
                      AbstractODEProblem{uType,tType,isinplace} end
abstract type AbstractAnalyticalProblem{uType,tType,isinplace} <:
                      AbstractODEProblem{uType,tType,isinplace} end

abstract type AbstractRODEProblem{uType,tType,isinplace,ND} <: DEProblem end

abstract type AbstractSDEProblem{uType,tType,isinplace,ND} <:
                      AbstractRODEProblem{uType,tType,isinplace,ND} end

abstract type AbstractDAEProblem{uType,duType,tType,isinplace} <: DEProblem end

abstract type AbstractDDEProblem{uType,tType,lType,isinplace} <: DEProblem end
abstract type AbstractConstantLagDDEProblem{uType,tType,lType,isinplace} <:
                      AbstractDDEProblem{uType,tType,lType,isinplace} end

abstract type AbstractSecondOrderODEProblem{uType,tType,isinplace} <: AbstractODEProblem{uType,tType,isinplace} end

abstract type AbstractBVProblem{uType,tType,isinplace} <: AbstractODEProblem{uType,tType,isinplace} end

abstract type AbstractJumpProblem{P,J} <: DiffEqBase.DEProblem end

# Algorithms
abstract type DEAlgorithm end
abstract type AbstractSteadyStateAlgorithm <: DEAlgorithm end
abstract type AbstractODEAlgorithm <: DEAlgorithm end
abstract type AbstractSecondOrderODEAlgorithm <: DEAlgorithm end
abstract type AbstractRODEAlgorithm <: DEAlgorithm end
abstract type AbstractSDEAlgorithm <: DEAlgorithm end
abstract type AbstractDAEAlgorithm <: DEAlgorithm end
abstract type AbstractDDEAlgorithm <: DEAlgorithm end

# Monte Carlo Simulations
abstract type AbstractMonteCarloProblem <: DEProblem end
abstract type AbstractMonteCarloEstimator <: DEProblem end

export MonteCarloProblem
export MonteCarloSolution, MonteCarloTestSolution, MonteCarloSummary

abstract type AbstractDiffEqInterpolation <: Function end
abstract type AbstractDEOptions end
abstract type DECache end
abstract type DECallback end
abstract type AbstractContinuousCallback <: DECallback end
abstract type AbstractDiscreteCallback <: DECallback end

abstract type DEDataArray{T,N} <: AbstractArray{T,N} end
const DEDataVector{T} = DEDataArray{T,1}
const DEDataMatrix{T} = DEDataArray{T,2}

# Integrators
abstract type DEIntegrator{Alg, IIP, U, T} end
abstract type AbstractSteadyStateIntegrator{Alg, IIP, U} <: DEIntegrator{Alg, IIP, U, Nothing} end
abstract type AbstractODEIntegrator{Alg, IIP, U, T} <: DEIntegrator{Alg, IIP, U, T} end
abstract type AbstractSecondOrderODEIntegrator{Alg, IIP, U, T} <: DEIntegrator{Alg, IIP, U, T} end
abstract type AbstractRODEIntegrator{Alg, IIP, U, T} <: DEIntegrator{Alg, IIP, U, T} end
abstract type AbstractSDEIntegrator{Alg, IIP, U, T} <: DEIntegrator{Alg, IIP, U, T} end
abstract type AbstractDDEIntegrator{Alg, IIP, U, T} <: DEIntegrator{Alg, IIP, U, T} end
abstract type AbstractDAEIntegrator{Alg, IIP, U, T} <: DEIntegrator{Alg, IIP, U, T} end

# Solutions
abstract type AbstractNoTimeSolution{T,N} <: AbstractArray{T,N} end
abstract type AbstractTimeseriesSolution{T,N} <: AbstractDiffEqArray{T,N} end
abstract type AbstractMonteCarloSolution{T,N} <: AbstractVectorOfArray{T,N} end
abstract type AbstractNoiseProcess{T,N,isinplace} <: AbstractDiffEqArray{T,N} end

const DESolution = Union{AbstractTimeseriesSolution,
                         AbstractNoTimeSolution,
                         AbstractMonteCarloSolution,
                         AbstractNoiseProcess}
export DESolution
abstract type AbstractSteadyStateSolution{T,N} <: AbstractNoTimeSolution{T,N} end
abstract type AbstractAnalyticalSolution{T,N} <: AbstractTimeseriesSolution{T,N} end
abstract type AbstractODESolution{T,N} <: AbstractTimeseriesSolution{T,N} end

# Needed for plot recipes
abstract type AbstractDDESolution{T,N} <: AbstractODESolution{T,N} end
abstract type AbstractRODESolution{T,N} <: AbstractODESolution{T,N} end
abstract type AbstractDAESolution{T,N} <: AbstractODESolution{T,N} end
abstract type AbstractSensitivitySolution{T,N} end

# Misc
abstract type Tableau end
abstract type ODERKTableau <: Tableau end
abstract type DECostFunction end
abstract type AbstractDiffEqOperator{T} end
abstract type AbstractDiffEqLinearOperator{T} <: AbstractDiffEqOperator{T} end
abstract type AbstractDiffEqFunction{iip} <: Function end
abstract type AbstractReactionNetwork <: Function end

include("destats.jl")
include("utils.jl")
include("extended_functions.jl")
include("solutions/steady_state_solutions.jl")
include("solutions/ode_solutions.jl")
include("solutions/rode_solutions.jl")
include("solutions/dae_solutions.jl")
include("solutions/monte_solutions.jl")
include("solutions/solution_interface.jl")
include("tableaus.jl")
include("diffeqfunction.jl")
include("problems/problem_utils.jl")
include("problems/discrete_problems.jl")
include("problems/steady_state_problems.jl")
include("problems/analytical_problems.jl")
include("problems/ode_problems.jl")
include("problems/rode_problems.jl")
include("problems/sde_problems.jl")
include("problems/noise_problems.jl")
include("problems/bvp_problems.jl")
include("problems/dae_problems.jl")
include("problems/dde_problems.jl")
include("problems/monte_problems.jl")
include("problems/problem_traits.jl")
include("interpolation.jl")
include("callbacks.jl")
include("integrator_interface.jl")
include("diffeq_operator.jl")
include("linear_nonlinear.jl")
include("common_defaults.jl")
include("data_array.jl")
include("solve.jl")
include("internal_euler.jl")
include("tabletraits.jl")
include("alg_traits.jl")
include("remake.jl")
include("init.jl")

abstract type AbstractParameterizedFunction{iip} <: AbstractODEFunction{iip} end

struct ConvergenceSetup{P,C}
    probs::P
    convergence_axis::C
end

export isinplace

export solve, solve!, init, step!

export tuples, intervals, TimeChoiceIterator

export resize!,deleteat!,addat!,get_tmp_cache,
       full_cache,user_cache,u_cache,du_cache,
       rand_cache,ratenoise_cache,
       resize_non_user_cache!,deleteat_non_user_cache!,addat_non_user_cache!,
       terminate!,
       add_tstop!,add_saveat!,set_abstol!,
       set_reltol!,get_du, get_du!, get_dt,get_proposed_dt,set_proposed_dt!,
       u_modified!, savevalues!,reinit!, auto_dt_reset!, set_t!,
       set_u!, check_error, change_t_via_interpolation!, addsteps!,
       isdiscrete, reeval_internals_due_to_modification!

export DiscreteProblem

export SteadyStateProblem, SteadyStateSolution
export NoiseProblem
export ODEProblem, ODESolution
export DynamicalODEFunction, DynamicalODEProblem,
       SecondOrderODEProblem, SplitFunction, SplitODEProblem
export SplitSDEProblem
export RODEProblem, RODESolution, SDEProblem
export DAEProblem, DAESolution
export DDEProblem

export BVProblem, TwoPointBVProblem

export remake

export DEDataArray, DEDataVector, DEDataMatrix

export ODEFunction, DiscreteFunction, SplitFunction, DAEFunction, DDEFunction,
       SDEFunction, SplitSDEFunction, RODEFunction

export ContinuousCallback, DiscreteCallback, CallbackSet

export initialize!

export LinSolveFactorize, DEFAULT_LINSOLVE

export AffineDiffEqOperator, update_coefficients!, update_coefficients, is_constant,
       has_expmv!, has_expmv, has_exp, has_mul, has_mul!, has_ldiv, has_ldiv!

end # module


text:
using RPOMDPModels, RPOMDPs, RPOMDPToolbox
using RobustValueIteration
using SimpleProbabilitySets
using DataFrames, ProgressMeter, CSV, BenchmarkTools
const RPBVI = RobustValueIteration
TOL = 1e-6

# intialize problems
ip = SimpleIPOMDP(0.8, 0.7, 0.66, 0.85)
rip = SimpleRIPOMDP(0.8, 0.7, 0.66, 0.85, 0.15)
tip = SimpleIPOMDP(0.65, 0.85, 0.51, 0.7)

# select belief points
ss = [[0.0, 1.0], [0.1, 0.9], [0.2, 0.8], [0.3, 0.7], [0.4, 0.6], [0.5, 0.5],
        [0.6, 0.4], [0.7, 0.3], [0.8, 0.2], [0.9, 0.1], [1.0, 0.0]]
bs = Vector{Vector{Float64}}(length(ss))
for i = 1:length(ss)
    bs[i] = ss[i]
end

# intialize solver
solver = RPBVISolver(beliefpoints = bs, max_iterations = 50)

# solve
@time solip = RPBVI.solve(solver, ip);
@time solrip = RPBVI.solve(solver, rip);
@time soltip = RPBVI.solve(solver, tip);

# calculate values
nS = length(states(ip))
e1 = zeros(nS); e1[1] = 1
println("Standard Value: ", policyvalue(solip, e1))
println("Robust Value: ", policyvalue(solrip, e1))
println("Off Nominal Precise Value: ", policyvalue(soltip, e1))

# ipomdp and ripomdp actions for some interesting states
actionind = ss
dbsip = [DiscreteBelief(ip, states(ip), s) for s in ss]
asip = [action(solip, db) for db in dbsip]
dbsrip = [DiscreteBelief(rip, states(rip), s) for s in ss]
asrip = [action(solrip, db) for db in dbsrip]
dbstip = [DiscreteBelief(tip, states(tip), s) for s in ss]
astip = [action(soltip, db) for db in dbstip]
actiondata = DataFrame(Belief = actionind, StdAction = asip,
                        RobustAction = asrip, OffNominalAction = astip)
@show actiondata

# sim values for nominal and robust solutions for off-nominal case
ntest = 3
nreps = 40
nsteps = 20
psim = RolloutSimulator(max_steps = nsteps)
simvals = [Vector{Float64}(nreps) for _ in 1:ntest] # simulated values
simps = [Vector{Float64}(nreps) for _ in 1:ntest] # simulated percent correct
ves = Array{Float64}(ntest) # expected values
vms = Array{Float64}(ntest) # mean of sim values
vss = Array{Float64}(ntest) # std dev of sim values
vmins = Array{Float64}(ntest) # min of sim values
pms = Array{Float64}(ntest) # mean percent correct
pss = Array{Float64}(ntest) # std percent correct

rseed = 92378432
simprob = rip
simdynamics = :worst
for i in 1:1
    # println("Run ", ceil(Int, i / 2))
    buip, burip, butip = updater(solip), updater(solrip), updater(soltip)
    println("Nominal")
    srand(rseed)
    @showprogress 1 "Simulating nominal value..." for j = 1:nreps
        if simdynamics == :worst
            sv, sp = simulate_worst(psim, simprob, solip, buip, solrip.alphas)
        else
            sv, sp = simulate(psim, simprob, solip, buip)
        end
        simvals[i][j] = sv
        simps[i][j] = sp
    end
    vms[i] = mean(simvals[i])
    vss[i] = std(simvals[i])
    vmins[i] = minimum(simvals[i])
    pms[i] = mean(simps[i])
    pss[i] = std(simps[i])
    println("Robust")
    srand(rseed)
    @showprogress 1 "Simulating robust value..." for j = 1:nreps
        sv, sp = simulate(psim, simprob, solrip, buip)
        if simdynamics == :worst
            sv, sp = simulate_worst(psim, simprob, solrip, burip, solrip.alphas)
        else
            sv, sp = simulate(psim, simprob, solrip, buip)
        end
        simvals[i+1][j] = sv
        simps[i+1][j] = sp
    end
    vms[i+1] = mean(simvals[i+1])
    vss[i+1] = std(simvals[i+1])
    vmins[i+1] = minimum(simvals[i+1])
    pms[i+1] = mean(simps[i+1])
    pss[i+1] = std(simps[i+1])
    println("OffNominal")
    srand(rseed)
    @showprogress 1 "Simulating off-nominal value..." for j = 1:nreps
        if simdynamics == :worst
            sv, sp = simulate_worst(psim, simprob, soltip, butip, solrip.alphas)
        else
            sv, sp = simulate(psim, simprob, soltip, butip)
        end
        simvals[i+2][j] = sv
        simps[i+2][j] = sp
    end
    vms[i+2] = mean(simvals[i+2])
    vss[i+2] = std(simvals[i+2])
    vmins[i+2] = minimum(simvals[i+2])
    pms[i+2] = mean(simps[i+2])
    pss[i+2] = std(simps[i+2])
end

sname = "simple"
sversion = "4.0"
ves = [policyvalue(solip, e1), policyvalue(solrip, e1),
        policyvalue(soltip, e1)]
rdata = DataFrame(ID = ["Nominal", "Robust","OffNominal"], ExpValue = ves,
                SimMean = vms, SimStd = vss, SimMin = vmins,
                SimPercentMean = pms, SimPercentStd = pss)
simdata = DataFrame(NominalSim = simvals[1], RobustSim = simvals[2],
                        OffNominal = simvals[1])
@show rdata

path = joinpath(homedir(),".julia\\v0.6\\RobustInfoPOMDP\\data")
fnresults = string("exp_results_", sname, "_", sversion, ".csv")
fnsim = string("exp_sim_values_", sname, "_", sversion, ".csv")
fnactions = string("exp_actions_", sname, "_", sversion, ".csv")
CSV.write(joinpath(path, fnresults), rdata)
CSV.write(joinpath(path, fnsim), simdata)
CSV.write(joinpath(path, fnactions), actiondata)

########### testing ############
rng = MersenneTwister(0)
b = [0.6, 0.4]

dbip = DiscreteBelief(ip, states(ip), b)
buip = updater(solip)
dbtip = DiscreteBelief(tip, states(tip), b)
butip = updater(soltip)
dbrip = DiscreteBelief(rip, states(rip), b)
burip = updater(solrip)
s = :left
a = :both
o = :LR

dbip = initialize_belief(buip, initial_state_distribution(ip))
dbrip = initialize_belief(burip, initial_state_distribution(rip))

dbip = DiscreteBelief(ip, states(ip), [0.745, 0.255])

o = :LL

update(buip, dbip, a, o).b
update(butip, dbtip, a, o).b

generate_sor(rip, dbip.b, s, a, rng)

sp = :left
observation(rip, a, sp)
psample(observation(rip, a, sp)...)

nsteps = 10
psim = RolloutSimulator(max_steps = nsteps)
simulate(psim, rip, solrip, burip)
simulate_worst(psim, rip, solrip, burip, solrip.alphas)

dbrip = DiscreteBelief(rip, states(rip), [0.7, 0.3])
a = :both
generate_sor(rip, dbrip.b, s, a, rng)
RPOMDPToolbox.generate_sor_worst(rip, dbrip.b, s, a, rng, solrip.alphas)
sp = :left
o = :L
bp = update(burip, dbrip, a, :R).b
reward(rip, bp, a)

initial_belief = initial_state_distribution(rip)
rand(psim.rng, initial_belief)

max_stars_repo_name: ajkeith/RobustInfoPOMDP

max_issues_repo_name: ajkeith/RobustInfoPOMDP

max_forks_repo_name: ajkeith/RobustInfoPOMDP


text:
function ms_transpose!(R::Array{T,2}) where T
    @inbounds for i in 1:3
        for j in i:3
            temp = R[j,i]
            R[j,i] = R[i,j]
            R[i,j] = temp
        end
    end
end

function ms_column_swap!(R::Array{T,2}, i, j) where T
    @inbounds for k in 1:3
        temp = R[k,i]
        R[k,i] = R[k,j]
        R[k,j] = temp
    end
end

function ms_row_swap!(R::Array{T,2}, i, j) where T
    @inbounds for k in 1:3
        temp = R[i,k]
        R[i,k] = R[j,k]
        R[j,k] = temp
    end
end

function SL_row_to_top!(R::Array{T,2}, S, L) where T
    if SL_in_row(R, S, L, 1)
        return
    elseif SL_in_row(R, S, L, 2)
        ms_row_swap!(R,1,2)
    elseif SL_in_row(R, S, L, 3)
        ms_row_swap!(R,1,3)
    end
end

# check if both S and L are in row i
SL_in_row(R, S, L, i) = ((S == R[i,1] || S == R[i,2] || S == R[i,3]) &&
                         (L == R[i,1] || L == R[i,2] || L == R[i,3]))

function SL_form!(R::Array{T,2}) where T
    S = minimum(R)
    L = maximum(R)

    # move S and L into first row
    SL_row_to_top!(R, S, L)
    if !SL_in_row(R, S, L, 1)
        ms_transpose!(R)
        SL_row_to_top!(R, S, L)
    end

    # move S into the first column
    S_col = argmin((R[1,1], R[1,2], R[1,3]))#ms_row_argmin(R[1,1], R[1,2], R[1,3])
    if S_col != 1
        ms_column_swap!(R, 1, S_col)
    end
    # move L into the second column
    if L != R[1,2]
        ms_column_swap!(R, 2, 3)
    end

    if R[2,2] < R[3,2]
        return
    elseif R[2,2] == R[3,2]
        # now require R₂₃ ≤ R₃₃
        if R[2,3] ≤ R[3,3]
            return
        else
            ms_row_swap!(R,2,3)
        end
    else  # R[2,2] > R[3,2]
        ms_row_swap!(R,2,3)
    end
end

function regge_variables!(R::Array{TR,2},
                          j₁, j₂, j₃,
                          m₁, m₂, m₃) where {TR}
    R[1,1] = -j₁+j₂+j₃
    R[1,2] = j₁-j₂+j₃
    R[1,3] = j₁+j₂-j₃
    R[2,1] = j₁-m₁
    R[2,2] = j₂-m₂
    R[2,3] = j₃-m₃
    R[3,1] = j₁+m₁
    R[3,2] = j₂+m₂
    R[3,3] = j₃+m₃
    SL_form!(R)
    vars = (R[1,2], R[2,1], R[3,3], R[2,2], R[1,1])
    @assert vars[1] ≥ vars[2] ≥ vars[3] ≥ vars[4] ≥ vars[5]
    @inbounds return vars  # L, X, T, B, S
end

function rasch_yu_index!(::Type{Tindex}, R::Array{Tint,2},
                        j₁, j₂, j₃, m₁, m₂, m₃) where {Tindex <: Integer, Tint <: Integer}
    L, X, T, B, S = Tindex.(regge_variables!(R, j₁, j₂, j₃, m₁, m₂, m₃))
    c = convert(Tindex, ceil(
        L * (24 + L * (50 + L * (35 + L * (10 + L)))) / 120 +
        X * (6 + (X * (11 + X * (6 + X)))) / 24 +
        T * (2 + T * (3 + T)) / 6 + B * (B + 1) / 2 + S + 1))
    return c
end

function rasch_yu_index(::Type{Tindex}, j₁, j₂, j₃, m₁, m₂, m₃) where {Tindex <: Integer}
    R = zeros(Int, (3,3))
    rasch_yu_index!(Tindex, R, j₁, j₂, j₃, m₁, m₂, m₃)
end

"""
Evens out an array which scales linearly with difficulty by interleaving elements such that
[1,2,3,4,5,6] is mapped to [1,6,2,5,3,4].
"""
function swap_triangular(arr)
    swapped = similar(arr)
    counter = 1
    n = length(arr)
    for i in 1:n
        swapped[i] = isodd(i) ? arr[div(i,2)+1] : arr[n + 1 - div(i+1,2)]
    end
    swapped
end