text:
#==============================================================================#
# KinesisAnalytics.jl
#
# This file is generated from:
# https://github.com/aws/aws-sdk-js/blob/master/apis/kinesisanalytics-2015-08-14.normal.json
#==============================================================================#

__precompile__()

module KinesisAnalytics

using AWSCore

"""
    using AWSSDK.KinesisAnalytics.add_application_cloud_watch_logging_option
    add_application_cloud_watch_logging_option([::AWSConfig], arguments::Dict)
    add_application_cloud_watch_logging_option([::AWSConfig]; ApplicationName=, CurrentApplicationVersionId=, CloudWatchLoggingOption=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "AddApplicationCloudWatchLoggingOption", arguments::Dict)
    kinesisanalytics([::AWSConfig], "AddApplicationCloudWatchLoggingOption", ApplicationName=, CurrentApplicationVersionId=, CloudWatchLoggingOption=)

# AddApplicationCloudWatchLoggingOption Operation

Adds a CloudWatch log stream to monitor application configuration errors. For more information about using CloudWatch log streams with Amazon Kinesis Analytics applications, see [Working with Amazon CloudWatch Logs](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/cloudwatch-logs.html).

# Arguments

## `ApplicationName = ::String` -- *Required*
The Kinesis Analytics application name.

## `CurrentApplicationVersionId = ::Int` -- *Required*
The version ID of the Kinesis Analytics application.

## `CloudWatchLoggingOption = [ ... ]` -- *Required*
Provides the CloudWatch log stream Amazon Resource Name (ARN) and the IAM role ARN. Note: To write application messages to CloudWatch, the IAM role that is used must have the `PutLogEvents` policy action enabled.
```
 CloudWatchLoggingOption = [
        "LogStreamARN" => <required> ::String,
        "RoleARN" => <required> ::String
    ]
```

# Returns

`AddApplicationCloudWatchLoggingOptionResponse`

# Exceptions

`ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException` or `ConcurrentModificationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/AddApplicationCloudWatchLoggingOption)
"""
@inline add_application_cloud_watch_logging_option(aws::AWSConfig=default_aws_config(); args...) = add_application_cloud_watch_logging_option(aws, args)

@inline add_application_cloud_watch_logging_option(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "AddApplicationCloudWatchLoggingOption", args)

@inline add_application_cloud_watch_logging_option(args) = add_application_cloud_watch_logging_option(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.add_application_input
    add_application_input([::AWSConfig], arguments::Dict)
    add_application_input([::AWSConfig]; ApplicationName=, CurrentApplicationVersionId=, Input=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "AddApplicationInput", arguments::Dict)
    kinesisanalytics([::AWSConfig], "AddApplicationInput", ApplicationName=, CurrentApplicationVersionId=, Input=)

# AddApplicationInput Operation

Adds a streaming source to your Amazon Kinesis application. For conceptual information, see [Configuring Application Input](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-input.html).

You can add a streaming source either when you create an application or you can use this operation to add a streaming source after you create an application. For more information, see [CreateApplication](@ref).

Any configuration update, including adding a streaming source using this operation, results in a new version of the application. You can use the [DescribeApplication](@ref) operation to find the current application version.

This operation requires permissions to perform the `kinesisanalytics:AddApplicationInput` action.

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of your existing Amazon Kinesis Analytics application to which you want to add the streaming source.

## `CurrentApplicationVersionId = ::Int` -- *Required*
Current version of your Amazon Kinesis Analytics application. You can use the [DescribeApplication](@ref) operation to find the current application version.

## `Input = [ ... ]` -- *Required*
The [Input](@ref) to add.
```
 Input = [
        "NamePrefix" => <required> ::String,
        "InputProcessingConfiguration" =>  ["InputLambdaProcessor" => <required> [
                "ResourceARN" => <required> ::String,
                "RoleARN" => <required> ::String
            ]],
        "KinesisStreamsInput" =>  [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ],
        "KinesisFirehoseInput" =>  [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ],
        "InputParallelism" =>  ["Count" =>  ::Int],
        "InputSchema" => <required> [
            "RecordFormat" => <required> [
                "RecordFormatType" => <required> "JSON" or "CSV",
                "MappingParameters" =>  [
                    "JSONMappingParameters" =>  ["RecordRowPath" => <required> ::String],
                    "CSVMappingParameters" =>  [
                        "RecordRowDelimiter" => <required> ::String,
                        "RecordColumnDelimiter" => <required> ::String
                    ]
                ]
            ],
            "RecordEncoding" =>  ::String,
            "RecordColumns" => <required> [[
                "Name" => <required> ::String,
                "Mapping" =>  ::String,
                "SqlType" => <required> ::String
            ], ...]
        ]
    ]
```

# Returns

`AddApplicationInputResponse`

# Exceptions

`ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException`, `ConcurrentModificationException` or `CodeValidationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/AddApplicationInput)
"""
@inline add_application_input(aws::AWSConfig=default_aws_config(); args...) = add_application_input(aws, args)

@inline add_application_input(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "AddApplicationInput", args)

@inline add_application_input(args) = add_application_input(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.add_application_input_processing_configuration
    add_application_input_processing_configuration([::AWSConfig], arguments::Dict)
    add_application_input_processing_configuration([::AWSConfig]; ApplicationName=, CurrentApplicationVersionId=, InputId=, InputProcessingConfiguration=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "AddApplicationInputProcessingConfiguration", arguments::Dict)
    kinesisanalytics([::AWSConfig], "AddApplicationInputProcessingConfiguration", ApplicationName=, CurrentApplicationVersionId=, InputId=, InputProcessingConfiguration=)

# AddApplicationInputProcessingConfiguration Operation

Adds an [InputProcessingConfiguration](@ref) to an application. An input processor preprocesses records on the input stream before the application's SQL code executes. Currently, the only input processor available is [AWS Lambda](https://aws.amazon.com/documentation/lambda/).

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of the application to which you want to add the input processing configuration.

## `CurrentApplicationVersionId = ::Int` -- *Required*
Version of the application to which you want to add the input processing configuration. You can use the [DescribeApplication](@ref) operation to get the current application version. If the version specified is not the current version, the `ConcurrentModificationException` is returned.

## `InputId = ::String` -- *Required*
The ID of the input configuration to add the input processing configuration to. You can get a list of the input IDs for an application using the [DescribeApplication](@ref) operation.

## `InputProcessingConfiguration = ["InputLambdaProcessor" => <required> [ ... ]]` -- *Required*
The [InputProcessingConfiguration](@ref) to add to the application.
```
 InputProcessingConfiguration = ["InputLambdaProcessor" => <required> [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ]]
```

# Returns

`AddApplicationInputProcessingConfigurationResponse`

# Exceptions

`ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException` or `ConcurrentModificationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/AddApplicationInputProcessingConfiguration)
"""
@inline add_application_input_processing_configuration(aws::AWSConfig=default_aws_config(); args...) = add_application_input_processing_configuration(aws, args)

@inline add_application_input_processing_configuration(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "AddApplicationInputProcessingConfiguration", args)

@inline add_application_input_processing_configuration(args) = add_application_input_processing_configuration(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.add_application_output
    add_application_output([::AWSConfig], arguments::Dict)
    add_application_output([::AWSConfig]; ApplicationName=, CurrentApplicationVersionId=, Output=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "AddApplicationOutput", arguments::Dict)
    kinesisanalytics([::AWSConfig], "AddApplicationOutput", ApplicationName=, CurrentApplicationVersionId=, Output=)

# AddApplicationOutput Operation

Adds an external destination to your Amazon Kinesis Analytics application.

If you want Amazon Kinesis Analytics to deliver data from an in-application stream within your application to an external destination (such as an Amazon Kinesis stream, an Amazon Kinesis Firehose delivery stream, or an Amazon Lambda function), you add the relevant configuration to your application using this operation. You can configure one or more outputs for your application. Each output configuration maps an in-application stream and an external destination.

You can use one of the output configurations to deliver data from your in-application error stream to an external destination so that you can analyze the errors. For conceptual information, see [Understanding Application Output (Destination)](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-output.html).

Note that any configuration update, including adding a streaming source using this operation, results in a new version of the application. You can use the [DescribeApplication](@ref) operation to find the current application version.

For the limits on the number of application inputs and outputs you can configure, see [Limits](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/limits.html).

This operation requires permissions to perform the `kinesisanalytics:AddApplicationOutput` action.

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of the application to which you want to add the output configuration.

## `CurrentApplicationVersionId = ::Int` -- *Required*
Version of the application to which you want to add the output configuration. You can use the [DescribeApplication](@ref) operation to get the current application version. If the version specified is not the current version, the `ConcurrentModificationException` is returned.

## `Output = [ ... ]` -- *Required*
An array of objects, each describing one output configuration. In the output configuration, you specify the name of an in-application stream, a destination (that is, an Amazon Kinesis stream, an Amazon Kinesis Firehose delivery stream, or an Amazon Lambda function), and record the formation to use when writing to the destination.
```
 Output = [
        "Name" => <required> ::String,
        "KinesisStreamsOutput" =>  [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ],
        "KinesisFirehoseOutput" =>  [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ],
        "LambdaOutput" =>  [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ],
        "DestinationSchema" => <required> ["RecordFormatType" =>  "JSON" or "CSV"]
    ]
```

# Returns

`AddApplicationOutputResponse`

# Exceptions

`ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException` or `ConcurrentModificationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/AddApplicationOutput)
"""
@inline add_application_output(aws::AWSConfig=default_aws_config(); args...) = add_application_output(aws, args)

@inline add_application_output(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "AddApplicationOutput", args)

