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

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

Turns off automatic rotation, and if a rotation is currently in progress, cancels the
rotation. To turn on automatic rotation again, call RotateSecret.  If you cancel a rotation
in progress, it can leave the VersionStage labels in an unexpected state. Depending on the
step of the rotation in progress, you might need to remove the staging label AWSPENDING
from the partially created version, specified by the VersionId response value. We recommend
you also evaluate the partially rotated new version to see if it should be deleted. You can
delete a version by removing all staging labels from it.

# Arguments
- `secret_id`: The ARN or name of the secret. For an ARN, we recommend that you specify a
  complete ARN rather than a partial ARN.

"""
function cancel_rotate_secret(SecretId; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "CancelRotateSecret",
        Dict{String,Any}("SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function cancel_rotate_secret(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "CancelRotateSecret",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SecretId" => SecretId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Creates a new secret. A secret is a set of credentials, such as a user name and password,
that you store in an encrypted form in Secrets Manager. The secret also includes the
connection information to access a database or other service, which Secrets Manager doesn't
encrypt. A secret in Secrets Manager consists of both the protected secret data and the
important information needed to manage the secret. For information about creating a secret
in the console, see Create a secret. To create a secret, you can provide the secret value
to be encrypted in either the SecretString parameter or the SecretBinary parameter, but not
both. If you include SecretString or SecretBinary then Secrets Manager creates an initial
secret version and automatically attaches the staging label AWSCURRENT to it. If you don't
specify an KMS encryption key, Secrets Manager uses the Amazon Web Services managed key
aws/secretsmanager. If this key doesn't already exist in your account, then Secrets Manager
creates it for you automatically. All users and roles in the Amazon Web Services account
automatically have access to use aws/secretsmanager. Creating aws/secretsmanager can result
in a one-time significant delay in returning the result. If the secret is in a different
Amazon Web Services account from the credentials calling the API, then you can't use
aws/secretsmanager to encrypt the secret, and you must create and use a customer managed
KMS key.

# Arguments
- `name`: The name of the new secret. The secret name can contain ASCII letters, numbers,
  and the following characters: /_+=.@- Do not end your secret name with a hyphen followed by
  six characters. If you do so, you risk confusion and unexpected results when searching for
  a secret by partial ARN. Secrets Manager automatically adds a hyphen and six random
  characters after the secret name at the end of the ARN.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AddReplicaRegions"`: A list of Regions and KMS keys to replicate secrets.
- `"ClientRequestToken"`: If you include SecretString or SecretBinary, then Secrets Manager
  creates an initial version for the secret, and this parameter specifies the unique
  identifier for the new version.   If you use the Amazon Web Services CLI or one of the
  Amazon Web Services SDKs to call this operation, then you can leave this parameter empty.
  The CLI or SDK generates a random UUID for you and includes it as the value for this
  parameter in the request. If you don't use the SDK and instead generate a raw HTTP request
  to the Secrets Manager service endpoint, then you must generate a ClientRequestToken
  yourself for the new version and include the value in the request.  This value helps ensure
  idempotency. Secrets Manager uses this value to prevent the accidental creation of
  duplicate versions if there are failures and retries during a rotation. We recommend that
  you generate a UUID-type value to ensure uniqueness of your versions within the specified
  secret.    If the ClientRequestToken value isn't already associated with a version of the
  secret then a new version of the secret is created.    If a version with this value already
  exists and the version SecretString and SecretBinary values are the same as those in the
  request, then the request is ignored.   If a version with this value already exists and
  that version's SecretString and SecretBinary values are different from those in the
  request, then the request fails because you cannot modify an existing version. Instead, use
  PutSecretValue to create a new version.   This value becomes the VersionId of the new
  version.
- `"Description"`: The description of the secret.
- `"ForceOverwriteReplicaSecret"`: Specifies whether to overwrite a secret with the same
  name in the destination Region.
- `"KmsKeyId"`: The ARN, key ID, or alias of the KMS key that Secrets Manager uses to
  encrypt the secret value in the secret. To use a KMS key in a different account, use the
  key ARN or the alias ARN. If you don't specify this value, then Secrets Manager uses the
  key aws/secretsmanager. If that key doesn't yet exist, then Secrets Manager creates it for
  you automatically the first time it encrypts the secret value. If the secret is in a
  different Amazon Web Services account from the credentials calling the API, then you can't
  use aws/secretsmanager to encrypt the secret, and you must create and use a customer
  managed KMS key.
- `"SecretBinary"`: The binary data to encrypt and store in the new version of the secret.
  We recommend that you store your binary data in a file and then pass the contents of the
  file as a parameter. Either SecretString or SecretBinary must have a value, but not both.
  This parameter is not available in the Secrets Manager console.
- `"SecretString"`: The text data to encrypt and store in this new version of the secret.
  We recommend you use a JSON structure of key/value pairs for your secret value. Either
  SecretString or SecretBinary must have a value, but not both. If you create a secret by
  using the Secrets Manager console then Secrets Manager puts the protected secret text in
  only the SecretString parameter. The Secrets Manager console stores the information as a
  JSON structure of key/value pairs that a Lambda rotation function can parse.
- `"Tags"`: A list of tags to attach to the secret. Each tag is a key and value pair of
  strings in a JSON text string, for example:
  [{\"Key\":\"CostCenter\",\"Value\":\"12345\"},{\"Key\":\"environment\",\"Value\":\"productio
  n\"}]  Secrets Manager tag key names are case sensitive. A tag with the key \"ABC\" is a
  different tag from one with key \"abc\". If you check tags in permissions policies as part
  of your security strategy, then adding or removing a tag can change permissions. If the
  completion of this operation would result in you losing your permissions for this secret,
  then Secrets Manager blocks the operation and returns an Access Denied error. For more
  information, see Control access to secrets using tags and Limit access to identities with
  tags that match secrets' tags. For information about how to format a JSON parameter for the
  various command line tool environments, see Using JSON for Parameters. If your command-line
  tool or SDK requires quotation marks around the parameter, you should use single quotes to
  avoid confusion with the double quotes required in the JSON text. The following
  restrictions apply to tags:   Maximum number of tags per secret: 50   Maximum key length:
  127 Unicode characters in UTF-8   Maximum value length: 255 Unicode characters in UTF-8
  Tag keys and values are case sensitive.   Do not use the aws: prefix in your tag names or
  values because Amazon Web Services reserves it for Amazon Web Services use. You can't edit
  or delete tag names or values with this prefix. Tags with this prefix do not count against
  your tags per secret limit.   If you use your tagging schema across multiple services and
  resources, other services might have restrictions on allowed characters. Generally allowed
  characters: letters, spaces, and numbers representable in UTF-8, plus the following special
  characters: + - = . _ : / @.
"""
function create_secret(Name; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "CreateSecret",
        Dict{String,Any}("Name" => Name, "ClientRequestToken" => string(uuid4()));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_secret(
    Name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return secrets_manager(
        "CreateSecret",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("Name" => Name, "ClientRequestToken" => string(uuid4())),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deletes the resource-based permission policy attached to the secret. To attach a policy to
a secret, use PutResourcePolicy.

# Arguments
- `secret_id`: The ARN or name of the secret to delete the attached resource-based policy
  for. For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

"""
function delete_resource_policy(SecretId; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "DeleteResourcePolicy",
        Dict{String,Any}("SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_resource_policy(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "DeleteResourcePolicy",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SecretId" => SecretId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Deletes a secret and all of its versions. You can specify a recovery window during which
you can restore the secret. The minimum recovery window is 7 days. The default recovery
window is 30 days. Secrets Manager attaches a DeletionDate stamp to the secret that
specifies the end of the recovery window. At the end of the recovery window, Secrets
Manager deletes the secret permanently. For information about deleting a secret in the
console, see
https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_delete-secret.html.
Secrets Manager performs the permanent secret deletion at the end of the waiting period as
a background task with low priority. There is no guarantee of a specific time after the
recovery window for the permanent delete to occur. At any time before recovery window ends,
you can use RestoreSecret to remove the DeletionDate and cancel the deletion of the secret.
In a secret scheduled for deletion, you cannot access the encrypted secret value. To access
that information, first cancel the deletion with RestoreSecret and then retrieve the
information.

# Arguments
- `secret_id`: The ARN or name of the secret to delete. For an ARN, we recommend that you
  specify a complete ARN rather than a partial ARN.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ForceDeleteWithoutRecovery"`: Specifies whether to delete the secret without any
  recovery window. You can't use both this parameter and RecoveryWindowInDays in the same
  call. If you don't use either, then Secrets Manager defaults to a 30 day recovery window.
  Secrets Manager performs the actual deletion with an asynchronous background process, so
  there might be a short delay before the secret is permanently deleted. If you delete a
  secret and then immediately create a secret with the same name, use appropriate back off
  and retry logic.  Use this parameter with caution. This parameter causes the operation to
  skip the normal recovery window before the permanent deletion that Secrets Manager would
  normally impose with the RecoveryWindowInDays parameter. If you delete a secret with the
  ForceDeleteWithouRecovery parameter, then you have no opportunity to recover the secret.
  You lose the secret permanently.
- `"RecoveryWindowInDays"`: The number of days from 7 to 30 that Secrets Manager waits
  before permanently deleting the secret. You can't use both this parameter and
  ForceDeleteWithoutRecovery in the same call. If you don't use either, then Secrets Manager
  defaults to a 30 day recovery window.
"""
function delete_secret(SecretId; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "DeleteSecret",
        Dict{String,Any}("SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_secret(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "DeleteSecret",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SecretId" => SecretId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Retrieves the details of a secret. It does not include the encrypted secret value. Secrets
Manager only returns fields that have a value in the response.

# Arguments
- `secret_id`: The ARN or name of the secret.  For an ARN, we recommend that you specify a
  complete ARN rather than a partial ARN.

"""
function describe_secret(SecretId; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "DescribeSecret",
        Dict{String,Any}("SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_secret(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "DescribeSecret",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SecretId" => SecretId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Generates a random password. We recommend that you specify the maximum length and include
every character type that the system you are generating a password for can support.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ExcludeCharacters"`: A string of the characters that you don't want in the password.
- `"ExcludeLowercase"`: Specifies whether to exclude lowercase letters from the password.
  If you don't include this switch, the password can contain lowercase letters.
- `"ExcludeNumbers"`: Specifies whether to exclude numbers from the password. If you don't
  include this switch, the password can contain numbers.
- `"ExcludePunctuation"`: Specifies whether to exclude the following punctuation characters
  from the password: ! \" #  % & ' ( ) * + , - . / : ; < = > ? @ [  ] ^ _ ` { | }
  ~. If you don't include this switch, the password can contain punctuation.
- `"ExcludeUppercase"`: Specifies whether to exclude uppercase letters from the password.
  If you don't include this switch, the password can contain uppercase letters.
- `"IncludeSpace"`: Specifies whether to include the space character. If you include this
  switch, the password can contain space characters.
- `"PasswordLength"`: The length of the password. If you don't include this parameter, the
  default length is 32 characters.
- `"RequireEachIncludedType"`: Specifies whether to include at least one upper and
  lowercase letter, one number, and one punctuation. If you don't include this switch, the
  password contains at least one of every character type.
"""
function get_random_password(; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "GetRandomPassword"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function get_random_password(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return secrets_manager(
        "GetRandomPassword", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

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

Retrieves the JSON text of the resource-based policy document attached to the secret. For
more information about permissions policies attached to a secret, see Permissions policies
attached to a secret.

# Arguments
- `secret_id`: The ARN or name of the secret to retrieve the attached resource-based policy
  for. For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

"""
function get_resource_policy(SecretId; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "GetResourcePolicy",
        Dict{String,Any}("SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_resource_policy(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "GetResourcePolicy",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SecretId" => SecretId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Retrieves the contents of the encrypted fields SecretString or SecretBinary from the
specified version of a secret, whichever contains content. For information about retrieving
the secret value in the console, see Retrieve secrets.  To run this command, you must have
secretsmanager:GetSecretValue permissions. If the secret is encrypted using a
customer-managed key instead of the Amazon Web Services managed key aws/secretsmanager,
then you also need kms:Decrypt permissions for that key.

# Arguments
- `secret_id`: The ARN or name of the secret to retrieve. For an ARN, we recommend that you
  specify a complete ARN rather than a partial ARN.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"VersionId"`: The unique identifier of the version of the secret to retrieve. If you
  include both this parameter and VersionStage, the two parameters must refer to the same
  secret version. If you don't specify either a VersionStage or VersionId, then Secrets
  Manager returns the AWSCURRENT version. This value is typically a UUID-type value with 32
  hexadecimal digits.
- `"VersionStage"`: The staging label of the version of the secret to retrieve.  Secrets
  Manager uses staging labels to keep track of different versions during the rotation
  process. If you include both this parameter and VersionId, the two parameters must refer to
  the same secret version. If you don't specify either a VersionStage or VersionId, Secrets
  Manager returns the AWSCURRENT version.
"""
function get_secret_value(SecretId; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "GetSecretValue",
        Dict{String,Any}("SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_secret_value(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "GetSecretValue",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SecretId" => SecretId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Lists the versions for a secret.  To list the secrets in the account, use ListSecrets. To
get the secret value from SecretString or SecretBinary, call GetSecretValue.  Minimum
permissions  To run this command, you must have secretsmanager:ListSecretVersionIds
permissions.

# Arguments
- `secret_id`: The ARN or name of the secret whose versions you want to list. For an ARN,
  we recommend that you specify a complete ARN rather than a partial ARN.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"IncludeDeprecated"`: Specifies whether to include versions of secrets that don't have
  any staging labels attached to them. Versions without staging labels are considered
  deprecated and are subject to deletion by Secrets Manager.
- `"MaxResults"`: The number of results to include in the response. If there are more
  results available, in the response, Secrets Manager includes NextToken. To get the next
  results, call ListSecretVersionIds again with the value from NextToken.
- `"NextToken"`: A token that indicates where the output should continue from, if a
  previous call did not show all results. To get the next results, call ListSecretVersionIds
  again with this value.
"""
function list_secret_version_ids(
    SecretId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return secrets_manager(
        "ListSecretVersionIds",
        Dict{String,Any}("SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_secret_version_ids(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "ListSecretVersionIds",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SecretId" => SecretId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Lists the secrets that are stored by Secrets Manager in the Amazon Web Services account.
To list the versions of a secret, use ListSecretVersionIds. To get the secret value from
SecretString or SecretBinary, call GetSecretValue. For information about finding secrets in
the console, see Enhanced search capabilities for secrets in Secrets Manager.  Minimum
permissions  To run this command, you must have secretsmanager:ListSecrets permissions.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Filters"`: The filters to apply to the list of secrets.
- `"MaxResults"`: The number of results to include in the response. If there are more
  results available, in the response, Secrets Manager includes NextToken. To get the next
  results, call ListSecrets again with the value from NextToken.
- `"NextToken"`: A token that indicates where the output should continue from, if a
  previous call did not show all results. To get the next results, call ListSecrets again
  with this value.
- `"SortOrder"`: Lists secrets in the requested order.
"""
function list_secrets(; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "ListSecrets"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_secrets(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return secrets_manager(
        "ListSecrets", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    put_resource_policy(resource_policy, secret_id)
    put_resource_policy(resource_policy, secret_id, params::Dict{String,<:Any})

Attaches a resource-based permission policy to a secret. A resource-based policy is
optional. For more information, see Authentication and access control for Secrets Manager
For information about attaching a policy in the console, see Attach a permissions policy to
a secret.

# Arguments
- `resource_policy`: A JSON-formatted string for an Amazon Web Services resource-based
  policy. For example policies, see Permissions policy examples.
- `secret_id`: The ARN or name of the secret to attach the resource-based policy. For an
  ARN, we recommend that you specify a complete ARN rather than a partial ARN.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"BlockPublicPolicy"`: Specifies whether to block resource-based policies that allow
  broad access to the secret. By default, Secrets Manager blocks policies that allow broad
  access, for example those that use a wildcard for the principal.
"""
function put_resource_policy(
    ResourcePolicy, SecretId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return secrets_manager(
        "PutResourcePolicy",
        Dict{String,Any}("ResourcePolicy" => ResourcePolicy, "SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function put_resource_policy(
    ResourcePolicy,
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "PutResourcePolicy",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "ResourcePolicy" => ResourcePolicy, "SecretId" => SecretId
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Creates a new version with a new encrypted secret value and attaches it to the secret. The
version can contain a new SecretString value or a new SecretBinary value.  We recommend you
avoid calling PutSecretValue at a sustained rate of more than once every 10 minutes. When
you update the secret value, Secrets Manager creates a new version of the secret. Secrets
Manager removes outdated versions when there are more than 100, but it does not remove
versions created less than 24 hours ago. If you call PutSecretValue more than once every 10
minutes, you create more versions than Secrets Manager removes, and you will reach the
quota for secret versions. You can specify the staging labels to attach to the new version
in VersionStages. If you don't include VersionStages, then Secrets Manager automatically
moves the staging label AWSCURRENT to this version. If this operation creates the first
version for the secret, then Secrets Manager automatically attaches the staging label
AWSCURRENT to it . If this operation moves the staging label AWSCURRENT from another
version to this version, then Secrets Manager also automatically moves the staging label
AWSPREVIOUS to the version that AWSCURRENT was removed from. This operation is idempotent.
If a version with a VersionId with the same value as the ClientRequestToken parameter
already exists, and you specify the same secret data, the operation succeeds but does
nothing. However, if the secret data is different, then the operation fails because you
can't modify an existing version; you can only create new ones.

# Arguments
- `secret_id`: The ARN or name of the secret to add a new version to. For an ARN, we
  recommend that you specify a complete ARN rather than a partial ARN. If the secret doesn't
  already exist, use CreateSecret instead.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ClientRequestToken"`: A unique identifier for the new version of the secret.   If you
  use the Amazon Web Services CLI or one of the Amazon Web Services SDKs to call this
  operation, then you can leave this parameter empty because they generate a random UUID for
  you. If you don't use the SDK and instead generate a raw HTTP request to the Secrets
  Manager service endpoint, then you must generate a ClientRequestToken yourself for new
  versions and include that value in the request.   This value helps ensure idempotency.
  Secrets Manager uses this value to prevent the accidental creation of duplicate versions if
  there are failures and retries during the Lambda rotation function processing. We recommend
  that you generate a UUID-type value to ensure uniqueness within the specified secret.    If
  the ClientRequestToken value isn't already associated with a version of the secret then a
  new version of the secret is created.    If a version with this value already exists and
  that version's SecretString or SecretBinary values are the same as those in the request
  then the request is ignored. The operation is idempotent.    If a version with this value
  already exists and the version of the SecretString and SecretBinary values are different
  from those in the request, then the request fails because you can't modify a secret
  version. You can only create new versions to store new secret values.   This value becomes
  the VersionId of the new version.
- `"SecretBinary"`: The binary data to encrypt and store in the new version of the secret.
  To use this parameter in the command-line tools, we recommend that you store your binary
  data in a file and then pass the contents of the file as a parameter.  You must include
  SecretBinary or SecretString, but not both. You can't access this value from the Secrets
  Manager console.
- `"SecretString"`: The text to encrypt and store in the new version of the secret.  You
  must include SecretBinary or SecretString, but not both. We recommend you create the secret
  string as JSON key/value pairs, as shown in the example.
- `"VersionStages"`: A list of staging labels to attach to this version of the secret.
  Secrets Manager uses staging labels to track versions of a secret through the rotation
  process. If you specify a staging label that's already associated with a different version
  of the same secret, then Secrets Manager removes the label from the other version and
  attaches it to this version. If you specify AWSCURRENT, and it is already attached to
  another version, then Secrets Manager also moves the staging label AWSPREVIOUS to the
  version that AWSCURRENT was removed from. If you don't include VersionStages, then Secrets
  Manager automatically moves the staging label AWSCURRENT to this version.
"""
function put_secret_value(SecretId; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "PutSecretValue",
        Dict{String,Any}("SecretId" => SecretId, "ClientRequestToken" => string(uuid4()));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function put_secret_value(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "PutSecretValue",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "SecretId" => SecretId, "ClientRequestToken" => string(uuid4())
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    remove_regions_from_replication(remove_replica_regions, secret_id)
    remove_regions_from_replication(remove_replica_regions, secret_id, params::Dict{String,<:Any})

For a secret that is replicated to other Regions, deletes the secret replicas from the
Regions you specify.

# Arguments
- `remove_replica_regions`: The Regions of the replicas to remove.
- `secret_id`: The ARN or name of the secret.

"""
function remove_regions_from_replication(
    RemoveReplicaRegions, SecretId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return secrets_manager(
        "RemoveRegionsFromReplication",
        Dict{String,Any}(
            "RemoveReplicaRegions" => RemoveReplicaRegions, "SecretId" => SecretId
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function remove_regions_from_replication(
    RemoveReplicaRegions,
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "RemoveRegionsFromReplication",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "RemoveReplicaRegions" => RemoveReplicaRegions, "SecretId" => SecretId
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    replicate_secret_to_regions(add_replica_regions, secret_id)
    replicate_secret_to_regions(add_replica_regions, secret_id, params::Dict{String,<:Any})

Replicates the secret to a new Regions. See Multi-Region secrets.

# Arguments
- `add_replica_regions`: A list of Regions in which to replicate the secret.
- `secret_id`: The ARN or name of the secret to replicate.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ForceOverwriteReplicaSecret"`: Specifies whether to overwrite a secret with the same
  name in the destination Region.
"""
function replicate_secret_to_regions(
    AddReplicaRegions, SecretId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return secrets_manager(
        "ReplicateSecretToRegions",
        Dict{String,Any}("AddReplicaRegions" => AddReplicaRegions, "SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function replicate_secret_to_regions(
    AddReplicaRegions,
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "ReplicateSecretToRegions",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "AddReplicaRegions" => AddReplicaRegions, "SecretId" => SecretId
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Cancels the scheduled deletion of a secret by removing the DeletedDate time stamp. You can
access a secret again after it has been restored.

# Arguments
- `secret_id`: The ARN or name of the secret to restore. For an ARN, we recommend that you
  specify a complete ARN rather than a partial ARN.

"""
function restore_secret(SecretId; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "RestoreSecret",
        Dict{String,Any}("SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function restore_secret(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "RestoreSecret",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SecretId" => SecretId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Configures and starts the asynchronous process of rotating the secret. If you include the
configuration parameters, the operation sets the values for the secret and then immediately
starts a rotation. If you don't include the configuration parameters, the operation starts
a rotation with the values already stored in the secret. For more information about
rotation, see Rotate secrets. To configure rotation, you include the ARN of an Amazon Web
Services Lambda function and the schedule for the rotation. The Lambda rotation function
creates a new version of the secret and creates or updates the credentials on the database
or service to match. After testing the new credentials, the function marks the new secret
version with the staging label AWSCURRENT. Then anyone who retrieves the secret gets the
new version. For more information, see How rotation works. When rotation is successful, the
AWSPENDING staging label might be attached to the same version as the AWSCURRENT version,
or it might not be attached to any version. If the AWSPENDING staging label is present but
not attached to the same version as AWSCURRENT, then any later invocation of RotateSecret
assumes that a previous rotation request is still in progress and returns an error. To run
this command, you must have secretsmanager:RotateSecret permissions and
lambda:InvokeFunction permissions on the function specified in the secret's metadata.

# Arguments
- `secret_id`: The ARN or name of the secret to rotate. For an ARN, we recommend that you
  specify a complete ARN rather than a partial ARN.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ClientRequestToken"`: A unique identifier for the new version of the secret that helps
  ensure idempotency. Secrets Manager uses this value to prevent the accidental creation of
  duplicate versions if there are failures and retries during rotation. This value becomes
  the VersionId of the new version. If you use the Amazon Web Services CLI or one of the
  Amazon Web Services SDK to call this operation, then you can leave this parameter empty.
  The CLI or SDK generates a random UUID for you and includes that in the request for this
  parameter. If you don't use the SDK and instead generate a raw HTTP request to the Secrets
  Manager service endpoint, then you must generate a ClientRequestToken yourself for new
  versions and include that value in the request. You only need to specify this value if you
  implement your own retry logic and you want to ensure that Secrets Manager doesn't attempt
  to create a secret version twice. We recommend that you generate a UUID-type value to
  ensure uniqueness within the specified secret.
- `"RotationLambdaARN"`: The ARN of the Lambda rotation function that can rotate the secret.
- `"RotationRules"`: A structure that defines the rotation configuration for this secret.
"""
function rotate_secret(SecretId; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "RotateSecret",
        Dict{String,Any}("SecretId" => SecretId, "ClientRequestToken" => string(uuid4()));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function rotate_secret(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "RotateSecret",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "SecretId" => SecretId, "ClientRequestToken" => string(uuid4())
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Removes the link between the replica secret and the primary secret and promotes the replica
to a primary secret in the replica Region. You must call this operation from the Region in
which you want to promote the replica to a primary secret.

# Arguments
- `secret_id`: The ARN of the primary secret.

"""
function stop_replication_to_replica(
    SecretId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return secrets_manager(
        "StopReplicationToReplica",
        Dict{String,Any}("SecretId" => SecretId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function stop_replication_to_replica(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "StopReplicationToReplica",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SecretId" => SecretId), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Attaches tags to a secret. Tags consist of a key name and a value. Tags are part of the
secret's metadata. They are not associated with specific versions of the secret. This
operation appends tags to the existing list of tags. The following restrictions apply to
tags:   Maximum number of tags per secret: 50   Maximum key length: 127 Unicode characters
in UTF-8   Maximum value length: 255 Unicode characters in UTF-8   Tag keys and values are
case sensitive.   Do not use the aws: prefix in your tag names or values because Amazon Web
Services reserves it for Amazon Web Services use. You can't edit or delete tag names or
values with this prefix. Tags with this prefix do not count against your tags per secret
limit.   If you use your tagging schema across multiple services and resources, other
services might have restrictions on allowed characters. Generally allowed characters:
letters, spaces, and numbers representable in UTF-8, plus the following special characters:
+ - = . _ : / @.    If you use tags as part of your security strategy, then adding or
removing a tag can change permissions. If successfully completing this operation would
result in you losing your permissions for this secret, then the operation is blocked and
returns an Access Denied error.

# Arguments
- `secret_id`: The identifier for the secret to attach tags to. You can specify either the
  Amazon Resource Name (ARN) or the friendly name of the secret. For an ARN, we recommend
  that you specify a complete ARN rather than a partial ARN.
- `tags`: The tags to attach to the secret as a JSON text string argument. Each element in
  the list consists of a Key and a Value. For storing multiple values, we recommend that you
  use a JSON text string argument and specify key/value pairs. For more information, see
  Specifying parameter values for the Amazon Web Services CLI in the Amazon Web Services CLI
  User Guide.

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

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

Removes specific tags from a secret. This operation is idempotent. If a requested tag is
not attached to the secret, no error is returned and the secret metadata is unchanged.  If
you use tags as part of your security strategy, then removing a tag can change permissions.
If successfully completing this operation would result in you losing your permissions for
this secret, then the operation is blocked and returns an Access Denied error.

# Arguments
- `secret_id`: The ARN or name of the secret. For an ARN, we recommend that you specify a
  complete ARN rather than a partial ARN.
- `tag_keys`: A list of tag key names to remove from the secret. You don't specify the
  value. Both the key and its associated value are removed. This parameter requires a JSON
  text string argument. For storing multiple values, we recommend that you use a JSON text
  string argument and specify key/value pairs. For more information, see Specifying parameter
  values for the Amazon Web Services CLI in the Amazon Web Services CLI User Guide.

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

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

Modifies the details of a secret, including metadata and the secret value. To change the
secret value, you can also use PutSecretValue. To change the rotation configuration of a
secret, use RotateSecret instead. We recommend you avoid calling UpdateSecret at a
sustained rate of more than once every 10 minutes. When you call UpdateSecret to update the
secret value, Secrets Manager creates a new version of the secret. Secrets Manager removes
outdated versions when there are more than 100, but it does not remove versions created
less than 24 hours ago. If you update the secret value more than once every 10 minutes, you
create more versions than Secrets Manager removes, and you will reach the quota for secret
versions. If you include SecretString or SecretBinary to create a new secret version,
Secrets Manager automatically attaches the staging label AWSCURRENT to the new version.  If
you call this operation with a VersionId that matches an existing version's
ClientRequestToken, the operation results in an error. You can't modify an existing
version, you can only create a new version. To remove a version, remove all staging labels
from it. See UpdateSecretVersionStage. If you don't specify an KMS encryption key, Secrets
Manager uses the Amazon Web Services managed key aws/secretsmanager. If this key doesn't
already exist in your account, then Secrets Manager creates it for you automatically. All
users and roles in the Amazon Web Services account automatically have access to use
aws/secretsmanager. Creating aws/secretsmanager can result in a one-time significant delay
in returning the result.  If the secret is in a different Amazon Web Services account from
the credentials calling the API, then you can't use aws/secretsmanager to encrypt the
secret, and you must create and use a customer managed key.  To run this command, you must
have secretsmanager:UpdateSecret permissions. If you use a customer managed key, you must
also have kms:GenerateDataKey and kms:Decrypt permissions .

# Arguments
- `secret_id`: The ARN or name of the secret. For an ARN, we recommend that you specify a
  complete ARN rather than a partial ARN.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ClientRequestToken"`: If you include SecretString or SecretBinary, then Secrets Manager
  creates a new version for the secret, and this parameter specifies the unique identifier
  for the new version.  If you use the Amazon Web Services CLI or one of the Amazon Web
  Services SDKs to call this operation, then you can leave this parameter empty. The CLI or
  SDK generates a random UUID for you and includes it as the value for this parameter in the
  request. If you don't use the SDK and instead generate a raw HTTP request to the Secrets
  Manager service endpoint, then you must generate a ClientRequestToken yourself for the new
  version and include the value in the request.  This value becomes the VersionId of the new
  version.
- `"Description"`: The description of the secret.
- `"KmsKeyId"`: The ARN, key ID, or alias of the KMS key that Secrets Manager uses to
  encrypt new secret versions as well as any existing versions the staging labels AWSCURRENT,
  AWSPENDING, or AWSPREVIOUS. For more information about versions and staging labels, see
  Concepts: Version.  You can only use the Amazon Web Services managed key aws/secretsmanager
  if you call this operation using credentials from the same Amazon Web Services account that
  owns the secret. If the secret is in a different account, then you must use a customer
  managed key and provide the ARN of that KMS key in this field. The user making the call
  must have permissions to both the secret and the KMS key in their respective accounts.
- `"SecretBinary"`: The binary data to encrypt and store in the new version of the secret.
  We recommend that you store your binary data in a file and then pass the contents of the
  file as a parameter.  Either SecretBinary or SecretString must have a value, but not both.
  You can't access this parameter in the Secrets Manager console.
- `"SecretString"`: The text data to encrypt and store in the new version of the secret. We
  recommend you use a JSON structure of key/value pairs for your secret value.  Either
  SecretBinary or SecretString must have a value, but not both.
"""
function update_secret(SecretId; aws_config::AbstractAWSConfig=global_aws_config())
    return secrets_manager(
        "UpdateSecret",
        Dict{String,Any}("SecretId" => SecretId, "ClientRequestToken" => string(uuid4()));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_secret(
    SecretId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "UpdateSecret",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "SecretId" => SecretId, "ClientRequestToken" => string(uuid4())
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_secret_version_stage(secret_id, version_stage)
    update_secret_version_stage(secret_id, version_stage, params::Dict{String,<:Any})

Modifies the staging labels attached to a version of a secret. Secrets Manager uses staging
labels to track a version as it progresses through the secret rotation process. Each
staging label can be attached to only one version at a time. To add a staging label to a
version when it is already attached to another version, Secrets Manager first removes it
from the other version first and then attaches it to this one. For more information about
versions and staging labels, see Concepts: Version.  The staging labels that you specify in
the VersionStage parameter are added to the existing list of staging labels for the
version.  You can move the AWSCURRENT staging label to this version by including it in this
call.  Whenever you move AWSCURRENT, Secrets Manager automatically moves the label
AWSPREVIOUS to the version that AWSCURRENT was removed from.  If this action results in the
last label being removed from a version, then the version is considered to be 'deprecated'
and can be deleted by Secrets Manager.

# Arguments
- `secret_id`: The ARN or the name of the secret with the version and staging labelsto
  modify. For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.
- `version_stage`: The staging label to add to this version.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MoveToVersionId"`: The ID of the version to add the staging label to. To remove a label
  from a version, then do not specify this parameter. If the staging label is already
  attached to a different version of the secret, then you must also specify the
  RemoveFromVersionId parameter.
- `"RemoveFromVersionId"`: The ID of the version that the staging label is to be removed
  from. If the staging label you are trying to attach to one version is already attached to a
  different version, then you must include this parameter and specify the version that the
  label is to be removed from. If the label is attached and you either do not specify this
  parameter, or the version ID does not match, then the operation fails.
"""
function update_secret_version_stage(
    SecretId, VersionStage; aws_config::AbstractAWSConfig=global_aws_config()
)
    return secrets_manager(
        "UpdateSecretVersionStage",
        Dict{String,Any}("SecretId" => SecretId, "VersionStage" => VersionStage);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_secret_version_stage(
    SecretId,
    VersionStage,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "UpdateSecretVersionStage",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("SecretId" => SecretId, "VersionStage" => VersionStage),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

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

Validates that a resource policy does not grant a wide range of principals access to your
secret. A resource-based policy is optional for secrets. The API performs three checks when
validating the policy:   Sends a call to Zelkova, an automated reasoning engine, to ensure
your resource policy does not allow broad access to your secret, for example policies that
use a wildcard for the principal.   Checks for correct syntax in a policy.   Verifies the
policy does not lock out a caller.

# Arguments
- `resource_policy`: A JSON-formatted string that contains an Amazon Web Services
  resource-based policy. The policy in the string identifies who can access or manage this
  secret and its versions. For example policies, see Permissions policy examples.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"SecretId"`: This field is reserved for internal use.
"""
function validate_resource_policy(
    ResourcePolicy; aws_config::AbstractAWSConfig=global_aws_config()
)
    return secrets_manager(
        "ValidateResourcePolicy",
        Dict{String,Any}("ResourcePolicy" => ResourcePolicy);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function validate_resource_policy(
    ResourcePolicy,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return secrets_manager(
        "ValidateResourcePolicy",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ResourcePolicy" => ResourcePolicy), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end


text:
using DiscreteEvents, Distributions

function people(sim::Simulation, β::Float64, queue::Array{Int64,1}, clerk::Resource)
    i = 1
    while true
        Δt = rand(Exponential(β))
        yield(Timeout(sim, Δt))
        @process customer(sim, i, queue, clerk)
        i += 1
    end
end

function customer(sim::Simulation, n::Int64, queue::Array{Int64,1}, clerk::Resource)
    wt = 0
    if length(queue) ≥ 5
        wt = -1
        logevent(sim, n, queue, "leaves - queue is full!", wt)
        return
    else
        arrivaltime = now(sim)
        logevent(sim, n, queue, "enqueues", wt)
        push!(queue, n)
        yield(Request(clerk))
        shift!(queue)
        logevent(sim, n, queue, "now being served", wt)
        Δt = rand(DiscreteUniform(1, 5)) + randn()*0.2
        yield(Timeout(sim, Δt))
        yield(Release(clerk))
        wt = now(sim)-arrivaltime
        logevent(sim, n, queue, "leaves", wt)
    end
end

simlog = newlog()
ev = Dict("customer"=>0, "queue_len"=>0, "status"=>"", "wait_time"=>0)
dict2log(simlog, ev)

function logevent(sim::Simulation, customer, queue, status, wt)
    ev["customer"] = customer
    ev["queue_len"] = length(queue)
    ev["status"] = status
    if wt != 0
        ev["wait_time"] = wt
    end
    lognow(sim, simlog)
end

srand(1234)  # seed random number generator for reproducibility
queue = Int64[]

sim = Simulation()
clerk = Resource(sim, 1)
@process people(sim, 3.333, queue, clerk)
run(sim, 600)
d = log2df(simlog)                   # logged data to dataframe
println(queue, " yet in queue")
tail(d)

ext: jl


text:
# ex is a hardware function block
# passedArguments is the passed Tuple which represents its arguments
function parameterize(ex::Expr, passedArgs::Expr)
    jexpr = Expr(:function)
    jargs = Array{Any}(2)

    funcArgs = ex.args[1]
    # Resolve the keyword parameters
    if isa(funcArgs.args[2], Expr) && funcArgs.args[2].head == :parameters
        # The funcArgs[2] arguments must be keywords
        l = length(funcArgs.args[2].args)
        pkArgs = passedArgs.args[1]
        if isa(pkArgs, Expr) && pkArgs.head == :parameters
            m = length(pkArgs.args)
            for i = 1:l
                keywordSymbol = funcArgs.args[2].args[i].args[1]
                keywordValue = funcArgs.args[2].args[i].args[2]
                for j = 1:m
                    if keywordSymbol == pkArgs.args[j].args[1]
                        keywordValue = pkArgs.args[j].args[2]
                        break
                    end
                end
                eval( :($(keywordSymbol) = $(keywordValue)) )
            end
        else
            for i = 1:l
                keywordSymbol = funcArgs.args[2].args[i].args[1]
                keywordValue = funcArgs.args[2].args[i].args[2]
                eval( :($(keywordSymbol) = $(keywordValue)) )
            end
        end

        # Remove the keywords
        jargs[1] = [funcArgs.args[1] ; funcArgs.args[3:end]]
    else
        jargs[1] = funcArgs
    end

    global wireSymArray = Array{Symbol}(0)
    # parameterize the expression block
    #  now with complete keyword information
    jargs[2] = JPblock(ex.args[2])

    jexpr.args = jargs
    return jexpr
end

function JPblock(ex::Expr)
    l = length(ex.args)
    for i = 1:l
        arg = ex.args[i]
        if     isa(arg, Expr)
            ex.args[i] = JPblockhelper(arg)
        elseif isa(arg, Symbol) && isdefined(arg)
            ex.args[i] = eval(arg)
        end
    end
    # scrub out the nothing(s)
    l = length(ex.args)
    i = 1
    while i <= l
        arg = ex.args[i]
        if arg === nothing
            deleteat!(ex.args, i)
            l = l - 1
        else
            i = i + 1
        end
    end
    # raise the blocks
    i = 1
    while i <= length(ex.args)
        arg = ex.args[i]
        if isa(arg, Expr) && arg.head == :block
            index = i
            args_ref = arg.args
            ar = length(args_ref)
            for j = 1:ar
                insert!(ex.args, index, args_ref[j])
                index = index + 1
            end
            deleteat!(ex.args, index)
        else
            i = i + 1
        end
    end

    return ex
end

function JPblockhelper(ex::Expr)
    h = ex.head
    if     h == :(=)
        return JPequals(ex)
    elseif h == :(:=)
        return JPassignment(ex)
    elseif h == :const
        return JPconst(ex)
    elseif h == :global
        if isa(ex.args[1], Expr)
            error("global expressions are not supported.")
        end
        eval(ex)
        return nothing
    elseif h == :import
        eval(ex)
        return nothing
    elseif h == :macrocall
        return JPmacro(ex)
    elseif h == :if
        return JPif(ex)
    elseif h == :for
        return JPfor(ex)
    elseif h == :while
        error("hit unfinished block: $(h)")
    else
        error("hit unexpected expr head $(h) in JPblockhelper:\n$(ex)")
    end
end

function JPequals(ex::Expr)
    global wireSymArray
    assn = ex.args[2]
    if     isa(assn, Expr)
        ex.args[2] = JPrhs(assn)
    elseif isa(assn, Symbol) && isdefined(assn)
        ex.args[2] = eval(assn)
    end

    if isa(ex.args[1], Expr)
        ex.args[1] = JPlhs(ex.args[1])
    else
        if isa(assn ,Expr) && JPwiredec(assn)
            push!(wireSymArray, ex.args[1])
        end
        if !isa(ex.args[2], Symbol) && !isa(ex.args[2], Expr) && !in(ex.args[1], wireSymArray)
            eval(ex)
            return nothing
        elseif isa(ex.args[2], Expr) && isevaluable(ex.args[2]) && !in(ex.args[1], wireSymArray)
            eval(ex)
            return nothing
        end
    end
    return ex
end

function JPassignment(ex::Expr)
    assn = ex.args[2]
    if     isa(assn, Expr)
        ex.args[2] = JPrhs(assn)
    elseif isa(assn, Symbol) && isdefined(assn)
        ex.args[2] = eval(assn)
    end

    if isa(ex.args[1], Expr)
        ex.args[1] = JPlhs(ex.args[1])
    end
    return ex
end

function JPconst(ex::Expr)
    assn = ex.args[1].args[2]
    if     isa(assn, Expr)
        ex.args[1].args[2] = JPrhs(assn)
    elseif isa(assn, Symbol) && isdefined(assn)
        ex.args[1].args[2] = eval(assn)
    end
    if isevaluable(ex.args[1].args[2])
        eval(ex)
        return nothing
    end
    return ex
end

function JPrhs(ex::Expr)
    h = ex.head
    if     h == :call
        return JPcall(ex)
    elseif h == :vcat
        return JPvcat(ex)
    elseif h == :ref
        return JPref(ex)
    elseif h == :if
        return JPif(ex)
    else
        error("Hit unexpected expression symbol $(h) in JPrhs on expression:\n$(ex)")
    end
end

function JPlhs(ex::Expr)
    h = ex.head
    if     h == :call
        return JPcall(ex)
    elseif h == :ref
        return JPref(ex)
    elseif h == :vcat
        return JPvcat(ex)
    elseif h == :tuple
        return JPtuple(ex)
    else
        error("Hit unexpected expression symbol $(h) in JPlhs on expression:\n$(ex)")
    end
end

function JPcall(ex::Expr)
    if ex.args[1] != :(<=)
        # Is not a Non-Blocking operator
        l = length(ex.args)
        for i = 1:l
            arg = ex.args[i]
            if     isa(arg, Expr)
                ex.args[i] = JPcallhelper(arg)
            # move to check for module i.e. main
            elseif isa(arg, Symbol) && isdefined(arg)
                ex.args[i] = eval(arg)
            end
        end
        if isevaluable(ex)
            return eval(ex)
        end
        return ex
    else
        # Definitely a Non-Blocking operator
        assn = ex.args[3]
        if     isa(assn, Expr)
            ex.args[3] = JPrhs(assn)
        elseif isa(assn, Symbol) && isdefined(assn)
            ex.args[3] = eval(assn)
        end

        if isa(ex.args[2], Expr)
            ex.args[2] = JPlhs(ex.args[1])
        end
        return ex
    end
end

function JPcallhelper(ex::Expr)
    h = ex.head
    if     h == :call
        return JPcall(ex)
    elseif h == :vcat
        return JPvcat(ex)
    elseif h == :ref
        return JPref(ex)
    elseif h == :if
        return JPif(ex)
    else
        error("Hit unexpected expression symbol $(h) in JPcall on expression:\n$(ex)")
    end
end

function JPvcat(ex::Expr)
    l = length(ex.args)
    for i = 1:l
        arg = ex.args[i]
        if     isa(arg, Expr)
            ex.args[i] = JPvcathelper(arg)
        # move to check for module i.e. main
        elseif isa(arg, Symbol) && isdefined(arg)
            ex.args[i] = eval(arg)
        end
    end
    if isevaluable(ex)
        return eval(ex)
    end
    return ex
end

# MOON vcats in vcats set up busses, matrices
function JPvcathelper(ex::Expr)
    h = ex.head
    if     h == :call
        return JPcall(ex)
    elseif h == :vcat
        return JPvcat(ex)
    elseif h == :ref
        return JPref(ex)
    else
        error("Hit unexpected expression symbol $(h) in JPvcat on expression:\n$(ex)")
    end
end

# MOON Confirm Matrix and Verilog notation operation
function JPref(ex::Expr)
    l = length(ex.args)
    for i = 1:l
        arg = ex.args[i]
        if isa(arg, Expr)
            ex.args[i] = JPrefhelper(arg)
        elseif isa(arg, Symbol) && isdefined(arg)
            ex.args[i] = eval(arg)
        end
    end
    if isa(ex.args[1], Symbol) && isdefined(ex.args[1]) && JPrefevaluable(ex)
        eval(ex)
        return ex
    end
    return ex
end

function JPrefhelper(ex::Expr)
    if     ex.head == :ref || ex.head == :(:)
        l = length(ex.args)
        for i = 1:l
            arg = ex.args[i]
            if     isa(arg, Expr)
                ex.args[i] = JPrefhelper(arg)
            elseif isa(arg, Symbol) && isdefined(arg)
                ex.args[i] = eval(arg)
            end
        end
        return ex
    elseif ex.head == :call
        return JPcall(ex)
    else
        error("Hit an unexpected expr head in JPrefhelper:\n$(ex)")
    end
end

function JPrefevaluable(ex::Expr)
    l = length(ex.args)
    for i = 1:l
        if isa(ex.args[i], Expr) && ex.args[i].head == :ref
            return false
        end
        if JPrefevaluable(ex.args[i]) == false
            return false
        end
    end
    return true
end

function JPif(ex::Expr)
    if isa(ex.args[1], Expr)
        if     ex.args[1].head == :ref
            ex.args[1] = JPref(ex.args[1])
        elseif ex.args[1].head == :call
            ex.args[1] = JPcall(ex.args[1])
        else
            error("Incorrect if condition syntax:\n$(ex)")
        end
    end

    condition = ex.args[1]
    if isa(condition, Bool)
        if condition
            arg = ex.args[2]
            if     isa(arg, Expr)
                return JPreduce(arg)
            elseif isa(arg, Symbol) && isdefined(arg)
                return eval(arg)
            else
                return arg
            end
        else
            if length(ex.args) == 3
                arg = ex.args[3]
                if     isa(arg, Expr)
                    return JPreduce(arg)
                elseif isa(arg, Symbol) && isdefined(arg)
                    return eval(arg)
                else
                    return arg
                end
            else
                return nothing
            end
        end
    else
        if     isa(ex.args[2], Expr)
            ex.args[2] = JPreduce(ex.args[2])
        elseif isa(ex.args[2], Symbol) && isdefined(ex.args[2])
            ex.args[2] = eval(ex.args[2])
        end
        if length(ex.args) == 3
            if     isa(ex.args[3], Expr)
                ex.args[3] = JPreduce(ex.args[3])
            elseif isa(ex.args[3], Symbol) && isdefined(ex.args[3])
                ex.args[3] = eval(ex.args[3])
            end
        end

        return ex
    end
end

function JPreduce(ex::Expr)
    h = ex.head
    if     h == :call
        return JPcall(ex)
    elseif h == :vcat
        return JPvcat(ex)
    elseif h == :ref
        return JPref(ex)
    elseif h == :if
        return JPif(ex)
    elseif h == :block
        return JPblock(ex)
    else
        error("Hit unexpected expression symbol $(h) in JPreduce on expression:\n$(ex)")
    end
end

function JPfor(ex::Expr)
    h = ex.args[1].args[2].head
    if     h == :(:)
        return JPforcolon(ex)
    elseif h == :hcat
        return JPforarray(ex)
        warn("hcat functionality not guaranteed in JPfor on expression:\n$(ex)")
    elseif h == :vcat
        return JPforarray(ex)
        warn("vcat functionality not guaranteed in JPfor on expression:\n$(ex)")
    elseif h == :vect
        return JPforarray(ex)
        warn("vect functionality not guaranteed in JPfor on expression:\n$(ex)")
    else
        error("Hit unexpected expression symbol $(h) in JPfor on expression:\n$(ex)")
    end
end

function JPforcolon(ex::Expr)
    subex = ex.args[1].args[2]
    # subex represents the looping condition
    l = length(subex.args)
    for i = 1:l
        arg = subex.args[i]
        if     isa(arg, Expr)
            ex.args[1].args[2].args[i] = JPreduce(arg)
        elseif isa(arg, Symbol) && isdefined(arg)
            ex.args[1].args[2].args[i] = eval(arg)
        end
    end

    l = length(subex.args)
    if isevaluable(subex)
        if l == 2 && subex.args[1] > subex.args[2]
            warn("Skipping over for loop due to negative order")
        end
        ex.args[1].args[2] = eval(subex)
    end

    loop = ex.args[1].args[2]
    sym = ex.args[1].args[1]
    block_arguments = Array{Any}(0)
    for i = loop
        arg_copy = copy(ex.args[2])
        overwrite = :($sym = $i)
        eval(overwrite)
        arg_copy = JPblock(arg_copy)
        append!(block_arguments, arg_copy.args)
    end
    new_ex = Expr(:block)
    new_ex.args = block_arguments
    return new_ex
end

function JPforarray(ex::Expr)
    subex = ex.args[1].args[2]
    # subex represents the looping condition
    l = length(subex.args)
    for i = 1:l
        arg = subex.args[i]
        if     isa(arg, Expr)
            ex.args[1].args[2].args[i] = JPreduce(arg)
        elseif isa(arg, Symbol) && isdefined(arg)
            ex.args[1].args[2].args[i] = eval(arg)
        end
    end

    loop = ex.args[1].args[2]
    sym = ex.args[1].args[1]
    block_arguments = Array{Any}(0)
    for i = loop
        arg_copy = copy(ex.args[2])
        overwrite = :($sym = $i)
        eval(overwrite)
        arg_copy = JPblock(arg_copy)
        append!(block_arguments, arg_copy.args)
    end
    new_ex = Expr(:block)
    new_ex.args = block_arguments
    return new_ex
end

function JPmacro(ex::Expr)
    if ex.args[1] == Symbol("@block")
        if isa(ex.args[3] , Expr)
            ex.args[3] = eval(ex.args[3])
        end

        if isa(ex.args[4], Expr)
            # This should always be the case
            #  because a function needs more than one argument
            l = length(ex.args[4].args)
            for i = 1:l
                arg = ex.args[4].args[i]
                if isa(arg, Expr)
                    ex.args[4].args[i] = JPreduce(arg)
                end
            end
        end

        eval(ex)
        return ex
    else
        # Any other macro calls
        l = length(ex.args)
        for i = 2:l
            arg = ex.args[i]
            if isa(arg, Expr)
                ex.args[i] = JPreduce(arg)
            end
        end
        return ex
    end
end

function JPwiredec(ex::Expr)
    if     ex.head == :call
        if length(ex.args) == 1
            arg = ex.args[1]
            return (arg == :Wire) || (arg == :Input) || (arg == :Output)
        else
            return false
        end
    elseif ex.head == :ref
        if isa(ex.args[1], Expr)
            return JPwiredec(ex.args[1])
        end
    end
    return false
end

function isevaluable(ex::Expr)
    for arg in ex.args
        if isa(arg, Symbol) && !isdefined(arg)
            return false
        elseif isa(arg, Expr)
            return false
        end
    end

    return true
end

max_stars_repo_name: trevortheblack/Juliog

max_issues_repo_name: trevortheblack/Juliog

max_forks_repo_name: trevortheblack/Juliog


text:
using MultiscaleGraphSignalTransforms, JLD, Plots, LightGraphs, Distances

## Build weighted toronto street network graph
G = loadgraph("../datasets/new_toronto_graph.lgz"); N = nv(G)
X = load("../datasets/new_toronto.jld", "xy")
dist_X = pairwise(Euclidean(), X; dims = 1)
A = 1.0 .* adjacency_matrix(G)
W = zeros(N, N); W[A .> 0] = 1 ./ dist_X[A .> 0]; W = A .* W
Q = incidence_matrix(G; oriented = true)
edge_weight = 1 ./ sqrt.(sum((Q' * X).^2, dims = 2)[:])

## eigenvectors of L(G)
deg = sum(W, dims = 1)[:]  # weighted degree vector
L = diagm(deg) - W
𝛌, 𝚽 = eigen(L)
standardize_eigenvectors!(𝚽)

## eigenvectors of Lsym(G)
Lsym = diagm(deg.^(-1/2)) * (diagm(deg) - W) * diagm(deg.^(-1/2))
𝛌sym, 𝚽sym = eigen(Lsym)
standardize_eigenvectors!(𝚽sym)

## Build Dual Graph by DAG metric
distDAG = eigDAG_Distance(𝚽, Q, N; edge_weight = edge_weight) #52.375477 seconds
Gstar_Sig = dualgraph(distDAG)
G_Sig = GraphSig(A, xy = X); G_Sig = Adj2InvEuc(G_Sig)
GP_dual = partition_tree_fiedler(Gstar_Sig; swapRegion = false)
GP_primal = pairclustering(𝚽, GP_dual)
jmax = size(GP_dual.rs, 2) - 1  # zero-indexed

if allNGWPs
    #1315.821724 seconds (3.05 M allocations: 495.010 GiB, 7.04% gc time)
    @time VM_NGWP = vm_ngwp(𝚽, GP_dual)
    #119.590168 seconds (12.14 M allocations: 158.035 GiB, 13.89% gc time)
    @time PC_NGWP = pc_ngwp(𝚽, GP_dual, GP_primal)
    @time LP_NGWP = lp_ngwp(𝚽, Gstar_Sig.W, GP_dual; ϵ = 0.3)
end

## Build Dual Graph by DAG metric (Lsym)
distDAG_Lsym = eigDAG_Distance(𝚽sym, Q, N; edge_weight = edge_weight)
Gstar_Sig_Lsym = dualgraph(distDAG_Lsym)
GP_dual_Lsym = partition_tree_fiedler(Gstar_Sig_Lsym; swapRegion = false)
GP_primal_Lsym = pairclustering(𝚽sym, GP_dual_Lsym)
jmax_Lsym = size(GP_dual_Lsym.rs, 2) - 1

if allNGWPs
    VM_NGWP_Lsym = vm_ngwp(𝚽sym, GP_dual_Lsym)
    PC_NGWP_Lsym = pc_ngwp(𝚽sym, GP_dual_Lsym, GP_primal_Lsym)
    LP_NGWP_Lsym = lp_ngwp(𝚽sym, Gstar_Sig_Lsym.W, GP_dual_Lsym; ϵ = 0.3)
end


text:
__precompile__()

module LorentzVectors

import LinearAlgebra: dot, ⋅, cross, ×, norm, normalize
import Random: rand, AbstractRNG

import Base: +, -, *, /, ==, isapprox, ≈, zero

export LorentzVector, SpatialVector, Vec4, Vec3
export dot, ⋅, cross, ×, norm, normalize
export boost, rotate

"""
    LorentzVector(t, x, y, z)

Lorentz 4-vector, as used in Special Relativity.

The metric convention is g = diag(+1,-1,-1,-1). No distinction is made between
co- and contravariant vectors.
"""
struct LorentzVector{T <: AbstractFloat}
    t :: T
    x :: T
    y :: T
    z :: T
end

"""
    SpatialVector(x, y, z)

Spatial part of a Lorentz 4-vector.
"""
struct SpatialVector{T <: AbstractFloat}
    x :: T
    y :: T
    z :: T
end

"""
    LorentzVector(t, x, y, z)

Promoting constructors for LorentzVector{T}.
"""
LorentzVector(t, x, y, z) = LorentzVector(promote(t, x, y, z)...)
LorentzVector(t::T, x::T, y::T, z::T) where {T <: Union{Integer, Rational, Irrational}} =
    LorentzVector(float(t), x, y, z)

"""
    SpatialVector(x, y, z)

Promoting constructors for SpatialVector{T}.
"""
SpatialVector(x, y, z) = SpatialVector(promote(x, y, z)...)
SpatialVector(x::T, y::T, z::T) where {T <: Union{Integer, Rational, Irrational}} =
    SpatialVector(float(x), y, z)

"""
    SpatialVector(u)

Construct a 3-vector from the spatial part of a 4-vector.
"""
SpatialVector(u::LorentzVector) = SpatialVector(u.x, u.y, u.z)

"""
    LorentzVector(t, u)

Construct a 4-vector from a time component and a 3-vector.
"""
LorentzVector(t::T, u::SpatialVector{U}) where {T,U} =
    LorentzVector(t, u.x, u.y, u.z)

"""
    zero(LorentzVector{T})
    zero(LorentzVector)

Constructs a zero four-vector.
"""
zero(::Type{LorentzVector{T}}) where {T} = LorentzVector{T}(zero(T), zero(T), zero(T), zero(T))
zero(::Type{LorentzVector}) = zero(LorentzVector{Float64})

"""
    zero(SpatialVector{T})
    zero(SpatialVector)

Constructs a zero three-vector.
"""
zero(::Type{SpatialVector{T}}) where {T} = SpatialVector{T}(zero(T), zero(T), zero(T))
zero(::Type{SpatialVector}) = zero(SpatialVector{Float64})

"Alias of LorentzVector"
const Vec4 = LorentzVector

"Alias of SpatialVector"
const Vec3 = SpatialVector

function +(u::LorentzVector)
    u
end

function +(u::LorentzVector, v::LorentzVector)
    @fastmath LorentzVector(u.t + v.t, u.x + v.x, u.y + v.y, u.z + v.z)
end

function -(u::LorentzVector)
    @fastmath LorentzVector(-u.t, -u.x, -u.y, -u.z)
end

function -(u::LorentzVector, v::LorentzVector)
    @fastmath u + (-v)
end

function *(λ::Number, u::LorentzVector)
    @fastmath LorentzVector(λ*u.t, λ*u.x, λ*u.y, λ*u.z)
end

function *(u::LorentzVector, λ::Number)
    @fastmath λ * u
end

function /(u::LorentzVector, λ::Number)
    @fastmath u * (one(λ) / λ)
end

function +(u::SpatialVector)
    u
end

function +(u::SpatialVector, v::SpatialVector)
    @fastmath SpatialVector(u.x + v.x, u.y + v.y, u.z + v.z)
end

function -(u::SpatialVector)
    @fastmath SpatialVector(-u.x, -u.y, -u.z)
end

function -(u::SpatialVector, v::SpatialVector)
    @fastmath u + (-v)
end

function *(λ::Number, u::SpatialVector)
    @fastmath SpatialVector(λ*u.x, λ*u.y, λ*u.z)
end

function *(u::SpatialVector, λ::Number)
    @fastmath λ * u
end

function /(u::SpatialVector, λ::Number)
    @fastmath u * (one(λ) / λ)
end

function ==(u::LorentzVector, v::LorentzVector)
    u.t == v.t && u.x == v.x && u.y == v.y && u.z == v.z
end

function ==(u::SpatialVector, v::SpatialVector)
    u.x == v.x && u.y == v.y && u.z == v.z
end

function isapprox(u::LorentzVector, v::LorentzVector;
                  atol::Real=0,
                  rtol::Real=atol>0 ? 0 : √min(eps(typeof(u.x)), eps(typeof(v.x))))
    err = max(abs(u.t - v.t), norm(Vec3(u)-Vec3(v)))
    err <= max(atol, rtol*max(abs(u.t), abs(v.t), norm(Vec3(u)), norm(Vec3(v))))
end

function isapprox(u::SpatialVector, v::SpatialVector;
                  atol::Real=0,
                  rtol::Real=atol>0 ? 0 : √min(eps(typeof(u.x)), eps(typeof(v.x))))
    err = norm(u-v)
    err <= max(atol, rtol*max(norm(u), norm(v)))
end

"""
    dot(u, v)
    u⋅v

Inner product of 4-vectors, in the Minkowsky metric (+,-,-,-).
"""
function dot(u::LorentzVector, v::LorentzVector)
    @fastmath u.t*v.t - u.x*v.x - u.y*v.y - u.z*v.z
end

function dot(u::SpatialVector, v::SpatialVector)
    @fastmath u.x*v.x + u.y*v.y + u.z*v.z
end

"""
    cross(u, v)
    u×v

Cross product of two spatial vectors.
"""
function cross(u::SpatialVector, v::SpatialVector)
    @fastmath SpatialVector(
        u.y*v.z - u.z*v.y,
        u.z*v.x - u.x*v.z,
        u.x*v.y - u.y*v.x)
end

"""
    norm(x)
"""
function norm(v::SpatialVector)
    @fastmath sqrt(v⋅v)
end

"""
    normalize(x)
"""
function normalize(v::SpatialVector)
    v / norm(v)
end

"""
    rand(rng, SpatialVector)
"""
function rand(r::AbstractRNG, ::Type{V}) where {U <: Real, V <: SpatialVector{U}}
    cθ = 2*rand(r, U) - 1
    sθ = sqrt(1-cθ^2)
    φ = 2π * rand(r, U)
    SpatialVector{U}(sθ * cos(φ), sθ * sin(φ), cθ)
end

function boost(u::LorentzVector, β::LorentzVector)
    boost(u, SpatialVector(β))
end

function boost(u::LorentzVector, β::SpatialVector)
    γ = one(β.x) / sqrt(one(β.x) - β⋅β)
    if γ == one(γ)
        return u
    end
    x_old = Vec3(u)
    t_new = γ * (u.t - β⋅x_old)
    x_new = x_old + ((γ-one(γ)) * (x_old⋅β) / (β⋅β) - γ*u.t) * β
    LorentzVector(t_new, x_new.x, x_new.y, x_new.z)
end

"""
Rotate a vector v by an angle θ around the unit vector k̂, using Rodrigues' rotation formula.

Note: k̂ *must* be normalized, otherwise this method will return the wrong result.

Source: https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula
"""
function rotate(v::SpatialVector, k̂::SpatialVector, θ::Real)
    v*cos(θ) + (k̂×v)*sin(θ) + k̂*(k̂⋅v)*(1-cos(θ))
end

end # module LorentzVectors


text:
function writeArrayForGnuplot(anArray, aFilename)
    writedlm(aFilename, anArray, '\t')
    anArray
end

type Clumped end
type Uniformed end

function drawBSpline(k, controlPoints, fittingPoints)

    if controlPoints[1,:] == controlPoints[end,:]

        m = length(controlPoints[:,1])
        newPartition = [i for i in (-k/(m-1):1/(m-1):(k+m-1)/(m-1))]

        M = sum(ones(m))
        matrix = buildFunctionsMatrix(k, M, newPartition)

        for i=1:k
            controlPoints = [controlPoints; controlPoints[i+1,:]]
        end

        return drawCurve(newPartition, k, M, controlPoints, matrix, fittingPoints)
    end

end

function drawCurve(extendedPartition, k, M, controlPoints, matrix, fittingPoints)

    ## paramRange = linspace(minimum(extendedPartition),
    ##                       maximum(extendedPartition),
    ##                       fittingPoints)

    ## fittingPoints += 1
    paramRange = linspace(0,
                          1-eps(Float64),
                          fittingPoints)

    bspline = zeros(fittingPoints, length(controlPoints[1,:]))
    for i=1:fittingPoints
        bspline[i,:] = bsplineAtParam(paramRange[i],
                                      k,
                                      M,
                                      controlPoints,
                                      matrix)
    end
    bspline
    ## bspline[1:end-1, :]
end

function bsplineAtParam(t, k, M, controlPoints, matrix)
    value = zeros(length(controlPoints[1,:]))'
    ## if length(controlPoints[:,1]) != (k+M)
    ##     error("Control points aren't enough")
    ## end
    for i=1:(k+M)
        v = controlPoints[i,:]
        N_ik = matrix[i,k]
        value += v*N_ik(t)
    end
    value
end

function extendedPartitionAttempt(k, partition, spacing::Clumped)
    previous_zeros = zeros(k)
    following_ones = ones(k)
    M = length(partition)
    middle = zeros(M)
    range = linspace(1/(M+1), M/(M+1), M)
    for i=1:length(range)
        middle[i] = range[i]
    end
    [previous_zeros; middle; following_ones;]
end

function extendedPartitionAttempt(k, partition, spacing::Uniformed)
    M = length(partition)
    range = (1-k)/(M+1):1/(M+1):(1+ (k-1)/(M+1))
    nel = length(range)
    extended = zeros(nel)
    for i=1:nel
        extended[i] = range[i]
    end
    extended
end

function buildFunctionsMatrix(k, M, extendedPartition)
    if (2*k + M) != length(extendedPartition)
        error("partition length mismatch dimension")
    end
    firstColumn = []
    for i=1:(k+M+1)
        fn = (t ->
              if (extendedPartition[i] <= t && t < extendedPartition[i+1])
                  1
              else
                  0
              end)
        firstColumn = [firstColumn; fn;]
    end
    ## firstColumn = [firstColumn; (t -> 0);]

    matrix = [firstColumn]
    for h=2:k
        column = []
        for i=1:(k+M)

            augend_coeff = 0
            augend_denominator = extendedPartition[i+h-1] - extendedPartition[i]
            if augend_denominator != 0
                augend_coeff =  1 / augend_denominator
            end

            addend_coeff = 0
            addend_denominator = extendedPartition[i+h] - extendedPartition[i+1]
            if addend_denominator != 0
                addend_coeff =  1 / addend_denominator
            end

            fn = t -> ((t - extendedPartition[i]) * augend_coeff * matrix[i,h-1](t) +
                       (extendedPartition[i+h] - t) * addend_coeff * matrix[i+1,h-1](t))

            column = [column; fn;]
        end
        lastFn = (t ->
              if (extendedPartition[k+M+1] <= t && t < extendedPartition[k+M+2])
                  0
              else
                  0
              end)

        column = [column; lastFn;]
        matrix = [matrix column]
    end

    matrix

end

type Maximum end

function normalizeRespect(vector, _::Maximum, k = 1)
    m = maximum(vector[1:end - (k-1)])
    return map(t -> t/m, vector)
end

function expandPartition(partition, multiplicityVector)

    extended = []

    for i=1:length(multiplicityVector)
        augmenting = [partition[i] for _=1:multiplicityVector[i] ]
        extended = [extended; augmenting;]
    end

    extended
end

function knotsInsertion_head(controlPoints, partition, n, L)

    fittingPoints = 100
    working_partition = partition[n:n+L]
    paramRange = linspace(working_partition[1],
                          working_partition[end],
                          fittingPoints)

    ## u = working_partition[1] + rand()*(working_partition[end]-working_partition[1])

    results = zeros(fittingPoints, length(controlPoints[1,:]))
    for j=1:fittingPoints-1

        u = paramRange[j]

        workingControlPoints = controlPoints
        workingPartition = partition
        workingL = L

        for i=1:n
            workingControlPoints, workingPartition, workingL =
                knotsInsertion(workingControlPoints, workingPartition, n, workingL, u)
        end

        ## for i=1:length(workingControlPoints[:,1])-1
        ##     if(workingControlPoints[i,:] == workingControlPoints[i+1,:])
                k = findfirst(x -> x == u, workingPartition)
                results[j,:] = workingControlPoints[k,:]
        ##         break
        ##     end
        ## end
    end

    results[1:end-1,:]
end

function knotsInsertion(controlPoints, partition, n, L, u)
    ## working_partition = partition[n:n+L]
    ## ## u = working_partition[1] + rand()*(working_partition[end]-working_partition[1])
    ## u = 2.5

    ## if (count(x -> x == u, partition) == n)
    ##     return controlPoints, partition, n, L
    ## end

    I = -1
    for i = length(partition):-1:(n+1)
        if(partition[i] > u && partition[i-1] <= u)
            I = i-1
            break
        end
    end

    last_index = L+n+1
    refined_partition = zeros(last_index+1)

    for i=1:I-n+2
        refined_partition[i] = partition[i]
    end

    for i=I-n+3:I+1
        refined_partition[i] = (1/n)*(sum(partition[i:i+n-2]) + u)
    end

    for i=I+2:last_index+1
        refined_partition[i] = partition[i-1]
    end

    refined_controlPoints = zeros(last_index+1, length(controlPoints[1,:]))

    for i=1:I-n+2
        refined_controlPoints[i,:] = controlPoints[i,:]
    end

    for i=I-n+3:I+1
        diff = partition[i+n-1]-partition[i-1]
        coeff = if (diff > 0) 1/diff else 0 end
        first_coeff = partition[i+n-1] - u
        second_coeff = u - partition[i-1]
        refined_controlPoints[i,:] = coeff*(first_coeff*controlPoints[i-1,:] +
                                            second_coeff*controlPoints[i,:])
    end

    for i=I+2:last_index+1
        refined_controlPoints[i,:] = controlPoints[i-1,:]
    end

    partition = [partition; u]
    refined_controlPoints, sort(partition), L+1
end

function deBoor (extendedBreakpointArray,
                 controlPointsMatrix,
                 tabulationArray)

    dimension, numberOfControlPoints = size (controlPointsMatrix)
    k = length (extendedBreakpointArray) - numberOfControlPoints

    C = zeros (dimension, length (tabulationArray))
    ind = 0

    for r = k:numberOfControlPoints

        comparison = r < n ? .< : .<= ;
        isd = (tabulationArray .>= extendedBreakpointArray [r]) & (comparison(tabulationArray, extendedBreakpointArray [r+1]))

        nloc = sum (isd)

        if nloc < 1
            continue
        end

        tloc = tabulationArray[isd]
        Qloc = zeros (k, nloc, dimension)

        ## the following is a one line in substitution of the next line of code
        ## broadcast(+, [[1 2 5]; [3 4 6];], zeros(2, 3, 2))
        [Qloc[:,:,i] = Q[i, r-k+1:r]' * ones(1,nloc) for i=1:dimension]

        for j=1:k-1
            alfa = zeros(k-1,nloc)
            for i=1:k-j
                alfa[i,:] = (tloc - t[i+r-k+j])/ (t[i+r] - t[i+r-k+j])
                [Qloc[i,:,s] = (1-alfa[i,:]) .* Qloc[i,:,s] + alfa[i,:] .* Qloc[i+1,:,s] for s=1:dimension]
            end
        end

        [C[i, ind+1:ind+nloc] = Qloc[1, 1:nloc, i] for i=1:dimension]
        ind += nloc

    end

end

max_stars_repo_name: massimo-nocentini/cagd

max_issues_repo_name: massimo-nocentini/cagd

max_forks_repo_name: massimo-nocentini/cagd


text:
using Flux
using Flux: onehot, argmax, onehotbatch
using Flux.Tracker
using Gadfly
using StatsBase
using Iterators: product
using DataFrames
using CSV
using Distributions: Uniform

# In a RL problem we have an agent A, a State space S and an Action space A

# We need a policy function Π: S x A -> [0,1]
# This means for every state and action we need to be able to make a desicion.

# aux function to calculate reward. If it chooses the winning result it wins
# 3 points if it guesses the winning team then 1 point eoc 0 points
function reward(chosen_a, real_a)
    if chosen_a == real_a
        return 3
    end
    chosen_result = map(x-> parse(Int32, x), split(action_space[chosen_a], " - "))
    real_result = map(x-> parse(Int32, x), split(action_space[real_a], " - "))
    if chosen_result[1] == chosen_result[2] && real_result[1] == real_result[2]
        return 1
    end
    if argmax(chosen_result) == argmax(real_result) &&
            !(chosen_result[1] == chosen_result[2] || real_result[1] == real_result[2])
        return 1
    end
    return 0
end

# Data from past world cups
df = CSV.read("data/worldcup_data.csv", weakrefstrings=false, nullable=false)

# this are all possible results (actions) for the problem.
action_space = ["$i - $j" for (i,j) in sort(collect(product(0:4 , 0:4)), by=sum)]
df[:action] = string.(min.(df[:home_res], 4)) .* " - " .* string.(min.(df[:away_res], 4))
df = sort(df, cols=[:cup, :match])
# with this we build a space from the data of the match. This is the
# space of the model. In this basic experiment we will choose only
# basic data like goals before the match, victories, etc
function build_space(row)
    vcat(row[:home_victories], row[:away_victories],
         row[:home_losses], row[:away_losses],
         row[:home_goals], row[:away_goals],
         row[:home_goals_against], row[:away_goals_against])
end

# build all states. Order by matchnum
states = hcat(map(build_space, eachrow(df))...)'

# normalize the data to improve neural net performance
# https://papers.nips.cc/paper/6114-weight-normalization-a-simple-reparameterization-to-accelerate-training-of-deep-neural-networks.pdf
train = zeros(states, Float32)
for col in 1:size(states)[2]
    train[:, col] = normalize(states[:, col])
end

# this functions update the parameters of the model
function update()
  λ = 0.005 # Learning Rate
  for p in params(model)
    p.data .-= λ .* p.grad # Apply the update
    p.grad .= 0            # Clear the gradient
  end
end

# build the model.
# This will be our Π: S x A -> [0,1]. It will give us the actions
# based on the current state
model = Chain(
  Dense(8, 15, σ),
  Dense(15, 20, relu),
  Dense(20, 25),
  softmax
  )

# one hot representation of the result of all the matches
real_actions = onehotbatch(df[:action], action_space)'

# auxiliary list to know when to train the model
cups = cumsum(Array(by(df, :cup, df -> DataFrame(N = size(df, 1)))[:N]))
push!(cups, 837)
# vanilla crossentropy loss
# our real loss will be crossentropy * reward
# this will help encourage good rewards and penalize bad ones
loss(x,y) = Flux.crossentropy(model(x), y )

# hyperparameters
ϵ = 0.1 # probability of taking random action
γ = 0.999 # discount of reward

# train the model for 100 episodes
for ep in 1:1000
    total_reward = 0
    c = 1
    for i in 1:836
        # get the result of the match
        real_action = argmax(real_actions[i, :])

        # choose a result from given the current state with ϵ of being random
        # ToDo: Fix to make this part of the loss function
        chosen_action = rand() < ϵ ? rand(1:25) : argmax(model(train[i, :]))

        # get reward of the action
        r = reward(chosen_action, real_action)

        # total reward of the episode
        total_reward += r

        # Calclulate loss multiplied by reward
        # given that we know how many actions we we'll take we can calculate
        # the discounted reward
        back!(loss(train[i,:], real_actions[i,:])*r*γ^(cups[c+1]-i))

        # if the cup is done update values of the model
        # from the gradients
        if i in cups
            c += 1
            update()
        end
    end
    println("Total reward for ep $ep: $total_reward")
    println("Loss for ep $ep: $(loss(train[end,:], real_actions[end,:]))")
end

max_stars_repo_name: fisimon/RL-for-FIFA-world-cup

max_issues_repo_name: fisimon/RL-for-FIFA-world-cup

max_forks_repo_name: fisimon/RL-for-FIFA-world-cup


text:
# uses variables from setup_tests.jl

### Verifications: basic Shimer-Smith model ###

"""
Element-by-element calculation of steady state flow equations

```julia
mres = (δ .+ ψ_m) .* ℓ_m - u_m .* ((δ .+ ψ_m) + λ * (α * u_f))
fres = (δ .+ ψ_f) .* ℓ_f - u_f .* ((δ .+ ψ_f) + λ * (α' * u_m))
```
"""
function sse_base(M::SearchMatch)

	mres = similar(M.ℓ_m)
	fres = similar(M.ℓ_f)

	for i in 1:length(M.ℓ_m)
		mres[i] = (M.δ + M.ψ_m[i]) * M.ℓ_m[i] - M.u_m[i] * ((M.δ + M.ψ_m[i]) + M.λ * dot(M.α[i,:], M.u_f))
	end
	for j in 1:length(M.ℓ_f)
		fres[j] = (M.δ + M.ψ_f[j]) * M.ℓ_f[j] - M.u_f[j] * ((M.δ + M.ψ_f[j]) + M.λ * dot(M.α[:,j], M.u_m))
	end
	return mres, fres
end

"""
Element-by-element calculation of value function equations
```julia
mres = 2*v_m - λ * (αS * u_f)
fres = 2*v_f - λ * (αS' * u_m),
```
where `αS = α .* s/(r+δ+ψ_m(x)+ψ_f(y))`.
"""
function vf_base(M::SearchMatch)

	mres = similar(M.v_m)
	fres = similar(M.v_f)

	for i in 1:length(M.v_m)
		mres[i] = 2*M.v_m[i] - M.λ * dot(M.α[i,:] .* M.s[i,:] ./ (M.r+M.δ+M.ψ_m[i].+M.ψ_f), M.u_f)
	end
	for j in 1:length(M.v_f)
		fres[j] = 2*M.v_f[j] - M.λ * dot(M.α[:,j] .* M.s[:,j] ./ (M.r+M.δ+M.ψ_f[j].+M.ψ_m), M.u_m)
	end
	return mres, fres
end

function surplus_base(M::SearchMatch)
	s = similar(M.h)

	for i in 1:length(M.v_m), j in 1:length(M.v_f)
		s[i,j] = M.h[i,j] - M.v_m[i] - M.v_f[j]
	end

	return s
end

### Tests: basic Shimer-Smith model ###

# check convergence
msse, fsse = sse_base(symm)
mvf, fvf = vf_base(symm)
α_err = symm.α .- convert(Array{Float64}, (surplus_base(symm) .> 0.0))

# valid solution
@test msse ≈ zero(msse) atol=1e-7 #market equilibrium: single men did not converge
@test fsse ≈ zero(fsse) atol=1e-7 #market equilibrium: single women did not converge
@test mvf ≈ zero(mvf) atol=1e-7 #matching equilibrium: man values did not converge
@test fvf ≈ zero(fvf) atol=1e-7 #matching equilibrium: woman values did not converge
@test α_err == zero(α_err) #matching equilibrium: match probabilities α did not converge

# symmetry
@test symm.v_m ≈ symm.v_f #expected symmetry of values
@test symm.u_m ≈ symm.u_f #expected symmetry of singles
@test symm.α ≈ symm.α' #expected symmetry of matching