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

"""
    CreateCluster()

Creates an Amazon EKS control plane.  The Amazon EKS control plane consists of control plane instances that run the Kubernetes software, such as etcd and the API server. The control plane runs in an account managed by AWS, and the Kubernetes API is exposed via the Amazon EKS API server endpoint. Each Amazon EKS cluster control plane is single-tenant and unique and runs on its own set of Amazon EC2 instances. The cluster control plane is provisioned across multiple Availability Zones and fronted by an Elastic Load Balancing Network Load Balancer. Amazon EKS also provisions elastic network interfaces in your VPC subnets to provide connectivity from the control plane instances to the worker nodes (for example, to support kubectl exec, logs, and proxy data flows). Amazon EKS worker nodes run in your AWS account and connect to your cluster's control plane via the Kubernetes API server endpoint and a certificate file that is created for your cluster. You can use the endpointPublicAccess and endpointPrivateAccess parameters to enable or disable public and private access to your cluster's Kubernetes API server endpoint. By default, public access is enabled, and private access is disabled. For more information, see Amazon EKS Cluster Endpoint Access Control in the  Amazon EKS User Guide .  You can use the logging parameter to enable or disable exporting the Kubernetes control plane logs for your cluster to CloudWatch Logs. By default, cluster control plane logs aren't exported to CloudWatch Logs. For more information, see Amazon EKS Cluster Control Plane Logs in the  Amazon EKS User Guide .  CloudWatch Logs ingestion, archive storage, and data scanning rates apply to exported control plane logs. For more information, see Amazon CloudWatch Pricing.  Cluster creation typically takes between 10 and 15 minutes. After you create an Amazon EKS cluster, you must configure your Kubernetes tooling to communicate with the API server and launch worker nodes into your cluster. For more information, see Managing Cluster Authentication and Launching Amazon EKS Worker Nodes in the Amazon EKS User Guide.

# Required Parameters
- `name`: The unique name to give to your cluster.
- `resourcesVpcConfig`: The VPC configuration used by the cluster control plane. Amazon EKS VPC resources have specific requirements to work properly with Kubernetes. For more information, see Cluster VPC Considerations and Cluster Security Group Considerations in the Amazon EKS User Guide. You must specify at least two subnets. You can specify up to five security groups, but we recommend that you use a dedicated security group for your cluster control plane.
- `roleArn`: The Amazon Resource Name (ARN) of the IAM role that provides permissions for the Kubernetes control plane to make calls to AWS API operations on your behalf. For more information, see Amazon EKS Service IAM Role in the  Amazon EKS User Guide .

# Optional Parameters
- `clientRequestToken`: Unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
- `encryptionConfig`: The encryption configuration for the cluster.
- `kubernetesNetworkConfig`: The Kubernetes network configuration for the cluster.
- `logging`: Enable or disable exporting the Kubernetes control plane logs for your cluster to CloudWatch Logs. By default, cluster control plane logs aren't exported to CloudWatch Logs. For more information, see Amazon EKS Cluster Control Plane Logs in the  Amazon EKS User Guide .  CloudWatch Logs ingestion, archive storage, and data scanning rates apply to exported control plane logs. For more information, see Amazon CloudWatch Pricing.
- `tags`: The metadata to apply to the cluster to assist with categorization and organization. Each tag consists of a key and an optional value, both of which you define.
- `version`: The desired Kubernetes version for your cluster. If you don't specify a value here, the latest version available in Amazon EKS is used.
"""
create_cluster(name, resourcesVpcConfig, roleArn; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters", Dict{String, Any}("name"=>name, "resourcesVpcConfig"=>resourcesVpcConfig, "roleArn"=>roleArn, "clientRequestToken"=>string(uuid4())); aws_config=aws_config)
create_cluster(name, resourcesVpcConfig, roleArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("name"=>name, "resourcesVpcConfig"=>resourcesVpcConfig, "roleArn"=>roleArn, "clientRequestToken"=>string(uuid4())), args)); aws_config=aws_config)