@inline add_application_output(args) = add_application_output(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.add_application_reference_data_source
    add_application_reference_data_source([::AWSConfig], arguments::Dict)
    add_application_reference_data_source([::AWSConfig]; ApplicationName=, CurrentApplicationVersionId=, ReferenceDataSource=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "AddApplicationReferenceDataSource", arguments::Dict)
    kinesisanalytics([::AWSConfig], "AddApplicationReferenceDataSource", ApplicationName=, CurrentApplicationVersionId=, ReferenceDataSource=)

# AddApplicationReferenceDataSource Operation

Adds a reference data source to an existing application.

Amazon Kinesis Analytics reads reference data (that is, an Amazon S3 object) and creates an in-application table within your application. In the request, you provide the source (S3 bucket name and object key name), name of the in-application table to create, and the necessary mapping information that describes how data in Amazon S3 object maps to columns in the resulting in-application table.

For conceptual information, see [Configuring Application Input](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-input.html). For the limits on data sources you can add to your application, see [Limits](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/limits.html).

This operation requires permissions to perform the `kinesisanalytics:AddApplicationOutput` action.

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of an existing application.

## `CurrentApplicationVersionId = ::Int` -- *Required*
Version of the application for which you are adding the reference data source. You can use the [DescribeApplication](@ref) operation to get the current application version. If the version specified is not the current version, the `ConcurrentModificationException` is returned.

## `ReferenceDataSource = [ ... ]` -- *Required*
The reference data source can be an object in your Amazon S3 bucket. Amazon Kinesis Analytics reads the object and copies the data into the in-application table that is created. You provide an S3 bucket, object key name, and the resulting in-application table that is created. You must also provide an IAM role with the necessary permissions that Amazon Kinesis Analytics can assume to read the object from your S3 bucket on your behalf.
```
 ReferenceDataSource = [
        "TableName" => <required> ::String,
        "S3ReferenceDataSource" =>  [
            "BucketARN" => <required> ::String,
            "FileKey" => <required> ::String,
            "ReferenceRoleARN" => <required> ::String
        ],
        "ReferenceSchema" => <required> [
            "RecordFormat" => <required> [
                "RecordFormatType" => <required> "JSON" or "CSV",
                "MappingParameters" =>  [
                    "JSONMappingParameters" =>  ["RecordRowPath" => <required> ::String],
                    "CSVMappingParameters" =>  [
                        "RecordRowDelimiter" => <required> ::String,
                        "RecordColumnDelimiter" => <required> ::String
                    ]
                ]
            ],
            "RecordEncoding" =>  ::String,
            "RecordColumns" => <required> [[
                "Name" => <required> ::String,
                "Mapping" =>  ::String,
                "SqlType" => <required> ::String
            ], ...]
        ]
    ]
```

# Returns

`AddApplicationReferenceDataSourceResponse`

# Exceptions

`ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException` or `ConcurrentModificationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/AddApplicationReferenceDataSource)
"""
@inline add_application_reference_data_source(aws::AWSConfig=default_aws_config(); args...) = add_application_reference_data_source(aws, args)

@inline add_application_reference_data_source(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "AddApplicationReferenceDataSource", args)

@inline add_application_reference_data_source(args) = add_application_reference_data_source(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.create_application
    create_application([::AWSConfig], arguments::Dict)
    create_application([::AWSConfig]; ApplicationName=, <keyword arguments>)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "CreateApplication", arguments::Dict)
    kinesisanalytics([::AWSConfig], "CreateApplication", ApplicationName=, <keyword arguments>)

# CreateApplication Operation

Creates an Amazon Kinesis Analytics application. You can configure each application with one streaming source as input, application code to process the input, and up to three destinations where you want Amazon Kinesis Analytics to write the output data from your application. For an overview, see [How it Works](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works.html).

In the input configuration, you map the streaming source to an in-application stream, which you can think of as a constantly updating table. In the mapping, you must provide a schema for the in-application stream and map each data column in the in-application stream to a data element in the streaming source.

Your application code is one or more SQL statements that read input data, transform it, and generate output. Your application code can create one or more SQL artifacts like SQL streams or pumps.

In the output configuration, you can configure the application to write data from in-application streams created in your applications to up to three destinations.

To read data from your source stream or write data to destination streams, Amazon Kinesis Analytics needs your permissions. You grant these permissions by creating IAM roles. This operation requires permissions to perform the `kinesisanalytics:CreateApplication` action.

For introductory exercises to create an Amazon Kinesis Analytics application, see [Getting Started](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/getting-started.html).

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of your Amazon Kinesis Analytics application (for example, `sample-app`).

## `ApplicationDescription = ::String`
Summary description of the application.

## `Inputs = [[ ... ], ...]`
Use this parameter to configure the application input.

You can configure your application to receive input from a single streaming source. In this configuration, you map this streaming source to an in-application stream that is created. Your application code can then query the in-application stream like a table (you can think of it as a constantly updating table).

For the streaming source, you provide its Amazon Resource Name (ARN) and format of data on the stream (for example, JSON, CSV, etc.). You also must provide an IAM role that Amazon Kinesis Analytics can assume to read this stream on your behalf.

To create the in-application stream, you need to specify a schema to transform your data into a schematized version used in SQL. In the schema, you provide the necessary mapping of the data elements in the streaming source to record columns in the in-app stream.
```
 Inputs = [[
        "NamePrefix" => <required> ::String,
        "InputProcessingConfiguration" =>  ["InputLambdaProcessor" => <required> [
                "ResourceARN" => <required> ::String,
                "RoleARN" => <required> ::String
            ]],
        "KinesisStreamsInput" =>  [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ],
        "KinesisFirehoseInput" =>  [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ],
        "InputParallelism" =>  ["Count" =>  ::Int],
        "InputSchema" => <required> [
            "RecordFormat" => <required> [
                "RecordFormatType" => <required> "JSON" or "CSV",
                "MappingParameters" =>  [
                    "JSONMappingParameters" =>  ["RecordRowPath" => <required> ::String],
                    "CSVMappingParameters" =>  [
                        "RecordRowDelimiter" => <required> ::String,
                        "RecordColumnDelimiter" => <required> ::String
                    ]
                ]
            ],
            "RecordEncoding" =>  ::String,
            "RecordColumns" => <required> [[
                "Name" => <required> ::String,
                "Mapping" =>  ::String,
                "SqlType" => <required> ::String
            ], ...]
        ]
    ], ...]
```

## `Outputs = [[ ... ], ...]`
You can configure application output to write data from any of the in-application streams to up to three destinations.

These destinations can be Amazon Kinesis streams, Amazon Kinesis Firehose delivery streams, Amazon Lambda destinations, or any combination of the three.

In the configuration, you specify the in-application stream name, the destination stream or Lambda function Amazon Resource Name (ARN), and the format to use when writing data. You must also provide an IAM role that Amazon Kinesis Analytics can assume to write to the destination stream or Lambda function on your behalf.

In the output configuration, you also provide the output stream or Lambda function ARN. For stream destinations, you provide the format of data in the stream (for example, JSON, CSV). You also must provide an IAM role that Amazon Kinesis Analytics can assume to write to the stream or Lambda function on your behalf.
```
 Outputs = [[
        "Name" => <required> ::String,
        "KinesisStreamsOutput" =>  [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ],
        "KinesisFirehoseOutput" =>  [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ],
        "LambdaOutput" =>  [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ],
        "DestinationSchema" => <required> ["RecordFormatType" =>  "JSON" or "CSV"]
    ], ...]
```

## `CloudWatchLoggingOptions = [[ ... ], ...]`
Use this parameter to configure a CloudWatch log stream to monitor application configuration errors. For more information, see [Working with Amazon CloudWatch Logs](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/cloudwatch-logs.html).
```
 CloudWatchLoggingOptions = [[
        "LogStreamARN" => <required> ::String,
        "RoleARN" => <required> ::String
    ], ...]
```

## `ApplicationCode = ::String`
One or more SQL statements that read input data, transform it, and generate output. For example, you can write a SQL statement that reads data from one in-application stream, generates a running average of the number of advertisement clicks by vendor, and insert resulting rows in another in-application stream using pumps. For more information about the typical pattern, see [Application Code](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-app-code.html).

You can provide such series of SQL statements, where output of one statement can be used as the input for the next statement. You store intermediate results by creating in-application streams and pumps.

Note that the application code must create the streams with names specified in the `Outputs`. For example, if your `Outputs` defines output streams named `ExampleOutputStream1` and `ExampleOutputStream2`, then your application code must create these streams.

# Returns

`CreateApplicationResponse`

# Exceptions

`CodeValidationException`, `ResourceInUseException`, `LimitExceededException` or `InvalidArgumentException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/CreateApplication)
"""
@inline create_application(aws::AWSConfig=default_aws_config(); args...) = create_application(aws, args)

@inline create_application(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "CreateApplication", args)

@inline create_application(args) = create_application(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.delete_application
    delete_application([::AWSConfig], arguments::Dict)
    delete_application([::AWSConfig]; ApplicationName=, CreateTimestamp=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "DeleteApplication", arguments::Dict)
    kinesisanalytics([::AWSConfig], "DeleteApplication", ApplicationName=, CreateTimestamp=)

# DeleteApplication Operation

Deletes the specified application. Amazon Kinesis Analytics halts application execution and deletes the application, including any application artifacts (such as in-application streams, reference table, and application code).

This operation requires permissions to perform the `kinesisanalytics:DeleteApplication` action.

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of the Amazon Kinesis Analytics application to delete.

## `CreateTimestamp = timestamp` -- *Required*
You can use the `DescribeApplication` operation to get this value.

# Returns

`DeleteApplicationResponse`

# Exceptions

`ConcurrentModificationException`, `ResourceNotFoundException` or `ResourceInUseException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/DeleteApplication)
"""
@inline delete_application(aws::AWSConfig=default_aws_config(); args...) = delete_application(aws, args)

@inline delete_application(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "DeleteApplication", args)

@inline delete_application(args) = delete_application(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.delete_application_cloud_watch_logging_option
    delete_application_cloud_watch_logging_option([::AWSConfig], arguments::Dict)
    delete_application_cloud_watch_logging_option([::AWSConfig]; ApplicationName=, CurrentApplicationVersionId=, CloudWatchLoggingOptionId=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "DeleteApplicationCloudWatchLoggingOption", arguments::Dict)
    kinesisanalytics([::AWSConfig], "DeleteApplicationCloudWatchLoggingOption", ApplicationName=, CurrentApplicationVersionId=, CloudWatchLoggingOptionId=)

# DeleteApplicationCloudWatchLoggingOption Operation

Deletes a CloudWatch log stream from an application. For more information about using CloudWatch log streams with Amazon Kinesis Analytics applications, see [Working with Amazon CloudWatch Logs](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/cloudwatch-logs.html).

# Arguments

## `ApplicationName = ::String` -- *Required*
The Kinesis Analytics application name.

## `CurrentApplicationVersionId = ::Int` -- *Required*
The version ID of the Kinesis Analytics application.

## `CloudWatchLoggingOptionId = ::String` -- *Required*
The `CloudWatchLoggingOptionId` of the CloudWatch logging option to delete. You can get the `CloudWatchLoggingOptionId` by using the [DescribeApplication](@ref) operation.

# Returns

`DeleteApplicationCloudWatchLoggingOptionResponse`

# Exceptions

`ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException` or `ConcurrentModificationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/DeleteApplicationCloudWatchLoggingOption)
"""
@inline delete_application_cloud_watch_logging_option(aws::AWSConfig=default_aws_config(); args...) = delete_application_cloud_watch_logging_option(aws, args)

@inline delete_application_cloud_watch_logging_option(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "DeleteApplicationCloudWatchLoggingOption", args)

@inline delete_application_cloud_watch_logging_option(args) = delete_application_cloud_watch_logging_option(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.delete_application_input_processing_configuration
    delete_application_input_processing_configuration([::AWSConfig], arguments::Dict)
    delete_application_input_processing_configuration([::AWSConfig]; ApplicationName=, CurrentApplicationVersionId=, InputId=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "DeleteApplicationInputProcessingConfiguration", arguments::Dict)
    kinesisanalytics([::AWSConfig], "DeleteApplicationInputProcessingConfiguration", ApplicationName=, CurrentApplicationVersionId=, InputId=)

# DeleteApplicationInputProcessingConfiguration Operation

Deletes an [InputProcessingConfiguration](@ref) from an input.

# Arguments

## `ApplicationName = ::String` -- *Required*
The Kinesis Analytics application name.

## `CurrentApplicationVersionId = ::Int` -- *Required*
The version ID of the Kinesis Analytics application.

## `InputId = ::String` -- *Required*
The ID of the input configuration from which to delete the input processing configuration. You can get a list of the input IDs for an application by using the [DescribeApplication](@ref) operation.

# Returns

`DeleteApplicationInputProcessingConfigurationResponse`

# Exceptions

`ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException` or `ConcurrentModificationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/DeleteApplicationInputProcessingConfiguration)
"""
@inline delete_application_input_processing_configuration(aws::AWSConfig=default_aws_config(); args...) = delete_application_input_processing_configuration(aws, args)

@inline delete_application_input_processing_configuration(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "DeleteApplicationInputProcessingConfiguration", args)

@inline delete_application_input_processing_configuration(args) = delete_application_input_processing_configuration(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.delete_application_output
    delete_application_output([::AWSConfig], arguments::Dict)
    delete_application_output([::AWSConfig]; ApplicationName=, CurrentApplicationVersionId=, OutputId=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "DeleteApplicationOutput", arguments::Dict)
    kinesisanalytics([::AWSConfig], "DeleteApplicationOutput", ApplicationName=, CurrentApplicationVersionId=, OutputId=)

# DeleteApplicationOutput Operation

Deletes output destination configuration from your application configuration. Amazon Kinesis Analytics will no longer write data from the corresponding in-application stream to the external output destination.

This operation requires permissions to perform the `kinesisanalytics:DeleteApplicationOutput` action.

# Arguments

## `ApplicationName = ::String` -- *Required*
Amazon Kinesis Analytics application name.

## `CurrentApplicationVersionId = ::Int` -- *Required*
Amazon Kinesis Analytics application version. You can use the [DescribeApplication](@ref) operation to get the current application version. If the version specified is not the current version, the `ConcurrentModificationException` is returned.

## `OutputId = ::String` -- *Required*
The ID of the configuration to delete. Each output configuration that is added to the application, either when the application is created or later using the [AddApplicationOutput](@ref) operation, has a unique ID. You need to provide the ID to uniquely identify the output configuration that you want to delete from the application configuration. You can use the [DescribeApplication](@ref) operation to get the specific `OutputId`.

# Returns

`DeleteApplicationOutputResponse`

# Exceptions

`ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException` or `ConcurrentModificationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/DeleteApplicationOutput)
"""
@inline delete_application_output(aws::AWSConfig=default_aws_config(); args...) = delete_application_output(aws, args)

