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

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

Authorizes the DDoS Response Team (DRT) to access the specified Amazon S3 bucket containing
your AWS WAF logs. You can associate up to 10 Amazon S3 buckets with your subscription. To
use the services of the DRT and make an AssociateDRTLogBucket request, you must be
subscribed to the Business Support plan or the Enterprise Support plan.

# Arguments
- `log_bucket`: The Amazon S3 bucket that contains your AWS WAF logs.

"""
associate_drtlog_bucket(LogBucket; aws_config::AbstractAWSConfig=global_aws_config()) = shield("AssociateDRTLogBucket", Dict{String, Any}("LogBucket"=>LogBucket); aws_config=aws_config)
associate_drtlog_bucket(LogBucket, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("AssociateDRTLogBucket", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LogBucket"=>LogBucket), params)); aws_config=aws_config)

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

Authorizes the DDoS Response Team (DRT), using the specified role, to access your AWS
account to assist with DDoS attack mitigation during potential attacks. This enables the
DRT to inspect your AWS WAF configuration and create or update AWS WAF rules and web ACLs.
You can associate only one RoleArn with your subscription. If you submit an
AssociateDRTRole request for an account that already has an associated role, the new
RoleArn will replace the existing RoleArn.  Prior to making the AssociateDRTRole request,
you must attach the AWSShieldDRTAccessPolicy managed policy to the role you will specify in
the request. For more information see Attaching and Detaching IAM Policies. The role must
also trust the service principal  drt.shield.amazonaws.com. For more information, see IAM
JSON Policy Elements: Principal. The DRT will have access only to your AWS WAF and Shield
resources. By submitting this request, you authorize the DRT to inspect your AWS WAF and
Shield configuration and create and update AWS WAF rules and web ACLs on your behalf. The
DRT takes these actions only if explicitly authorized by you. You must have the
iam:PassRole permission to make an AssociateDRTRole request. For more information, see
Granting a User Permissions to Pass a Role to an AWS Service.  To use the services of the
DRT and make an AssociateDRTRole request, you must be subscribed to the Business Support
plan or the Enterprise Support plan.

# Arguments
- `role_arn`: The Amazon Resource Name (ARN) of the role the DRT will use to access your
  AWS account. Prior to making the AssociateDRTRole request, you must attach the
  AWSShieldDRTAccessPolicy managed policy to this role. For more information see Attaching
  and Detaching IAM Policies.

"""
associate_drtrole(RoleArn; aws_config::AbstractAWSConfig=global_aws_config()) = shield("AssociateDRTRole", Dict{String, Any}("RoleArn"=>RoleArn); aws_config=aws_config)
associate_drtrole(RoleArn, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("AssociateDRTRole", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RoleArn"=>RoleArn), params)); aws_config=aws_config)

"""
    associate_health_check(health_check_arn, protection_id)
    associate_health_check(health_check_arn, protection_id, params::Dict{String,<:Any})

Adds health-based detection to the Shield Advanced protection for a resource. Shield
Advanced health-based detection uses the health of your AWS resource to improve
responsiveness and accuracy in attack detection and mitigation.  You define the health
check in Route 53 and then associate it with your Shield Advanced protection. For more
information, see Shield Advanced Health-Based Detection in the AWS WAF and AWS Shield
Developer Guide.

# Arguments
- `health_check_arn`: The Amazon Resource Name (ARN) of the health check to associate with
  the protection.
- `protection_id`: The unique identifier (ID) for the Protection object to add the health
  check association to.

"""
associate_health_check(HealthCheckArn, ProtectionId; aws_config::AbstractAWSConfig=global_aws_config()) = shield("AssociateHealthCheck", Dict{String, Any}("HealthCheckArn"=>HealthCheckArn, "ProtectionId"=>ProtectionId); aws_config=aws_config)
associate_health_check(HealthCheckArn, ProtectionId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("AssociateHealthCheck", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("HealthCheckArn"=>HealthCheckArn, "ProtectionId"=>ProtectionId), params)); aws_config=aws_config)

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

Initializes proactive engagement and sets the list of contacts for the DDoS Response Team
(DRT) to use. You must provide at least one phone number in the emergency contact list.
After you have initialized proactive engagement using this call, to disable or enable
proactive engagement, use the calls DisableProactiveEngagement and
EnableProactiveEngagement.   This call defines the list of email addresses and phone
numbers that the DDoS Response Team (DRT) can use to contact you for escalations to the DRT
and to initiate proactive customer support. The contacts that you provide in the request
replace any contacts that were already defined. If you already have contacts defined and
want to use them, retrieve the list using DescribeEmergencyContactSettings and then provide
it to this call.

# Arguments
- `emergency_contact_list`: A list of email addresses and phone numbers that the DDoS
  Response Team (DRT) can use to contact you for escalations to the DRT and to initiate
  proactive customer support.  To enable proactive engagement, the contact list must include
  at least one phone number.  The contacts that you provide here replace any contacts that
  were already defined. If you already have contacts defined and want to use them, retrieve
  the list using DescribeEmergencyContactSettings and then provide it here.

"""
associate_proactive_engagement_details(EmergencyContactList; aws_config::AbstractAWSConfig=global_aws_config()) = shield("AssociateProactiveEngagementDetails", Dict{String, Any}("EmergencyContactList"=>EmergencyContactList); aws_config=aws_config)
associate_proactive_engagement_details(EmergencyContactList, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("AssociateProactiveEngagementDetails", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EmergencyContactList"=>EmergencyContactList), params)); aws_config=aws_config)

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

Enables AWS Shield Advanced for a specific AWS resource. The resource can be an Amazon
CloudFront distribution, Elastic Load Balancing load balancer, AWS Global Accelerator
accelerator, Elastic IP Address, or an Amazon Route 53 hosted zone. You can add protection
to only a single resource with each CreateProtection request. If you want to add protection
to multiple resources at once, use the AWS WAF console. For more information see Getting
Started with AWS Shield Advanced and Add AWS Shield Advanced Protection to more AWS
Resources.

# Arguments
- `name`: Friendly name for the Protection you are creating.
- `resource_arn`: The ARN (Amazon Resource Name) of the resource to be protected. The ARN
  should be in one of the following formats:   For an Application Load Balancer:
  arn:aws:elasticloadbalancing:region:account-id:loadbalancer/app/load-balancer-name/load-bala
  ncer-id     For an Elastic Load Balancer (Classic Load Balancer):
  arn:aws:elasticloadbalancing:region:account-id:loadbalancer/load-balancer-name     For an
  AWS CloudFront distribution: arn:aws:cloudfront::account-id:distribution/distribution-id
   For an AWS Global Accelerator accelerator:
  arn:aws:globalaccelerator::account-id:accelerator/accelerator-id     For Amazon Route 53:
  arn:aws:route53:::hostedzone/hosted-zone-id     For an Elastic IP address:
  arn:aws:ec2:region:account-id:eip-allocation/allocation-id

"""
create_protection(Name, ResourceArn; aws_config::AbstractAWSConfig=global_aws_config()) = shield("CreateProtection", Dict{String, Any}("Name"=>Name, "ResourceArn"=>ResourceArn); aws_config=aws_config)
create_protection(Name, ResourceArn, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("CreateProtection", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name, "ResourceArn"=>ResourceArn), params)); aws_config=aws_config)

"""
    create_protection_group(aggregation, pattern, protection_group_id)
    create_protection_group(aggregation, pattern, protection_group_id, params::Dict{String,<:Any})

Creates a grouping of protected resources so they can be handled as a collective. This
resource grouping improves the accuracy of detection and reduces false positives.

# Arguments
- `aggregation`: Defines how AWS Shield combines resource data for the group in order to
  detect, mitigate, and report events.   Sum - Use the total traffic across the group. This
  is a good choice for most cases. Examples include Elastic IP addresses for EC2 instances
  that scale manually or automatically.   Mean - Use the average of the traffic across the
  group. This is a good choice for resources that share traffic uniformly. Examples include
  accelerators and load balancers.   Max - Use the highest traffic from each resource. This
  is useful for resources that don't share traffic and for resources that share that traffic
  in a non-uniform way. Examples include CloudFront distributions and origin resources for
  CloudFront distributions.
- `pattern`: The criteria to use to choose the protected resources for inclusion in the
  group. You can include all resources that have protections, provide a list of resource
  Amazon Resource Names (ARNs), or include all resources of a specified resource type.
- `protection_group_id`: The name of the protection group. You use this to identify the
  protection group in lists and to manage the protection group, for example to update,
  delete, or describe it.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Members"`: The Amazon Resource Names (ARNs) of the resources to include in the
  protection group. You must set this when you set Pattern to ARBITRARY and you must not set
  it for any other Pattern setting.
- `"ResourceType"`: The resource type to include in the protection group. All protected
  resources of this type are included in the protection group. Newly protected resources of
  this type are automatically added to the group. You must set this when you set Pattern to
  BY_RESOURCE_TYPE and you must not set it for any other Pattern setting.
"""
create_protection_group(Aggregation, Pattern, ProtectionGroupId; aws_config::AbstractAWSConfig=global_aws_config()) = shield("CreateProtectionGroup", Dict{String, Any}("Aggregation"=>Aggregation, "Pattern"=>Pattern, "ProtectionGroupId"=>ProtectionGroupId); aws_config=aws_config)
create_protection_group(Aggregation, Pattern, ProtectionGroupId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("CreateProtectionGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Aggregation"=>Aggregation, "Pattern"=>Pattern, "ProtectionGroupId"=>ProtectionGroupId), params)); aws_config=aws_config)

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

Activates AWS Shield Advanced for an account. When you initally create a subscription, your
subscription is set to be automatically renewed at the end of the existing subscription
period. You can change this by submitting an UpdateSubscription request.