"""
    CreateFargateProfile()

Creates an AWS Fargate profile for your Amazon EKS cluster. You must have at least one Fargate profile in a cluster to be able to run pods on Fargate. The Fargate profile allows an administrator to declare which pods run on Fargate and specify which pods run on which Fargate profile. This declaration is done through the profile’s selectors. Each profile can have up to five selectors that contain a namespace and labels. A namespace is required for every selector. The label field consists of multiple optional key-value pairs. Pods that match the selectors are scheduled on Fargate. If a to-be-scheduled pod matches any of the selectors in the Fargate profile, then that pod is run on Fargate. When you create a Fargate profile, you must specify a pod execution role to use with the pods that are scheduled with the profile. This role is added to the cluster's Kubernetes Role Based Access Control (RBAC) for authorization so that the kubelet that is running on the Fargate infrastructure can register with your Amazon EKS cluster so that it can appear in your cluster as a node. The pod execution role also provides IAM permissions to the Fargate infrastructure to allow read access to Amazon ECR image repositories. For more information, see Pod Execution Role in the Amazon EKS User Guide. Fargate profiles are immutable. However, you can create a new updated profile to replace an existing profile and then delete the original after the updated profile has finished creating. If any Fargate profiles in a cluster are in the DELETING status, you must wait for that Fargate profile to finish deleting before you can create any other profiles in that cluster. For more information, see AWS Fargate Profile in the Amazon EKS User Guide.

# Required Parameters
- `fargateProfileName`: The name of the Fargate profile.
- `name`: The name of the Amazon EKS cluster to apply the Fargate profile to.
- `podExecutionRoleArn`: The Amazon Resource Name (ARN) of the pod execution role to use for pods that match the selectors in the Fargate profile. The pod execution role allows Fargate infrastructure to register with your cluster as a node, and it provides read access to Amazon ECR image repositories. For more information, see Pod Execution Role in the Amazon EKS User Guide.

# Optional Parameters
- `clientRequestToken`: Unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
- `selectors`: The selectors to match for pods to use this Fargate profile. Each selector must have an associated namespace. Optionally, you can also specify labels for a namespace. You may specify up to five selectors in a Fargate profile.
- `subnets`: The IDs of subnets to launch your pods into. At this time, pods running on Fargate are not assigned public IP addresses, so only private subnets (with no direct route to an Internet Gateway) are accepted for this parameter.
- `tags`: The metadata to apply to the Fargate profile to assist with categorization and organization. Each tag consists of a key and an optional value, both of which you define. Fargate profile tags do not propagate to any other resources associated with the Fargate profile, such as the pods that are scheduled with it.
"""
create_fargate_profile(fargateProfileName, name, podExecutionRoleArn; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/fargate-profiles", Dict{String, Any}("fargateProfileName"=>fargateProfileName, "podExecutionRoleArn"=>podExecutionRoleArn, "clientRequestToken"=>string(uuid4())); aws_config=aws_config)
create_fargate_profile(fargateProfileName, name, podExecutionRoleArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/fargate-profiles", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("fargateProfileName"=>fargateProfileName, "podExecutionRoleArn"=>podExecutionRoleArn, "clientRequestToken"=>string(uuid4())), args)); aws_config=aws_config)

"""
    CreateNodegroup()

Creates a managed worker node group for an Amazon EKS cluster. You can only create a node group for your cluster that is equal to the current Kubernetes version for the cluster. All node groups are created with the latest AMI release version for the respective minor Kubernetes version of the cluster, unless you deploy a custom AMI using a launch template. For more information about using launch templates, see Launch template support. An Amazon EKS managed node group is an Amazon EC2 Auto Scaling group and associated Amazon EC2 instances that are managed by AWS for an Amazon EKS cluster. Each node group uses a version of the Amazon EKS-optimized Amazon Linux 2 AMI. For more information, see Managed Node Groups in the Amazon EKS User Guide.

# Required Parameters
- `name`: The name of the cluster to create the node group in.
- `nodeRole`: The Amazon Resource Name (ARN) of the IAM role to associate with your node group. The Amazon EKS worker node kubelet daemon makes calls to AWS APIs on your behalf. Worker nodes receive permissions for these API calls through an IAM instance profile and associated policies. Before you can launch worker nodes and register them into a cluster, you must create an IAM role for those worker nodes to use when they are launched. For more information, see Amazon EKS Worker Node IAM Role in the  Amazon EKS User Guide . If you specify launchTemplate, then don't specify  IamInstanceProfile  in your launch template, or the node group deployment will fail. For more information about using launch templates with Amazon EKS, see Launch template support in the Amazon EKS User Guide.
- `nodegroupName`: The unique name to give your node group.
- `subnets`: The subnets to use for the Auto Scaling group that is created for your node group. These subnets must have the tag key kubernetes.io/cluster/CLUSTER_NAME with a value of shared, where CLUSTER_NAME is replaced with the name of your cluster. If you specify launchTemplate, then don't specify  SubnetId  in your launch template, or the node group deployment will fail. For more information about using launch templates with Amazon EKS, see Launch template support in the Amazon EKS User Guide.

# Optional Parameters
- `amiType`: The AMI type for your node group. GPU instance types should use the AL2_x86_64_GPU AMI type. Non-GPU instances should use the AL2_x86_64 AMI type. Arm instances should use the AL2_ARM_64 AMI type. All types use the Amazon EKS-optimized Amazon Linux 2 AMI. If you specify launchTemplate, and your launch template uses a custom AMI, then don't specify amiType, or the node group deployment will fail. For more information about using launch templates with Amazon EKS, see Launch template support in the Amazon EKS User Guide.
- `clientRequestToken`: Unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
- `diskSize`: The root device disk size (in GiB) for your node group instances. The default disk size is 20 GiB. If you specify launchTemplate, then don't specify diskSize, or the node group deployment will fail. For more information about using launch templates with Amazon EKS, see Launch template support in the Amazon EKS User Guide.
- `instanceTypes`: The instance type to use for your node group. You can specify a single instance type for a node group. The default value for instanceTypes is t3.medium. If you choose a GPU instance type, be sure to specify AL2_x86_64_GPU with the amiType parameter. If you specify launchTemplate, then don't specify instanceTypes, or the node group deployment will fail. For more information about using launch templates with Amazon EKS, see Launch template support in the Amazon EKS User Guide.
- `labels`: The Kubernetes labels to be applied to the nodes in the node group when they are created.
- `launchTemplate`: An object representing a node group's launch template specification. If specified, then do not specify instanceTypes, diskSize, or remoteAccess and make sure that the launch template meets the requirements in launchTemplateSpecification.
- `releaseVersion`: The AMI version of the Amazon EKS-optimized AMI to use with your node group. By default, the latest available AMI version for the node group's current Kubernetes version is used. For more information, see Amazon EKS-Optimized Linux AMI Versions in the Amazon EKS User Guide. If you specify launchTemplate, and your launch template uses a custom AMI, then don't specify releaseVersion, or the node group deployment will fail. For more information about using launch templates with Amazon EKS, see Launch template support in the Amazon EKS User Guide.
- `remoteAccess`: The remote access (SSH) configuration to use with your node group. If you specify launchTemplate, then don't specify remoteAccess, or the node group deployment will fail. For more information about using launch templates with Amazon EKS, see Launch template support in the Amazon EKS User Guide.
- `scalingConfig`: The scaling configuration details for the Auto Scaling group that is created for your node group.
- `tags`: The metadata to apply to the node group to assist with categorization and organization. Each tag consists of a key and an optional value, both of which you define. Node group tags do not propagate to any other resources associated with the node group, such as the Amazon EC2 instances or subnets.
- `version`: The Kubernetes version to use for your managed nodes. By default, the Kubernetes version of the cluster is used, and this is the only accepted specified value. If you specify launchTemplate, and your launch template uses a custom AMI, then don't specify version, or the node group deployment will fail. For more information about using launch templates with Amazon EKS, see Launch template support in the Amazon EKS User Guide.
"""
create_nodegroup(name, nodeRole, nodegroupName, subnets; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/node-groups", Dict{String, Any}("nodeRole"=>nodeRole, "nodegroupName"=>nodegroupName, "subnets"=>subnets, "clientRequestToken"=>string(uuid4())); aws_config=aws_config)
create_nodegroup(name, nodeRole, nodegroupName, subnets, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/node-groups", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("nodeRole"=>nodeRole, "nodegroupName"=>nodegroupName, "subnets"=>subnets, "clientRequestToken"=>string(uuid4())), args)); aws_config=aws_config)

"""
    DeleteCluster()

Deletes the Amazon EKS cluster control plane. If you have active services in your cluster that are associated with a load balancer, you must delete those services before deleting the cluster so that the load balancers are deleted properly. Otherwise, you can have orphaned resources in your VPC that prevent you from being able to delete the VPC. For more information, see Deleting a Cluster in the Amazon EKS User Guide. If you have managed node groups or Fargate profiles attached to the cluster, you must delete them first. For more information, see DeleteNodegroup and DeleteFargateProfile.

# Required Parameters
- `name`: The name of the cluster to delete.

"""
delete_cluster(name; aws_config::AWSConfig=global_aws_config()) = eks("DELETE", "/clusters/$(name)"; aws_config=aws_config)
delete_cluster(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("DELETE", "/clusters/$(name)", args; aws_config=aws_config)

"""
    DeleteFargateProfile()

Deletes an AWS Fargate profile. When you delete a Fargate profile, any pods running on Fargate that were created with the profile are deleted. If those pods match another Fargate profile, then they are scheduled on Fargate with that profile. If they no longer match any Fargate profiles, then they are not scheduled on Fargate and they may remain in a pending state. Only one Fargate profile in a cluster can be in the DELETING status at a time. You must wait for a Fargate profile to finish deleting before you can delete any other profiles in that cluster.

# Required Parameters
- `fargateProfileName`: The name of the Fargate profile to delete.
- `name`: The name of the Amazon EKS cluster associated with the Fargate profile to delete.

"""
delete_fargate_profile(fargateProfileName, name; aws_config::AWSConfig=global_aws_config()) = eks("DELETE", "/clusters/$(name)/fargate-profiles/$(fargateProfileName)"; aws_config=aws_config)
delete_fargate_profile(fargateProfileName, name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("DELETE", "/clusters/$(name)/fargate-profiles/$(fargateProfileName)", args; aws_config=aws_config)

"""
    DeleteNodegroup()

Deletes an Amazon EKS node group for a cluster.

# Required Parameters
- `name`: The name of the Amazon EKS cluster that is associated with your node group.
- `nodegroupName`: The name of the node group to delete.

"""
delete_nodegroup(name, nodegroupName; aws_config::AWSConfig=global_aws_config()) = eks("DELETE", "/clusters/$(name)/node-groups/$(nodegroupName)"; aws_config=aws_config)
delete_nodegroup(name, nodegroupName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("DELETE", "/clusters/$(name)/node-groups/$(nodegroupName)", args; aws_config=aws_config)

"""
    DescribeCluster()

Returns descriptive information about an Amazon EKS cluster. The API server endpoint and certificate authority data returned by this operation are required for kubelet and kubectl to communicate with your Kubernetes API server. For more information, see Create a kubeconfig for Amazon EKS.  The API server endpoint and certificate authority data aren't available until the cluster reaches the ACTIVE state.

# Required Parameters
- `name`: The name of the cluster to describe.

"""
describe_cluster(name; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)"; aws_config=aws_config)
describe_cluster(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)", args; aws_config=aws_config)

"""
    DescribeFargateProfile()

Returns descriptive information about an AWS Fargate profile.

# Required Parameters
- `fargateProfileName`: The name of the Fargate profile to describe.
- `name`: The name of the Amazon EKS cluster associated with the Fargate profile.

"""
describe_fargate_profile(fargateProfileName, name; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/fargate-profiles/$(fargateProfileName)"; aws_config=aws_config)
describe_fargate_profile(fargateProfileName, name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/fargate-profiles/$(fargateProfileName)", args; aws_config=aws_config)

"""
    DescribeNodegroup()

Returns descriptive information about an Amazon EKS node group.

# Required Parameters
- `name`: The name of the Amazon EKS cluster associated with the node group.
- `nodegroupName`: The name of the node group to describe.

"""
describe_nodegroup(name, nodegroupName; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/node-groups/$(nodegroupName)"; aws_config=aws_config)
describe_nodegroup(name, nodegroupName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/node-groups/$(nodegroupName)", args; aws_config=aws_config)

"""
    DescribeUpdate()

Returns descriptive information about an update against your Amazon EKS cluster or associated managed node group. When the status of the update is Succeeded, the update is complete. If an update fails, the status is Failed, and an error detail explains the reason for the failure.

# Required Parameters
- `name`: The name of the Amazon EKS cluster associated with the update.
- `updateId`: The ID of the update to describe.

# Optional Parameters
- `nodegroupName`: The name of the Amazon EKS node group associated with the update.
"""
describe_update(name, updateId; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/updates/$(updateId)"; aws_config=aws_config)
describe_update(name, updateId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/updates/$(updateId)", args; aws_config=aws_config)

"""
    ListClusters()

Lists the Amazon EKS clusters in your AWS account in the specified Region.

# Optional Parameters
- `maxResults`: The maximum number of cluster results returned by ListClusters in paginated output. When you use this parameter, ListClusters returns only maxResults results in a single page along with a nextToken response element. You can see the remaining results of the initial request by sending another ListClusters request with the returned nextToken value. This value can be between 1 and 100. If you don't use this parameter, ListClusters returns up to 100 results and a nextToken value if applicable.
- `nextToken`: The nextToken value returned from a previous paginated ListClusters request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value.  This token should be treated as an opaque identifier that is used only to retrieve the next items in a list and not for other programmatic purposes.
"""
list_clusters(; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters"; aws_config=aws_config)
list_clusters(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters", args; aws_config=aws_config)

"""
    ListFargateProfiles()

Lists the AWS Fargate profiles associated with the specified cluster in your AWS account in the specified Region.

# Required Parameters
- `name`: The name of the Amazon EKS cluster that you would like to listFargate profiles in.

# Optional Parameters
- `maxResults`: The maximum number of Fargate profile results returned by ListFargateProfiles in paginated output. When you use this parameter, ListFargateProfiles returns only maxResults results in a single page along with a nextToken response element. You can see the remaining results of the initial request by sending another ListFargateProfiles request with the returned nextToken value. This value can be between 1 and 100. If you don't use this parameter, ListFargateProfiles returns up to 100 results and a nextToken value if applicable.
- `nextToken`: The nextToken value returned from a previous paginated ListFargateProfiles request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value.
"""
list_fargate_profiles(name; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/fargate-profiles"; aws_config=aws_config)
list_fargate_profiles(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/fargate-profiles", args; aws_config=aws_config)

"""
    ListNodegroups()

Lists the Amazon EKS managed node groups associated with the specified cluster in your AWS account in the specified Region. Self-managed node groups are not listed.

# Required Parameters
- `name`: The name of the Amazon EKS cluster that you would like to list node groups in.

# Optional Parameters
- `maxResults`: The maximum number of node group results returned by ListNodegroups in paginated output. When you use this parameter, ListNodegroups returns only maxResults results in a single page along with a nextToken response element. You can see the remaining results of the initial request by sending another ListNodegroups request with the returned nextToken value. This value can be between 1 and 100. If you don't use this parameter, ListNodegroups returns up to 100 results and a nextToken value if applicable.
- `nextToken`: The nextToken value returned from a previous paginated ListNodegroups request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value.
"""
list_nodegroups(name; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/node-groups"; aws_config=aws_config)
list_nodegroups(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/node-groups", args; aws_config=aws_config)

"""
    ListTagsForResource()

List the tags for an Amazon EKS resource.

# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the supported resources are Amazon EKS clusters and managed node groups.

"""
list_tags_for_resource(resourceArn; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/tags/$(resourceArn)"; aws_config=aws_config)
list_tags_for_resource(resourceArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/tags/$(resourceArn)", args; aws_config=aws_config)

"""
    ListUpdates()

Lists the updates associated with an Amazon EKS cluster or managed node group in your AWS account, in the specified Region.

# Required Parameters
- `name`: The name of the Amazon EKS cluster to list updates for.

# Optional Parameters
- `maxResults`: The maximum number of update results returned by ListUpdates in paginated output. When you use this parameter, ListUpdates returns only maxResults results in a single page along with a nextToken response element. You can see the remaining results of the initial request by sending another ListUpdates request with the returned nextToken value. This value can be between 1 and 100. If you don't use this parameter, ListUpdates returns up to 100 results and a nextToken value if applicable.
- `nextToken`: The nextToken value returned from a previous paginated ListUpdates request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value.
- `nodegroupName`: The name of the Amazon EKS managed node group to list updates for.
"""
list_updates(name; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/updates"; aws_config=aws_config)
list_updates(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("GET", "/clusters/$(name)/updates", args; aws_config=aws_config)

"""
    TagResource()

Associates the specified tags to a resource with the specified resourceArn. If existing tags on a resource are not specified in the request parameters, they are not changed. When a resource is deleted, the tags associated with that resource are deleted as well. Tags that you create for Amazon EKS resources do not propagate to any other resources associated with the cluster. For example, if you tag a cluster with this operation, that tag does not automatically propagate to the subnets and worker nodes associated with the cluster.

# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) of the resource to which to add tags. Currently, the supported resources are Amazon EKS clusters and managed node groups.
- `tags`: The tags to add to the resource. A tag is an array of key-value pairs.

"""
tag_resource(resourceArn, tags; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/tags/$(resourceArn)", Dict{String, Any}("tags"=>tags); aws_config=aws_config)
tag_resource(resourceArn, tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/tags/$(resourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("tags"=>tags), args)); aws_config=aws_config)

"""
    UntagResource()

Deletes specified tags from a resource.

# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) of the resource from which to delete tags. Currently, the supported resources are Amazon EKS clusters and managed node groups.
- `tagKeys`: The keys of the tags to be removed.

"""
untag_resource(resourceArn, tagKeys; aws_config::AWSConfig=global_aws_config()) = eks("DELETE", "/tags/$(resourceArn)", Dict{String, Any}("tagKeys"=>tagKeys); aws_config=aws_config)
untag_resource(resourceArn, tagKeys, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("DELETE", "/tags/$(resourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("tagKeys"=>tagKeys), args)); aws_config=aws_config)

"""
    UpdateClusterConfig()

Updates an Amazon EKS cluster configuration. Your cluster continues to function during the update. The response output includes an update ID that you can use to track the status of your cluster update with the DescribeUpdate API operation. You can use this API operation to enable or disable exporting the Kubernetes control plane logs for your cluster to CloudWatch Logs. By default, cluster control plane logs aren't exported to CloudWatch Logs. For more information, see Amazon EKS Cluster Control Plane Logs in the  Amazon EKS User Guide .  CloudWatch Logs ingestion, archive storage, and data scanning rates apply to exported control plane logs. For more information, see Amazon CloudWatch Pricing.  You can also use this API operation to enable or disable public and private access to your cluster's Kubernetes API server endpoint. By default, public access is enabled, and private access is disabled. For more information, see Amazon EKS Cluster Endpoint Access Control in the  Amazon EKS User Guide .   At this time, you can not update the subnets or security group IDs for an existing cluster.  Cluster updates are asynchronous, and they should finish within a few minutes. During an update, the cluster status moves to UPDATING (this status transition is eventually consistent). When the update is complete (either Failed or Successful), the cluster status moves to Active.

# Required Parameters
- `name`: The name of the Amazon EKS cluster to update.

# Optional Parameters
- `clientRequestToken`: Unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
- `logging`: Enable or disable exporting the Kubernetes control plane logs for your cluster to CloudWatch Logs. By default, cluster control plane logs aren't exported to CloudWatch Logs. For more information, see Amazon EKS Cluster Control Plane Logs in the  Amazon EKS User Guide .  CloudWatch Logs ingestion, archive storage, and data scanning rates apply to exported control plane logs. For more information, see Amazon CloudWatch Pricing.
- `resourcesVpcConfig`:
"""
update_cluster_config(name; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/update-config", Dict{String, Any}("clientRequestToken"=>string(uuid4())); aws_config=aws_config)
update_cluster_config(name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/update-config", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("clientRequestToken"=>string(uuid4())), args)); aws_config=aws_config)

"""
    UpdateClusterVersion()

Updates an Amazon EKS cluster to the specified Kubernetes version. Your cluster continues to function during the update. The response output includes an update ID that you can use to track the status of your cluster update with the DescribeUpdate API operation. Cluster updates are asynchronous, and they should finish within a few minutes. During an update, the cluster status moves to UPDATING (this status transition is eventually consistent). When the update is complete (either Failed or Successful), the cluster status moves to Active. If your cluster has managed node groups attached to it, all of your node groups’ Kubernetes versions must match the cluster’s Kubernetes version in order to update the cluster to a new Kubernetes version.

# Required Parameters
- `name`: The name of the Amazon EKS cluster to update.
- `version`: The desired Kubernetes version following a successful update.

# Optional Parameters
- `clientRequestToken`: Unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
"""
update_cluster_version(name, version; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/updates", Dict{String, Any}("version"=>version, "clientRequestToken"=>string(uuid4())); aws_config=aws_config)
update_cluster_version(name, version, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/updates", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("version"=>version, "clientRequestToken"=>string(uuid4())), args)); aws_config=aws_config)

"""
    UpdateNodegroupConfig()

Updates an Amazon EKS managed node group configuration. Your node group continues to function during the update. The response output includes an update ID that you can use to track the status of your node group update with the DescribeUpdate API operation. Currently you can update the Kubernetes labels for a node group or the scaling configuration.

# Required Parameters
- `name`: The name of the Amazon EKS cluster that the managed node group resides in.
- `nodegroupName`: The name of the managed node group to update.

# Optional Parameters
- `clientRequestToken`: Unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
- `labels`: The Kubernetes labels to be applied to the nodes in the node group after the update.
- `scalingConfig`: The scaling configuration details for the Auto Scaling group after the update.
"""
update_nodegroup_config(name, nodegroupName; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/node-groups/$(nodegroupName)/update-config", Dict{String, Any}("clientRequestToken"=>string(uuid4())); aws_config=aws_config)
update_nodegroup_config(name, nodegroupName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/node-groups/$(nodegroupName)/update-config", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("clientRequestToken"=>string(uuid4())), args)); aws_config=aws_config)

"""
    UpdateNodegroupVersion()

Updates the Kubernetes version or AMI version of an Amazon EKS managed node group. You can update a node group using a launch template only if the node group was originally deployed with a launch template. If you need to update a custom AMI in a node group that was deployed with a launch template, then update your custom AMI, specify the new ID in a new version of the launch template, and then update the node group to the new version of the launch template. If you update without a launch template, then you can update to the latest available AMI version of a node group's current Kubernetes version by not specifying a Kubernetes version in the request. You can update to the latest AMI version of your cluster's current Kubernetes version by specifying your cluster's Kubernetes version in the request. For more information, see Amazon EKS-Optimized Linux AMI Versions in the Amazon EKS User Guide. You cannot roll back a node group to an earlier Kubernetes version or AMI version. When a node in a managed node group is terminated due to a scaling action or update, the pods in that node are drained first. Amazon EKS attempts to drain the nodes gracefully and will fail if it is unable to do so. You can force the update if Amazon EKS is unable to drain the nodes as a result of a pod disruption budget issue.

# Required Parameters
- `name`: The name of the Amazon EKS cluster that is associated with the managed node group to update.
- `nodegroupName`: The name of the managed node group to update.

# Optional Parameters
- `clientRequestToken`: Unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
- `force`: Force the update if the existing node group's pods are unable to be drained due to a pod disruption budget issue. If an update fails because pods could not be drained, you can force the update after it fails to terminate the old node whether or not any pods are running on the node.
- `launchTemplate`: An object representing a node group's launch template specification. You can only update a node group using a launch template if the node group was originally deployed with a launch template.
- `releaseVersion`: The AMI version of the Amazon EKS-optimized AMI to use for the update. By default, the latest available AMI version for the node group's Kubernetes version is used. For more information, see Amazon EKS-Optimized Linux AMI Versions  in the Amazon EKS User Guide. If you specify launchTemplate, and your launch template uses a custom AMI, then don't specify releaseVersion, or the node group update will fail. For more information about using launch templates with Amazon EKS, see Launch template support in the Amazon EKS User Guide.
- `version`: The Kubernetes version to update to. If no version is specified, then the Kubernetes version of the node group does not change. You can specify the Kubernetes version of the cluster to update the node group to the latest AMI version of the cluster's Kubernetes version. If you specify launchTemplate, and your launch template uses a custom AMI, then don't specify version, or the node group update will fail. For more information about using launch templates with Amazon EKS, see Launch template support in the Amazon EKS User Guide.
"""
update_nodegroup_version(name, nodegroupName; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/node-groups/$(nodegroupName)/update-version", Dict{String, Any}("clientRequestToken"=>string(uuid4())); aws_config=aws_config)
update_nodegroup_version(name, nodegroupName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = eks("POST", "/clusters/$(name)/node-groups/$(nodegroupName)/update-version", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("clientRequestToken"=>string(uuid4())), args)); aws_config=aws_config)


text:
"""
    make_overdub(make_body, ::Type{Ctx}, f::F, sig::Tuple)

    - `make_body` is a function that gets as inputs the symbols for all the
      functions inputs, and must return an `Expr` for its body
"""
function make_overdub(make_body, ::Type{Ctx}, f::F, sig::Tuple) where {Ctx, F}
    sig_exs = Expr[]
    sig_names = []

    foreach(sig) do T
        T_uw = Base.unwrap_unionall(T)

        name = gensym()
        if T_uw isa TypeVar
            T = T_uw
        elseif T_uw.name.name === :Vararg
            if T isa UnionAll && T.body isa UnionAll  # Vararg{T, N} where {T, N}.
                T = Vararg{Any}
            end
            if T isa UnionAll  # Vararg{T, N} where N.
                push!(sig_exs, :($name::$(T_uw.parameters[1])...))
                push!(sig_names, :($name...))
            else  # Vararg{T, N}.
                foreach(1:T.parameters[2]) do _i
                    push!(sig_exs, :($name::$(T.parameters[1])))
                    push!(sig_names, name)
                    name = gensym()
                end
            end
        else
            push!(sig_exs, :($name::$T))
            push!(sig_names, name)
        end
    end

    overdub_code = quote
        function Cassette.overdub(ctx::$Ctx, f::$F, $(sig_exs...))
            $(make_body(sig_names...))
        end
    end
    #@show overdub_code
    eval(overdub_code)
end

function make_interpretted_mode_overdub(f, sig::Tuple)
    make_overdub(MixModeDebugCtx, f, sig) do args...
        quote
            thunk = ()->(println($args); f($(args...)))
            Debugger.@run(thunk())
        end
    end
end

function make_interpretted_mode_overdub(meth::Method)
    sigp = parameter_typeof(meth.sig)
    func_t = first(sigp)
    func = func_t.instance
    arg_sig = Tuple(sigp[2:end])
    return make_interpretted_mode_overdub(func, arg_sig)
end

function make_interpretted_mode_overdub(bp::BreakpointSignature)
    return make_interpretted_mode_overdub(bp.f)
end

ext: jl


text:
# Autogenerated wrapper script for Minuit2_Julia_Wrapper_jll for armv7l-linux-musleabihf-cxx11
export minuit2wrap

using libcxxwrap_julia_jll
using Minuit2_jll
JLLWrappers.@generate_wrapper_header("Minuit2_Julia_Wrapper")
JLLWrappers.@declare_library_product(minuit2wrap, "libminuit2wrap.so")
function __init__()
    JLLWrappers.@generate_init_header(libcxxwrap_julia_jll, Minuit2_jll)
    JLLWrappers.@init_library_product(
        minuit2wrap,
        "lib/libminuit2wrap.so",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
"""
Subroutine dtrpcg

Given a sparse symmetric matrix A in compressed column storage,
this subroutine uses a preconditioned conjugate gradient method
to find an approximate minimizer of the trust region subproblem

  min { q(s) : || L'*s || <= delta }.

where q is the quadratic

  q(s) = 0.5*s'*A*s + g'*s,

A is a symmetric matrix in compressed column storage, L is a
lower triangular matrix in compressed column storage, and g
is a vector.

This subroutine generates the conjugate gradient iterates for
the equivalent problem

  min { Q(w) : || w || <= delta },

where Q is the quadratic defined by

  Q(w) = q(s),        w = L'*s.

Termination occurs if the conjugate gradient iterates leave
the trust regoin, a negative curvature direction is generated,
or one of the following two convergence tests is satisfied.

Convergence in the original variables:

  || grad q(s) || <= tol

Convergence in the scaled variables:

  || grad Q(w) || <= stol

Note that if w = L'*s, then L*grad Q(w) = grad q(s).

MINPACK-2 Project. March 1999.
Argonne National Laboratory.
Chih-Jen Lin and Jorge J. More'.

August 1999

Corrected documentation for l, ldiag, lcol_ptr, and lrow_ind.

February 2001

We now set iters = 0 in the special case g = 0.
"""
function dtrpcg(n,A,g,delta,L,
                tol,stol,itermax,w,
                p,q,r,t,z)
    zero = 0.0
    one = 1.0

    # Initialize the iterate w and the residual r.
    fill!(w, 0)

    # Initialize the residual t of grad q to -g.
    # Initialize the residual r of grad Q by solving L*r = -g.
    # Note that t = L*r.
    dcopy(n,g,1,t,1)
    dscal(n,-one,t,1)
    dcopy(n,t,1,r,1)
    dnsol(n, L, r)

    # Initialize the direction p.
    dcopy(n,r,1,p,1)

    # Initialize rho and the norms of r and t.
    rho = ddot(n,r,1,r,1)
    rnorm0 = sqrt(rho)

    # Exit if g = 0.
    iters = 0
    if rnorm0 == zero
        iters = 0
        info = 1
        return info, iters
    end

    for iters=1:itermax

        # Note:
        # Q(w) = 0.5*w'Bw + h'w, where B=L^{-1}AL^{-T}, h=L^{-1}g.
        # Then p'Bp = p'L^{-1}AL^{-T}p = p'L^{-1}Az = p'q.
        # alpha = r'r / p'Bp.

        dcopy(n,p,1,z,1)
        dtsol(n, L, z)

        # Compute q by solving L*q = A*z and save L*q for
        # use in updating the residual t.
        dssyax(n, A, z, q)
        dcopy(n,q,1,z,1)
        dnsol(n, L, q)

        # Compute alpha and determine sigma such that the trust region
        # constraint || w + sigma*p || = delta is satisfied.
        ptq = ddot(n,p,1,q,1)
        if ptq > zero
            alpha = rho/ptq
        else
            alpha = zero
        end
        sigma = dtrqsol(n,w,p,delta)

        # Exit if there is negative curvature or if the
        # iterates exit the trust region.

        if (ptq <= zero) || (alpha >= sigma)
            daxpy(n,sigma,p,1,w,1)
            if ptq <= zero
                info = 3
            else
                info = 4
            end

            return info, iters
        end

        # Update w and the residuals r and t.
        # Note that t = L*r.

        daxpy(n,alpha,p,1,w,1)
        daxpy(n,-alpha,q,1,r,1)
        daxpy(n,-alpha,z,1,t,1)

        # Exit if the residual convergence test is satisfied.

        rtr = ddot(n,r,1,r,1)
        rnorm = sqrt(rtr)
        tnorm = sqrt(ddot(n,t,1,t,1))

        if tnorm <= tol
            info = 1
            return info, iters
        end

        if rnorm <= stol
            info = 2
            return info, iters
        end

        # Compute p = r + beta*p and update rho.
        beta = rtr/rho
        dscal(n,beta,p,1)
        daxpy(n,one,r,1,p,1)
        rho = rtr
    end

    iters = itermax
    info = 5
    return info, iters
end

@inline function dtrpcg(n::Int, A::CuDeviceArray{Float64,2},
                        g::CuDeviceArray{Float64,1}, delta::Float64,
                        L::CuDeviceArray{Float64,2},
                        tol::Float64, stol::Float64, itermax::Int,
                        w::CuDeviceArray{Float64,1},
                        p::CuDeviceArray{Float64,1},
                        q::CuDeviceArray{Float64,1},
                        r::CuDeviceArray{Float64,1},
                        t::CuDeviceArray{Float64,1},
                        z::CuDeviceArray{Float64,1})
  zero = 0.0
  one = 1.0

  # Initialize the iterate w and the residual r.
  fill!(w, 0)

  # Initialize the residual t of grad q to -g.
  # Initialize the residual r of grad Q by solving L*r = -g.
  # Note that t = L*r.
  dcopy(n,g,1,t,1)
  dscal(n,-one,t,1)
  dcopy(n,t,1,r,1)
  dnsol(n, L, r)

  # Initialize the direction p.
  dcopy(n,r,1,p,1)

  # Initialize rho and the norms of r and t.
  rho = ddot(n,r,1,r,1)
  rnorm0 = sqrt(rho)

  # Exit if g = 0.
  iters = 0
  if rnorm0 == zero
    iters = 0
    info = 1
    return info, iters
  end

  for iters=1:itermax

    # Note:
    # Q(w) = 0.5*w'Bw + h'w, where B=L^{-1}AL^{-T}, h=L^{-1}g.
    # Then p'Bp = p'L^{-1}AL^{-T}p = p'L^{-1}Az = p'q.
    # alpha = r'r / p'Bp.

    dcopy(n,p,1,z,1)
    dtsol(n, L, z)

    # Compute q by solving L*q = A*z and save L*q for
    # use in updating the residual t.
    dssyax(n, A, z, q)
    dcopy(n,q,1,z,1)
    dnsol(n, L, q)

    # Compute alpha and determine sigma such that the trust region
    # constraint || w + sigma*p || = delta is satisfied.
    ptq = ddot(n,p,1,q,1)
    if ptq > zero
      alpha = rho/ptq
    else
      alpha = zero
    end
    sigma = dtrqsol(n,w,p,delta)

    # Exit if there is negative curvature or if the
    # iterates exit the trust region.

    if (ptq <= zero) || (alpha >= sigma)
      daxpy(n,sigma,p,1,w,1)
      if ptq <= zero
        info = 3
      else
        info = 4
      end

      return info, iters
    end

    # Update w and the residuals r and t.
    # Note that t = L*r.

    daxpy(n,alpha,p,1,w,1)
    daxpy(n,-alpha,q,1,r,1)
    daxpy(n,-alpha,z,1,t,1)

    # Exit if the residual convergence test is satisfied.

    rtr = ddot(n,r,1,r,1)
    rnorm = sqrt(rtr)
    tnorm = sqrt(ddot(n,t,1,t,1))

    if tnorm <= tol
      info = 1
      return info, iters
    end

    if rnorm <= stol
      info = 2
      return info, iters
    end

    # Compute p = r + beta*p and update rho.
    beta = rtr/rho
    dscal(n,beta,p,1)
    daxpy(n,one,r,1,p,1)
    rho = rtr
  end

  iters = itermax
  info = 5
  return info, iters
end


text:
"""
    TruncKernel(P::Integer, logweight)
    TruncKernel(ps::NTuple{N,Int64}, logweight) where N

Structure to hold precomputed normalization constants of Herglotz polynomials.

This is a convenience structure to hold precomputed normalization constants
[`αp`](@ref) of Herglotz polynomials which are expensive to compute.

All the normalized Herglotz polynomials ``a_p`` (see [`ap`](@ref)) for ``p`` in
the argument `ps` (noted ``\\mathcal{P}``) are precomputed and stored in the
attribute `as` which is a `Tuple`.
The `logweight` function is used to compute the normalization constants.
If only an `Integer` ``P`` is given as first argument, the terms in the kernel
are the ``a_p`` functions for ``p`` ranging from ``-P`` to ``P``.

A kernel can be evaluated at `(x,y)` where `x=(ζx,φx)` and `y=(ζy,φy)` are
points in the complex strip.

```math
(\\mathbf{x},\\mathbf{y}) ↦ K(\\mathbf{x}, \\mathbf{y})
= \\sum_{p \\in \\mathcal{P}} \\overline{a_{p}(\\mathbf{x})} a_{p}(\\mathbf{y}).
```
"""
struct TruncKernel{N}
    ps::NTuple{N,Int64}
    logweight
    as::NTuple{N} # Tuple containing the a_p functions for p in ps
end
function TruncKernel(ps::NTuple{N,Int64}, logweight) where N
    # Computing the weights
    αs = [αp(p, logweight) for p in ps]
    # ãp's Herglotz polynomials
    ãs = [ãp(p) for p in ps]
    # Normalized ap's Herglotz polynomials
    as = [(ζ,φ) -> α * ã(ζ,φ) for (α,ã) in zip(αs, ãs)]
    return TruncKernel(ps, logweight, Tuple(as))
end
TruncKernel(P::Int64, logweight) = TruncKernel(Tuple(-P:P), logweight)
(K::TruncKernel)(x, y) = sum([ajoint(a(x...))*a(y...) for a in K.as])

"""
    kernel_diagonal(K::TruncKernel)

Closure that defines the evaluation function of the diagonal of a
[`TruncKernel`](@ref).

```math
\\mathbf{y} ↦ K(\\mathbf{y}, \\mathbf{y})
= \\sum_{p \\in \\mathcal{P}} |a_{p}(\\mathbf{y})|^2,
\\qquad\\mathbf{y}=(ζ,φ).
```
"""
function kernel_diagonal(K::TruncKernel)
    return (ζ, φ) -> sum([abs(a(ζ, φ))^2 for a in K.as])
end

"""
    probabilitydensityfunction(K::TruncKernel)

Probability density function defined by a [`TruncKernel`](@ref).

```math
(ζ, φ) ↦ \\frac{1}{|\\mathcal{P}|} K(\\mathbf{y}, \\mathbf{y})
= \\frac{1}{|\\mathcal{P}|} \\sum_{p \\in \\mathcal{P}} |a_{p}(\\mathbf{y})|^2,
\\qquad\\mathbf{y}=(ζ,φ).
```

Notice that it is indeed a PDF since all the ``a_p`` functions are orthonormal.
"""
function probabilitydensityfunction(K::TruncKernel)
    return (ζ, φ) -> kernel_diagonal(K)(ζ, φ) / length(K.ps)
end
function probabilitydensityfunction_weighted(K::TruncKernel)
    return (ζ, φ) -> probabilitydensityfunction(K)(ζ, φ) * exp(2 * K.logweight(ζ))
end

"""
    cumulativedensityfunction(K::TruncKernel)

Cumulative density function defined by a [`TruncKernel`](@ref).

The probability density function is provided by the function
[`probabilitydensityfunction`](@ref).

```math
ζ ↦ \\frac{2π}{|\\mathcal{P}|} \\int_{-\\infty}^{ζ} K(ζ,ζ) \\mathrm{d}ζ
= \\frac{2π}{|\\mathcal{P}|} \\int_{-\\infty}^{ζ} \\sum_{p \\in \\mathcal{P}} |a_{p}|^2(ζ) \\mathrm{d}ζ,
```
where, abusing notations, we used ``K(ζ,ζ) = K(\\mathbf{y},\\mathbf{y})``
and ``|a_{p}|^2(ζ) = |a_{p}|^2(\\mathbf{y})`` for any ``\\mathbf{y} = (ζ,φ)``
since they both are quantities independent of ``φ``.

The implementation relies on the convenience functions
[`ϵsupport`](@ref) and [`adaptive_G_quad`](@ref).

!!! danger "Beware!"
    The implementation *assumes* that the probability density function is
    constant with respect to the second variable ``φ``.
    This is the reason why the resulting CDF is a univariate function.
"""
function cumulativedensityfunction(K::TruncKernel; tol=1e-12)
    pdf = ζ -> probabilitydensityfunction_weighted(K)(ζ, 0)
    # Chunking the support of the integrand for some h-adaptivity
    ϵs = pdf(0) .* 10. .^ (-12:3:0)
    supps = sort(vcat(0, [collect(ϵsupport(pdf, ϵ)) for ϵ in ϵs]...))
    as = supps[1:end-1]
    bs = supps[2:end]
    # CDF evaluation on whole real line and creation of quadrature rule
    cdf∞ = Float64(0)
    xs = Vector{Float64}[]; ws = Vector{Float64}[];
    for (a, b) in zip(as, bs)
        val, _, q = adaptive_G_quad(pdf; a=a, b=b, tol=tol)
        cdf∞ += 2π * val # using that CDF constant w.r.t φ ∈ [0,2π]
        x, w = gausslegendre(q)
        push!(xs, x); push!(ws, w)
    end
    # Sanity checks
    if abs(supps[1] + supps[end]) > 1e-12
        @warn "PDF ϵ-support = [$(supps[1]),$(supps[end])] not symmetric."
    end
    if abs(cdf∞ - 1) > 1e-8
        @warn "PDF not normalized ∫pdf = $(cdf∞)."
    end
    # CDF evaluation function
    function cdf(ζ)
        c = Float64(0)
        for (a, b, x, w) in zip(as, bs, xs, ws)
            if a < ζ
                b = min(b, ζ)
                c += 2π * sum((b-a)/2 .* w .* pdf.((b-a)/2 .* x .+ (a+b)/2))
            end
        end
        return c
    end
    return cdf
end

"""
    Sampler(K::TruncKernel)

Structure to compute sampling nodes and weights.

The nodes and weights are sampled according to the probability density function
defined by a [`TruncKernel`](@ref).

!!! note "Note!"
    The implementation uses the secant method as root finding algorithm to
    compute the pre-image of the CDF.
    There is probably some room for improvement in the implementation,
    specially since we know that the first derivative of the CDF is the PDF.
    The Newton-Raphson method fails to converge for instance.
"""
struct Sampler
    K::TruncKernel
    pdf
    cdf
    supp
end
function Sampler(K::TruncKernel)
    pdf = ζ -> probabilitydensityfunction_weighted(K)(ζ, 0)
    cdf = cumulativedensityfunction(K)
    supp = ϵsupport(pdf, pdf(0) * 10. ^ -12)
    return Sampler(K, pdf, cdf, supp)
end

"""
    inversion(smpl::Sampler, u)

Computes the pre-image ``ζ`` of `u` under the cumulative density function.

This function allows to perform *Inversion Transform Sampling*.

This is a univariate inversion function because the cdf is constant with
respect to the other variable ``φ``.
"""
function inversion(smpl::Sampler, u)
    f = x -> smpl.cdf(x) - u # Objective function
    ζ = begin
        try
            find_zero((f, smpl.pdf), 0, Roots.Secant())
        catch # Fall back to slower but robust method if not converging
            find_zero((f, smpl.pdf), smpl.supp)
        end
    end
    return ζ
end

"""
    weight(smpl::Sampler, node)

Computes the weight associated to a node ``(ζ,φ)``.

The weight at ``\\mathbf{y}=(ζ,φ)`` is defined by
```math
ω(\\mathbf{y}) := \\sqrt{\\frac{|\\mathcal{P}|}{\\sum_{p \\in \\mathcal{P}} |a_{p}(\\mathbf{y})|^2}},
\\qquad\\mathbf{y}=(ζ,φ).
```
"""
function weight(smpl::Sampler, node)
    return 1 / sqrt(probabilitydensityfunction(smpl.K)(node...))
end

"""
    random_sampling(smpl::Sampler)
    random_sampling(smpl::Sampler, M)

Draw `M` random samples according to the distribution stored in `smpl`.
"""
function random_sampling(smpl::Sampler)
    node = (inversion(smpl, rand()), 2π * rand())
    wght = weight(smpl, node)
    return node, wght
end
function random_sampling(smpl::Sampler, M)
    xw = [random_sampling(smpl) for _ in 1:M]
    nodes = [x for (x,_) in xw]
    wghts = [w for (_,w) in xw]
    return nodes, wghts
end

"""
    uniform_sampling(smpl::Sampler, M)

Draw `M` deterministic samples according to the distribution stored in `smpl`.

This has a tensor-like structure, with the same number of samples in both
directions.
"""
function uniform_sampling(smpl::Sampler, M)
    Ms = Integer(ceil(sqrt(M)))
    φs = range(0, stop=2π, length=Ms+1)[1:end-1]
    uζs = range(0, stop=1, length=Ms+1)[1:end-1]
    uζs = collect(uζs) .+ uζs[2]/2
    nodes = [(inversion(smpl, u), φ) for u in uζs, φ in φs][:]
    wghts = weight.(Ref(smpl), nodes)
    return nodes, wghts
end

"""
    sobol_sampling(smpl::Sampler, M)

Draw `M` quasi-random samples according to the distribution stored in `smpl`.

This function uses Sobol sequences computed according to the package
[QuasiMonteCarlo.jl](https://github.com/SciML/QuasiMonteCarlo.jl).
"""
function sobol_sampling(smpl::Sampler, M)
    s = QuasiMonteCarlo.sample(M,[0,0],[1,2π],SobolSample())
    ζs = s[1,:]
    φs = s[2,:]
    nodes = [(inversion(smpl, ζ), φ) for (ζ, φ) in zip(ζs, φs)][:]
    wghts = weight.(Ref(smpl), nodes)
    return nodes, wghts
end

max_stars_repo_name: EmileParolin/STrAW

max_issues_repo_name: EmileParolin/STrAW

max_forks_repo_name: EmileParolin/STrAW


text:
# first example 2D

using ApproxManifoldProducts
using Test

const AMP = ApproxManifoldProducts

Λ1 = 1.0
Λ2 = 0.25
Λ3 = 5/4.0

μ1 = 1.0
μ2 = 4.0
μ3 = 2.4

@testset "basic linear 1D find mu and Lambdas Gaussian product test..." begin

Lambdas = [Λ1; Λ2]
mus = [μ1; μ2]

resid2DLinear(0.0, mus, Lambdas)

resid2DLinear(8/5, mus, Lambdas)

μ = get2DMu(mus, Lambdas)
Λ = get2DLambda(Lambdas)

@test abs(μ[1] - 8/5) < 1e-10

@test abs(Λ - 5/4) < 1e-10

end

## These work, but we are not sure about how to get the scale for product of more than 2 elements

# preS = nullspace(Lambdas*(Lambdas'))
#
# sc = sum(abs.(preS)) / abs(μ1-μ2)
#
# mu = vec(preS / sc)
# Λ = getΛ(Lambdas)
#
#
# u,s,v = svd(Lambdas*(Lambdas'))
#
# s[1,1]*u[:,2]

@testset "test 1D with 3 components on basic Euclidean line..." begin

Lambdas = [Λ1; Λ2; Λ3]
mus = [μ1; μ2; μ3]

μ = get2DMu(mus, Lambdas)
Λ = get2DLambda(Lambdas)

@test abs(μ[1] - 2.0) < 1e-10

@test abs(Λ - 10/4) < 1e-10

end

#


text:
#!/usr/bin/env julia

# This script will gather coverage information with the currently active julia,
# and will process it with Coverage.jl using the system-wide Julia at /usr/bin
# (this for compatibility reasons, but might break if .cov parsing changes).

cmd = Base.julia_cmd()

system_cmd = "/usr/bin/julia"
system_env = copy(ENV)
for (k,v) in system_env
    if startswith(k, "JULIA_")
        delete!(system_env, k)
    end
end

# make sure Coverage.jl is available on the clean Julia
run(setenv(`$system_cmd -E "using Coverage"`, system_env))

#
# Measure
#

dir = dirname(@__FILE__)
root = "$dir/../"
cd(root)

run(`$cmd --compilecache=no --inline=no --code-coverage=user "test/runtests.jl"`)

ENV["DEBUG"] = 1
run(`$cmd --compilecache=no --inline=no --code-coverage=user "test/runtests.jl"`)

ENV["TRACE"] = 1
run(`$cmd --compilecache=no --inline=no --code-coverage=user "test/runtests.jl"`)

#
# Submit (with the system Julia)
#

let code = """
    using Coverage

    coverage = process_folder()

    codecov = haskey(ENV, "USE_CODECOV")
    lcov    = haskey(ENV, "USE_LCOV")
    if !codecov && !lcov
        codecov = true
    end

    if codecov
        ENV["REPO_TOKEN"] = "d8b27424-577e-4851-a490-9e5459b5d787"
        Codecov.submit_token(coverage)
    end

    if lcov
        isdir("test/coverage") || mkdir("test/coverage")
        LCOV.writefile("test/coverage/lcov.info", coverage)
        run(`genhtml test/coverage/lcov.info -o test/coverage/html`)
        println("Done! Open your browser at file://$dir/coverage/html/index.html")
    end

    clean_folder(".")
    """

    run(setenv(`$system_cmd -E "$code"`, system_env))
end


text:
export iauFw2xy
"""
CIP X,Y given Fukushima-Williams bias-precession-nutation angles.

This function is part of the International Astronomical Union's
SOFA (Standards Of Fundamental Astronomy) software collection.

Status:  support function.

Given:
   gamb     double    F-W angle gamma_bar (radians)
   phib     double    F-W angle phi_bar (radians)
   psi      double    F-W angle psi (radians)
   eps      double    F-W angle epsilon (radians)

Returned:
   x,y      double    CIP unit vector X,Y

Notes:

   1. Naming the following points:

         e = J2000.0 ecliptic pole,
         p = GCRS pole
         E = ecliptic pole of date,
   and   P = CIP,

   the four Fukushima-Williams angles are as follows:

      gamb = gamma = epE
      phib = phi = pE
      psi = psi = pEP
      eps = epsilon = EP

   2. The matrix representing the combined effects of frame bias,
   precession and nutation is:

      NxPxB = R_1(-epsA).R_3(-psi).R_1(phib).R_3(gamb)

   The returned values x,y are elements [2][0] and [2][1] of the
   matrix.  Near J2000.0, they are essentially angles in radians.

Called:
   iauFw2m      F-W angles to r-matrix
   iauBpn2xy    extract CIP X,Y coordinates from NPB matrix

Reference:

   Hilton, J. et al., 2006, Celest.Mech.Dyn.Astron. 94, 351

This revision:  2013 September 2

SOFA release 2018-01-30

Copyright (C) 2018 IAU SOFA Board.  See notes at end.
"""

# void iauFw2xy(double gamb, double phib, double psi, double eps,
#               double *x, double *y)

function iauFw2xy(gamb::Real, phib::Real, psi::Real, eps::Real)
   ref_x = Ref{Float64}(0.0)
   ref_y = Ref{Float64}(0.0)

   ccall((:iauFw2xy, libsofa_c), Cvoid,
         (Cdouble, Cdouble, Cdouble, Cdouble,
         Ref{Cdouble}, Ref{Cdouble}),
          convert(Float64, gamb), convert(Float64, phib),
          convert(Float64, psi), convert(Float64, eps),
          ref_x, ref_y)

   return ref_x[], ref_y[]
end


text:
prediction_device = "cpu";
u_nominal_cand = append!([u_nominal_base],
                         [round.([a*cos(deg2rad(θ)), a*sin(deg2rad(θ))], digits=5)
                          for a = [3.] for θ = 0.:45.:(360. - 45.)])            # nominal control candidate value [ax, ay] [m/s^2]
nominal_search_depth = 4;
prediction_steps = 4;
dtr = 0.4;
tcalc = 0.4;
dtexec = [0.0];
constraint_time = nothing;


text:
module PkgAuthentication

using Downloads, Random, JSON, Pkg

## abstract state types

abstract type State end

step(state::State) =
    throw(ArgumentError("no step function defined for this state: `$(state)`"))

struct Success <: State
    token::Dict{String, Any}
end

abstract type Failure <: State end

## authentication state machine

"""
    authenticate(pkgserver::AbstractString)

Starts browser based pkg-server authentication (blocking).

`pkgserver` must be a URL pointing to a server that provides the `/pkgserver/challenge`,
`/pkgserver/response`, and `/pkgserver/claimtoken` endpoints.
"""
function authenticate(
    server::AbstractString;
    force::Bool = false,
    tries::Integer = 1,
)::Union{Success, Failure}
    server = strip(server, '/')

    local state
    for i in 1:tries
        initial = force ? NoAuthentication : NeedAuthentication

        state = initial(server)
        try
            while !(isa(state, Success) || isa(state, Failure))
                state = step(state)
            end
        catch err
            state = GenericError((err, catch_backtrace()))
        end
        if state isa Success
            continue
        end
    end

    return state
end

## initial states

struct NeedAuthentication <: State
    server::String
end
function step(state::NeedAuthentication)::Union{HasToken, NoAuthentication}
    path = token_path(state.server)
    if isfile(path)
        toml = Pkg.TOML.parsefile(path)
        if is_token_valid(toml)
            return HasToken(state.server, mtime(path), toml)
        else
            return NoAuthentication(state.server)
        end
    else
        return NoAuthentication(state.server)
    end
end

struct NoAuthentication <: State
    server::String
end
function step(state::NoAuthentication)::Union{RequestLogin, Failure}
    challenge = Random.randstring(32)
    output = IOBuffer()
    response = request(
        string(state.server, "/challenge"),
        method = "POST",
        input = IOBuffer(challenge),
        output = output,
        throw = false,
    )
    if response isa Response && response.status == 200
        return RequestLogin(state.server, challenge, String(take!(output)))
    else
        return HttpError(response)
    end
end

## intermediate states

struct HasToken <: State
    server::String
    mtime::Float64
    token::Dict{String, Any}
end
function step(state::HasToken)::Union{NeedRefresh, Success}
    expiry = get(state.token, "expires_at", get(state.token, "expires", 0))
    expires_in = get(state.token, "expires_in", Inf)
    if min(expiry, expires_in + state.mtime) < time()
        return NeedRefresh(state.server, state.token)
    else
        return Success(state.token)
    end
end

struct NeedRefresh <: State
    server::String
    token::Dict{String, Any}
end
function step(state::NeedRefresh)::Union{HasNewToken, NoAuthentication, Failure}
    refresh_token = state.token["refresh_token"]
    headers = ["Authorization" => "Bearer $refresh_token"]
    output = IOBuffer()
    response = request(
        state.token["refresh_url"],
        method = "GET",
        headers = headers,
        output = output,
        throw = false,
    )
    # errors are recoverable by just getting a new token:
    if response isa Response && response.status == 200
        try
            body = JSON.parse(String(take!(output)))
            if haskey(body, "token")
                return HasNewToken(state.server, body["token"])
            end
        catch err
            @debug "invalid body received while refreshing token" exception=(err, catch_backtrace())
        end
        return NoAuthentication(state.server)
    else
        @debug "request for refreshing token failed" exception=(err, catch_backtrace())
        return NoAuthentication(state.server)
    end

    return GenericError(response)
end

struct HasNewToken <: State
    server::String
    token::Dict{String, Any}
    tries::Int
end
HasNewToken(server, token) = HasNewToken(server, token, 0)
function step(state::HasNewToken)::Union{HasNewToken, Success, Failure}
    if state.tries >= 3
        return GenericError("Failed to write token.")
    end
    path = token_path(state.server)
    mkpath(dirname(path))
    try
        open(path, "w") do io
            Pkg.TOML.print(io, state.token)
        end
        if Pkg.TOML.parsefile(path) == state.token
            return Success(state.token)
        else
            return HasNewToken(state.server, state.token, 0)
        end
    catch err
        @debug "failed to write token" exception=(err, catch_backtrace())
        return GenericError("Failed to write token.")
    end
end

struct RequestLogin <: State
    server::String
    challenge::String
    response::String
end
function step(state::RequestLogin)::Union{ClaimToken, Failure}
    success = open_browser(string(state.server, "/response?", state.response))
    if success
        return ClaimToken(state.server, state.challenge, state.response)
    else # this can only happen for the browser hook
        return GenericError("Failed to execute open_browser hook.")
    end
end

struct ClaimToken <: State
    server::String
    challenge::String
    response::String
    expiry::Float64
    start_time::Float64
    timeout::Float64
    poll_interval::Float64
    failures::Int
    max_failures::Int
end
ClaimToken(server, challenge, response, expiry = Inf, failures = 0) =
    ClaimToken(server, challenge, response, expiry, time(), 180, 2, failures, 10)

function step(state::ClaimToken)::Union{ClaimToken, HasNewToken, Failure}
    if time() > state.expiry || (time() - state.start_time)/1e6 > state.timeout # server-side or client-side timeout
        return GenericError("Timeout waiting for user to authenticate in browser.")
    end

    if state.failures > state.max_failures
        return GenericError("Too many failed attempts.")
    end

    sleep(state.poll_interval)

    output = IOBuffer()
    data = """{ "challenge": "$(state.challenge)", "response": "$(state.response)" }"""
    response = request(
        string(state.server, "/claimtoken"),
        method = "POST",
        input = IOBuffer(data),
        output = output,
        throw = false,
    )

    if response isa Response && response.status == 200
        body = try
            JSON.parse(String(take!(output)))
        catch err
            return ClaimToken(state.server, state.challenge, state.response, state.expiry, state.start_time, state.timeout, state.poll_interval, state.failures + 1, state.max_failures)
        end

        if haskey(body, "token")
            return HasNewToken(state.server, body["token"])
        elseif haskey(body, "expiry") # time at which the response/challenge pair will expire on the server
            return ClaimToken(state.server, state.challenge, state.response, body["expiry"], state.start_time, state.timeout, state.poll_interval, state.failures, state.max_failures)
        else
            return ClaimToken(state.server, state.challenge, state.response, state.expiry, state.start_time, state.timeout, state.poll_interval, state.failures + 1, state.max_failures)
        end
    else
        return HttpError(response)
    end

    return state
end

## errors

struct GenericError{T} <: Failure
    reason::T
end

abstract type HttpError <: Failure end

struct ClientError{T} <: HttpError
    reason::T
end

struct ServerError{T} <: HttpError
    reason::T
end

struct OtherHttpError{T} <: HttpError
    reason::T
end

function HttpError(response::Downloads.Response)::HttpError
    if 400 <= response.status < 500
        return ClientError(response)
    elseif 500 <= response.status < 600
        return ServerError(response)
    else
        return OtherHttpError(response)
    end
end

function HttpError(response::Downloads.RequestError)::HttpError
    return ClientError(response.message)
end

## utils
is_new_auth_mechanism() =
    isdefined(Pkg, :PlatformEngines) &&
    isdefined(Pkg.PlatformEngines, :get_server_dir) &&
    isdefined(Pkg.PlatformEngines, :register_auth_error_handler)

is_token_valid(toml) =
    get(toml, "id_token", nothing) isa AbstractString &&
    get(toml, "refresh_token", nothing) isa AbstractString &&
    get(toml, "refresh_url", nothing) isa AbstractString &&
    (get(toml, "expires_at", nothing) isa Union{Integer, AbstractFloat} ||
     get(toml, "expires", nothing) isa Union{Integer, AbstractFloat})

# This implementation of `get_server_dir` handles `domain:port` servers correctly (fixed on Pkg#master but not in older Julia versions).
function get_server_dir(url::AbstractString, server=Pkg.pkg_server())
    server === nothing && return
    url == server || startswith(url, "$server/") || return
    m = match(r"^\w+://(?:[^\\/@]+@)?([^\\/:]+)(?:$|/|:)", server)
    if m === nothing
        @warn "malformed Pkg server value" server
        return
    end
    joinpath(Pkg.depots1(), "servers", m.captures[1])
end

function token_path(url::AbstractString)
    if is_new_auth_mechanism()
        server_dir = get_server_dir(url)
        if server_dir !== nothing
            return joinpath(server_dir, "auth.toml")
        end
    end
    # older auth mechanism uses a different token location
    default = joinpath(Pkg.depots1(), "token.toml")
    get(ENV, "JULIA_PKG_TOKEN_PATH", default)
end

const OPEN_BROWSER_HOOK = Ref{Union{Base.Callable, Nothing}}(nothing)

function register_open_browser_hook(f::Base.Callable)
    if !hasmethod(f, Tuple{AbstractString})
        throw(ArgumentError("Browser hook must be a function taking a single URL string argument."))
    end
    OPEN_BROWSER_HOOK[] = f
end

function clear_open_browser_hook()
    OPEN_BROWSER_HOOK[] = nothing
end

function open_browser(url::AbstractString)
    @debug "opening auth in browser"
    printstyled(color = :yellow, bold = true,
        "Authentication required: please authenticate in browser.\n")
    printstyled(color = :yellow, """
    The authentication page should open in your browser automatically, but you may need to switch to the opened window or tab. If the authentication page is not automatically opened, you can authenticate by manually opening the following URL: """)
    printstyled(color = :light_blue, "$url\n")
    try
        if OPEN_BROWSER_HOOK[] !== nothing
            try
                OPEN_BROWSER_HOOK[](url)
                return true
            catch err
                @debug "error executing browser hook" exception=(err, catch_backtrace())
                return false
            end
        elseif Sys.iswindows()
            run(`cmd /c "start $url"`)
        elseif Sys.isapple()
            run(`open $url`)
        elseif Sys.islinux() || Sys.isbsd()
            run(`xdg-open $url`)
        end
    catch err
        @warn "There was a problem opening the authentication URL in a browser, please try opening this URL manually to authenticate." url, error = err
    end
    return true
end

"""
    install(server = nothing; maxcount = 3)

Install Pkg authentication hooks for `Pkg.pkg_server()`.

Will instead use `server` (and set the `JULIA_PKG_SERVER` environment variable accordingly) if given.
`maxcount` determines the number of retries.

Julia versions older than 1.4 do not support authentication hooks, so this function will force
authentication right away.
"""
function install(server = nothing; maxcount = 3)
    if server !== nothing
        ENV["JULIA_PKG_SERVER"] = server
    end
    server = string(Pkg.pkg_server())

    failed_auth_count = 0

    authenticate = (url, svr, err) -> begin
        ret = PkgAuthentication.authenticate(string(svr, "/auth"), tries = 2)
        if ret isa PkgAuthentication.Success
            failed_auth_count = 0
            @debug "Authentication successful."
        else
            failed_auth_count += 1
            if failed_auth_count >= maxcount
                printstyled(color = :red, bold = true, "\nAuthentication failed.\n\n")
                return true, false # handled, but Pkg shouldn't try again
            else
                printstyled(color = :yellow, bold = true, "\nAuthentication failed. Retrying...\n\n")
            end
        end
        return true, true # handled, and Pkg should try again now
    end

    register_auth_handler = (pkgserver::Union{Regex, AbstractString}) -> begin
        return Pkg.PlatformEngines.register_auth_error_handler(pkgserver, authenticate)
    end

    if PkgAuthentication.is_new_auth_mechanism()
        register_auth_handler(server)
    else
        # old Julia versions don't support auth hooks, so let's authenticate now and be done with it
        authenticate(server)
    end
end

end # module


text:
module MAGMA

export gesvd!, libmagma#,magmaInit,magmaFinalize

include("common.jl")

include("utilities/Utilities.jl")
include("dense/Dense.jl")

end  # modul MAGMA


text:
@inline function safe_regress!(coef, XX, X, W, F_)
    try
        coef .= XX\(X'F_)
    catch
        @warn "Regression failed"
        coef .= 0.0
        coef[1] = dot(W, F_)
    end
    nothing
end

@inline function intercept_var_factor(XWX::Matrix{FT}) where {FT <: AbstractFloat}
    try
        max(zero(FT), inv(XWX)[1,1])
    catch
        FT(Inf)
    end
end

"""
    est = abc_regress(out, f, tol; kernel=out.cutoff.fun)

Calculate post-correction estimates for ABC-MCMC output using regression
correction of Beaumont (2002), and producing approximate confidence
intervals similar to `abc_postprocess`

# Arguments
- `out`: Output of the `abc_mcmc` function (with `record_summaries=true`)
- `f`: Function of interest.
- `tol`: Vector of tolerance values for which estimates are calculated.
- `kernel`: Kernel function used in regression correction.
- `est`: Estimates which may be inspected by `ABCPlots.plot_abc(est)`
"""
function abc_regress(out, f::Function, tol::T;
    kernel::Function=out.cutoff.fun,
    normal_quantile=FT(1.96),
    iact=nothing) where {FT <: AbstractFloat, T <: AbstractVector{FT}}
    if typeof(out.Summary) == Missing
        error("Summary statistics not recorded; please re-run abc_mcmc with 'record_summaries=true'")
    end
    F = eval_testfunction(out, f)
    (d_f,n) = size(F)
    n_tol = length(tol)
    E = Matrix{FT}(undef, d_f, n_tol)
    S = Matrix{FT}(undef, d_f, n_tol)
    ci_L = Matrix{FT}(undef, d_f, n_tol)
    ci_U = Matrix{FT}(undef, d_f, n_tol)

    d_s = size(out.Summary, 1)
    X = Matrix{FT}(undef, n, d_s+1)
    WX = Matrix{FT}(undef, n, d_s+1)
    W = Vector{FT}(undef, n)
    F_ = Vector{FT}(undef, n)
    phi_0 = out.cutoff.(out.Dist)
    invalid = phi_0 .== zero(FT)

    # Construct the regression data matrix X:
    for i in 1:n
        X[i, 1] = one(FT)
        X[i, 2:end] .= out.Summary[:,i] .- out.s_obs
    end

    # Calculate the integrated autocorrelation for
    # regression-corrected samples (using all!)
    tau0 = Vector{FT}(undef, d_f)
    XX = X'*X
    W .= one(FT)/n

    coef = Vector{FT}(undef, d_s+1)

    for j in 1:d_f
        F_ .= F[j,:]
        safe_regress!(coef, XX, X, W, F_)
        F_ .= F[j,:]
        F_ -= X*coef
        tau0[j] = iact(F_)
    end

    for i in 1:n_tol
        tol_ = tol[i]
        # Calculate unnormalised weights
        map!(x -> kernel(x/tol_), W, out.Dist)
        W .= W./phi_0
        W[invalid] .= zero(FT)

        # Normalise (and warn if cannot)
        Ws = sum(W)
        if Ws == zero(FT)
            @warn string("No matching observations for tolerance ", tol_)
            continue
        end
        W /= Ws

        # Calculate weighted regression
        WX .= X
        @inbounds for j in 1:n
            WX[j,:] *= W[j]
        end
        # The 'projection matrix' for tolerance tol_
        XWX = X'*WX
        for j in 1:d_f
            F_ .= F[j,:]
            # Calculate the regression coefficients:
            safe_regress!(coef, XWX, WX, W, F_)
            #coef = XWX\(WX'F_)
            # The mean estimate is simply the intercept:
            alpha = coef[1]
            E[j,i] = alpha
            # F_ = -(regression-corrected values)
            mul!(F_, X, coef)
            F_ -= F[j,:]
            # Calculate S:
            s_ = zero(FT)
            @inbounds for k in 1:n
                s_ += W[k]^2 * F_[k]^2
            end
            s_ *= intercept_var_factor(XWX)
            S[j,i] = s_
            # Confidence bounds:
            dx = normal_quantile*sqrt(s_*tau0[j])
            ci_L[j,i] = alpha - dx
            ci_U[j,i] = alpha + dx
        end
    end
    (E=E, S=S, eps=tol, ci_L=ci_L, ci_U=ci_U, normal_quantile=normal_quantile)
end


text:
## TODO: Whenever I pass a type (e.g. `Int`), is it better to pass `R`? #src

# If the polynomial degree is < 0, we use an `EmptyPolySystem`:

"Drop-In Alternative to `StaticPolynomials.PolynomialSystem` when there are no outputs."
struct EmptyPolySystem{Nvars} end
Base.length(::EmptyPolySystem) = 0
StaticPolynomials.npolynomials(::EmptyPolySystem) = 0

"Evaluate for usual vector input. (Scalar input also supported, there are no checks)"
StaticPolynomials.evaluate(:: EmptyPolySystem, :: Union{R, Vector{R}}) where R<:Real = Int[]
"Evaluate for sized input."
StaticPolynomials.evaluate(:: EmptyPolySystem{Nvars}, :: StaticVector ) where {Nvars} = SVector{0,Int}()
(p :: EmptyPolySystem)( x :: NumberOrVector) = evaluate(p, x)

function StaticPolynomials.jacobian( :: EmptyPolySystem{Nvars}, args... ) where Nvars
    Matrix{Int}(undef, 0, Nvars )
end

function StaticPolynomials.evaluate_and_jacobian( p :: EmptyPolySystem, args ... )
    return p(args...), jacobian(p, args...)
end


text:
@pyclass dolfin FeAny

const DEBUG = 10
const INFO = 20
const WARNING = 30
const ERROR = 40
const CRITICAL = 40
const PROGRESS = 16

export DEBUG, INFO, WARNING, ERROR, CRITICAL, PROGRESS

############################################
#
#    dolfin.cpp.common
#    dolfin.common
#    dolfin.cpp.parameter
#    dolfin.cpp.refinement
#
# https://fenicsproject.org/docs/dolfin/latest/python/_autogenerated/dolfin.cpp.common.html
# https://fenicsproject.org/docs/dolfin/2017.2.0/python/programmers-reference/common/index.html
# https://fenicsproject.org/docs/dolfin/latest/python/_autogenerated/dolfin.cpp.parameter.html
# https://fenicsproject.org/docs/dolfin/latest/python/_autogenerated/dolfin.cpp.refinement.html
#
############################################

@pyclass dolfin Variable

# no need to export
@pyclass dolfin Parameters

# no need to export
# not exported in `dolfin` or `ufl`
@pyclass dolfin Parameter
@pyclass dolfin GlobalParameters

@pyfunc dolfin has_mpi
@pyfunc dolfin has_debug
@pyfunc dolfin has_hdf5
@pyfunc dolfin has_hdf5_parallel
@pyfunc dolfin has_parmetis
@pyfunc dolfin has_petsc
@pyfunc dolfin has_scotch
@pyfunc dolfin has_slepc
@pyfunc dolfin has_sundials
@pyfunc dolfin refine

#@pyfunc dolfin plot
plot(u::FeObject, args...; kwargs...) = dolfin.plot(u.pyobject, args...; kwargs...)

export Variable, Parameters, plot, has_mpi, has_debug, has_hdf5, has_hdf5_parallel, has_parmetis,
       has_petsc, has_scotch, has_slepc, has_sundials, refine

############################################
#
#    dolfin.cpp.log
#
# https://fenicsproject.org/docs/dolfin/latest/python/_autogenerated/dolfin.cpp.log.html
#
############################################

@pyclass dolfin Progress

@pyfunc dolfin get_log_level
@pyfunc dolfin set_log_level
@pyfunc dolfin set_log_active
@pyfunc dolfin info
log(level::Integer, str::String) = dolfin.cpp.log.log(dolfin.LogLevel(level), str)

export Progress, get_log_level, set_log_level, set_log_active, info


text:
# Seed random generator to avoid random effects in testing
srand(1)

X = [1 1; 2 2;  1 -1]

# binomial
y = [-1; -1; 1]
@test_approx_eq_eps optimize(BinomialLogReg(X, y), optimizer=:l_bfgs).theta [-0.07276615319846116,-0.1680076736259885] 5e-5
@test_approx_eq_eps optimize(BinomialLogReg(X, y, λ=1.0), optimizer=:l_bfgs).theta [-0.16588135026949055,-0.840712964600344] 5e-5
@test_approx_eq_eps optimize(BinomialLogReg(X, y, λ= 10.0), optimizer=:l_bfgs).theta [-0.0745584919313508,-2.20259301054857] 5e-5

# TODO: should be moved to test/sgd.jl
@test_approx_eq_eps optimize(BinomialLogReg(X, y), optimizer=:sgd).theta [-0.07276615319846116,-0.1680076736259885] 5e-2
@test_approx_eq_eps optimize(BinomialLogReg(X, y, λ=1.0), optimizer=:sgd).theta [-0.16588135026949055,-0.840712964600344] 5e-2
@test_approx_eq_eps optimize(BinomialLogReg(X, y, λ=10.0), optimizer=:sgd).theta [-0.0745584919313508,-2.20259301054857] 5e-2
model = optimize(BinomialLogReg(X, y, λ=10.0), optimizer=:sgd)
@test predict(model, X) == y
show(IOBuffer(), BinomialLogReg(X, y))

@test_throws DimensionMismatch BinomialLogReg(X', y)
@test_throws ArgumentError BinomialLogReg(X, [3; 3; 2])
@test_throws ArgumentError optimize(BinomialLogReg(X, y, λ=0.0))

# multinomial
y = [1; 1; 2]
method = MultinomialLogReg(X, y, λ=10.0)
model = optimize(method, optimizer=:l_bfgs)
@test predict(model, X) == y


text:
module AutoOptimize

using DiffEqBase, ModelingToolkit, SparsityDetection, SparseDiffTools,
      CUDA, Logging, LinearAlgebra, SparseArrays, OrdinaryDiffEq, StaticArrays

MULTITHREADING_CUTOFF = 2^10
SPARSE_CUTOFF = 2^8
SPARSE_PERCENTAGE_CUTOFF = 0.01
COLORVEC_PERCENTAGE_CUTOFF = 0.5
STATIC_ARRAY_CUTOFF = 10

"""
tune_system

Tunes SciML variables in auto_optimize and beyond to maximize performance.
"""
function tune_system()

end

"""
auto_optimize(prob,alg=nothing;kwargs...)

A go fast button for those who are lazy or just don't know how to
optimize code. I don't trust that your code is fast, you don't trust
that your code is fast, so let's just get this over with and call it
a day.
"""
function auto_optimize(prob::ODEProblem,alg=nothing;
                       verbose = true,
                       stiff = true,
                       mtkify = true,
                       sparsify = true,
                       gpuify = true,
                       static = true,
                       gpup = nothing)
      N = length(prob.u0)

      if mtkify
            verbose && println("Try ModelingToolkitization")
            try
                  sys = modelingtoolkitize(prob)
                  sparsejac = ModelingToolkit.jacobian_sparsity(sys)
                  sparsity_percentage = length(nonzeros(sparsejac))/length(vec(sparsejac))

                  form = N > MULTITHREADING_CUTOFF ? ModelingToolkit.MultithreadedForm() : ModelingToolkit.SerialForm()
                  static = static && N < STATIC_ARRAY_CUTOFF

                  if static
                        prob = ODEProblem{false}(sys,SArray{Tuple{size(prob.u0)...}}(prob.u0),prob.tspan,prob.p,
                                          jac = true, tgrad = true, simplify = true,
                                          sparse = false,
                                          parallel = false,
                                          prob.kwargs...)
                  else
                        prob = ODEProblem(sys,prob.u0,prob.tspan,prob.p,
                                          jac = true, tgrad = true, simplify = true,
                                          sparse = N > SPARSE_CUTOFF &&
                                                   sparsity_percentage < SPARSE_PERCENTAGE_CUTOFF,
                                          parallel = form,
                                          prob.kwargs...)
                  end
                  return prob,alg
            catch e
                  @warn("ModelingToolkitization Approach Failed")
                  verbose && println(e)
                  throw(e)
            end
      end

      if stiff && N > SPARSE_CUTOFF && sparsify
            verbose && println("Try SparsityDetection")
            try
                  input = copy(prob.u0)
                  output = similar(input)
                  function f(du,u,p,t)
                        if isinplace(prob.f)
                              prob.f.f(du,u,p,t)
                        else
                              du .= prob.f.f(u,p,t)
                        end
                        return nothing
                  end
                  sparsity_pattern = jacobian_sparsity(f,output,input,SparsityDetection.Fixed(prob.p),prob.tspan[1])
                  sparsejac = sparse(sparsity_pattern)
                  sparsity_percentage = length(nonzeros(sparsejac))/prod(size(jac))
                  if sparsity_percentage < SPARSE_PERCENTAGE_CUTOFF && sparsity_percentage > COLORVEC_PERCENTAGE_CUTOFF
                        # Doesn't make sense to do sparsity for lu but does make sense for differentiation
                        colorvec = matrix_colors(sparsejac)
                        _f = ODEFunction(prob.f, jac=prob.jac, sparsity = sparsejac, tgrad = prob.tgrad, colorvec=colorvec)
                        prob = remake(prob;f=_f)
                  elseif sparsity_percentage > SPARSE_PERCENTAGE_CUTOFF
                        colorvec = matrix_colors(sparsejac)
                        _f = ODEFunction(prob.f, jac=prob.jac, jac_prototype = sparsejac, tgrad = prob.tgrad, colorvec=colorvec)
                        prob = remake(prob;f=_f)
                  else
                        error("Not sparse enough. Sparsity percentage = $sparsity_percentage")
                  end
            catch e
                  @warn("SparsityDetection Approach Failed")
                  verbose && println(e)
            end
      end

      if gpuify
            verbose && println("Try GPUification")
            try
                  CUDA.allowscalar(false)
                  u0 = prob.u0
                  gu0 = cu(u0)

                  if gpup isa Bool && gpup
                        gp = cu(prob.p)
                  elseif gpup isa Bool && !gpup
                        gp = prob.p
                  else
                        # Guess whether p should be on the GPU too
                        gp = typeof(prob.p) <: Array && eltype(prob.p) <: AbstractFloat && length(prob.p) > 100 ? cu(prob.p) : prob.p
                  end

                  if DiffEqBase.isinplace(prob)
                        gdu0 = similar(gu0)
                        prob.f(gdu0,gu0,gp,prob.tspan[1])
                        gputime = @elapsed prob.f(gdu0,gu0,gp,prob.tspan[1])
                  else
                        prob.f(gu0,gp,prob.tspan[1])
                        gputime = @elapsed prob.f(gu0,gp,prob.tspan[1])
                  end

                  if DiffEqBase.isinplace(prob)
                        du0 = similar(u0)
                        prob.f(du0,u0,prob.p,prob.tspan[1])
                        cputime = @elapsed prob.f(du0,u0,prob.p,prob.tspan[1])
                  else
                        prob.f(u0,prob.p,prob.tspan[1])
                        cputime = @elapsed prob.f(u0,prob.p,prob.tspan[1])
                  end

                  cputime < gputime/2 && error("GPU did not increase `f` speed")
                  prob = remake(prob,u0=gu0,p=gp)
            catch e
                  @warn("GPUificiation Approach Failed")
                  verbose && println(e)
            end
      end
      prob,alg
end

"""
auto_optimize_multiple(prob,alg=nothing;kwargs...)

Look, you're going to be doing a bunch of parameter estimation and
stuff on this, so you need to solve this multiple times, and by
multiple I mean 10,000x. So by all means, go ahead and call this and
I'll use a few solves to figure out something that will hopefully
make it go zoooooooooom.
"""
function auto_optimize_multiple(prob::ODEProblem,alg=nothing;kwargs...)
      prob,alg
end

export tune_system, auto_optimize, auto_optimize_multiple

end


text:
"""
    ObservationModel{S1, S2, T} <: AbstractModel{S2}

Abstract type for any model of observations of type `S2` and hidden states of type `S1`.

Calling the model samples a new observation. For discrete-time or static models,

    model(x)

returns a new observation based on hidden state `x`.

For continuous-time models,

    model(x, dt)

returns a new observation based on hidden state `x` and time-step `dt`.

If `x` is a vector of `state_type` elements or a batch matrix, an observation is generated for each element of the batch.
"""
abstract type ObservationModel{S1, S2, T} <: AbstractModel{S2} end

function state_dim(model::ObservationModel) end
function obs_dim(model::ObservationModel) end

state_type(model::ObservationModel{S1, S2, T}) where {S1, S2, T} = S1
obs_type(model::ObservationModel{S1, S2, T}) where {S1, S2, T}   = S2
time_type(model::ObservationModel{S1, S2, T}) where {S1, S2, T}  = T

function emit!(obs, hidden_state, obs_model::ObservationModel{S1, S2, ContinuousTime}, dt) where {S1, S2}
    obs .= obs_model(hidden_state, dt)
end

max_stars_repo_name: simsurace/FeedbackParticleFilters

max_issues_repo_name: simsurace/FeedbackParticleFilters

max_forks_repo_name: simsurace/FeedbackParticleFilters


text:
using Test
using SpineBasedRecordLinkage

using CSV
using DataFrames
using Schemata

# NOTE: pwd is /path/to/SpineBasedRecordLinkage.jl/test/
const outdir = joinpath(pwd(), "output")

if !isdir(outdir)
    mkdir(outdir)
end

# Support functions
"Returns: A set of Dict{Symbol, Any}, with each element being a row of the table in the supplied datafile."
function table_to_set_of_dicts(datafile::String)
    result   = Set{Dict{Symbol, Any}}()
    data     = DataFrame(CSV.File(datafile))
    colnames = Symbol.(names(data))
    for row in eachrow(data)
        d = Dict{Symbol, Any}(colname => getproperty(row, colname) for colname in colnames)
        push!(result, d)
    end
    result
end

function cleanup()
    contents = readdir(outdir; join=true)
    for x in contents
        rm(x; recursive=true)
    end
end

# Test sets
cleanup()
include("testset1.jl")  # Construct spine from 1 table (influenza cases)
include("testset2.jl")  # Construct spine from multiple data sets
include("testset3.jl")  # Compare the results from test sets 1 and 2
cleanup()


text:
@testset "kernelembeddings" begin
    rng = MersenneTwister(42)
    N = 3
    measure = MvNormal(ones(3), ones(3))
    k = SqExponentialKernel()
    l = 2.0
    σ = 0.5
    ke = KernelEmbedding(k, σ, l, measure)
    kernel = σ * with_lengthscale(k, l)
    @test BQ.scale(ke) == σ

    sample = [rand(rng, 3)]
    @test kernel_mean(ke, sample) ≈ [mean(kernel.(sample, eachcol(rand(rng, measure, 10000))))] atol=1e-2
    @test kernel_variance(ke) ≈ mean(kernel.(eachcol(rand(rng, measure, 10000)), eachcol(rand(rng, measure, 10000)))) atol=1e-2

    s = 2.0
    l = [1.0, 2.0]
    L = LowerTriangular(rand(2, 2))
    @test BQ.Λ(s) ≈ s^2 * I
    @test BQ.Λ(l) ≈ Diagonal(abs2.(l))
    @test Matrix(BQ.Λ(L)) ≈ L * L'
end


text:
## Tests relating to data integrity. ##

@testset "Data" begin

# long symbols should be unique
alllongsymbols = values(CurrenciesBase.LONG_SYMBOL)
@test length(Set(alllongsymbols)) == length(alllongsymbols)

# symbols should all be registered currencies
registeredcurrencies = keys(CurrenciesBase.ISO4217)
for sym in keys(CurrenciesBase.SHORT_SYMBOL)
    @test sym ∈ registeredcurrencies
end
for sym in keys(CurrenciesBase.LONG_SYMBOL)
    @test sym ∈ registeredcurrencies
end

# locale keys should be registered currencies, and value :before or :after
for (sym, val) in CurrenciesBase.LOCAL_SYMBOL_LOCATION
    @test sym ∈ registeredcurrencies
    @test val ∈ (:before, :after)
end

end  # @testset "Data"


text:
#=
CMU:
- Julia version: 1.6.2
- Author: samuel
- Date: 2021-09-10
=#

using SuiteSparseGraphBLAS
using SparseArrays
using LinearAlgebra

#A is the input matrix, n is the number of nodes in the original matrix, Output: Triangle Count
function cmu(A, n)

        t = 0

        for i = 2:n-1

            #rpva
            A20 = A[i+1:n,begin:i]
            a10 = A[begin:i, i]
            a12 = A[i, i+1:n]

            partial1 = mul(a10', A20', Semirings.PLUS_TIMES)
            partial2 = mul(partial1, a12', Semirings.PLUS_TIMES)

            t = t + partial2[1]
    end

    print("RESULT: ")
    print(t)

    return t
end


text:
# A total ordering

<ₑ(a::Real,    b::Real) = abs(a) < abs(b)
<ₑ(a::Complex, b::Complex) = (abs(real(a)), abs(imag(a))) < (abs(real(b)), abs(imag(b)))
<ₑ(a::Real,    b::Complex) = true
<ₑ(a::Complex, b::Real) = false

<ₑ(a::Symbolic, b::Number) = false
<ₑ(a::Number,   b::Symbolic) = true

arglength(a) = length(arguments(a))
function <ₑ(a, b)
    if a isa Term && (b isa Symbolic && !(b isa Term))
        return false
    elseif  b isa Term && (a isa Symbolic && !(a isa Term))
        return true
    elseif !istree(a) && !istree(b)
        T = typeof(a)
        S = typeof(b)
        return T===S ? (T <: Number ? isless(a, b) : hash(a) < hash(b)) : nameof(T) < nameof(S)
    elseif istree(b) && !istree(a)
        return true
    elseif istree(a) && istree(b)
        return cmp_term_term(a,b)
    else
        return !(b <ₑ a)
    end
end

<ₑ(a::Symbolic, b::Sym) = !(b <ₑ a)

function <ₑ(a::Symbol, b::Symbol)
    # Enforce the order [+,-,\,/,^,*]
    if b === :*
        a in (:^, :/, :\, :-, :+)
    elseif b === :^
        a in (:/, :\, :-, :+) && return true
    elseif b === :/
        a in (:\, :-, :+) && return true
    elseif b === :\
        a in (:-, :+) && return true
    elseif b === :-
        a === :+ && return true
    elseif a in (:*, :^, :/, :-, :+)
        false
    else
        a < b
    end
end

<ₑ(a::Sym, b::Sym) = a.name < b.name

<ₑ(a::Function, b::Function) = nameof(a) <ₑ nameof(b)

function cmp_term_term(a, b)
    la = arglength(a)
    lb = arglength(b)

    if la == 0 && lb == 0
        return operation(a) <ₑ operation(b)
    elseif la === 0
        return operation(a) <ₑ b
    elseif lb === 0
        return a <ₑ operation(b)
    end

    na = operation(a)
    nb = operation(b)

    if 0 < arglength(a) <= 2 && 0 < arglength(b) <= 2
        # e.g. a < sin(a) < b ^ 2 < b
        @goto compare_args
    end

    if na !== nb
        return na <ₑ nb
    elseif arglength(a) != arglength(b)
        return arglength(a) < arglength(b)
    else
        @label compare_args
        aa, ab = arguments(a), arguments(b)
        if length(aa) !== length(ab)
            return length(aa) < length(ab)
        else
            terms = zip(Iterators.filter(!is_literal_number, aa), Iterators.filter(!is_literal_number, ab))

            for (x,y) in terms
                if x <ₑ y
                    return true
                elseif y <ₑ x
                    return false
                end
            end

            # compare the numbers
            nums = zip(Iterators.filter(is_literal_number, aa),
                       Iterators.filter(is_literal_number, ab))

            for (x,y) in nums
                if x <ₑ y
                    return true
                elseif y <ₑ x
                    return false
                end
            end

        end
        return na <ₑ nb # all args are equal, compare the name
    end
end


text:
using StructJuMP

numScen = 2
m = StructuredModel(num_scenarios=numScen)

@variable(m, 0 <= x <= 1)
@variable(m, 0 <= y <= 1)

@constraint(m, x + y == 1)
@objective(m, :Min, x*x + y)

for i in 1:numScen
    bl = StructuredModel(parent=m, id=i)
    @variable(bl, w >= 0)
    @constraint(bl, w - x - y <= 1)
    @objective(bl, :Min, w*w + w)
end


text:
using Test
using Random
using StatsBase
using Printf
using JITrench

include("test_utils.jl")

operators = [+, -, /, *]

N_TEST_COUNT = 100

@testset "OperatorTest" begin
    @testset "ForwardTest" begin
        for i in 1:N_TEST_COUNT
            for op in operators
                x1 = rand()
                x2 = rand()
                @test isAbout(op(Variable(x1), Variable(x2)).values, op(x1, x2), )
            end
        end
    end
    @testset "backwardTest" begin
        for i in 1:N_TEST_COUNT
            for op in operators[1:end-1]
                x1 = rand()
                x2 = rand()
                @test isAbout(backward_diff(op, [x1, x2]), numerical_diff(op, [x1, x2]))
            end
        end
    end
end

funcitons = [
    sin,
    cos,
    tan,
    log,
    exp
]

@testset "MathFuncTest" begin
    @testset "ForwardTest" begin
        for i in 1:N_TEST_COUNT
            for op in funcitons
                x = rand()
                @test isAbout(op(x), op(Variable(x).values))
            end
        end
    end
    @testset "backwardTest" begin
        for i in 1:N_TEST_COUNT
            for op in funcitons
                x = rand()
                @test isAbout(backward_diff(op, [x]), numerical_diff(op, [x]))
            end
        end
    end
end

activations = Dict(
    JITrench._sigmoid => JITrench.sigmoid
)

@testset "ActivationTest" begin
    @testset "ForwardTest" begin
        for i in 1:N_TEST_COUNT
            for (func, jt_func) in activations
                x = rand()
                isAbout(func(x), jt_func(Variable(x)).values)
            end
        end
    end
    @testset "backwardTest" begin
        for i in 1:N_TEST_COUNT
            for (func, jt_func) in activations
                x = rand()
                @test isAbout(backward_diff(jt_func, [x]), numerical_diff(func, [x]))
            end
        end
    end
end

@testset "ArrOperateTest" begin
    max_size = 120
    @testset "forward" begin
        @testset "reshape" begin
            for _ in 1:N_TEST_COUNT
                in_shape, out_shape = generate_shape(rand(1:max_size))
                x = rand(in_shape...)
                y_arr = reshape(x, out_shape)
                y_var = reshape(Variable(x), out_shape)
                @test y_arr == y_var.values
            end
        end
        @testset "transpose" begin
            for _ in 1:N_TEST_COUNT
                in_shape, out_shape = generate_shape(rand(1:max_size), max_dim=2)
                x = rand(in_shape...)
                y_arr = transpose(x)
                y_var = transpose(Variable(x))
                @test y_arr == y_var.values
            end
        end
    end
    @testset "backward" begin
        @testset "reshape" begin
            for _ in 1:N_TEST_COUNT
                in_shape, out_shape = generate_shape(rand(1:max_size))
                x = Variable(rand(in_shape...))
                y = reshape(x, out_shape)
                backward!(y, retain_grad=true)
                @test y.grad.values == ones(size(y.values))
                @test x.grad.values == ones(size(x.values))
            end
        end
        @testset "transpose" begin
            for _ in 1:N_TEST_COUNT
                in_shape, out_shape = generate_shape(rand(1:max_size), min_dim=2, max_dim=2)
                x = Variable(rand(in_shape...))
                y = JITrench.transpose(x)
                backward!(y, retain_grad=true)
                @test y.grad.values == ones(size(y.values))
                @test x.grad.values == ones(size(x.values))
            end
        end
    end
end