@inline delete_application_output(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "DeleteApplicationOutput", args)

@inline delete_application_output(args) = delete_application_output(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.delete_application_reference_data_source
    delete_application_reference_data_source([::AWSConfig], arguments::Dict)
    delete_application_reference_data_source([::AWSConfig]; ApplicationName=, CurrentApplicationVersionId=, ReferenceId=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "DeleteApplicationReferenceDataSource", arguments::Dict)
    kinesisanalytics([::AWSConfig], "DeleteApplicationReferenceDataSource", ApplicationName=, CurrentApplicationVersionId=, ReferenceId=)

# DeleteApplicationReferenceDataSource Operation

Deletes a reference data source configuration from the specified application configuration.

If the application is running, Amazon Kinesis Analytics immediately removes the in-application table that you created using the [AddApplicationReferenceDataSource](@ref) operation.

This operation requires permissions to perform the `kinesisanalytics.DeleteApplicationReferenceDataSource` action.

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of an existing application.

## `CurrentApplicationVersionId = ::Int` -- *Required*
Version of the application. You can use the [DescribeApplication](@ref) operation to get the current application version. If the version specified is not the current version, the `ConcurrentModificationException` is returned.

## `ReferenceId = ::String` -- *Required*
ID of the reference data source. When you add a reference data source to your application using the [AddApplicationReferenceDataSource](@ref), Amazon Kinesis Analytics assigns an ID. You can use the [DescribeApplication](@ref) operation to get the reference ID.

# Returns

`DeleteApplicationReferenceDataSourceResponse`

# Exceptions

`ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException` or `ConcurrentModificationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/DeleteApplicationReferenceDataSource)
"""
@inline delete_application_reference_data_source(aws::AWSConfig=default_aws_config(); args...) = delete_application_reference_data_source(aws, args)

@inline delete_application_reference_data_source(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "DeleteApplicationReferenceDataSource", args)

@inline delete_application_reference_data_source(args) = delete_application_reference_data_source(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.describe_application
    describe_application([::AWSConfig], arguments::Dict)
    describe_application([::AWSConfig]; ApplicationName=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "DescribeApplication", arguments::Dict)
    kinesisanalytics([::AWSConfig], "DescribeApplication", ApplicationName=)

# DescribeApplication Operation

Returns information about a specific Amazon Kinesis Analytics application.

If you want to retrieve a list of all applications in your account, use the [ListApplications](@ref) operation.

This operation requires permissions to perform the `kinesisanalytics:DescribeApplication` action. You can use `DescribeApplication` to get the current application versionId, which you need to call other operations such as `Update`.

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of the application.

# Returns

`DescribeApplicationResponse`

# Exceptions

`ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/DescribeApplication)
"""
@inline describe_application(aws::AWSConfig=default_aws_config(); args...) = describe_application(aws, args)

@inline describe_application(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "DescribeApplication", args)

@inline describe_application(args) = describe_application(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.discover_input_schema
    discover_input_schema([::AWSConfig], arguments::Dict)
    discover_input_schema([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "DiscoverInputSchema", arguments::Dict)
    kinesisanalytics([::AWSConfig], "DiscoverInputSchema", <keyword arguments>)

# DiscoverInputSchema Operation

Infers a schema by evaluating sample records on the specified streaming source (Amazon Kinesis stream or Amazon Kinesis Firehose delivery stream) or S3 object. In the response, the operation returns the inferred schema and also the sample records that the operation used to infer the schema.

You can use the inferred schema when configuring a streaming source for your application. For conceptual information, see [Configuring Application Input](http://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-input.html). Note that when you create an application using the Amazon Kinesis Analytics console, the console uses this operation to infer a schema and show it in the console user interface.

This operation requires permissions to perform the `kinesisanalytics:DiscoverInputSchema` action.

# Arguments

## `ResourceARN = ::String`
Amazon Resource Name (ARN) of the streaming source.

## `RoleARN = ::String`
ARN of the IAM role that Amazon Kinesis Analytics can assume to access the stream on your behalf.

## `InputStartingPositionConfiguration = ["InputStartingPosition" =>  "NOW", "TRIM_HORIZON" or "LAST_STOPPED_POINT"]`
Point at which you want Amazon Kinesis Analytics to start reading records from the specified streaming source discovery purposes.

## `S3Configuration = [ ... ]`
Specify this parameter to discover a schema from data in an S3 object.
```
 S3Configuration = [
        "RoleARN" => <required> ::String,
        "BucketARN" => <required> ::String,
        "FileKey" => <required> ::String
    ]
```

## `InputProcessingConfiguration = ["InputLambdaProcessor" => <required> [ ... ]]`
The [InputProcessingConfiguration](@ref) to use to preprocess the records before discovering the schema of the records.
```
 InputProcessingConfiguration = ["InputLambdaProcessor" => <required> [
            "ResourceARN" => <required> ::String,
            "RoleARN" => <required> ::String
        ]]
```

# Returns

`DiscoverInputSchemaResponse`

# Exceptions

`InvalidArgumentException`, `UnableToDetectSchemaException`, `ResourceProvisionedThroughputExceededException` or `ServiceUnavailableException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/DiscoverInputSchema)
"""
@inline discover_input_schema(aws::AWSConfig=default_aws_config(); args...) = discover_input_schema(aws, args)

@inline discover_input_schema(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "DiscoverInputSchema", args)