"""
create_subscription(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("CreateSubscription"; aws_config=aws_config)
create_subscription(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("CreateSubscription", params; aws_config=aws_config)

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

Deletes an AWS Shield Advanced Protection.

# Arguments
- `protection_id`: The unique identifier (ID) for the Protection object to be deleted.

"""
delete_protection(ProtectionId; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DeleteProtection", Dict{String, Any}("ProtectionId"=>ProtectionId); aws_config=aws_config)
delete_protection(ProtectionId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DeleteProtection", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ProtectionId"=>ProtectionId), params)); aws_config=aws_config)

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

Removes the specified protection group.

# Arguments
- `protection_group_id`: The name of the protection group. You use this to identify the
  protection group in lists and to manage the protection group, for example to update,
  delete, or describe it.

"""
delete_protection_group(ProtectionGroupId; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DeleteProtectionGroup", Dict{String, Any}("ProtectionGroupId"=>ProtectionGroupId); aws_config=aws_config)
delete_protection_group(ProtectionGroupId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DeleteProtectionGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ProtectionGroupId"=>ProtectionGroupId), params)); aws_config=aws_config)

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

Removes AWS Shield Advanced from an account. AWS Shield Advanced requires a 1-year
subscription commitment. You cannot delete a subscription prior to the completion of that
commitment.

"""
delete_subscription(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DeleteSubscription"; aws_config=aws_config)
delete_subscription(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DeleteSubscription", params; aws_config=aws_config)

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

Describes the details of a DDoS attack.

# Arguments
- `attack_id`: The unique identifier (ID) for the attack that to be described.

"""
describe_attack(AttackId; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeAttack", Dict{String, Any}("AttackId"=>AttackId); aws_config=aws_config)
describe_attack(AttackId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeAttack", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AttackId"=>AttackId), params)); aws_config=aws_config)

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

Provides information about the number and type of attacks AWS Shield has detected in the
last year for all resources that belong to your account, regardless of whether you've
defined Shield protections for them. This operation is available to Shield customers as
well as to Shield Advanced customers. The operation returns data for the time range of
midnight UTC, one year ago, to midnight UTC, today. For example, if the current time is
2020-10-26 15:39:32 PDT, equal to 2020-10-26 22:39:32 UTC, then the time range for the
attack data returned is from 2019-10-26 00:00:00 UTC to 2020-10-26 00:00:00 UTC.  The time
range indicates the period covered by the attack statistics data items.

"""
describe_attack_statistics(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeAttackStatistics"; aws_config=aws_config)
describe_attack_statistics(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeAttackStatistics", params; aws_config=aws_config)

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

Returns the current role and list of Amazon S3 log buckets used by the DDoS Response Team
(DRT) to access your AWS account while assisting with attack mitigation.

"""
describe_drtaccess(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeDRTAccess"; aws_config=aws_config)
describe_drtaccess(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeDRTAccess", params; aws_config=aws_config)

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

A list of email addresses and phone numbers that the DDoS Response Team (DRT) can use to
contact you if you have proactive engagement enabled, for escalations to the DRT and to
initiate proactive customer support.

"""
describe_emergency_contact_settings(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeEmergencyContactSettings"; aws_config=aws_config)
describe_emergency_contact_settings(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeEmergencyContactSettings", params; aws_config=aws_config)

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

Lists the details of a Protection object.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ProtectionId"`: The unique identifier (ID) for the Protection object that is described.
  When submitting the DescribeProtection request you must provide either the ResourceArn or
  the ProtectionID, but not both.
- `"ResourceArn"`: The ARN (Amazon Resource Name) of the AWS resource for the Protection
  object that is described. When submitting the DescribeProtection request you must provide
  either the ResourceArn or the ProtectionID, but not both.
"""
describe_protection(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeProtection"; aws_config=aws_config)
describe_protection(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeProtection", params; aws_config=aws_config)

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

Returns the specification for the specified protection group.

# Arguments
- `protection_group_id`: The name of the protection group. You use this to identify the
  protection group in lists and to manage the protection group, for example to update,
  delete, or describe it.

"""
describe_protection_group(ProtectionGroupId; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeProtectionGroup", Dict{String, Any}("ProtectionGroupId"=>ProtectionGroupId); aws_config=aws_config)
describe_protection_group(ProtectionGroupId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeProtectionGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ProtectionGroupId"=>ProtectionGroupId), params)); aws_config=aws_config)

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

Provides details about the AWS Shield Advanced subscription for an account.

"""
describe_subscription(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeSubscription"; aws_config=aws_config)
describe_subscription(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DescribeSubscription", params; aws_config=aws_config)

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

Removes authorization from the DDoS Response Team (DRT) to notify contacts about
escalations to the DRT and to initiate proactive customer support.

"""
disable_proactive_engagement(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DisableProactiveEngagement"; aws_config=aws_config)
disable_proactive_engagement(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DisableProactiveEngagement", params; aws_config=aws_config)

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

Removes the DDoS Response Team's (DRT) access to the specified Amazon S3 bucket containing
your AWS WAF logs. To make a DisassociateDRTLogBucket request, you must be subscribed to
the Business Support plan or the Enterprise Support plan. However, if you are not
subscribed to one of these support plans, but had been previously and had granted the DRT
access to your account, you can submit a DisassociateDRTLogBucket request to remove this
access.

# Arguments
- `log_bucket`: The Amazon S3 bucket that contains your AWS WAF logs.

"""
disassociate_drtlog_bucket(LogBucket; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DisassociateDRTLogBucket", Dict{String, Any}("LogBucket"=>LogBucket); aws_config=aws_config)
disassociate_drtlog_bucket(LogBucket, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DisassociateDRTLogBucket", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LogBucket"=>LogBucket), params)); aws_config=aws_config)

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

Removes the DDoS Response Team's (DRT) access to your AWS account. To make a
DisassociateDRTRole request, you must be subscribed to the Business Support plan or the
Enterprise Support plan. However, if you are not subscribed to one of these support plans,
but had been previously and had granted the DRT access to your account, you can submit a
DisassociateDRTRole request to remove this access.

"""
disassociate_drtrole(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DisassociateDRTRole"; aws_config=aws_config)
disassociate_drtrole(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DisassociateDRTRole", params; aws_config=aws_config)

"""
    disassociate_health_check(health_check_arn, protection_id)
    disassociate_health_check(health_check_arn, protection_id, params::Dict{String,<:Any})

Removes health-based detection from the Shield Advanced protection for a resource. Shield
Advanced health-based detection uses the health of your AWS resource to improve
responsiveness and accuracy in attack detection and mitigation.  You define the health
check in Route 53 and then associate or disassociate it with your Shield Advanced
protection. For more information, see Shield Advanced Health-Based Detection in the AWS WAF
and AWS Shield Developer Guide.

# Arguments
- `health_check_arn`: The Amazon Resource Name (ARN) of the health check that is associated
  with the protection.
- `protection_id`: The unique identifier (ID) for the Protection object to remove the
  health check association from.

"""
disassociate_health_check(HealthCheckArn, ProtectionId; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DisassociateHealthCheck", Dict{String, Any}("HealthCheckArn"=>HealthCheckArn, "ProtectionId"=>ProtectionId); aws_config=aws_config)
disassociate_health_check(HealthCheckArn, ProtectionId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("DisassociateHealthCheck", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("HealthCheckArn"=>HealthCheckArn, "ProtectionId"=>ProtectionId), params)); aws_config=aws_config)

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

Authorizes the DDoS Response Team (DRT) to use email and phone to notify contacts about
escalations to the DRT and to initiate proactive customer support.

"""
enable_proactive_engagement(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("EnableProactiveEngagement"; aws_config=aws_config)
enable_proactive_engagement(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("EnableProactiveEngagement", params; aws_config=aws_config)

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

Returns the SubscriptionState, either Active or Inactive.

"""
get_subscription_state(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("GetSubscriptionState"; aws_config=aws_config)
get_subscription_state(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("GetSubscriptionState", params; aws_config=aws_config)

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

Returns all ongoing DDoS attacks or all DDoS attacks during a specified time period.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"EndTime"`: The end of the time period for the attacks. This is a timestamp type. The
  sample request above indicates a number type because the default used by WAF is Unix time
  in seconds. However any valid timestamp format is allowed.
- `"MaxResults"`: The maximum number of AttackSummary objects to return. If you leave this
  blank, Shield Advanced returns the first 20 results. This is a maximum value. Shield
  Advanced might return the results in smaller batches. That is, the number of objects
  returned could be less than MaxResults, even if there are still more objects yet to return.
  If there are more objects to return, Shield Advanced returns a value in NextToken that you
  can use in your next request, to get the next batch of objects.
- `"NextToken"`: The ListAttacksRequest.NextMarker value from a previous call to
  ListAttacksRequest. Pass null if this is the first call.
- `"ResourceArns"`: The ARN (Amazon Resource Name) of the resource that was attacked. If
  this is left blank, all applicable resources for this account will be included.
- `"StartTime"`: The start of the time period for the attacks. This is a timestamp type.
  The sample request above indicates a number type because the default used by WAF is Unix
  time in seconds. However any valid timestamp format is allowed.
"""
list_attacks(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("ListAttacks"; aws_config=aws_config)
list_attacks(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("ListAttacks", params; aws_config=aws_config)

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

Retrieves the ProtectionGroup objects for the account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of ProtectionGroup objects to return. If you leave
  this blank, Shield Advanced returns the first 20 results. This is a maximum value. Shield
  Advanced might return the results in smaller batches. That is, the number of objects
  returned could be less than MaxResults, even if there are still more objects yet to return.
  If there are more objects to return, Shield Advanced returns a value in NextToken that you
  can use in your next request, to get the next batch of objects.
- `"NextToken"`: The next token value from a previous call to ListProtectionGroups. Pass
  null if this is the first call.
"""
list_protection_groups(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("ListProtectionGroups"; aws_config=aws_config)
list_protection_groups(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("ListProtectionGroups", params; aws_config=aws_config)

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

Lists all Protection objects for the account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of Protection objects to return. If you leave this
  blank, Shield Advanced returns the first 20 results. This is a maximum value. Shield
  Advanced might return the results in smaller batches. That is, the number of objects
  returned could be less than MaxResults, even if there are still more objects yet to return.
  If there are more objects to return, Shield Advanced returns a value in NextToken that you
  can use in your next request, to get the next batch of objects.
- `"NextToken"`: The ListProtectionsRequest.NextToken value from a previous call to
  ListProtections. Pass null if this is the first call.
"""
list_protections(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("ListProtections"; aws_config=aws_config)
list_protections(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("ListProtections", params; aws_config=aws_config)

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

Retrieves the resources that are included in the protection group.

# Arguments
- `protection_group_id`: The name of the protection group. You use this to identify the
  protection group in lists and to manage the protection group, for example to update,
  delete, or describe it.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of resource ARN objects to return. If you leave this
  blank, Shield Advanced returns the first 20 results. This is a maximum value. Shield
  Advanced might return the results in smaller batches. That is, the number of objects
  returned could be less than MaxResults, even if there are still more objects yet to return.
  If there are more objects to return, Shield Advanced returns a value in NextToken that you
  can use in your next request, to get the next batch of objects.
- `"NextToken"`: The next token value from a previous call to
  ListResourcesInProtectionGroup. Pass null if this is the first call.
"""
list_resources_in_protection_group(ProtectionGroupId; aws_config::AbstractAWSConfig=global_aws_config()) = shield("ListResourcesInProtectionGroup", Dict{String, Any}("ProtectionGroupId"=>ProtectionGroupId); aws_config=aws_config)
list_resources_in_protection_group(ProtectionGroupId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("ListResourcesInProtectionGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ProtectionGroupId"=>ProtectionGroupId), params)); aws_config=aws_config)

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

Updates the details of the list of email addresses and phone numbers that the DDoS Response
Team (DRT) can use to contact you if you have proactive engagement enabled, for escalations
to the DRT and to initiate proactive customer support.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"EmergencyContactList"`: A list of email addresses and phone numbers that the DDoS
  Response Team (DRT) can use to contact you if you have proactive engagement enabled, for
  escalations to the DRT and to initiate proactive customer support. If you have proactive
  engagement enabled, the contact list must include at least one phone number.
"""
update_emergency_contact_settings(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("UpdateEmergencyContactSettings"; aws_config=aws_config)
update_emergency_contact_settings(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("UpdateEmergencyContactSettings", params; aws_config=aws_config)

"""
    update_protection_group(aggregation, pattern, protection_group_id)
    update_protection_group(aggregation, pattern, protection_group_id, params::Dict{String,<:Any})

Updates an existing protection group. A protection group is a grouping of protected
resources so they can be handled as a collective. This resource grouping improves the
accuracy of detection and reduces false positives.

# Arguments
- `aggregation`: Defines how AWS Shield combines resource data for the group in order to
  detect, mitigate, and report events.   Sum - Use the total traffic across the group. This
  is a good choice for most cases. Examples include Elastic IP addresses for EC2 instances
  that scale manually or automatically.   Mean - Use the average of the traffic across the
  group. This is a good choice for resources that share traffic uniformly. Examples include
  accelerators and load balancers.   Max - Use the highest traffic from each resource. This
  is useful for resources that don't share traffic and for resources that share that traffic
  in a non-uniform way. Examples include CloudFront distributions and origin resources for
  CloudFront distributions.
- `pattern`: The criteria to use to choose the protected resources for inclusion in the
  group. You can include all resources that have protections, provide a list of resource
  Amazon Resource Names (ARNs), or include all resources of a specified resource type.
- `protection_group_id`: The name of the protection group. You use this to identify the
  protection group in lists and to manage the protection group, for example to update,
  delete, or describe it.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Members"`: The Amazon Resource Names (ARNs) of the resources to include in the
  protection group. You must set this when you set Pattern to ARBITRARY and you must not set
  it for any other Pattern setting.
- `"ResourceType"`: The resource type to include in the protection group. All protected
  resources of this type are included in the protection group. You must set this when you set
  Pattern to BY_RESOURCE_TYPE and you must not set it for any other Pattern setting.
"""
update_protection_group(Aggregation, Pattern, ProtectionGroupId; aws_config::AbstractAWSConfig=global_aws_config()) = shield("UpdateProtectionGroup", Dict{String, Any}("Aggregation"=>Aggregation, "Pattern"=>Pattern, "ProtectionGroupId"=>ProtectionGroupId); aws_config=aws_config)
update_protection_group(Aggregation, Pattern, ProtectionGroupId, params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("UpdateProtectionGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Aggregation"=>Aggregation, "Pattern"=>Pattern, "ProtectionGroupId"=>ProtectionGroupId), params)); aws_config=aws_config)

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

Updates the details of an existing subscription. Only enter values for parameters you want
to change. Empty parameters are not updated.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AutoRenew"`: When you initally create a subscription, AutoRenew is set to ENABLED. If
  ENABLED, the subscription will be automatically renewed at the end of the existing
  subscription period. You can change this by submitting an UpdateSubscription request. If
  the UpdateSubscription request does not included a value for AutoRenew, the existing value
  for AutoRenew remains unchanged.
"""
update_subscription(; aws_config::AbstractAWSConfig=global_aws_config()) = shield("UpdateSubscription"; aws_config=aws_config)
update_subscription(params::AbstractDict{String, <:Any}; aws_config::AbstractAWSConfig=global_aws_config()) = shield("UpdateSubscription", params; aws_config=aws_config)


text:
# Author: Youngjun Kim, youngjun@stanford.edu
# Date: 06/09/2014

module AbstractWorldModelImpl

export AbstractWorldModel

abstract AbstractWorldModel

end

module AbstractWorldModelInterfaces

export updateObjectState,
       getAllObjectStates,
       getAll,
       updateAll

function updateObjectState()
end

function getAllObjectStates()
end

function getAll()
end

function updateAll()
end

end

ext: jl

max_stars_repo_name: sisl/RLES-SISLES

max_issues_repo_name: sisl/RLES-SISLES

max_forks_repo_name: sisl/RLES-SISLES


text:
export
    PositivePreservingIterator,
    next!,
    run!

mutable struct PositivePreservingIterator{S, T}
    dim::S
    π̂s::Vector{Matrix{Complex{T}}}
    ρ::Matrix{Complex{T}}
    steps::S
end

"""
    gen_π̂s(θs::AbstractVector, xs::AbstractVector, dim::Integer)

Calculate ``\\hat{\\Pi}`` for all given ``(\\theta, x)`` pairs.
"""
function gen_π̂s(θs::AbstractVector{T}, xs::AbstractVector{T}, dim) where {T<:Real}
    n = length(θs)
    π̂s = [Matrix{Complex{T}}(undef, dim, dim) for _ in 1:n]

    return gen_π̂s!(π̂s, θs, xs, dim)
end

function gen_π̂s!(π̂s, θs::AbstractVector, xs::AbstractVector, dim)
    n = length(θs)

    @info "preprocessing..."
    p = Progress(n)
    Threads.@threads for i in 1:n
        𝛑̂!(π̂s[i], θs[i], xs[i], dim=dim)
        ProgressMeter.next!(p)
    end

    return π̂s
end

"""
    PositivePreservingIterator(data::Matrix, steps::Integer; dim::Integer)

The maximum likelihood estimator with the magical positive preserving iterator
derived by variational calculus.

## Example

```julia-repl
julia> using QuantumStateBase

julia> ρ = SqueezedState(0.8, π/4, Matrix, dim=100);

julia> data = rand(GaussianStateBHD(ρ), 8192);

julia> ρ_mle = run!(PositivePreservingIterator(data, 50, dim=35));
```
"""
function PositivePreservingIterator(data::Matrix{T}, steps::S; dim::S) where {T<:Real, S<:Integer}
    π̂s = gen_π̂s(data[1, :], data[2, :], dim)
    ρ = glorot_uniform(Complex{T}, dim)
    ρ ./= tr(ρ)

    return PositivePreservingIterator{S, T}(dim, π̂s, ρ, steps)
end

"""
    frac_π_p(ppit::PositivePreservingIterator)

A positive preserving iterator.

``\\mathcal{R} = \\sum_i \\frac{\\hat{\\pi_i}}{p_i}``
"""
function frac_π_p(ppit::PositivePreservingIterator{S, T}) where {S, T}
    sum_frac_πᵢ_pᵢ = zeros(Complex{T}, ppit.dim, ppit.dim)

    for π̂ in ppit.π̂s
        sum_frac_πᵢ_pᵢ .+= π̂ ./ tr_mul(π̂, ppit.ρ)
    end

    return sum_frac_πᵢ_pᵢ
end

"""
    next!(ppit::PositivePreservingIterator)

Iterate one step with the magic positive preserving iterator.

``\\rho^{t+1} = \\mathcal{R} \\rho^t \\mathcal{R}``
"""
function next!(ppit::PositivePreservingIterator)
    𝐫 = frac_π_p(ppit)

    ppit.ρ .= 𝐫 * ppit.ρ * 𝐫
    ppit.ρ ./= tr(ppit.ρ)

    return ppit
end

"""
    run!(ppit::PositivePreservingIterator)

Iterate `n` step with the magic positive preserving iterator.
"""
function run!(ppit::PositivePreservingIterator)
    @info "estimating..."
    p = Progress(ppit.steps)
    for _ in 1:ppit.steps
        next!(ppit)
        ProgressMeter.next!(p)
    end

    return ppit
end

# #########
# # utils #
# #########

glorot_uniform(T::Type{<:Real}, rng::AbstractRNG, dim) = (rand(rng, T, dim, dim) .- 0.5) .* sqrt(24 / 2dim)

glorot_uniform(::Type{Complex{U}}, rng, dim) where {U} = glorot_uniform(U, rng, dim) + im * glorot_uniform(U, rng, dim)

glorot_uniform(T, dim) = glorot_uniform(T, Random.GLOBAL_RNG, dim)

tr_mul(𝐚, 𝐛) = sum(𝐚[i, :]' * 𝐛[:, i] for i in 1:size(𝐚, 1))


text:
abstract type Simulation end

function iterate!( sim::Simulation )
    move_dogs!( sim.world, sim.dt )
    move_sheep!( sim )
    work!( sim.world, sim.dt )
    sim.time[] += sim.dt
end # function

function move_sheep!( sim::Simulation )
    if sim.time[] >= sim.t_sheep_boredom[]
        i,j = Tuple(getRandomSheep( sim.world.sheeps ))
        diffuseSheep!( sim.world.sheeps, i, j )

        sim.t_sheep_boredom[] = sim.time[] +
            rand(
                Exponential(
                    sim.world.meanSheepDiffusionTime / sim.world.sheeps.current_sheep[]
                    )
                )

        kickSheep!( sim.world.sheeps )
        return true
    end # if
    return false
end # function


text:
using Documenter
using InformationGeometry

makedocs(
    sitename = "InformationGeometry",
    authors = "Rafael Arutjunjan",
    format = Documenter.HTML(),
    modules = [InformationGeometry],
    pages = Any["Getting Started" => "index.md",
                "Basics of Information Geometry" => "basics.md",
                "Tutorial" => Any[  "Providing Data and Models" => "datamodels.md",
                                    "Confidence Regions" => "confidence-regions.md",
                                    "Model Transformations" => "transformations.md",
                                    "Parallelization" => "parallelization.md",
                                    "Exporting" => "exporting.md",
                                    "Kullback-Leibler Divergences" => "kullback-leibler.md"],
                # Advanced Tutorial: Confidence Bands, Geodesics, Profile Likelihood, DataSetExact, Plotting, PDE / Stochastic Examples, Exporting
                "Advanced Examples" => Any["ODE-based models" => "ODEmodels.md", "Advanced Datasets" => "AdvancedData.md"],
                "List of useful methods" => "methodlist.md",
                "Contributing" => "todo.md",
            ],
)

# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
deploydocs(
    repo = "github.com/RafaelArutjunjan/InformationGeometry.jl.git",
    # julia = "1.5",
    # osname = "linux",
    # target = "build",
)


text:
using LazySets.Approximations: overapproximate

for N in [Float64, Float32, Rational{Int}]
    # Cartesian Product of a centered 1D BallInf and a centered 2D BallInf
    # Here a 3D BallInf
    b1 = BallInf(N[0], N(1))
    b2 = BallInf(N[0, 0], N(1))
    # Test Construction
    cp = CartesianProduct(b1, b2)
    @test cp.X == b1
    @test cp.Y == b2

    # swap
    cp2 = swap(cp)
    @test cp.X == cp2.Y && cp.Y == cp2.X

    # Test Dimension
    @test dim(cp) == 3
    # Test Support Vector
    d = N[1, 1, 1]
    @test σ(d, cp) == N[1, 1, 1]
    d = N[1, 1, -1]
    @test σ(d, cp) == N[1, 1, -1]
    d = N[1, -1, 1]
    @test σ(d, cp) == N[1, -1, 1]
    d = N[1, -1, -1]
    @test σ(d, cp) == N[1, -1, -1]
    d = N[-1, 1, 1]
    @test σ(d, cp) == N[-1, 1, 1]
    d = N[-1, 1, -1]
    @test σ(d, cp) == N[-1, 1, -1]
    d = N[-1, -1, 1]
    @test σ(d, cp) == N[-1, -1, 1]
    d = N[-1, -1, -1]
    @test σ(d, cp) == N[-1, -1, -1]

    # boundedness
    @test isbounded(cp) && isboundedtype(typeof(cp))
    cp2 = Singleton(N[1]) * HalfSpace(N[1], N(1))
    @test !isbounded(cp2) && !isboundedtype(typeof(cp2))

    # is_polyhedral
    @test is_polyhedral(cp)
    if N isa AbstractFloat
        cp2 = CartesianProduct(b1, Ball2(N[0, 0], N(1)))
        @test !is_polyhedral(cp2)
    end

    # isempty
    @test !isempty(cp)

    # Cartesian Product of a not-centered 1D BallInf and a not-centered 2D BallInf
    # Here a Hyperrectangle where c = [1, -3, 4] and r = [3, 2, 2]
    b1 = BallInf(N[1], N(3))
    b2 = BallInf(N[-3, 4], N(2))
    # Test Construction
    c = CartesianProduct(b1, b2)
    # Test Dimension
    @test dim(c) == 3
    # Test Support Vector
    d = N[1, 1, 1]
    @test σ(d, c) == N[4, -1, 6]
    d = N[1, 1, -1]
    @test σ(d, c) == N[4, -1, 2]
    d = N[1, -1, 1]
    @test σ(d, c) == N[4, -5, 6]
    d = N[1, -1, -1]
    @test σ(d, c) == N[4, -5, 2]
    d = N[-1, 1, 1]
    @test σ(d, c) == N[-2, -1, 6]
    d = N[-1, 1, -1]
    @test σ(d, c) == N[-2, -1, 2]
    d = N[-1, -1, 1]
    @test σ(d, c) == N[-2, -5, 6]
    d = N[-1, -1, -1]
    @test σ(d, c) == N[-2, -5, 2]

    # Test Cartesian Product with EmptySet
    s = Singleton(N[1])
    E = EmptySet{N}(1)
    cs1 = E * s
    cs2 = s * E
    @test cs1 isa EmptySet
    @test cs2 isa EmptySet

    # Test containment with respect to CartesianProduct
    p1 = HPolygon{N}()
    addconstraint!(p1, LinearConstraint(N[2, 2], N(12)))
    addconstraint!(p1, LinearConstraint(N[-3, 3], N(6)))
    addconstraint!(p1, LinearConstraint(N[-1, -1], N(0)))
    addconstraint!(p1, LinearConstraint(N[2, -4], N(0)))
    p2 = HPolygon{N}()
    addconstraint!(p2, LinearConstraint(N[1, 0], N(1)))
    addconstraint!(p2, LinearConstraint(N[-1, 0], N(1)))
    addconstraint!(p2, LinearConstraint(N[0, 1], N(1)))
    addconstraint!(p2, LinearConstraint(N[0, -1], N(1)))
    cp = CartesianProduct(p1, p2)

    @test N[0, 0, 0, 0] ∈ cp
    @test N[4, 2, 1, 0] ∈ cp
    @test N[2, 4, -1, 0] ∈ cp
    @test N[-1, 1, 0.5, 0.7] ∈ cp
    @test N[2, 3, -0.8, 0.9] ∈ cp
    @test N[1, 1, -1, 0] ∈ cp
    @test N[3, 2, 0, 1] ∈ cp
    @test N[5 / 4, 7 / 4, 1, 1] ∈ cp
    @test N[4, 1, 0, 0] ∉ cp
    @test N[5, 2, 0, 0] ∉ cp
    @test N[3, 4, 0, 0] ∉ cp
    @test N[-1, 5, 0, 0] ∉ cp
    @test N[4, 2, 3, 1] ∉ cp
    @test N[2, 3, 3, 1] ∉ cp
    @test N[0, 0, 3, 1] ∉ cp
    @test N[1, 1, 3, 1] ∉ cp

    # vertices_list
    i1 = Interval(N[0, 1])
    i2 = Interval(N[2, 3])
    vlist = vertices_list(CartesianProduct(i1, i2))
    @test ispermutation(vlist, [N[0, 2], N[0, 3], N[1, 2], N[1, 3]])

    # constraints_list
    hlist = constraints_list(CartesianProduct(i1, i2))
    @test ispermutation(hlist,
        [LinearConstraint(sparsevec(N[1], N[1], 2), N(1)),
        LinearConstraint(sparsevec(N[1], N[-1], 2), N(0)),
        LinearConstraint(sparsevec(N[2], N[1], 2),  N(3)),
        LinearConstraint(sparsevec(N[2], N[-1], 2), N(-2))])
    @test all(H -> dim(H) == 2, hlist)

    # linear_map
    cp = CartesianProduct(Interval(N(0), N(1)), Interval(N(2), N(3)))
    M = N[2 1; 0 2]  # invertible matrix
    lm = linear_map(M, cp)
    @test lm isa HPolytope{N} && length(constraints_list(lm)) ==
        length(constraints_list(cp)) == 4
    M = N[2 1; 0 0]  # singular matrix
    lm = linear_map(M, cp)
    @test lm isa (N == Float64 ? HPolytope{N} : HPolytope)
    @test box_approximation(lm) == Hyperrectangle(N[7//2, 0], N[3//2, 0])

    cp = CartesianProduct(VPolytope([N[1]]), VPolytope([N[2]]))
    if test_suite_polyhedra
        # concretize
        @test concretize(cp) == VPolytope([N[1, 2]])
    else
        @test concretize(cp) === cp
    end

    # inclusion
    # same block structure
    cp1 = CartesianProduct(Ball1(N[2], N(1)), Ball1(N[0, 0], N(2)))
    cp2 = CartesianProduct(Interval(N(1), N(3)), BallInf(N[0, 0], N(3)))
    res, w = ⊆(cp1, cp2, true)
    @test cp1 ⊆ cp2 && res && w == N[]
    res, w = ⊆(cp2, cp1, true)
    @test cp2 ⊈ cp1 && !res && w ∈ cp2 && w ∉ cp1
    # different block structure
    cp1 = CartesianProduct(Interval(N(1), N(2)), BallInf(N[1, 1], N(1)))
    cp2 = CartesianProduct(BallInf(N[1, 1], N(2)), Interval(N(0), N(2)))
    res, w = ⊆(cp1, cp2, true)
    @test cp1 ⊆ cp2 && res && w == N[]
    res, w = ⊆(cp2, cp1, true)
    @test cp2 ⊈ cp1 && !res && w ∈ cp2 && w ∉ cp1

    # projection
    P = Singleton(N[11, 12])
    Q = Singleton(N[13, 14, 15])
    cp = P × Q
    @test project(cp, [2]) == Singleton(N[12])
    @test project(cp, [3, 5]) == Singleton(N[13, 15])
    @test project(cp, [1, 4, 5]) == Singleton(N[11]) × Singleton(N[14, 15])

    # ==================================
    # Conversions of Cartesian Products
    # ==================================

    # convert the cartesian product of two hyperrectangles to one hyperrectangle
    h1 = Hyperrectangle(N[1/2],  N[1/2])
    h2 = Hyperrectangle(N[2.5, 4.5],  N[1/2, 1/2])
    H = convert(Hyperrectangle, h1 × h2)
    @test low(H) == N[0, 2, 4] && high(H) == N[1, 3, 5]

    # make one of the sets a BallInf, to test that the conversion does
    # not depend on the Hyperrectangle type
    b1 = BallInf(N[1/2],  N(1/2))
    H = convert(Hyperrectangle, b1 × h2)
    @test low(H) == N[0, 2, 4] && high(H) == N[1, 3, 5]

    # convert a hyperrectangle to a cartesian product of intervals
    H = Hyperrectangle(N[0, 0], N[1, 1])
    Hcp = convert(CartesianProduct{N, Interval{N}, Interval{N}}, H)
    @test Hcp isa CartesianProduct &&
          Hcp.X == Interval(N(-1), N(1)) &&
          Hcp.Y == Interval(N(-1), N(1))

    # checking that the order is correct
    H = Hyperrectangle(N[0, 1], N[1, 3])
    Hcp = convert(CartesianProduct{N, Interval{N}, Interval{N}}, H)
    @test Hcp isa CartesianProduct &&
          Hcp.X == Interval(N(-1), N(1)) &&
          Hcp.Y == Interval(N(-2), N(4))

    cp = Zonotope(N[0, 0], N[1 0; 0 1]) × Zonotope(N[1, 1], N[0 1; 1 0])
    @test convert(Zonotope, cp) == Zonotope(N[0, 0, 1, 1], N[1 0 0 0; 0 1 0 0;
                                                             0 0 0 1; 0 0 1 0])

    # cartesian product of singletons
    S1 = Singleton(N[1, 2, 3])
    S2 = Singleton(N[4, 5, 6])
    @test convert(Singleton, S1 × S2) == Singleton(N[1, 2, 3, 4, 5, 6])

    # =====================
    # CartesianProductArray
    # =====================

    # relation to base type (internal helper functions)
    @test LazySets.array_constructor(CartesianProduct) == CartesianProductArray
    @test LazySets.is_array_constructor(CartesianProductArray)

    # standard constructor
    v = Vector{Singleton{N}}()
    S1 = Singleton(N[1, 2])
    S2 = Singleton(N[3, 4])
    push!(v, S1)
    push!(v, S2)
    cpa = CartesianProductArray(v)

    # constructor with size hint and type
    CartesianProductArray(10, N)

    # array getter
    @test array(cpa) ≡ v

    # getindex & length
    @test cpa[1] == S1 && cpa[2] == S2
    @test length(cpa) == 2

    # support function & support vector
    svec = N[1, 2, 3, 4]
    for dd in [N[1, 1, 0, 0], N[0, 0, 1, 1], N[0, 1, 0, 1], N[0, 0, 1, 0], N[0, 0, 0, 0]]
        ds = sparse(dd)
        @test σ(dd, cpa) == σ(ds, cpa) == svec
        @test ρ(dd, cpa) == ρ(ds, cpa) == dot(svec, dd)
    end

    # boundedness
    @test isbounded(cpa) && isboundedtype(typeof(cpa))
    cpa2 = CartesianProductArray([Singleton(N[1]), HalfSpace(N[1], N(1))])
    @test !isbounded(cpa2) && !isboundedtype(typeof(cpa2))

    # membership
    @test N[1, 2, 3, 4] ∈ cpa
    @test N[3, 4, 1, 2] ∉ cpa

    # in-place modification
    b = BallInf(N[0, 0], N(2))
    cpa = CartesianProductArray(LazySet{N}[])
    @test CartesianProduct!(b, b) isa CartesianProduct &&
          length(array(cpa)) == 0
    res = CartesianProduct!(b, cpa)
    @test res isa CartesianProductArray && length(array(cpa)) == 1
    res = CartesianProduct!(cpa, b)
    @test res isa CartesianProductArray && length(array(cpa)) == 2
    res = CartesianProduct!(cpa, cpa)
    @test res isa CartesianProductArray && length(array(cpa)) == 4

    # vertices_list
    i1 = Interval(N[0, 1])
    i2 = Interval(N[2, 3])
    i3 = Interval(N[4, 5])
    vlist = vertices_list(CartesianProductArray([i1, i2, i3]))
    @test ispermutation(vlist, [N[0, 2, 4], N[0, 3, 4], N[1, 2, 4],
        N[1, 3, 4], N[0, 2, 5], N[0, 3, 5], N[1, 2, 5], N[1, 3, 5]])

    # constraints_list
    hlist = constraints_list(CartesianProductArray([i1, i2, i3]))
    @test ispermutation(hlist,
        [LinearConstraint(sparsevec(N[1], N[1], 3), N(1)),
        LinearConstraint(sparsevec(N[1], N[-1], 3), N(0)),
        LinearConstraint(sparsevec(N[2], N[1], 3), N(3)),
        LinearConstraint(sparsevec(N[2], N[-1], 3), N(-2)),
        LinearConstraint(sparsevec(N[3], N[1], 3), N(5)),
        LinearConstraint(sparsevec(N[3], N[-1], 3), N(-4)),
        ])
    @test all(H -> dim(H) == 3, hlist)
    # is_intersection_empty
    cpa = CartesianProductArray([BallInf(ones(N, 5), N(1)),
                                 BallInf(2 * ones(N, 5), N(0.5))])
    b = BallInf(zeros(N, 10), N(1))
    for (x, y) in [(cpa, b), (b, cpa)]
        res, w = isdisjoint(x, y, true)
        @test isdisjoint(x, y) && res && w == N[]
    end
    b = BallInf(ones(N, 10), N(1))
    for (x, y) in [(cpa, b), (b, cpa)]
        res, w = isdisjoint(x, y, true)
        @test !isdisjoint(x, y) && !res && w ∈ x && w ∈ y
    end

    # concrete intersection where all dimensions are unconstrained
    @test intersection(cpa, HPolyhedron{N}()) == cpa

    # linear_map
    cpa = CartesianProductArray([Interval(N(0), N(1)), Interval(N(2), N(3))])
    M = N[2 1; 0 2]  # invertible matrix
    lm = linear_map(M, cpa)
    @test lm isa HPolytope{N} && length(constraints_list(lm)) ==
        length(constraints_list(cpa)) == 4
    M = N[2 1; 0 0]  # singular matrix
    lm = linear_map(M, cpa)
    @test lm isa (N == Float64 ? HPolytope{N} : HPolytope)
    @test box_approximation(lm) == Hyperrectangle(N[7//2, 0], N[3//2, 0])

    cpa = CartesianProductArray([VPolytope([N[1]]), VPolytope([N[2]])])
    if test_suite_polyhedra
        # concretize
        @test concretize(cpa) == VPolytope([N[1, 2]])
    else
        @test concretize(cpa) === cpa
    end

    # projection
    P = Singleton(N[11, 12])
    Q = Singleton(N[13, 14, 15])
    R = Singleton(N[16, 17])
    cpa = CartesianProductArray([P, Q, R])
    @test project(cpa, [2]) == Singleton(N[12])
    @test project(cpa, [4]) == Singleton(N[14])
    @test project(cpa, [6]) == Singleton(N[16])
    @test project(cpa, [3, 5]) == Singleton(N[13, 15])
    @test project(cpa, [2, 7]) == Singleton(N[12]) × Singleton(N[17])
    @test project(cpa, [1, 4, 5]) == Singleton(N[11]) × Singleton(N[14, 15])
    @test project(cpa, [1, 4, 7]) == CartesianProductArray(
        [Singleton(N[11]), Singleton(N[14]), Singleton(N[17])])

    # ========================================
    # Conversions of Cartesian Product Arrays
    # ========================================

    # conversion of the cartesian product array of intervals to a hyperrectangle
    i1 = Interval(N[0, 1])
    i2 = Interval(N[2, 3])
    i3 = Interval(N[4, 5])
    H = convert(Hyperrectangle, CartesianProductArray([i1, i2, i3]))
    @test low(H) == N[0, 2, 4] && high(H) == N[1, 3, 5]

    M = hcat(N(1))
    h1 = Hyperrectangle(N[1/2],  N[1/2])
    h2 = Hyperrectangle(N[2.5, 4.5],  N[1/2, 1/2])
    H = convert(Hyperrectangle, CartesianProductArray([h1, h2]))
    @test low(H) == N[0, 2, 4] && high(H) == N[1, 3, 5]

    # same block structure
    aX = [Ball1(N[2], N(1)), Ball1(N[0, 0], N(2))]
    aY = [Interval(N(1), N(3)), BallInf(N[0, 0], N(3))]
    @test LazySets.same_block_structure(aX, aY)

    # inclusion
    cpa1 = CartesianProductArray(aX)
    cpa2 = CartesianProductArray(aY)
    res, w = ⊆(cpa1, cpa2, true)
    @test cpa1 ⊆ cpa2 && res && w == N[]
    res, w = ⊆(cpa2, cpa1, true)
    @test cpa2 ⊈ cpa1 && !res && w ∈ cpa2 && w ∉ cpa1
    # different block structure
    cpa1 = CartesianProductArray([Interval(N(1), N(2)), BallInf(N[1, 1], N(1))])
    cpa2 = CartesianProductArray([BallInf(N[1, 1], N(2)), Interval(N(0), N(2))])
    res, w = ⊆(cpa1, cpa2, true)
    @test cpa1 ⊆ cpa2 && res && w == N[]
    res, w = ⊆(cpa2, cpa1, true)
    @test cpa2 ⊈ cpa1 && !res && w ∈ cpa2 && w ∉ cpa1

    # convert a hyperrectangle to the cartesian product array of intervals
    # convert a hyperrectangle to a cartesian product of intervals
    H = Hyperrectangle(N[0, 0, 0], N[1, 1, 1])
    Hcp = convert(CartesianProductArray{N, Interval{N}}, H)
    @test Hcp isa CartesianProductArray &&
          all([Hcpi == Interval(N(-1), N(1)) for Hcpi in array(Hcp)])

    # check that the order is correct
    H = Hyperrectangle(N[0, 1, 2], N[1, 2, 3])
    Hcp = convert(CartesianProductArray{N, Interval{N}}, H)
    @test Hcp isa CartesianProductArray &&
          all([array(Hcp)[i] == Interval(N(-1), N(2*i-1)) for i in 1:3])

    cpa = CartesianProductArray([Zonotope(N[0, 0], N[1 0; 0 1]),
                                 Zonotope(N[1, 1], N[0 1; 1 0])])
    @test convert(Zonotope, cpa) == Zonotope(N[0, 0, 1, 1], N[1 0 0 0; 0 1 0 0;
                                                              0 0 0 1; 0 0 1 0])

    # ================
    # common functions
    # ================

    # absorbing element
    e = EmptySet{N}(2)
    b = BallInf(N[0, 0], N(2))
    @test absorbing(CartesianProduct) == absorbing(CartesianProductArray) ==
          EmptySet
    @test b × e == e × b == cpa × e == e × cpa == e × e == e

    # volume
    b2 = BallInf(zeros(N, 3), N(3))
    cp = CartesianProduct(b, b2)
    cpa = CartesianProductArray([b, b2])
    @test volume(cp) == volume(cpa) == N(3456)
end

for N in [Float64, Float32]
    # is_intersection_empty
    i1 = Interval(N[0, 1])
    i2 = Interval(N[2, 3])
    h1 = Hyperrectangle(low=N[3, 4], high=N[5, 7])
    h2 = Hyperrectangle(low=N[5, 5], high=N[6, 8])
    cpa1 = CartesianProductArray([i1, i2, h1])
    cpa2 = CartesianProductArray([i1, i2, h2])
    G = HalfSpace(N[1, 0, 0, 0], N(1))
    G_empty = HalfSpace(N[1, 0, 0, 0], N(-1))
    cpa1_box = overapproximate(cpa1)
    cpa2_box = overapproximate(cpa2)

    @test !is_intersection_empty(cpa1, cpa2) &&
          !is_intersection_empty(cpa1_box, cpa2_box)
    @test is_intersection_empty(cpa1, G_empty) &&
          is_intersection_empty(cpa1_box, G_empty)
    @test !is_intersection_empty(cpa1, G) &&
          !is_intersection_empty(Approximations.overapproximate(cpa1), G)
    @test !is_intersection_empty(cpa1, Universe{N}(4)) &&
          !is_intersection_empty(Universe{N}(4), cpa2)
    @test_throws AssertionError is_intersection_empty(cpa1, Universe{N}(3))
    @test_throws AssertionError is_intersection_empty(Universe{N}(5), cpa2)

    # projection
    cp = Interval(N(0), N(2)) × Hyperrectangle(N[2, 3], N[1, 1])
    @test project(cp, 1:2) == Hyperrectangle(N[1, 2], N[1, 1])
    @test project(cp, 2:3) == Hyperrectangle(N[2, 3], N[1, 1])

    if VERSION >= v"1.4" || N == Float64
        cp = Interval(N(0), N(2)) × Zonotope(N[2, 3], N[1 0; 0 1])
        @test isequivalent(project(cp, 1:2), Zonotope(N[1, 2], N[1 0; 0 1]))
        @test isequivalent(project(cp, 2:3), Zonotope(N[2, 3], N[1 0; 0 1]))
    end
end

for N in [Float64]
    # concrete intersection
    # constrained dimensions cover all dimensions
    cpa = CartesianProductArray([Interval(N[0, 1]), Interval(N[1, 2]),
                                 Interval(N[2, 3])])
    P = HalfSpace(N[1, 0, 1], N(2))
    cap = intersection(cpa, P)
    @test cap isa CartesianProductArray && length(array(cap)) == 1
    Q = array(cap)[1]
    @test ispermutation(constraints_list(Q), [HalfSpace(N[-1, 0, 0], N(0)),
        HalfSpace(N[0, 1, 0], N(2)), HalfSpace(N[0, -1, 0], N(-1)),
        HalfSpace(N[0, 0, -1], N(-2)), HalfSpace(N[1, 0, 1], N(2))])
    # some dimensions are unconstrained
    cpa = CartesianProductArray([Interval(N[0, 1]),
                                 Hyperrectangle(N[2, 3], N[1, 1]),
                                 Interval(N[3, 4])])
    P = HalfSpace(N[0, 1, 1, 0], N(3))
    cap = intersection(cpa, P)
    @test cap isa CartesianProductArray && length(array(cap)) == 3
    for i in [1, 3]
        @test array(cap)[1] === array(cpa)[1]
    end
    Q = array(cap)[2]
    @test ispermutation(constraints_list(Q), [HalfSpace(N[-1, 0], N(-1)),
        HalfSpace(N[0, -1], N(-2)), HalfSpace(N[1, 1], N(3))])

    if test_suite_polyhedra
        # projection to mixed dimensions
        P = Singleton(N[11, 12])
        Q = Singleton(N[13, 14, 15])
        cp = P × Q
        @test isequivalent(project(cp, [1, 4]), Singleton(N[11, 14]))
    end
end


text:
@testset "test functions var N" begin

    function f1(x)
        return exp(-0.2*sin(3*x))
    end
    function f2(x)
        return exp(-0.3*cos(3*x)) + 20
    end

    c1 = ChebyshevQuantum.Chebyshev.make_Cheb(f1 , a=2, b = 3)
    c2 = ChebyshevQuantum.Chebyshev.make_Cheb(f2 , a=2, b = 3)

    x=2.712
    @test isapprox( (c1+c2)(x), f1(x)+f2(x) , atol=tol_val)
    @test isapprox( (c1-c2)(x), f1(x)-f2(x) , atol=tol_val)
    @test isapprox( (c1^2)(x), f1(x)^2 , atol=tol_val)
    @test isapprox( (c1/c2)(x), f1(x)/f2(x) , atol=tol_val)

    @test isapprox( (-c1)(x), -f1(x) , atol=tol_val)
    @test isapprox( (2*c1)(x), 2*f1(x) , atol=tol_val)
    @test isapprox( (c1*2)(x), 2*f1(x) , atol=tol_val)
    @test isapprox( (2+c1)(x), 2+f1(x) , atol=tol_val)
    @test isapprox( (c1+2)(x), f1(x)+2 , atol=tol_val)

    @test isapprox( (2 / c2)(x), 2 / f2(x) , atol=tol_val)
    @test isapprox( (2 - c2)(x), 2 - f2(x) , atol=tol_val)

end

@testset "test Cheb functions fixed N" begin

    function f1(x)
        return exp(-0.2*sin(3*x))
    end
    function f2(x)
        return exp(-0.3*cos(3*x)) + 20
    end

    c1 = ChebyshevQuantum.Chebyshev.make_Cheb(f1 , N = 20,thr=-1,   a=2, b = 3, edgesearch=false)
    c2 = ChebyshevQuantum.Chebyshev.make_Cheb(f2 , N = 20,thr=-1,  a=2, b = 3, edgesearch=false)

    x=2.712
    @test isapprox( (c1+c2)(x), f1(x)+f2(x) , atol=tol_val)
    @test isapprox( (c1-c2)(x), f1(x)-f2(x) , atol=tol_val)
    @test isapprox( (c1^2)(x), f1(x)^2 , atol=tol_val)
    @test isapprox( (c1/c2)(x), f1(x)/f2(x) , atol=tol_val)

    @test isapprox( (-c1)(x), -f1(x) , atol=tol_val)
    @test isapprox( (2*c1)(x), 2*f1(x) , atol=tol_val)
    @test isapprox( (c1*2)(x), 2*f1(x) , atol=tol_val)
    @test isapprox( (2+c1)(x), 2+f1(x) , atol=tol_val)
    @test isapprox( (c1+2)(x), f1(x)+2 , atol=tol_val)

    @test isapprox( (2 / c2)(x), 2 / f2(x) , atol=tol_val)
    @test isapprox( (2 - c2)(x), 2 - f2(x) , atol=tol_val)

end


text:
map_tt_t(f, tt::Type{<:Tuple}) = Base.tuple_type_cons(f(Base.tuple_type_head(tt)), map_tt_t(f, Base.tuple_type_tail(tt)))
map_tt_t(f, tt::Type{Tuple{}}) = Tuple{}

function mapreduce_tt(f, op, v0, tt)
    op(f(Base.tuple_type_head(tt)), mapreduce_tt(f, op, v0, Base.tuple_type_tail(tt)))
end
mapreduce_tt(f, op, v0, tt::Type{Tuple{}}) = v0
mapreduce_tt(f, op, v0, tt::Type{Tuple{T}}) where {T} = op(f(T), v0)
mapreduce_tt(f, op, v0, tt::Type{Tuple{Vararg{T, N}} where N}) where {T} = op(f(T), f(T))


text:
using DifferentialEquations
using SimpleDiffEq
using Random
using Distributions
using GpABC
using Distances
using ApproxBayes
using Plots

function sir_ode!(du,u,p,t)
    (S,I,R,C) = u
    (β,c,γ) = p
    N = S+I+R
    infection = β*c*I/N*S
    recovery = γ*I
    @inbounds begin
        du[1] = -infection
        du[2] = infection - recovery
        du[3] = recovery
        du[4] = infection
    end
    nothing
end;

tmax = 40.0
δt = 1.0
tspan = (0.0,tmax)
obstimes = 1.0:δt:tmax;
u0 = [990.0,10.0,0.0,0.0]; # S,I.R,C
p = [0.05,10.0,0.25]; # β,c,γ

prob_ode = ODEProblem(sir_ode!,u0,tspan,p)
sol_ode = solve(prob_ode,saveat=δt)
out_ode = Array(sol_ode)
C = out_ode[4,:]
X = C[2:end] .- C[1:(end-1)];

Random.seed!(1234)
Y = rand.(Poisson.(X));

bar(obstimes,Y)
plot!(obstimes,X)

function simdata(x)
    (i0,β) = x
    I = i0*1000.0
    prob = remake(prob_ode,u0=[1000-I,I,0.0,0.0],p=[β,10.0,0.25])
    sol = solve(prob,Tsit5(),saveat=δt)
    out = Array(sol)
    C = out[4,:]
    X = C[2:end] .- C[1:(end-1)]
    transpose(X)
end;

priors = [Uniform(0.0,0.1),Uniform(0.0,0.1)];

Yt = transpose(float.(Y));

n_particles = 2000
threshold = 80.0
sim_rej_result = SimulatedABCRejection(
    Yt, # data
    simdata, # simulator
    priors, # priors
    threshold, # threshold distance
    n_particles; # particles required
    max_iter=convert(Int, 1e7),
    distance_function = Distances.euclidean,
    write_progress=false);

plot(sim_rej_result)

n_design_points = 500
emu_rej_result = EmulatedABCRejection(Yt,
    simdata,
    priors,
    threshold,
    n_particles,
    n_design_points;
    max_iter=convert(Int, 1e7),
    distance_function = Distances.euclidean,
    write_progress=false);

plot(emu_rej_result)

threshold_schedule = [110.0,100.0,90.0,80.0];

sim_smc_result = SimulatedABCSMC(Yt,
    simdata,
    priors,
    threshold_schedule,
    n_particles;
    max_iter=convert(Int, 1e7),
    distance_function = Distances.euclidean,
    write_progress=false);

population_colors=["#FF2F4E", "#D0001F", "#A20018", "#990017"]
plot(sim_smc_result, population_colors=population_colors)

emu_smc_result = EmulatedABCSMC(Yt,
    simdata,
    priors,
    threshold_schedule,
    n_particles,
    n_design_points;
    distance_metric = Distances.euclidean,
    batch_size=1000,
    write_progress=false,
    emulator_retraining = PreviousPopulationThresholdRetraining(n_design_points, 100, 10),
    emulated_particle_selection = MeanVarEmulatedParticleSelection());

plot(emu_smc_result, population_colors=population_colors)

function simdist(x, constants, y)
  s = transpose(simdata(x))
  Distances.euclidean(s, y), 1
end;

ab_rej_setup = ABCRejection(simdist, #simulation function
  2, # number of parameters
  threshold, #target ϵ
  Prior(priors); # Prior for each of the parameters
  maxiterations = 10^7, #Maximum number of iterations before the algorithm terminates
  nparticles = n_particles
  );

ab_rej = runabc(ab_rej_setup,
            Y,
            verbose = true,
            progress = true,
            parallel = true);

plot(ab_rej)

ab_smc_setup = ABCSMC(simdist, #simulation function
  2, # number of parameters
  threshold, #target ϵ
  Prior(priors), #Prior for each of the parameters
  maxiterations=convert(Int,1e7),
  nparticles=n_particles,
  α = 0.3,
  convergence = 0.05,
  kernel = uniformkernel
  );

ab_smc = runabc(ab_smc_setup,
            Y,
            verbose = true,
            progress = true,
            parallel = true);

plot(ab_smc)


text:
using MAT

@testset "predictSNR" begin
    # MATLAB output
    test = matread("resources/predictSNR.mat")

    # low pass
    ntf = synthesizeNTF(5, 32, 1)
    snr, amp, k0, k1, sigma_e2 = predictSNR(ntf, 32)
    @test isapprox(vec(test["snr_low"]), snr)
    @test [-120:10:-20; -15; -10:0] == amp   # default
    @test isapprox(vec(test["k0_low"]), k0)
    @test isapprox(vec(test["k1_low"]), k1)
    @test isapprox(vec(test["sigma_e2_low"]), sigma_e2)

    # band pass
    ntf = synthesizeNTF(8, 64, 1, 1.5, 0.125)
    amp_test = [-120:10:-20; -15; -10:0]
    snr, amp, k0, k1, sigma_e2 = predictSNR(ntf, 64, amp_test, 0.125)
    # Allow higher error tolerance because of differences in MATLAB and Julia
    # interpolation libraries. Default tolerance is sqrt(eps).
    rtol = 1e4*sqrt(eps(Float64))
    @test isapprox(vec(test["snr_band"]), snr, rtol=rtol)
    @test amp_test == amp   # passed through without changes
    @test isapprox(vec(test["k0_band"]), k0, rtol=rtol)
    @test isapprox(vec(test["k1_band"]), k1, rtol=rtol)
    @test isapprox(vec(test["sigma_e2_band"]), sigma_e2, rtol=rtol)
end

max_stars_repo_name: Mahmoud-Kharsa/DeltaSigma

max_issues_repo_name: Mahmoud-Kharsa/DeltaSigma

max_forks_repo_name: Mahmoud-Kharsa/DeltaSigma


text:
idprop_string(idprop::IdProp) = "$(idprop[1]).$(idprop[2])"

function output_string(id::CallbackId)
    if length(id.output) == 1
        return idprop_string(id.output[1])
    end
    return ".." *
    join(map(idprop_string, id.output), "...") *
    ".."
end

"""
    callback!(func::Function, app::Dash, id::CallbackId)

Create a callback that updates the output by calling function `func`.

# Examples

```julia
app = dash() do
    html_div() do
        dcc_input(id="graphTitle", value="Let's Dance!", type = "text"),
        dcc_input(id="graphTitle2", value="Let's Dance!", type = "text"),
        html_div(id="outputID"),
        html_div(id="outputID2")

    end
end
callback!(app, CallbackId(
    state = [(:graphTitle, :type)],
    input = [(:graphTitle, :value)],
    output = [(:outputID, :children), (:outputID2, :children)]
    )
    ) do stateType, inputValue
    return (stateType * "..." * inputValue, inputValue)
end
```

Alternatively, the `callid` string macro is also available when passing `input`, `state`, and `output` arguments to `callback!`:

```julia
callback!(app, callid"{graphTitle.type} graphTitle.value => outputID.children, outputID2.children") do stateType, inputValue

    return (stateType * "..." * inputValue, inputValue)
end
```

"""
function callback!(func::Union{Function, ClientsideFunction, String}, app::DashApp, id::CallbackId)

    check_callback(func, app, id)

    out_symbol = Symbol(output_string(id))
    callback_func = make_callback_func!(app, func, id)
    push!(app.callbacks, out_symbol => Callback(callback_func, id))
end

make_callback_func!(app::DashApp, func::Union{Function, ClientsideFunction}, id::CallbackId) = func

function make_callback_func!(app::DashApp, func::String, id::CallbackId)
    first_output = first(id.output)
    namespace = replace("_dashprivate_$(first_output[1])", "\""=>"\\\"")
    function_name = replace("$(first_output[2])", "\""=>"\\\"")

    function_string = """
            var clientside = window.dash_clientside = window.dash_clientside || {};
            var ns = clientside["$namespace"] = clientside["$namespace"] || {};
            ns["$function_name"] = $func;
    """
    push!(app.inline_scripts, function_string)
    return ClientsideFunction(namespace, function_name)
end

function check_callback(func, app::DashApp, id::CallbackId)

    isempty(id.input) && error("The callback method requires that one or more properly formatted inputs are passed.")

    length(id.output) != length(unique(id.output)) && error("One or more callback outputs have been duplicated; please confirm that all outputs are unique.")

    for out in id.output
        if any(x->out in x.id.output, values(app.callbacks))
            error("output \"$(out)\" already registered")
        end
    end

    args_count = length(id.state) + length(id.input)

    check_callback_func(func, args_count)

    for id_prop in id.input
        id_prop in id.output && error("Circular input and output arguments were found. Please verify that callback outputs are not also input arguments.")
    end
end

function check_callback_func(func::Function, args_count)
    !hasmethod(func, NTuple{args_count, Any}) && error("The arguments of the specified callback function do not align with the currently defined callback; please ensure that the arguments to `func` are properly defined.")
end
function check_callback_func(func, args_count)
end


text:
@plugin struct SystemImage <: PkgTemplates.Plugin
    path::String="deps/lib"
    incremental::Bool=false
    filter_stdlibs::Bool=true
    cpu_target::String="x86-64"
end

@plugin struct ComoniconFiles <: PkgTemplates.Plugin
    name::Union{Nothing, String} = nothing
    # install
    completion::Bool=true
    quiet::Bool=false
    compile::Union{Nothing, String} = nothing
    optimize::Int=2
end

PkgTemplates.customizable(::Type{<:ComoniconFiles}) = [
    :name=>String,
    :completion=>Bool,
    :quiet=>Bool,
    :compile=>String,
    :optimize=>Int
]

PkgTemplates.customizable(::Type{<:SystemImage}) = [
    :path=>String,
    :incremental=>Bool,
    :filter_stdlibs=>Bool,
    :cpu_target=>String,
]

# set up deps
function PkgTemplates.prehook(::ComoniconFiles, ::Template, pkg_dir::AbstractString)
    if !ispath(joinpath(pkg_dir, "deps"))
        mkpath(joinpath(pkg_dir, "deps"))
    end
end

# create Comonicon.toml and build.jl
function PkgTemplates.hook(p::ComoniconFiles, t::Template, pkg_dir::AbstractString)
    suffix = ".jl"
    sysimg = nothing
    for each in t.plugins
        if (each isa PkgTemplates.Git) && (each.jl == false)
            suffix = ""
        end

        if each isa SystemImage
            sysimg = each
        end
    end

    pkg = basename(pkg_dir)
    toml = OrderedDict{String, Any}(
        "name" => isnothing(p.name) ? default_name(pkg) : p.name
    )

    toml["install"] = OrderedDict(
        "completion" => p.completion,
        "quiet" => p.quiet,
        "optimize" => p.optimize,
    )

    if !isnothing(p.compile)
        toml["install"]["compile"] = p.compile
    end

    # system image related files/configs
    if !isnothing(sysimg)
        toml["sysimg"] = OrderedDict(
            "path" => sysimg.path,
            "incremental" => sysimg.incremental,
            "filter_stdlibs" => sysimg.filter_stdlibs,
            "cpu_target" => sysimg.cpu_target,
        )

        toml["download"] = OrderedDict(
            "host" => t.host,
            "user" => t.user,
            "repo" => pkg * suffix,
        )
    end # system image related files/configs

    open(joinpath(pkg_dir, "Comonicon.toml"), "w") do f
        Pkg.TOML.print(f, toml)
    end

    open(joinpath(pkg_dir, "deps", "build.jl"); append=true) do f
        println(f, "using $pkg; $pkg.comonicon_install()")
    end
end

function PkgTemplates.hook(p::SystemImage, t::Template, pkg_dir::AbstractString)
    any(x->(x isa ComoniconFiles), t.plugins) || error("SystemImage plugin must be used with ComoniconFiles")
    workflow_dir = joinpath(pkg_dir, ".github", "workflows")
    mkpath(workflow_dir)
    cp(
        joinpath(
            PATH.templates("command", "github", "workflows", "sysimg.yml")
        ),
        joinpath(workflow_dir, "sysimg.yml")
    )
end

PkgTemplates.gitignore(::ComoniconFiles) = ["/deps/build.log"]
PkgTemplates.gitignore(::SystemImage) = ["/deps/lib", "/deps/precompile.jl"]
PkgTemplates.needs_username(::ComoniconFiles) = true

function template_plugins(::PDTN"comonicon")
    return [
        Readme(;
            file = PATH.templates("command", "README.md"),
            destination="README.md",
            inline_badges=false
        ),
        ComoniconFiles(),
    ]
end

function template_plugins(::PDTN"comonicon-sysimg")
    return [
        Readme(;
            file = PATH.templates("command", "README.md"),
            destination="README.md",
            inline_badges=false
        ),
        ComoniconFiles(),
        SystemImage(),
    ]
end


text:
# functions for pedigree

"""
    update_inbreeding!(pop)

Calculate inbreeding coeffcients for individuals in the population.
"""
function update_inbreeding!(sires::Vector{Int}, dams::Vector{Int}, inb::Vector{Float64}; first::Int=1)
   if first == 1
      f = get_inbreeding(sires, dams)
      if length(f) == length(inb)
         inb .= f
      else
         error("size mismatch: f and inb")
      end
   else
      get_inbreeding!(sires, dams, inb, first=first)
   end
   return
end

function update_inbreeding!(pop::PTPopulation; first::Int=1)
   update_inbreeding!(pop.df.sire, pop.df.dam, pop.df.inb, first=first)
end

"""
   f = get_inbreeding(sires::Vector{Int},dams::Vector{Int})
   get_inbreeding(sires::Vector{Int},dams::Vector{Int},inb::Vector{Float64})

Calculate inbreeding coeffcients out of pedigree arrays.
"""
function get_inbreeding(sires::Vector{Int}, dams::Vector{Int})
   pedlist = get_pedigree_list(sires,dams,ml=true)
   f = kernel_meuwissen_and_luo!(Float64, pedlist)
   return f
end

function get_inbreeding!(sires::Vector{Int}, dams::Vector{Int}, inb::Vector{Float64}; first::Int=1)
   pedlist = get_pedigree_list(sires,dams,ml=true)
   kernel_meuwissen_and_luo2!(pedlist, inb, first=first)
   return nothing
end

"""
    pedlist = get_pedigree_list(sires::Vector{Int},dams::Vector{Int}; ml=false)

Convert two pedigree vectors to a pedigree matrix.
If `ml=true`, sire ID and dam ID would be exchanged so that sire ID > dam ID for the Meuwissen and Luo algorithm.
"""
function get_pedigree_list(sires::Vector{Int}, dams::Vector{Int}; ml::Bool=false)
   if length(sires) != length(dams)
      throw(ArgumentError("unequal size of sire and dam vectors"))
   end
   n = length(sires)
   pedlist = zeros(Int,2,n)
   for i=1:n
      s = sires[i]
      d = dams[i]
      if ml==true
         pedlist[1,i] = max(s,d)
         pedlist[2,i] = min(s,d)
      else
         pedlist[1,i] = s
         pedlist[2,i] = d
      end
   end
   return pedlist
end

# kernel of Meuwissen and Luo (1992)
# the argument "ped" being rewritten
function kernel_meuwissen_and_luo!(Tv::DataType, ped::Matrix{Ti}) where Ti<:Integer
   n::Ti = size(ped,2)
   f = OffsetArray{Tv}(undef,0:n)
   i::Ti = 0
   j::Ti = 0
   k::Ti = 0
   s0::Ti = 0
   d0::Ti = 0
   ks::Ti = 0
   kd::Ti = 0
   fi::Tv = 0.0
   r::Tv = 0.0
   point = zeros(Ti,n)
   T = zeros(Tv,n)
   B = zeros(Tv,n)

   # start
   f[0] = -1
   for i=1:n
      s0 = ped[1,i]
      d0 = ped[2,i]
      ped[1,i] = max(s0,d0)
      ped[2,i] = min(s0,d0)
      B[i] = 0.5 - 0.25*(f[s0]+f[d0])

      if s0==0 || d0==0
         f[i] = 0.0
      else
         fi = -1.0
         T[i] = 1.0
         j = i
         while(j!=0)
            k = j
            r = 0.5 * T[k]
            ks = ped[1,k]
            kd = ped[2,k]
            if ks != 0
               while(point[k]>ks)
                  k = point[k]
               end
               T[ks] = T[ks] + r
               if ks != point[k]
                  point[ks] = point[k]
                  point[k] = ks
               end
               if kd != 0
                  while(point[k]>kd)
                     k = point[k]
                  end
                  T[kd] = T[kd] + r
                  if kd != point[k]
                     point[kd] = point[k]
                     point[k] = kd
                  end
               end
            end
            fi = fi + T[j]*T[j]*B[j]
            T[j] = 0.0
            k = j
            j = point[j]
            point[k] = 0
         end
         f[i] = fi
      end
   end
   return f[1:n]
end

# kernel of Meuwissen and Luo (1992)
# specialized for new animals in the same generation
# the argument "ped" not being rewritten
function kernel_meuwissen_and_luo2!(ped::Matrix{Ti}, inb::Vector{Tv}; first=1) where {Tv<:Real, Ti<:Integer}
   n::Ti = size(ped,2)
   if n<length(inb)
      throw(DimensionMismatch("inb shorter than pedigree size"))
   end
   f = OffsetArray{Tv}(undef,0:n)
   f[1:n] .= inb[1:n]
   point = zeros(Ti,n,Threads.nthreads())
   T = zeros(Tv,n,Threads.nthreads())
   B = zeros(Tv,n)

   # start
   f[0] = -1
   for i=1:first-1
      s0 = ped[1,i]
      d0 = ped[2,i]
      B[i] = 0.5 - 0.25*(f[s0]+f[d0])
   end
   Base.Threads.@threads for i=first:n
      local s0 = ped[1,i]
      local d0 = ped[2,i]
      B[i] = 0.5 - 0.25*(f[s0]+f[d0])

      if s0==0 || d0==0
         f[i] = 0.0
      else
         local fi = -1.0
         T[i,Threads.threadid()] = 1.0
         local j = i
         while(j!=0)
            local k = j
            local r = 0.5 * T[k,Threads.threadid()]
            local ks = ped[1,k]
            local kd = ped[2,k]
            if ks != 0
               while(point[k,Threads.threadid()]>ks)
                  k = point[k,Threads.threadid()]
               end
               T[ks,Threads.threadid()] = T[ks,Threads.threadid()] + r
               if ks != point[k,Threads.threadid()]
                  point[ks,Threads.threadid()] = point[k,Threads.threadid()]
                  point[k,Threads.threadid()] = ks
               end
               if kd != 0
                  while(point[k,Threads.threadid()]>kd)
                     k = point[k,Threads.threadid()]
                  end
                  T[kd,Threads.threadid()] = T[kd,Threads.threadid()] + r
                  if kd != point[k,Threads.threadid()]
                     point[kd,Threads.threadid()] = point[k,Threads.threadid()]
                     point[k,Threads.threadid()] = kd
                  end
               end
            end
            fi = fi + T[j,Threads.threadid()]*T[j,Threads.threadid()]*B[j]
            T[j,Threads.threadid()] = 0.0
            k = j
            j = point[j,Threads.threadid()]
            point[k,Threads.threadid()] = 0
         end
         f[i] = fi
      end
   end
   inb[first:n] .= f[first:n]
   return nothing
end