@inline discover_input_schema(args) = discover_input_schema(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.list_applications
    list_applications([::AWSConfig], arguments::Dict)
    list_applications([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "ListApplications", arguments::Dict)
    kinesisanalytics([::AWSConfig], "ListApplications", <keyword arguments>)

# ListApplications Operation

Returns a list of Amazon Kinesis Analytics applications in your account. For each application, the response includes the application name, Amazon Resource Name (ARN), and status. If the response returns the `HasMoreApplications` value as true, you can send another request by adding the `ExclusiveStartApplicationName` in the request body, and set the value of this to the last application name from the previous response.

If you want detailed information about a specific application, use [DescribeApplication](@ref).

This operation requires permissions to perform the `kinesisanalytics:ListApplications` action.

# Arguments

## `Limit = ::Int`
Maximum number of applications to list.

## `ExclusiveStartApplicationName = ::String`
Name of the application to start the list with. When using pagination to retrieve the list, you don't need to specify this parameter in the first request. However, in subsequent requests, you add the last application name from the previous response to get the next page of applications.

# Returns

`ListApplicationsResponse`

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/ListApplications)
"""
@inline list_applications(aws::AWSConfig=default_aws_config(); args...) = list_applications(aws, args)

@inline list_applications(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "ListApplications", args)

@inline list_applications(args) = list_applications(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.start_application
    start_application([::AWSConfig], arguments::Dict)
    start_application([::AWSConfig]; ApplicationName=, InputConfigurations=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "StartApplication", arguments::Dict)
    kinesisanalytics([::AWSConfig], "StartApplication", ApplicationName=, InputConfigurations=)

# StartApplication Operation

Starts the specified Amazon Kinesis Analytics application. After creating an application, you must exclusively call this operation to start your application.

After the application starts, it begins consuming the input data, processes it, and writes the output to the configured destination.

The application status must be `READY` for you to start an application. You can get the application status in the console or using the [DescribeApplication](@ref) operation.

After you start the application, you can stop the application from processing the input by calling the [StopApplication](@ref) operation.

This operation requires permissions to perform the `kinesisanalytics:StartApplication` action.

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of the application.

## `InputConfigurations = [[ ... ], ...]` -- *Required*
Identifies the specific input, by ID, that the application starts consuming. Amazon Kinesis Analytics starts reading the streaming source associated with the input. You can also specify where in the streaming source you want Amazon Kinesis Analytics to start reading.
```
 InputConfigurations = [[
        "Id" => <required> ::String,
        "InputStartingPositionConfiguration" => <required> ["InputStartingPosition" =>  "NOW", "TRIM_HORIZON" or "LAST_STOPPED_POINT"]
    ], ...]
```

# Returns

`StartApplicationResponse`

# Exceptions

`ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException` or `InvalidApplicationConfigurationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/StartApplication)
"""
@inline start_application(aws::AWSConfig=default_aws_config(); args...) = start_application(aws, args)

@inline start_application(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "StartApplication", args)

@inline start_application(args) = start_application(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.stop_application
    stop_application([::AWSConfig], arguments::Dict)
    stop_application([::AWSConfig]; ApplicationName=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "StopApplication", arguments::Dict)
    kinesisanalytics([::AWSConfig], "StopApplication", ApplicationName=)

# StopApplication Operation

Stops the application from processing input data. You can stop an application only if it is in the running state. You can use the [DescribeApplication](@ref) operation to find the application state. After the application is stopped, Amazon Kinesis Analytics stops reading data from the input, the application stops processing data, and there is no output written to the destination.

This operation requires permissions to perform the `kinesisanalytics:StopApplication` action.

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of the running application to stop.

# Returns

`StopApplicationResponse`

# Exceptions

`ResourceNotFoundException` or `ResourceInUseException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/StopApplication)
"""
@inline stop_application(aws::AWSConfig=default_aws_config(); args...) = stop_application(aws, args)

@inline stop_application(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "StopApplication", args)

@inline stop_application(args) = stop_application(default_aws_config(), args)

"""
    using AWSSDK.KinesisAnalytics.update_application
    update_application([::AWSConfig], arguments::Dict)
    update_application([::AWSConfig]; ApplicationName=, CurrentApplicationVersionId=, ApplicationUpdate=)

    using AWSCore.Services.kinesisanalytics
    kinesisanalytics([::AWSConfig], "UpdateApplication", arguments::Dict)
    kinesisanalytics([::AWSConfig], "UpdateApplication", ApplicationName=, CurrentApplicationVersionId=, ApplicationUpdate=)

# UpdateApplication Operation

Updates an existing Amazon Kinesis Analytics application. Using this API, you can update application code, input configuration, and output configuration.

Note that Amazon Kinesis Analytics updates the `CurrentApplicationVersionId` each time you update your application.

This operation requires permission for the `kinesisanalytics:UpdateApplication` action.

# Arguments

## `ApplicationName = ::String` -- *Required*
Name of the Amazon Kinesis Analytics application to update.

## `CurrentApplicationVersionId = ::Int` -- *Required*
The current application version ID. You can use the [DescribeApplication](@ref) operation to get this value.

## `ApplicationUpdate = [ ... ]` -- *Required*
Describes application updates.
```
 ApplicationUpdate = [
        "InputUpdates" =>  [[
            "InputId" => <required> ::String,
            "NamePrefixUpdate" =>  ::String,
            "InputProcessingConfigurationUpdate" =>  ["InputLambdaProcessorUpdate" => <required> [
                    "ResourceARNUpdate" =>  ::String,
                    "RoleARNUpdate" =>  ::String
                ]],
            "KinesisStreamsInputUpdate" =>  [
                "ResourceARNUpdate" =>  ::String,
                "RoleARNUpdate" =>  ::String
            ],
            "KinesisFirehoseInputUpdate" =>  [
                "ResourceARNUpdate" =>  ::String,
                "RoleARNUpdate" =>  ::String
            ],
            "InputSchemaUpdate" =>  [
                "RecordFormatUpdate" =>  [
                    "RecordFormatType" => <required> "JSON" or "CSV",
                    "MappingParameters" =>  [
                        "JSONMappingParameters" =>  ["RecordRowPath" => <required> ::String],
                        "CSVMappingParameters" =>  [
                            "RecordRowDelimiter" => <required> ::String,
                            "RecordColumnDelimiter" => <required> ::String
                        ]
                    ]
                ],
                "RecordEncodingUpdate" =>  ::String,
                "RecordColumnUpdates" =>  [[
                    "Name" => <required> ::String,
                    "Mapping" =>  ::String,
                    "SqlType" => <required> ::String
                ], ...]
            ],
            "InputParallelismUpdate" =>  ["CountUpdate" =>  ::Int]
        ], ...],
        "ApplicationCodeUpdate" =>  ::String,
        "OutputUpdates" =>  [[
            "OutputId" => <required> ::String,
            "NameUpdate" =>  ::String,
            "KinesisStreamsOutputUpdate" =>  [
                "ResourceARNUpdate" =>  ::String,
                "RoleARNUpdate" =>  ::String
            ],
            "KinesisFirehoseOutputUpdate" =>  [
                "ResourceARNUpdate" =>  ::String,
                "RoleARNUpdate" =>  ::String
            ],
            "LambdaOutputUpdate" =>  [
                "ResourceARNUpdate" =>  ::String,
                "RoleARNUpdate" =>  ::String
            ],
            "DestinationSchemaUpdate" =>  ["RecordFormatType" =>  "JSON" or "CSV"]
        ], ...],
        "ReferenceDataSourceUpdates" =>  [[
            "ReferenceId" => <required> ::String,
            "TableNameUpdate" =>  ::String,
            "S3ReferenceDataSourceUpdate" =>  [
                "BucketARNUpdate" =>  ::String,
                "FileKeyUpdate" =>  ::String,
                "ReferenceRoleARNUpdate" =>  ::String
            ],
            "ReferenceSchemaUpdate" =>  [
                "RecordFormat" => <required> [
                    "RecordFormatType" => <required> "JSON" or "CSV",
                    "MappingParameters" =>  [
                        "JSONMappingParameters" =>  ["RecordRowPath" => <required> ::String],
                        "CSVMappingParameters" =>  [
                            "RecordRowDelimiter" => <required> ::String,
                            "RecordColumnDelimiter" => <required> ::String
                        ]
                    ]
                ],
                "RecordEncoding" =>  ::String,
                "RecordColumns" => <required> [[
                    "Name" => <required> ::String,
                    "Mapping" =>  ::String,
                    "SqlType" => <required> ::String
                ], ...]
            ]
        ], ...],
        "CloudWatchLoggingOptionUpdates" =>  [[
            "CloudWatchLoggingOptionId" => <required> ::String,
            "LogStreamARNUpdate" =>  ::String,
            "RoleARNUpdate" =>  ::String
        ], ...]
    ]
```

# Returns

`UpdateApplicationResponse`

# Exceptions

`CodeValidationException`, `ResourceNotFoundException`, `ResourceInUseException`, `InvalidArgumentException` or `ConcurrentModificationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/UpdateApplication)
"""
@inline update_application(aws::AWSConfig=default_aws_config(); args...) = update_application(aws, args)

@inline update_application(aws::AWSConfig, args) = AWSCore.Services.kinesisanalytics(aws, "UpdateApplication", args)

@inline update_application(args) = update_application(default_aws_config(), args)

end # module KinesisAnalytics

#==============================================================================#
# End of file
#==============================================================================#


text:
using Test, SafeTestsets

@safetestset "Multithreading" begin include("multithreading.jl") end

ext: jl


text:
# SPDX-License-Identifier: X11
# 2020-11-10
# Frog 1 (100pt)

function main()
  N = parse(Int, readline())
  H = parse.(Int, (split ∘ readline)())

  DP = zeros(Int, N)
  if N == 1
    println(DP[1])
    return
  end

  DP[2] = abs(H[1] - H[2])
  if N == 2
    println(DP[2])
    return
  end

  for i ∈ 3:N
    DP[i] = min(abs(H[i - 1] - H[i]) + DP[i - 1],
                abs(H[i - 2] - H[i]) + DP[i - 2])
  end

  println(DP[N])
end

main()

max_stars_repo_name: jthvai/competitive-programming

max_issues_repo_name: jthvai/competitive-programming

max_forks_repo_name: jthvai/competitive-programming


text:
module TestBatchedVector

include("preamble.jl")

function makedata(V::Type, nbatches::Integer)
    batch_lengths = collect(testdims(nbatches))
    offsets = [0, cumsum(batch_lengths)...]
    nested = Vector{V}[rand(V, bl) for bl in batch_lengths]
    flat = nbatches == 0 ? V[] : reduce(vcat, nested)
    return (batch_lengths = batch_lengths, offsets = offsets, nested=nested, flat=flat)
end

@testset "nbatches = $nbatches, V = $V" for nbatches in (1, 10), V in (Float64, )
    @testset "constructors" begin
        @unpack batch_lengths, offsets, nested, flat = makedata(V, nbatches)
        Expected = BatchedVector{<:AbstractArray{V,inner_ndims(nested)},typeof(flat)}
        @test BatchedVector(flat, offsets) isa Expected
        @test_inferred BatchedVector(flat, offsets)
    end

    @testset "Extra" begin
        @unpack batch_lengths, offsets, nested, flat = makedata(V, nbatches)
        Expected = BatchedVector{<:AbstractArray{V,inner_ndims(nested)},typeof(flat)}
        @test batch(flat, batch_lengths) isa Expected
        @test_inferred batch(flat, batch_lengths)
        let B1 = batch(flat, batch_lengths)
            B2 = similarbatch(copy(flat), B1)
            @test B1 == B2
            @test B1.parent !== B2.parent
        end
    end

    let nbatches = nbatches, V = V
        test_array_AB() do
            @unpack batch_lengths, nested, flat = makedata(V, nbatches)
            A = batch(flat, batch_lengths)
            B = nested
            return A, B
        end
    end
end

@testset "Misc" begin
    d = makedata(Float64, 5)
    B = BatchedVector(d.flat, d.offsets)
    @test Base.dataids(B) === (Base.dataids(d.flat)..., Base.dataids(d.offsets)...)
    @test parent(B) === d.flat
end

@testset "UnsafeArrays" begin
    d = makedata(Float64, 5)
    B = BatchedVector(d.flat, d.offsets)
    U = uview(B)
    @test U == B
    @test U.parent isa UnsafeArray{eltype(d.flat),1}
    @test U.offsets isa Vector{Int}
    @test_inferred uview(B)
end

end # module


text:
module GVFHordes

import Lazy: @forward

export GVFParamFuncs, AbstractGVF, GVF, Horde

"""
    GVFParamFuncs

Module containing and the GVF parameter function types. Cleaner to keep these in a seperate namespace where the user can decide to `using` if desired.
"""
module GVFParamFuncs

import Base.get

using Random
using ..GVFHordes

export
    AbstractCumulant,
    FeatureCumulant,
    PredictionCumulant,
    ScaledCumulant,
    FunctionalCumulant
include("gvf/cumulant.jl")

export
    AbstractDiscount,
    ConstantDiscount,
    StateTerminationDiscount
include("gvf/discount.jl")

export
    AbstractPolicy,
    NullPolicy,
    PersistentPolicy,
    RandomPolicy,
    FucntionalPolicy
include("gvf/policy.jl")

end

"""
    AbstractGVF

This is the base type for a General Value Function. See the "Horde: A scalable real-time architecture for learning knowledge from unsupervised sensorimotor interaction" paper for more details.
"""
abstract type AbstractGVF end

"""
    get(gvf::AbstractGVF, state_t, action_t, state_tp1, action_tp1, preds_tp1)

Get the parameters for the cumulant, discount, and probability of taking an action given the parameters.
"""
function Base.get(gvf::AbstractGVF, state_t, action_t, state_tp1, action_tp1, preds_tp1) end

function cumulant(gvf::AbstractGVF) end
function discount(gvf::AbstractGVF) end
function policy(gvf::AbstractGVF) end

"""
    GVF{C<:AbstractCumulant, D<:AbstractDiscount, P<:AbstractPolicy} <: AbstractGVF

A realized version of a GVF where the cumulant, discount, and policies can be any structure following the AbstractCumulant, AbstractDiscount, or AbstractPolicy api respectively.
"""
struct GVF{C<:GVFParamFuncs.AbstractCumulant,
           D<:GVFParamFuncs.AbstractDiscount,
           P<:GVFParamFuncs.AbstractPolicy} <: AbstractGVF
    cumulant::C
    discount::D
    policy::P
end

cumulant(gvf::GVF) = gvf.cumulant
discount(gvf::GVF) = gvf.discount
policy(gvf::GVF) = gvf.policy

function Base.get(gvf::GVF, state_t, action_t, state_tp1, action_tp1, preds_tp1)

    c = get(gvf.cumulant, state_tp1, action_tp1, preds_tp1)
    γ = get(gvf.discount, state_t, action_t, state_tp1, action_tp1, preds_tp1)
    π_prob = get(gvf.policy, state_t, action_t)
    return c, γ, π_prob
end

"""
    AbstractHorde

An abstract collection of GVFs.
"""
abstract type AbstractHorde end

"""
    Horde{T<:AbstractGVF} <: AbstractHorde

The simplest implementation of a horde as a collection of AbstractGVFs.
"""
struct Horde{T<:AbstractGVF} <: AbstractHorde
    gvfs::Vector{T}
end

merge(h1::Horde, h2::Horde) =
    Horde([deepcopy(h1.gvfs); deepcopy(h2.gvfs)])

function Base.get(gvfh::Horde, state_t, action_t, state_tp1, action_tp1, preds_tp1)
    C = map(gvf -> get(cumulant(gvf), state_tp1, action_tp1, preds_tp1), gvfh.gvfs)
    Γ = map(gvf -> get(discount(gvf), state_t, action_t, state_tp1, action_tp1, preds_tp1), gvfh.gvfs)
    Π_probs = map(gvf -> get(policy(gvf), state_t, action_t), gvfh.gvfs)
    return C, Γ, Π_probs
end

function Base.get!(C::Array{T, 1}, Γ::Array{F, 1}, Π_probs::Array{H, 1}, gvfh::Horde, state_t, action_t, state_tp1, action_tp1, preds_tp1) where {T, F, H}
    C .= map(gvf -> get(cumulant(gvf), state_tp1, action_tp1, preds_tp1), gvfh.gvfs)
    Γ .= map(gvf -> get(discount(gvf), state_t, action_t, state_tp1, action_tp1, preds_tp1), gvfh.gvfs)
    Π_probs .= map(gvf -> get(policy(gvf), state_t, action_t), gvfh.gvfs)
    return C, Γ, Π_probs
end

Base.get(gvfh::Horde, state_tp1, preds_tp1) =
    get(gvfh::Horde, nothing, nothing, state_tp1, nothing, preds_tp1)

Base.get(gvfh::Horde, state_t, action_t, state_tp1) =
    get(gvfh::Horde, state_t, action_t, state_tp1, nothing, nothing)

Base.get(gvfh::Horde, state_t, action_t, state_tp1, preds_tp1) =
    get(gvfh::Horde, state_t, action_t, state_tp1, nothing, preds_tp1)

@forward Horde.gvfs Base.length

end # module

max_stars_repo_name: MatthewMcLeod/curiosity

max_issues_repo_name: MatthewMcLeod/curiosity

max_forks_repo_name: MatthewMcLeod/curiosity


text:
# ---
# title: 1022. Sum of Root To Leaf Binary Numbers
# id: problem1022
# author: Tian Jun
# date: 2020-10-31
# difficulty: Easy
# categories: Tree
# link: <https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/description/>
# hidden: true
# ---
#
# You are given the `root` of a binary tree where each node has a value `0` or
# `1`.  Each root-to-leaf path represents a binary number starting with the most
# significant bit.  For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then
# this could represent `01101` in binary, which is `13`.
#
# For all leaves in the tree, consider the numbers represented by the path from
# the root to that leaf.
#
# Return _the sum of these numbers_. The answer is **guaranteed** to fit in a
# **32-bits** integer.
#
#
#
# **Example 1:**
#
# ![](https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-
# numbers.png)
#
#
#
#     Input: root = [1,0,1,0,1,0,1]
#     Output: 22
#     Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
#
#
# **Example 2:**
#
#
#
#     Input: root = [0]
#     Output: 0
#
#
# **Example 3:**
#
#
#
#     Input: root = [1]
#     Output: 1
#
#
# **Example 4:**
#
#
#
#     Input: root = [1,1]
#     Output: 3
#
#
#
#
# **Constraints:**
#
#   * The number of nodes in the tree is in the range `[1, 1000]`.
#   * `Node.val` is `0` or `1`.
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
module CellDofBasesTests

using Test
using Gridap.Geometry
using Gridap.FESpaces
using Gridap.Arrays
using Gridap.Fields
using Gridap.CellData

domain =(0,1,0,1)
partition = (3,3)
model = CartesianDiscreteModel(domain,partition)

order = 1

V = TestFESpace(
  reffe = :Lagrangian,
  conformity = :H1,
  valuetype=Float64,
  order = order,
  model = model,
  dirichlet_tags = [1,6],
  dof_space = :physical)

cell_dof_basis = get_cell_dof_basis(V)
@test is_in_physical_space(cell_dof_basis)

indices = [2,3,3,1]

f = reindex(cell_dof_basis,indices)
@test length(get_array(f)) == length(indices)
@test is_in_physical_space(f)

cell_basis = get_cell_basis(V)
@test is_in_physical_space(cell_basis)

test_cell_dof_basis(cell_dof_basis,cell_basis)

#display(evaluate(cell_dof_basis,cell_basis))

V = TestFESpace(
  reffe = :Lagrangian,
  conformity = :H1,
  valuetype=Float64,
  order = order,
  model = model,
  dirichlet_tags = [1,6])

cell_dof_basis = get_cell_dof_basis(V)
@test is_in_ref_space(cell_dof_basis)

cell_basis = get_cell_basis(V)
@test is_in_ref_space(cell_basis)

test_cell_dof_basis(cell_dof_basis,cell_basis)

#display(evaluate(cell_dof_basis,cell_basis))

end # module


text:
using Ensemblearn
using Test

include("util.jl")

function test_create_tree(min_score=0.8::AbstractFloat)
    # Get iris data
    x, y = get_iris_data()
    n = size(y, 1)

    # Create a DecisionTree
    dt = DecisionTree()

    # Fit DecisionTree
    fit!(dt, x, y)

    # Get predictions over x
    p = predict(dt, x)

    # Obtain tuples of (pred, actual)
    p_y = collect(zip(p, y))

    # Score as rate of hits (accuracy)
    score = sum(map(t -> t[1] == t[2], p_y)) / Float64(n)

    # Assert a minimum score on predictions
    @test score >= min_score

    # Print tree obtained
    println("Resulting tree:")
    println("---------------")
    print_tree(dt)

end

@testset "RunTestDecisionTree" begin
    # Normal case
    test_create_tree()
end


text:
using ReachabilityBenchmarks, LazySets, MathematicalPredicates, MAT

function pde_specification()
    # initial set:
    # xᵢ = 0 for i ≤ 64
    # xᵢ ∈ [0.001, 0.0015] for i ∈ [65, 80]
    # xᵢ ∈ [-0.002, -0.0015] for i > 80
    X0 = Hyperrectangle(low=[zeros(64); fill(0.001, 16); fill(-0.002, 4)],
                        high=[zeros(64); fill(0.0015, 16); fill(-0.0015, 4)])

    # safety property: y ≤ 12 for linear combination y (defined in out.mat)
    y = read(matopen(@relpath "out.mat"), "M")[1, :]
    property = is_contained_in(HalfSpace(y, 12.0))

    # time horizon: 20 time units
    time_horizon = 20.0

    # specification
    O = Dict(:T => time_horizon, :property => property)

    return X0, O
end

max_stars_repo_name: JuliaReach/ReachabilityBenchmarks

max_issues_repo_name: JuliaReach/ReachabilityBenchmarks

max_forks_repo_name: JuliaReach/ReachabilityBenchmarks


text:
"""
    DynamicBin{TPS<:Tuple}
    DynamicBin(size::Int, types::Type...) -> DynamicBin{Tuple{types...}}

A bin that can push! items into. It contains a vector of vector, with each sub-vector has specific types.
"""
struct DynamicBin{TPS<:Tuple} <: AbstractBin
    binsize::Int
    data::Vector{Vector}
end
DynamicBin(size::Int, types::Type...) = DynamicBin{Tuple{types...}}(size, [tp[] for tp in types])
function Base.push!(bin::DynamicBin, item)
    for (ii, vec) in zip(item, bin.data)
        push!(vec, ii)
    end
    bin
end

Base.length(bin::DynamicBin) = bin.data[1] |> length
fitted(bin::DynamicBin) = length(bin)%bin.binsize == 0

print_lastbin(bin::DynamicBin) = print_lastbin(stdout, bin)
function print_lastbin(io::IO, bin::DynamicBin)  # only show the mean of last batch
    if length(bin) < bin.binsize
        print(io, "No filled bin | N = $(length(bin))")
    else
        means = [mean(v[end-bin.binsize+1:end]) for v in bin.data]
        print(io, join([(@sprintf " %1.3e " m) for m in means], " "), " | N = $(length(bin))")
    end
    means
end


text:
include("../imports.jl")

@testset ExtendedTestSet "Data container transformations" begin
    @testset ExtendedTestSet "mapobs" begin
        data = 1:10
        mdata = mapobs(-, data)
        @test getobs(mdata, 8) == -8

        mdata2 = mapobs((-, x -> 2x), data)
        @test getobs(mdata2, 8) == (-8, 16)

        nameddata = mapobs((x = sqrt, y = log), data)
        @test getobs(nameddata, 10) == (x = sqrt(10), y = log(10))
        @test getobs(nameddata.x, 10) == sqrt(10)
    end

    @testset ExtendedTestSet "filterobs" begin
        data = 1:10
        fdata = filterobs(>(5), data)
        @test nobs(fdata) == 5
    end

    @testset ExtendedTestSet "groupobs" begin
        data = -10:10
        datas = groupobs(>(0), data)
        @test length(datas) == 2
    end

    @testset ExtendedTestSet "joinobs" begin
        data1, data2 = 1:10, 11:20
        jdata = joinobs(data1, data2)
        @test getobs(jdata, 15) == 15
    end
end


text:
# Autogenerated wrapper script for nPth_jll for armv7l-linux-gnueabihf
export libnpth

JLLWrappers.@generate_wrapper_header("nPth")
JLLWrappers.@declare_library_product(libnpth, "libnpth.so.0")
function __init__()
    JLLWrappers.@generate_init_header()
    JLLWrappers.@init_library_product(
        libnpth,
        "lib/libnpth.so",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
```
    ui_basic(img::AstroImage, indx::Int = 1)

Opens a basic GUI panel to visualize AstroImages.
```
function ui_basic(img::AstroImage, indx::Int = 1)
    header = img.wcs[indx]
    win = Window("Image", 700,700)
    g = Grid()
    set_gtk_property!(g, :column_homogeneous, true)
    set_gtk_property!(g, :column_spacing, 15)
    push!(win, g)

    # Sets toolbar widget
    toolbar = Toolbar()
    headerbtn = get_button("Header")
    closebtn = get_button("Close")
    map(w->push!(toolbar,w),[headerbtn,closebtn])
    g[1:2,1] = toolbar

    # Create canvas to display image
    c = canvas(UserUnit)
    g[1:2,2] = c
    set_gtk_property!(c, :expand, true)
    fv,zr,surf = form_image(img, indx)

    # Sets labels showing informations
    g[1,3] = get_label("Physical Coordinate X =")
    g[2,3] = get_label("Physical Coordinate Y =")
    g[1,4] = get_label("World Coordinate X =")
    g[2,4] = get_label("World Coordinate Y =")
    g[1:2,5] = get_label("Value = ")

    # interactive signals
    signal_connect(headerbtn, :clicked) do widget
        showall(header_window(header))
    end
    init_zoom_scroll(c,zr)
    close_window(closebtn, win)
    map_mouse_motion(img, indx, c, g, header)
    draw_canvas(c,zr,surf)

    showall(win)
end


text:
module DTU_BrayamValqui_SP2021
using JuMP
using Statistics
using StatsBase
using CSV
using DataFrames
using Distributed
using SharedArrays
import MathOptInterface: AbstractOptimizer

#Data OPF
#include("Data_RTS3_OPF.jl")
#include("Data_RTS24_OPF.jl")
#Data Investment Planning-OPF
#include("Data_RTS3.jl")
include("Data_RTS24.jl")
#Functions
include("OPF.jl")
include("OPF_dual.jl")
include("solver_OPF.jl")
include("solver_OPF_dual.jl")
include("Investment_OPF_stage1.jl")
include("Investment_OPF_stage2.jl")
include("Investment_OPF_original.jl")
include("Solver_Benders.jl")
include("Solver_CentralPlanner.jl")
include("loadinputs.jl")

export OPF,solver_OPF,OPF_dual,solver_OPF_dual,Investment_OPF_stage1,Investment_OPF_stage2,Solver_Benders,loadinputs,Solver_CentralPlanner,Investment_OPF_original

end
#cd("C:\\Users\\braya\\.julia\\dev\\DTU_BrayamValqui_SP2021\\src")


text:
using Test
include("../src/LTriMatrix.jl")

@testset "LTriMatrix.jl" begin
    n = 4
    nentries = (n*(n+1)) ÷ 2
    m = LTriMatrix(n, BigInt(1))
    @test size(m) == (n,n)
    @test length(m) == nentries

    for i in 1:n
        for j in 1:i
            m[i,j] = i+j
        end
    end

    @test m[1,1] == 2
    @test m[2,1] == 3
    @test m[3,2] == 5
    @test m[4,4] == 8
    @test_throws BoundsError m[1,2]
end

@testset "BitsLTriMatrix.jl" begin
    n = 4
    nentries = (n*(n+1)) ÷ 2
    m = BitsLTriMatrix(n, 1)
    @test size(m) == (n,n)
    @test length(m) == nentries

    for i in 1:n
        for j in 1:i
            m[i,j] = i+j
        end
    end

    @test m[1,1] == 2
    @test m[2,1] == 3
    @test m[3,2] == 5
    @test m[4,4] == 8
    @test_throws BoundsError m[1,2]
end


text:
using Crystallography
using CrystallographyBase
using Documenter

DocMeta.setdocmeta!(Crystallography, :DocTestSetup, :(using Crystallography); recursive=true)

makedocs(;
    modules=[Crystallography,CrystallographyBase],
    authors="Qi Zhang <singularitti@outlook.com>",
    repo="https://github.com/MineralsCloud/Crystallography.jl/blob/{commit}{path}#{line}",
    sitename="Crystallography.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://mineralscloud.github.io/Crystallography.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
        "Manual" => Any["Installation"=>"installation.md", "Development"=>"develop.md"],
        "API by modules" => Any[
            "`Crystallography` module"=>"api.md",
        ],
    ],
)

deploydocs(;
    repo="github.com/MineralsCloud/Crystallography.jl",
)


text:
clear()
@testset "check pooling op's gradient at single dim" begin
    for d in [1 2 3]
        for pool in [maximum minimum sum mean linearpool exppool]
            @testset "check $pool op's gradient at dim = $d" begin
                DIMS = d
                TYPE = Array{Float64};
                # [1] prepare input data and its label
                inputdims = 64;
                timeSteps = 16;
                batchsize = 32;
                x = Variable(rand(inputdims, timeSteps, batchsize); type=TYPE, keepsgrad=true,);
                if d==1;l = Variable(rand(1, timeSteps, batchsize); type=TYPE);end
                if d==2;l = Variable(rand(inputdims, 1, batchsize); type=TYPE);end
                if d==3;l = Variable(rand(inputdims, timeSteps, 1); type=TYPE);end

                # [2] forward and backward propagation
                COST1 = cost(mseLoss(pool(x; dims=DIMS), l));
                backward();

                # [3] with a samll change of a weight
                GRAD = x.delta[1];
                DELTA = 1e-6;
                x.value[1] += DELTA;

                # [4] forward and backward propagation
                COST2 = cost(mseLoss(pool(x; dims=DIMS), l));
                backward();

                # [5] check if the auto-grad is true or not
                dLdW = (COST2 - COST1)/DELTA;   # numerical gradient
                err  = abs((dLdW-GRAD)/(GRAD+eps(Float32)))*100;  # relative error in %
                err  = err < 1e-1 ? 0.0 : err;
                @test err<1.0
            end
        end
    end
end

@testset "check pooling op's gradient at mutiple dims" begin
    for pool in [maximum minimum sum mean linearpool exppool]
        @testset "check $pool op's gradient" begin
            DIMS = (1,2)
            TYPE = Array{Float64};

            # [1] prepare input data and its label
            inputdims = 64;
            timeSteps = 16;
            batchsize = 32;
            x = Variable(rand(inputdims, timeSteps, batchsize); type=TYPE,keepsgrad=true);
            l = Variable(rand(1,         1,         batchsize); type=TYPE);

            # [2] forward and backward propagation
            COST1 = cost(mseLoss(pool(x; dims=DIMS), l));
            backward();

            # [3] with a samll change of a weight
            GRAD = x.delta[1];
            DELTA = 1e-6;
            x.value[1] += DELTA;

            # [4] forward and backward propagation with a samll change of a weight
            COST2 = cost(mseLoss(pool(x; dims=DIMS), l));
            backward();

            # [5] check if the auto-grad is true or not
            dLdW = (COST2 - COST1)/DELTA;   # numerical gradient
            err  = abs((dLdW-GRAD)/(GRAD+eps(Float64)))*100;  # relative error in %
            err  = err < 1e-1 ? 0.0 : err;
            @test err<1.0
        end
    end
end

@testset "check maxmin and minmax op's gradient at mutiple dims" begin
    for pool in [maxmin minmax]
        @testset "check $pool op's gradient" begin
            DIM1 = 1
            DIM2 = 2
            TYPE = Array{Float64};

            # [1] prepare input data and its label
            inputdims = 64;
            timeSteps = 16;
            batchsize = 32;
            x = Variable(rand(inputdims, timeSteps, batchsize); type=TYPE,keepsgrad=true);
            l = Variable(rand(1,         1,         batchsize); type=TYPE);

            # [2] forward and backward propagation
            COST1 = mseLoss(pool(x; dims1=DIM1, dims2=DIM2), l) |> cost
            backward();

            # [3] with a samll change of a weight
            GRAD = x.delta[1];
            DELTA = 1e-6;
            x.value[1] += DELTA;

            # [4] forward and backward propagation with a samll change of a weight
            COST2 = mseLoss(pool(x; dims1=DIM1, dims2=DIM2), l) |> cost
            backward();

            # [5] check if the auto-grad is true or not
            dLdW = (COST2 - COST1)/DELTA;   # numerical gradient
            err  = abs((dLdW-GRAD)/(GRAD+eps(Float64)))*100;  # relative error in %
            err  = err < 1e-1 ? 0.0 : err;
            @test err<1.0
        end
    end
end

max_stars_repo_name: sonosole/Delta

max_issues_repo_name: sonosole/Delta

max_forks_repo_name: sonosole/Delta


text:
"""

#### References

A Fast and Accurate Online Sequential Learning Algorithm for Feedforward
Networks

Guang-Bin Huang, Qin-Yu Zhu, and Chee-Kheong Siew.

Neurocomputing, 2006 vol. 70 (1-3) pp. 489-501.

http://linkinghub.elsevier.com/retrieve/pii/S0925231206000385
"""
mutable struct OSELM{TN,TV} <: AbstractSLFN where TN <: AbstractNodeInput where TV <: AbstractArray{Float64}
    p::Int  # Number of training points
    q::Int  # Dimensionality of function domain
    s::Int  # number of neurons
    neuron_type::TN
    μx::Vector{Float64}
    σx::Vector{Float64}
    Wt::Matrix{Float64}  # transpose of W matrix
    d::Vector{Float64}

    M::Matrix{Float64}  # internal
    p_tot::Int
    v::TV

    function OSELM(p::Int, q::Int, s::Int, neuron_type::TN, μx, σx) where TN
        # NOTE: Wt and d are constant throughout all learning chunks
        Wt = 2*rand(q, s) .- 1
        d = rand(s)
        M = zeros(Float64, s, s)
        new{TN,typeof(d)}(p, q, s, neuron_type, μx, σx, Wt, d, M, 0)
    end
end

function OSELM(x::AbstractArray, y::TV;
               neuron_type::TN=Linear(Tanh()),
               s::Int=size(x, 1)) where TN <: AbstractNodeInput where TV <: AbstractArray
    q = size(x, 2)  # dimensionality of function domain
    p = size(x, 1)  # number of training points
    s = min(p, s)   # Can't have more neurons than training points
    xn, μx, σx = standardize(x[:, :])
    out = OSELM(p, q, s, neuron_type, μx, σx)
    fit!(out, xn, y)
end

## API methods
function fit!(elm::OSELM, x::AbstractArray, y::AbstractArray)
    # check if we are boosting or not
    S = hidden_out(elm, x)
    if elm.p_tot == 0  # this is the initialization phase
        # elm.v = S \ y
        elm.M = pinv(S'S)
        elm.v = elm.M*S'y
    else
        elm.M -= elm.M*S' * inv(I + S*elm.M*S') * S * elm.M
        elm.v += elm.M * S' * (y - S*elm.v)
    end
    elm.p_tot += size(x, 1)
    elm
end

function Base.show(io::IO, elm::OSELM{TA}) where TA
    s =
    """
    OSELM with
      - $(TA) Activation function
      - $(elm.q) input dimension(s)
      - $(elm.s) neuron(s)
      - $(elm.p) initial training point(s)
      - $(elm.p_tot) total training points
    """
    print(io, s)
end

function test_me(::Type{OSELM})
    x = range(0, stop=1, length=20)
    y = sin.(6*x[:])
    oselm = OSELM(x, y)

    xt = range(0, stop=1, length=300)
    yt = sin.(6*xt)

    @show maximum(abs.(oselm(xt) .- yt))

    for i in 1:50
        x2 = rand(15)
        y2 = sin.(6*x2)
        fit!(oselm, x2, y2)
        @printf "%i\t%2.4e\n" i maximum(abs.(oselm(xt) - yt))
    end
end


text:
# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/JuliaFEM.jl/blob/master/LICENSE.md

using JuliaFEM
using JuliaFEM.Preprocess
using JuliaFEM.Postprocess
using JuliaFEM.Testing

#=
Two rings, RING1 is inner, RING2 is outer. Inner diameter is from 0.8 .. 0.9 and
outer ring is 0.9 .. 1.0. Contact surface pair is RING1_OUTER <- RING2_INNER.
Put constant temperature 1.0 for inner surface of inner ring and 2.0 for outer
surface of outer ring. We should expect constant temperature in contact surface.
This is conforming mesh so result should match to the conforming situation.
=#
@testset "test that curved interface transfers constant field without error, two rings problem" begin
    meshfile = Pkg.dir("JuliaFEM") * "/test/testdata/primitives.med"
    mesh = aster_read_mesh(meshfile, "RINGS")

    ring1 = Problem(Heat, "RING1", 1)
    ring1.elements = create_elements(mesh, "RING1")
    update!(ring1.elements, "temperature thermal conductivity", 1.0)

    ring2 = Problem(Heat, "RING2", 1)
    ring2.elements = create_elements(mesh, "RING2")
    update!(ring2.elements, "temperature thermal conductivity", 1.0)

    bc_inner = Problem(Dirichlet, "INNER SURFACE", 1, "temperature")
    bc_inner.elements = create_elements(mesh, "RING1_INNER")
    update!(bc_inner, "temperature 1", 1.0)

    bc_outer = Problem(Dirichlet, "OUTER SURFACE", 1, "temperature")
    bc_outer.elements = create_elements(mesh, "RING2_OUTER")
    update!(bc_outer, "temperature 1", 2.0)

    interface = Problem(Mortar, "interface between rings", 1, "temperature")
    interface_slave = create_elements(mesh, "RING1_OUTER")
    interface_master = create_elements(mesh, "RING2_INNER")
    interface.elements = [interface_slave; interface_master]
    update!(interface_slave, "master elements", interface_master)

    solver = LinearSolver(ring1, ring2, bc_inner, bc_outer, interface)
    solver()

    fn = Pkg.dir("JuliaFEM") * "/test/testdata/rings.rmed"
    results = RMEDFile(fn)
    nodes = aster_read_nodes(results)
    temp_ca = aster_read_data(results, "TEMP")

    passed = true
    for j in sort(collect(keys(nodes)))
        X = nodes[j]
        T1 = solver("temperature", X, 0.0)
        T2 = temp_ca[j]
        rtol = norm(T1-T2) / max(T1,T2)
        @printf "% 5i : %8.5f %8.5f %8.5f | %8.5f %8.5f | %8.5f\n" j X... T1 T2 rtol
        passed = passed && (rtol < 1.0e-12)
    end
    @test passed
end


text:
function twoNumbers(a::Float64, b::Float64)
   println("multiply floats");
   return a * b;
end

function twoNumbers(a, b)
   println("multiply numbers");
   return a * b;
end

println(twoNumbers(23.1, 23.2));


text:
function computecosts()
    global ECᵢ, ECₒ, rtracs

    ECᵢ, ECₒ = zero(pᵢ), zero(pᵢ)
    ECᵢ[:,end,..] .= M
    ECₒ[:,end,..] .= M
    for (snkid,snk) in enumerate(snks)
        i = inlinkids(net, snk)[1]
        ECₒ[i,:,:,1] .= M
        r = collect(1:T)
        ECₒ[i,:,snkid,1] .= clamp.(trgt .- r, 0., Inf) * β .+ clamp.(r .- trgt, 0., Inf) * γ # overwriting
    end

    rtracs = zeros(nlinks, T+1)
    for i in 1:nlinks
        l = length(link(net, i))
        rtracs[i,(T-l+1):end] .= T
        for τ in (T-l):-1:2
            if CFᵢ[i,τ] > CFₒ[i,end]
                rtracs[i,τ] = T
            else
                rtracs[i,τ] = rcvalarg(@view(CFₒ[i,:]), CFᵢ[i,τ-1], rtracs[i,τ+1], τ+l-1)
            end
        end
        rtracs[i,1] = l
    end

    function costupdate!(i, τ)
        # goal: set ECᵢ[i,τ,..]
        if rtracs[i,τ+1] == T
            ECᵢ[i,τ,..] .= M
        else
            #@show i, τ
            rng = rtracs[i,τ]:rtracs[i,τ+1]
            inds = indexify(rng)
            #@show i, τ, rng, inds
            if size(rng) == 0.
                ind = lastidx(rng)
                ECᵢ[i,τ,..] .= (ind - τ) .+ ECₒ[i,ind,..]
            else
                tmp = mucsum(@view(CFₒ[i,:]), rng)
                tmp[end] += ϵ;
                tf = (CFᵢ[i,τ] - ((τ == 1) ? 0. : CFᵢ[i,τ-1])) + ϵ
                #@show rng, inds
                #@show tmp, tf, (tmp ./ tf), (inds .- τ)
                ECᵢ[i,τ,..] .= squeezesum((tmp ./ tf) .* ((inds .- τ) .+ ECₒ[i,inds,..]), dims=1)
                #@show i, τ, ECᵢ[i,τ,:,1]
            end
        end
    end

    for τ in T:-1:1
        for src in srcs
            i = outlinkids(net, src)[1]
            costupdate!(i,τ)
        end

        for mrg in mrgs
            ili = inlinkids(net,mrg)
            oli = outlinkids(net,mrg)[1]

            costupdate!(oli,τ)

            ECₒ[ili[1],τ,..] .= ECᵢ[oli,τ,..]
            ECₒ[ili[2],τ,..] .= ECᵢ[oli,τ,..]
        end

        for div in divs
            ili = inlinkids(net,div)[1]
            oli = outlinkids(net,div)

            for li in oli
                costupdate!(li,τ)
            end

            sr = [SR[div][i][τ,..] for i in 1:2]
            ECₒ[ili,τ,..] .= sr[1] .* ECᵢ[oli[1],τ,..] .+ sr[2] .* ECᵢ[oli[2],τ,..]
        end
    end

    return ECᵢ, ECₒ, rtracs
end


text:
using FileIO
using LasIO
using Test

workdir = dirname(@__FILE__)
# source: http://www.liblas.org/samples/
filename = "libLAS_1.2.las" # point format 0
testfile = joinpath(workdir, filename)
writefile = joinpath(workdir, "libLAS_1.2-out.las")

# test if output file matches input file
header, pointdata = load(testfile, mmap=true)
n = length(pointdata)
save(writefile, header, pointdata)
@test hash(read(testfile)) == hash(read(writefile))
rm(writefile)

# testing a las file version 1.0 point format 1 file with VLRs
srsfile = joinpath(workdir, "srs.las")
srsfile_out = joinpath(workdir, "srs-out.las")
srsheader, srspoints = load(srsfile, mmap=true)
save(srsfile_out, srsheader, srspoints)
@test hash(read(srsfile)) == hash(read(srsfile_out))
rm(srsfile_out)

# Test editing stream file
srsfile = joinpath(workdir, "srs.las")
srsfile_out = joinpath(workdir, "srs-out.las")
srsheader, srspoints = load(srsfile, mmap=true)
@test_throws ErrorException srspoints[5] = LasPoint1(1,1,1,1,1,1,1,1,1,1.0)


text:
function ChainRulesCore.rrule(ℓ::Union{DebiasedWhittleLikelihood,WhittleLikelihood},θ)
    G = zeros(Float64, npars(getmodel(ℓ)))
    y = ℓ(zero(Float64),G,nothing,θ)
    function whittlelikelihood_pullback(Δy)
        return NoTangent(), G * Δy
    end
    return y, whittlelikelihood_pullback
end


text:
for v in [0,1,2,3//2,3//1,1.5,1.5im,1im]
    scal(v)
end

param(:g)'

Pr"ω_i,j,3"

σx(:i)*σy(:i)
σz(3)*σy(2)

a(:m)*adag(:n)*adag(3)*a(3)*adag(3)*a(:n)*adag(:m)

σy(1)'
σy(:m)'
(adag(1)*a(:n))' == adag(:n)*a(1)
a(1) * (σy(1) * a(1))'

let
    tmp = ∑(:i,adag(:i)*a(:i))
    adag(:n)*tmp
    a(:n)*tmp
    σz(:n)*tmp
    tmp*scal(2)
    tmp*param(:g,:n)
    tmp*a(:n)
    tmp*adag(:n)
    tmp*(adag(:n)*adag(:n))
    tmp*(adag(:n)*a(:n))
end
∑(:i,σx(:i))*σy(:j)
∑(:i,σx(:i))*σy(:a)
∑(:i,σx(:i)*σy(:a))

comm(σx(5),σy(3))
comm(σx(5),σx(5))
comm(σx(1),σz(1))
scal(2)*comm(σx(5),σy(5))
comm(σy(5),comm(σx(5),σy(5)))

comm(scal(2//5)*param(:h)*σx(5),scal(3)*param(:g)*σy(5))

σx(1)*σy(1)
σx(3)*σy(2)*σy(2)

σx(5)*σy(5)*σz(5)
σx(5)*σy(5)*σx(5)

param(:g,2)*param(:g,1)*param(:g,'c',3)*param(:b)*param(:a)*param(:d,'c',3)*param(:f,'r',1)

a(2)*adag(2)*adag(3)*σy(1)*adag(2)*adag(4)*σz(1)*a(2)*adag(3)

adag(2)*a(2)*adag(2)*σy(1) + scal(2)*param(:g,'c',1)

scal(-1//2) + σp(1) * σm(1)

σp(2)
σm(2)
σp(1)*σm(1)

comm(σp(1),σp(1))
comm(σm(:n),σp(:n))
comm(a(2),adag(:m))

comm(a(1),adag(1)*a(1))
comm(a(1),adag(1)*a(2)*a(1))
comm(a(1),a(2)*adag(1)*a(1)*adag(2))

ascorr(scal(3))
ascorr(a(2))
ascorr(scal(3)*a(2))

ascorr(a(2)*a(2))
ascorr(scal(2)*a(1)*a(2)*a(3))
ascorr(a(1)*a(2)*a(3)*a(4))
ascorr(adag(2)*a(1)*σz(1))

ascorr(param(:g,'r')*adag(3)*a(2)*a(2))
ascorr(scal(-1)*param(:g,'r',1)*σz(1))
ascorr(adag(:n)*σy(:k)*a(:m)*adag(:m))

let
    H = ∑(:i,param(:ω,'r',:i)*adag(:i)*a(:i)) + ∑(:j,scal(1//2)*param(:ωe,'r',:j)*σz(:j)) +
        ∑(:i,∑(:j,param(:g,'r',(:i,:j))*(adag(:i)+a(:i))*σx(:j)))
    comm(adag(:n)*a(:m),H)
    comm(adag(:n)*a(:n),H)
    for op in [a(:n),adag(:n),σx(:k),σy(:k),σz(:k)]
        latex(op),latex(comm(op,H))
    end
    for op in [adag(:n)*σz(:k),a(:n)*σz(:k)]
        latex(op),latex(comm(op,H))
    end

    for op in [adag(:n)*σz(:k),a(:n)*σz(:k)]
        for x = 1:5
            op = comm(op,H)
        end
    end

    ExpVal(H)
    #ascorr(H)
end

vacA(Avac(σp(1)*σm(1)))
vacA(Avac(σm(1)*σp(1)))

for i2 = (:n,:m)
    stateop = scal(1/√2)*adag(:n)*adag(:n)*adag(:n) + scal(1/√2)*adag(i2)
    for A in [scal(1),adag(:n)*a(:n),adag(:n)*adag(:n)*a(:n)*a(:n)]
        latex(A),latex(vacExpVal(A,stateop))
    end
end


text:
#bring end points to the equator -> define 3D rotation matrix
function rotate_points(lons,lats)
	#... and of end points
	x0=cosd.(lats).*cosd.(lons)
	y0=cosd.(lats).*sind.(lons)
	z0=sind.(lats)

	#get the rotation matrix:
	#1) rotate around x axis to put first point at z=0
	theta=atan(-z0[1],y0[1])
	R1=[[1;0;0] [0;cos(theta);sin(theta)] [0;-sin(theta);cos(theta)]]
	tmp0=[x0;y0;z0]; tmp1=R1*tmp0; x1=tmp1[1,:]; y1=tmp1[2,:]; z1=tmp1[3,:]
	x0=x1; y0=y1; z0=z1
	#2) rotate around z axis to put first point at y=0
	theta=atan(x0[1],y0[1])
	R2=[[cos(theta);sin(theta);0] [-sin(theta);cos(theta);0] [0;0;1]]
	tmp0=transpose([x0 y0 z0]); tmp1=R2*tmp0; x1=tmp1[1,:]; y1=tmp1[2,:]; z1=tmp1[3,:]
	x0=x1; y0=y1; z0=z1
	#3) rotate around y axis to put second point at z=0
	theta=atan(-z0[2],-x0[2])
	R3=[[cos(theta);0;-sin(theta)] [0;1;0] [sin(theta);0;cos(theta)]]
	tmp0=transpose([x0 y0 z0]); tmp1=R3*tmp0; x1=tmp1[1,:]; y1=tmp1[2,:]; z1=tmp1[3,:]
	x0=x1; y0=y1; z0=z1

	x0,y0,z0,R3*R2*R1
end

function rotate_XCYC(Γ,R)
	#3D carthesian coordinates:
	lon=Γ.XC; lat=Γ.YC
	x=cosd.(lat)*cosd.(lon)
	y=cosd.(lat)*sind.(lon)
	z=sind.(lat)

	#rotation R:
    γ=Γ.XC.grid
	tmpx=γ.write(x); tmpy=γ.write(y); tmpz=γ.write(z)
	tmp1=findall((!isnan).(tmpx))
	tmpx2=tmpx[tmp1]; tmpy2=tmpy[tmp1]; tmpz2=tmpz[tmp1]
	tmp2=[tmpx2';tmpy2';tmpz2']

	tmp3=R*tmp2

	tmpx2=tmp3[1,:]; tmpy2=tmp3[2,:]; tmpz2=tmp3[3,:]
	tmpx[tmp1]=tmpx2; tmpy[tmp1]=tmpy2; tmpz[tmp1]=tmpz2
	x=γ.read(tmpx,Γ.XC); y=γ.read(tmpy,Γ.XC); z=γ.read(tmpz,Γ.XC)

	x,y,z
end

##

function shorter_paths!(xyz,xyz0,msk_in)
	(x0,y0,z0)=xyz0[:]
	(x,y,z)=xyz[:]

	#split in two segments:
	theta=zeros(2)
	theta[1]=atan(y0[1],x0[1])
	theta[2]=atan(y0[2],x0[2])

    γ=msk_in[1].grid
	tmpx=γ.write(x); tmpy=γ.write(y); tmpz=γ.write(z);
	tmptheta=atan.(tmpy,tmpx)
	if theta[2]<0;
		tmp00=findall(tmptheta.<=theta[2])
		tmptheta[tmp00].=tmptheta[tmp00].+2*pi
		theta[2]=theta[2]+2*pi
	end

	msk_out=[]
	for kk in 1:3
		#select field to treat:
		mm=msk_in[kk]
		#select the shorther segment:
		tmpm=γ.write(mm)
       if theta[2]-theta[1]<=pi
            tmpm[findall( (tmptheta.>theta[2]).|(tmptheta.<theta[1]) )].=0.0
        else
            tmpm[findall( (tmptheta.<=theta[2]).&(tmptheta.>=theta[1]) )].=0.0
        end
        mm=γ.read(tmpm,mm);
        #store result:
		push!(msk_out,mm)
    end
	msk_out[:]
end


text:
using Gadfly

# wide-form plotting of heterogenous arrays of arrays

set_default_plot_size(4inch, 4inch)

xs = [ rand(Float32, 10),
       rand(Float64, 15),
       rand(Float32, 5) ]
plot(xs, x=Row.index, y=Col.value, color=Col.index, Scale.color_discrete, Geom.line)


text:
struct BarrierHandle{Barrier<:SyncBarriers.Barrier}
    barrier::Barrier
    i::Int
end

Base.length(barrier::SyncBarriers.Barrier) = barrier.n

@inline function Base.getindex(barrier::SyncBarriers.Barrier, i::Integer)
    @boundscheck 1 <= i <= length(barrier) || throw(BoundsError(barrier, i))
    return BarrierHandle(barrier, i)
end


text:
module BioTools

using FastaIO
using BioSequences, BioSymbols
using Dates

# import BioSequences: @aa_str, @dna_str, @rna_str
import Base.getindex, Base.get, Base.setindex!, Base.keys, Base.values
import Base.isempty, Base.length, Base.enumerate, Base.iterate
import Base.show
import BioSequences.alphabet, BioSequences.isambiguous

global hello="hello"
export hello

export AbstractStrain, Strain
export SiteFrequency, Profile
export isambiguous, ambiguous

include("global.jl")
include("types.jl")
include("sequences.jl")
include("IO.jl")
include("filtering.jl")
include("alignments.jl")

end

max_stars_repo_name: PierreBarrat/FluPredictibility

max_issues_repo_name: PierreBarrat/FluPredictibility

max_forks_repo_name: PierreBarrat/FluPredictibility


text:
using JuMP

m = Model()

type Recipe
	time::Float64
	outs::Dict{AbstractString, Float64}
	ins::Dict{AbstractString, Float64}
	function Recipe(name, time::Float64, speed::Float64)
		recipes[name] = new(time/speed, Dict{AbstractString, Float64}(), Dict{AbstractString, Float64}())
		recipes[name]
	end
end

function production(name)
	nfacs = getvalue(Factory[name])
	r = recipes[name]
	if nfacs == 0 return end
	@printf "%s: %d\n" name nfacs
	@printf "\tProduces\n"
	for (k,v) in r.outs
		@printf "\t\t%0.2f \"%s\" per min - %0.2f per second\n" 60v * nfacs k v * nfacs
	end
	@printf "\tConsumes\n"
	for (k,v) in r.ins
		@printf "\t\t%0.2f \"%s\" per min - %0.2f per second\n" 60v * nfacs k v * nfacs
	end
end

macro IN(iname, iqty) :(recipe.ins[$iname] = $iqty / recipe.time) end

macro OUT(iname, iqty)
	return quote
		push!(Products, $iname)
		recipe.outs[$iname] = $iqty / recipe.time
	end
end

recipes = Dict{AbstractString, Recipe}()
Products = Set{AbstractString}()

recipe  = Recipe("Advanced Oil Processing", 5.0, 1.)
@IN "Crude Oil" 10.
@IN "Water" 5.
@OUT "Heavy Oil" 1.
@OUT "Light Oil" 4.5
@OUT "Petroleum Gas" 5.5

recipe  = Recipe("Heavy Oil Cracking", 5.0 , 1.25)
@IN "Heavy Oil" 4.
@IN "Water" 3.
@OUT "Light Oil" 3.

recipe  = Recipe("Light Oil Cracking", 5.0 , 1.25)
@IN "Light Oil" 3.
@IN "Water" 3.
@OUT "Petroleum Gas" 2.

recipe  = Recipe("Petroleum Gas Solid Fuel", 2., 1.25)
@IN "Petroleum Gas" 2.0
@OUT "Solid Fuel" 1.

recipe  = Recipe("Light Oil Solid Fuel", 2., 1.25)
@IN "Light Oil" 1.0
@OUT "Solid Fuel" 1.

recipe = Recipe("Heavy Oil Solid Fuel", 2., 1.25)
@IN "Heavy Oil" 1.0
@OUT "Solid Fuel" 1.

recipe = Recipe("Rocket Fuel", 30., 1.25)
@IN "Solid Fuel" 10.
@OUT "Rocket Fuel" 1.

recipe = Recipe("Crude Oil Pumping", 1., 1.)
@IN "Pump" 0.1
@OUT "crude-oil" 0.1

include("recipe_protos.jl")

macro Factories() :(collect(keys(recipes))) end

@variable(m, Factory[@Factories] >= 0, Int)

macro FSUM(fac, recipe, dir) :(Factory[$fac] * get(recipes[$fac].$dir, $recipe, 0)) end
macro ALLFSUM(recipe, dir) :(sum([@FSUM(F, $recipe, $dir) for F in @Factories])) end
macro OUTS(recipe) :(@ALLFSUM($recipe, outs)) end
macro INS(recipe)  :(@ALLFSUM($recipe, ins)) end

for r in Products @constraint(m, @INS(r) <= @OUTS(r)) end
@constraint(m, Factory["@INS("heavy-oil") >= @FSUM("advanced-oil-processing, "heavy-oil", outs))

@constraint(m, Factory["Crude Oil Pumping"] == 20)
@objective(m, Max, @OUTS("rocket-fuel"))

solve(m)

for m in @Factories
	production(m)
end

max_stars_repo_name: lawless-m/factorio-utils

max_issues_repo_name: lawless-m/factorio-utils

max_forks_repo_name: lawless-m/factorio-utils


text:
# bmark_solvers  avec des OrderedDict

function my_bmark_solvers(solvers :: OrderedDict{Symbol,<: Any}, args...;
                       kwargs...)
  stats = OrderedDict{Symbol, DataFrame}()
  for (name, solver) in solvers
    @debug "running" name solver
    stats[name] = solve_problems(solver, args...; kwargs...)
  end
  return stats
end

# performance_profile  avec un OrderedDict
function my_performance_profile(stats::OrderedDict{Symbol,DataFrame}, cost::Function, args...; kwargs...)
  solvers = keys(stats)
  dfs = (stats[s] for s in solvers)
  P = hcat([cost(df) for df in dfs]...)
  performance_profile(P, string.(solvers), args...; kwargs...)
end

# profile_solvers  avec un OrderedDict
function my_profile_solvers(stats::OrderedDict{Symbol,DataFrame},
                            costs::Vector{<:Function},
                            costnames::Vector{String};
                            width::Int=400,
                            height::Int=400
                            )
  solvers = collect(keys(stats))
  dfs = (stats[solver] for solver in solvers)
  Ps = [hcat([cost(df) for df in dfs]...) for cost in costs]

  nprobs = size(stats[first(solvers)], 1)
  nsolvers = length(solvers)
  ncosts = length(costs)
  npairs = div(nsolvers * (nsolvers - 1), 2)
  colors = get_color_palette(:auto, nsolvers)

  # profiles with all solvers
  ps = [performance_profile(Ps[1], string.(solvers), palette=colors, title=costnames[1], legend=:bottomright)]
  nsolvers > 2 && xlabel!(ps[1], "")
  for k = 2 : ncosts
    p = performance_profile(Ps[k], string.(solvers), palette=colors, title=costnames[k], legend=false)
    nsolvers > 2 && xlabel!(p, "")
    ylabel!(p, "")
    push!(ps, p)
  end

  if nsolvers > 2
    ipairs = 0
    # combinations of solvers 2 by 2
    for i = 2 : nsolvers
      for j = 1 : i-1
        ipairs += 1
        pair = [solvers[i], solvers[j]]
        dfs = (stats[solver] for solver in pair)
        Ps = [hcat([cost(df) for df in dfs]...) for cost in costs]

        clrs = [colors[i], colors[j]]
        p = performance_profile(Ps[1], string.(pair), palette=clrs, legend=:bottomright)
        ipairs < npairs && xlabel!(p, "")
        push!(ps, p)
        for k = 2 : length(Ps)
          p = performance_profile(Ps[k], string.(pair), palette=clrs, legend=false)
          ipairs < npairs && xlabel!(p, "")
          ylabel!(p, "")
          push!(ps, p)
        end
      end
    end
    p = plot(ps..., layout=(1 + ipairs, ncosts), size=(ncosts * width, (1 + ipairs) * height))
  else
    p = plot(ps..., layout=(1, ncosts), size=(ncosts * width, height))
  end
  p
end